diff --git a/jwk.go b/jwk.go index 448e693..fc8d11b 100644 --- a/jwk.go +++ b/jwk.go @@ -73,6 +73,7 @@ type JWKCache struct { // maintaining consistent behavior in the token verification process. type JWKCacheInterface interface { GetJWKS(jwksURL string, httpClient *http.Client) (*JWKSet, error) + Cleanup() // Add Cleanup method to the interface } // GetJWKS retrieves the JSON Web Key Set, either from cache or by fetching it @@ -111,6 +112,17 @@ func (c *JWKCache) GetJWKS(jwksURL string, httpClient *http.Client) (*JWKSet, er return jwks, nil } +// Cleanup removes expired JWKs from the cache. +func (c *JWKCache) Cleanup() { + c.mutex.Lock() + defer c.mutex.Unlock() + + now := time.Now() + if c.jwks != nil && now.After(c.expiresAt) { + c.jwks = nil + } +} + // fetchJWKS retrieves the JSON Web Key Set from the OIDC provider's JWKS endpoint. // It handles HTTP communication and JSON parsing of the response. // Parameters: diff --git a/main.go b/main.go index 1c1823a..cf24e7a 100644 --- a/main.go +++ b/main.go @@ -714,8 +714,9 @@ func (t *TraefikOidc) startTokenCleanup() { defer ticker.Stop() for range ticker.C { t.logger.Debug("Starting token cleanup cycle") - t.tokenCache.Cleanup() - t.tokenBlacklist.Cleanup() +t.tokenCache.Cleanup() +t.tokenBlacklist.Cleanup() +t.jwkCache.Cleanup() // Assuming jwkCache is the cache from cache.go // Removed runtime.GC() call } }() diff --git a/main_test.go b/main_test.go index f71369f..883b6b3 100644 --- a/main_test.go +++ b/main_test.go @@ -135,6 +135,12 @@ func (m *MockJWKCache) GetJWKS(jwksURL string, httpClient *http.Client) (*JWKSet return m.JWKS, m.Err } +func (m *MockJWKCache) Cleanup() { + // Mock cleanup implementation + m.JWKS = nil + m.Err = nil +} + // Helper function to create a JWT token func createTestJWT(privateKey *rsa.PrivateKey, alg, kid string, claims map[string]interface{}) (string, error) { header := map[string]interface{}{ diff --git a/metadata_cache.go b/metadata_cache.go index 7b44164..521f0b4 100644 --- a/metadata_cache.go +++ b/metadata_cache.go @@ -19,6 +19,17 @@ func NewMetadataCache() *MetadataCache { return &MetadataCache{} } +// Cleanup removes expired metadata from the cache. +func (c *MetadataCache) Cleanup() { + c.mutex.Lock() + defer c.mutex.Unlock() + + now := time.Now() + if c.metadata != nil && now.After(c.expiresAt) { + c.metadata = nil + } +} + // GetMetadata retrieves the metadata from cache or fetches it if expired func (c *MetadataCache) GetMetadata(providerURL string, httpClient *http.Client, logger *Logger) (*ProviderMetadata, error) { c.mutex.RLock()