|
| 1 | +package module |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "sync" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/CrisisTextLine/modular" |
| 10 | + "github.com/redis/go-redis/v9" |
| 11 | +) |
| 12 | + |
| 13 | +// TokenBlacklist is the interface for checking and adding revoked JWT IDs. |
| 14 | +type TokenBlacklist interface { |
| 15 | + Add(jti string, expiresAt time.Time) |
| 16 | + IsBlacklisted(jti string) bool |
| 17 | +} |
| 18 | + |
| 19 | +// TokenBlacklistModule maintains a set of revoked JWT IDs (JTIs). |
| 20 | +// It supports two backends: "memory" (default) and "redis". |
| 21 | +type TokenBlacklistModule struct { |
| 22 | + name string |
| 23 | + backend string |
| 24 | + redisURL string |
| 25 | + cleanupInterval time.Duration |
| 26 | + |
| 27 | + // memory backend |
| 28 | + entries sync.Map // jti (string) -> expiry (time.Time) |
| 29 | + |
| 30 | + // redis backend |
| 31 | + redisClient *redis.Client |
| 32 | + |
| 33 | + logger modular.Logger |
| 34 | + stopCh chan struct{} |
| 35 | +} |
| 36 | + |
| 37 | +// NewTokenBlacklistModule creates a new TokenBlacklistModule. |
| 38 | +func NewTokenBlacklistModule(name, backend, redisURL string, cleanupInterval time.Duration) *TokenBlacklistModule { |
| 39 | + if backend == "" { |
| 40 | + backend = "memory" |
| 41 | + } |
| 42 | + if cleanupInterval <= 0 { |
| 43 | + cleanupInterval = 5 * time.Minute |
| 44 | + } |
| 45 | + return &TokenBlacklistModule{ |
| 46 | + name: name, |
| 47 | + backend: backend, |
| 48 | + redisURL: redisURL, |
| 49 | + cleanupInterval: cleanupInterval, |
| 50 | + stopCh: make(chan struct{}), |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +// Name returns the module name. |
| 55 | +func (m *TokenBlacklistModule) Name() string { return m.name } |
| 56 | + |
| 57 | +// Init initializes the module. |
| 58 | +func (m *TokenBlacklistModule) Init(app modular.Application) error { |
| 59 | + m.logger = app.Logger() |
| 60 | + return nil |
| 61 | +} |
| 62 | + |
| 63 | +// Start connects to Redis (if configured) and starts the cleanup goroutine. |
| 64 | +func (m *TokenBlacklistModule) Start(ctx context.Context) error { |
| 65 | + if m.backend == "redis" { |
| 66 | + if m.redisURL == "" { |
| 67 | + return fmt.Errorf("auth.token-blacklist %q: redis_url is required for redis backend", m.name) |
| 68 | + } |
| 69 | + opts, err := redis.ParseURL(m.redisURL) |
| 70 | + if err != nil { |
| 71 | + return fmt.Errorf("auth.token-blacklist %q: invalid redis_url: %w", m.name, err) |
| 72 | + } |
| 73 | + m.redisClient = redis.NewClient(opts) |
| 74 | + if err := m.redisClient.Ping(ctx).Err(); err != nil { |
| 75 | + _ = m.redisClient.Close() |
| 76 | + m.redisClient = nil |
| 77 | + return fmt.Errorf("auth.token-blacklist %q: redis ping failed: %w", m.name, err) |
| 78 | + } |
| 79 | + m.logger.Info("token blacklist started", "name", m.name, "backend", "redis") |
| 80 | + return nil |
| 81 | + } |
| 82 | + |
| 83 | + // memory backend: start cleanup goroutine |
| 84 | + go m.runCleanup() |
| 85 | + m.logger.Info("token blacklist started", "name", m.name, "backend", "memory") |
| 86 | + return nil |
| 87 | +} |
| 88 | + |
| 89 | +// Stop shuts down the module. |
| 90 | +func (m *TokenBlacklistModule) Stop(_ context.Context) error { |
| 91 | + select { |
| 92 | + case <-m.stopCh: |
| 93 | + // already closed |
| 94 | + default: |
| 95 | + close(m.stopCh) |
| 96 | + } |
| 97 | + if m.redisClient != nil { |
| 98 | + return m.redisClient.Close() |
| 99 | + } |
| 100 | + return nil |
| 101 | +} |
| 102 | + |
| 103 | +// Add marks a JTI as revoked until expiresAt. |
| 104 | +func (m *TokenBlacklistModule) Add(jti string, expiresAt time.Time) { |
| 105 | + if m.backend == "redis" && m.redisClient != nil { |
| 106 | + ttl := time.Until(expiresAt) |
| 107 | + if ttl <= 0 { |
| 108 | + return // already expired, nothing to blacklist |
| 109 | + } |
| 110 | + _ = m.redisClient.Set(context.Background(), m.redisKey(jti), "1", ttl).Err() |
| 111 | + return |
| 112 | + } |
| 113 | + m.entries.Store(jti, expiresAt) |
| 114 | +} |
| 115 | + |
| 116 | +// IsBlacklisted returns true if the JTI is revoked and has not yet expired. |
| 117 | +func (m *TokenBlacklistModule) IsBlacklisted(jti string) bool { |
| 118 | + if m.backend == "redis" && m.redisClient != nil { |
| 119 | + n, err := m.redisClient.Exists(context.Background(), m.redisKey(jti)).Result() |
| 120 | + return err == nil && n > 0 |
| 121 | + } |
| 122 | + val, ok := m.entries.Load(jti) |
| 123 | + if !ok { |
| 124 | + return false |
| 125 | + } |
| 126 | + expiry, ok := val.(time.Time) |
| 127 | + return ok && time.Now().Before(expiry) |
| 128 | +} |
| 129 | + |
| 130 | +func (m *TokenBlacklistModule) redisKey(jti string) string { |
| 131 | + return "blacklist:" + jti |
| 132 | +} |
| 133 | + |
| 134 | +func (m *TokenBlacklistModule) runCleanup() { |
| 135 | + ticker := time.NewTicker(m.cleanupInterval) |
| 136 | + defer ticker.Stop() |
| 137 | + for { |
| 138 | + select { |
| 139 | + case <-m.stopCh: |
| 140 | + return |
| 141 | + case <-ticker.C: |
| 142 | + now := time.Now() |
| 143 | + m.entries.Range(func(key, value any) bool { |
| 144 | + if expiry, ok := value.(time.Time); ok && now.After(expiry) { |
| 145 | + m.entries.Delete(key) |
| 146 | + } |
| 147 | + return true |
| 148 | + }) |
| 149 | + } |
| 150 | + } |
| 151 | +} |
| 152 | + |
| 153 | +// ProvidesServices registers this module as a service. |
| 154 | +func (m *TokenBlacklistModule) ProvidesServices() []modular.ServiceProvider { |
| 155 | + return []modular.ServiceProvider{ |
| 156 | + {Name: m.name, Description: "JWT token blacklist", Instance: m}, |
| 157 | + } |
| 158 | +} |
| 159 | + |
| 160 | +// RequiresServices returns service dependencies (none). |
| 161 | +func (m *TokenBlacklistModule) RequiresServices() []modular.ServiceDependency { |
| 162 | + return nil |
| 163 | +} |
0 commit comments