From 0f2c6cee11a1819c6ce360f635b6eb54df8e39e4 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Tue, 21 Jul 2026 18:24:16 +0800 Subject: [PATCH] fix: normalize API key expiry timestamps to UTC (#2137) Store authorization timestamps as timestamptz and normalize Unix expiry inputs to UTC so tenant/platform API keys expire at the intended instant even when the app process timezone differs from the PostgreSQL session. --- .../application/repository/tenant_api_key.go | 4 +- .../repository/tenant_api_key_test.go | 42 +++++++++++++++++++ internal/application/service/resource.go | 6 +-- .../application/service/tenant_api_key.go | 11 +++-- .../service/tenant_api_key_test.go | 19 +++++++++ internal/handler/system.go | 4 +- internal/handler/tenant.go | 4 +- .../000072_auth_timestamp_tz.down.sql | 35 ++++++++++++++++ .../versioned/000072_auth_timestamp_tz.up.sql | 37 ++++++++++++++++ 9 files changed, 150 insertions(+), 12 deletions(-) create mode 100644 internal/application/repository/tenant_api_key_test.go create mode 100644 migrations/versioned/000072_auth_timestamp_tz.down.sql create mode 100644 migrations/versioned/000072_auth_timestamp_tz.up.sql diff --git a/internal/application/repository/tenant_api_key.go b/internal/application/repository/tenant_api_key.go index 61ab0229..1daff605 100644 --- a/internal/application/repository/tenant_api_key.go +++ b/internal/application/repository/tenant_api_key.go @@ -57,7 +57,7 @@ func (r *tenantAPIKeyRepository) ListPlatformAPIKeys(ctx context.Context) ([]*ty } func (r *tenantAPIKeyRepository) RevokeAPIKey(ctx context.Context, tenantID uint64, id uint64) error { - now := time.Now() + now := time.Now().UTC() res := r.db.WithContext(ctx). Model(&types.TenantAPIKey{}). Where("id = ? AND tenant_id = ? AND revoked_at IS NULL", id, tenantID). @@ -72,7 +72,7 @@ func (r *tenantAPIKeyRepository) RevokeAPIKey(ctx context.Context, tenantID uint } func (r *tenantAPIKeyRepository) RevokePlatformAPIKey(ctx context.Context, id uint64) error { - now := time.Now() + now := time.Now().UTC() res := r.db.WithContext(ctx). Model(&types.TenantAPIKey{}). Where("id = ? AND scope_type = ? AND revoked_at IS NULL", id, types.APIKeyScopePlatform). diff --git a/internal/application/repository/tenant_api_key_test.go b/internal/application/repository/tenant_api_key_test.go new file mode 100644 index 00000000..c7a3a0cf --- /dev/null +++ b/internal/application/repository/tenant_api_key_test.go @@ -0,0 +1,42 @@ +package repository + +import ( + "context" + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/stretchr/testify/require" + "gorm.io/driver/sqlite" + "gorm.io/gorm" +) + +func TestTenantAPIKeyRepositoryPersistsUTCExpiry(t *testing.T) { + t.Setenv("TZ", "Asia/Shanghai") + + db, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=shared"), &gorm.Config{}) + require.NoError(t, err) + require.NoError(t, db.AutoMigrate(&types.TenantAPIKey{})) + + repo := NewTenantAPIKeyRepository(db) + ctx := context.Background() + + expiresAt := time.Unix(time.Now().UTC().Add(5*time.Second).Unix(), 0).UTC() + tenantID := uint64(42) + key := &types.TenantAPIKey{ + TenantID: &tenantID, + ScopeType: types.APIKeyScopeTenant, + Name: "integration", + KeyHash: "hash-expiry", + APIKey: "sk-test", + FullAccess: true, + ExpiresAt: &expiresAt, + } + require.NoError(t, repo.CreateAPIKey(ctx, key)) + + loaded, err := repo.GetAPIKeyByHash(ctx, key.KeyHash) + require.NoError(t, err) + require.NotNil(t, loaded.ExpiresAt) + require.Equal(t, time.UTC, loaded.ExpiresAt.Location()) + require.True(t, loaded.ExpiresAt.Equal(expiresAt)) +} diff --git a/internal/application/service/resource.go b/internal/application/service/resource.go index a837d70a..0a343300 100644 --- a/internal/application/service/resource.go +++ b/internal/application/service/resource.go @@ -169,7 +169,7 @@ func (s *resourceCatalog) CreateAccessGrant(ctx context.Context, reference strin } // Opportunistic cleanup keeps high-volume IM rendering from accumulating // expired capability rows; failure is non-fatal to the current grant. - _ = s.repo.DeleteExpiredGrants(ctx, time.Now()) + _ = s.repo.DeleteExpiredGrants(ctx, time.Now().UTC()) for attempt := 0; attempt < 4; attempt++ { token, tokenErr := randomResourceToken() if tokenErr != nil { @@ -179,7 +179,7 @@ func (s *resourceCatalog) CreateAccessGrant(ctx context.Context, reference strin TokenHash: resourceLocationHash(token), ResourceID: resource.ID, AccessScope: "read", - ExpiresAt: time.Now().Add(ttl), + ExpiresAt: time.Now().UTC().Add(ttl), } if err := s.repo.CreateGrant(ctx, grant); err == nil { return token, nil @@ -191,7 +191,7 @@ func (s *resourceCatalog) CreateAccessGrant(ctx context.Context, reference strin } func (s *resourceCatalog) ResolveAccessGrant(ctx context.Context, token string) (*types.StoredResource, error) { - grant, err := s.repo.GetValidGrant(ctx, resourceLocationHash(strings.TrimSpace(token)), time.Now()) + grant, err := s.repo.GetValidGrant(ctx, resourceLocationHash(strings.TrimSpace(token)), time.Now().UTC()) if err != nil { return nil, err } diff --git a/internal/application/service/tenant_api_key.go b/internal/application/service/tenant_api_key.go index e0eabdaf..f6a187e6 100644 --- a/internal/application/service/tenant_api_key.go +++ b/internal/application/service/tenant_api_key.go @@ -53,6 +53,11 @@ func (s *tenantAPIKeyService) CreateAPIKey( if err != nil { return nil, err } + expiresAt := req.ExpiresAt + if expiresAt != nil { + utc := expiresAt.UTC() + expiresAt = &utc + } var tenantID *uint64 if scopeType == types.APIKeyScopeTenant { tenantID = &req.TenantID @@ -66,7 +71,7 @@ func (s *tenantAPIKeyService) CreateAPIKey( FullAccess: req.FullAccess, KnowledgeBaseIDs: normalizeAPIKeyIDs(req.KnowledgeBaseIDs), Capabilities: capabilities, - ExpiresAt: req.ExpiresAt, + ExpiresAt: expiresAt, } if key.FullAccess { key.KnowledgeBaseIDs = nil @@ -90,7 +95,7 @@ func (s *tenantAPIKeyService) AuthenticateAPIKey(ctx context.Context, token stri if key.RevokedAt != nil { return nil, apprepo.ErrTenantAPIKeyNotFound } - if key.ExpiresAt != nil && time.Now().After(*key.ExpiresAt) { + if key.ExpiresAt != nil && time.Now().UTC().After(key.ExpiresAt.UTC()) { return nil, apprepo.ErrTenantAPIKeyNotFound } s.touchAPIKeyLastUsedAsync(key.ID) @@ -101,7 +106,7 @@ func (s *tenantAPIKeyService) AuthenticateAPIKey(ctx context.Context, token stri // apiKeyLastUsedMinInterval. The write runs in a detached goroutine so auth // latency is not tied to an UPDATE on the hot path. func (s *tenantAPIKeyService) touchAPIKeyLastUsedAsync(keyID uint64) { - now := time.Now() + now := time.Now().UTC() if v, ok := s.lastUsedTouch.Load(keyID); ok { if now.Sub(v.(time.Time)) < apiKeyLastUsedMinInterval { return diff --git a/internal/application/service/tenant_api_key_test.go b/internal/application/service/tenant_api_key_test.go index 9c77c5f1..7c192f77 100644 --- a/internal/application/service/tenant_api_key_test.go +++ b/internal/application/service/tenant_api_key_test.go @@ -260,3 +260,22 @@ func TestTenantAPIKeyServiceAuthenticateThrottlesLastUsedUpdates(t *testing.T) { t.Fatalf("last_used update count = %d, want 1 (throttled async write)", repo.lastUsedUpdateCount) } } + +func TestTenantAPIKeyServiceAuthenticateRejectsExpiredKey(t *testing.T) { + ctx := context.Background() + repo := newFakeTenantAPIKeyRepo() + svc := NewTenantAPIKeyService(repo) + + expired := time.Now().UTC().Add(-time.Minute) + created, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{ + TenantID: 42, + Name: "short-lived", + ExpiresAt: &expired, + }) + if err != nil { + t.Fatalf("CreateAPIKey returned error: %v", err) + } + if _, err := svc.AuthenticateAPIKey(ctx, created.Token); err == nil { + t.Fatal("expired key should not authenticate") + } +} diff --git a/internal/handler/system.go b/internal/handler/system.go index b3ab7717..eb0fee64 100644 --- a/internal/handler/system.go +++ b/internal/handler/system.go @@ -150,8 +150,8 @@ func (h *SystemHandler) CreatePlatformAPIKey(c *gin.Context) { } var expiresAt *time.Time if req.ExpiresAt != nil { - value := time.Unix(*req.ExpiresAt, 0) - if !value.After(time.Now()) { + value := time.Unix(*req.ExpiresAt, 0).UTC() + if !value.After(time.Now().UTC()) { c.Error(apperrors.NewValidationError("expires_at_unix must be in the future")) return } diff --git a/internal/handler/tenant.go b/internal/handler/tenant.go index bae6d4f8..c5a56964 100644 --- a/internal/handler/tenant.go +++ b/internal/handler/tenant.go @@ -685,8 +685,8 @@ func (h *TenantHandler) CreateAPIKey(c *gin.Context) { } var expiresAt *time.Time if req.ExpiresAt != nil { - t := time.Unix(*req.ExpiresAt, 0) - if !t.After(time.Now()) { + t := time.Unix(*req.ExpiresAt, 0).UTC() + if !t.After(time.Now().UTC()) { c.Error(errors.NewValidationError("expires_at_unix must be in the future")) return } diff --git a/migrations/versioned/000072_auth_timestamp_tz.down.sql b/migrations/versioned/000072_auth_timestamp_tz.down.sql new file mode 100644 index 00000000..07c79775 --- /dev/null +++ b/migrations/versioned/000072_auth_timestamp_tz.down.sql @@ -0,0 +1,35 @@ +DO $$ BEGIN RAISE NOTICE '[Migration 000072 down] Reverting authorization timestamps to timestamp...'; END $$; + +ALTER TABLE tenant_api_keys + ALTER COLUMN last_used_at TYPE TIMESTAMP WITHOUT TIME ZONE + USING last_used_at AT TIME ZONE 'UTC'; + +ALTER TABLE tenant_api_keys + ALTER COLUMN expires_at TYPE TIMESTAMP WITHOUT TIME ZONE + USING expires_at AT TIME ZONE 'UTC'; + +ALTER TABLE tenant_api_keys + ALTER COLUMN revoked_at TYPE TIMESTAMP WITHOUT TIME ZONE + USING revoked_at AT TIME ZONE 'UTC'; + +ALTER TABLE tenant_api_keys + ALTER COLUMN created_at TYPE TIMESTAMP WITHOUT TIME ZONE + USING created_at AT TIME ZONE 'UTC'; + +ALTER TABLE tenant_api_keys + ALTER COLUMN updated_at TYPE TIMESTAMP WITHOUT TIME ZONE + USING updated_at AT TIME ZONE 'UTC'; + +ALTER TABLE resource_access_grants + ALTER COLUMN expires_at TYPE TIMESTAMP WITHOUT TIME ZONE + USING expires_at AT TIME ZONE 'UTC'; + +ALTER TABLE resource_access_grants + ALTER COLUMN revoked_at TYPE TIMESTAMP WITHOUT TIME ZONE + USING revoked_at AT TIME ZONE 'UTC'; + +ALTER TABLE resource_access_grants + ALTER COLUMN created_at TYPE TIMESTAMP WITHOUT TIME ZONE + USING created_at AT TIME ZONE 'UTC'; + +DO $$ BEGIN RAISE NOTICE '[Migration 000072 down] Authorization timestamps reverted'; END $$; diff --git a/migrations/versioned/000072_auth_timestamp_tz.up.sql b/migrations/versioned/000072_auth_timestamp_tz.up.sql new file mode 100644 index 00000000..40997840 --- /dev/null +++ b/migrations/versioned/000072_auth_timestamp_tz.up.sql @@ -0,0 +1,37 @@ +DO $$ BEGIN RAISE NOTICE '[Migration 000072] Converting authorization timestamps to timestamptz...'; END $$; + +-- Naive TIMESTAMP values were read through a GORM session with TimeZone=UTC. +-- Treat existing literals as UTC when promoting to timestamptz. +ALTER TABLE tenant_api_keys + ALTER COLUMN last_used_at TYPE TIMESTAMP WITH TIME ZONE + USING last_used_at AT TIME ZONE 'UTC'; + +ALTER TABLE tenant_api_keys + ALTER COLUMN expires_at TYPE TIMESTAMP WITH TIME ZONE + USING expires_at AT TIME ZONE 'UTC'; + +ALTER TABLE tenant_api_keys + ALTER COLUMN revoked_at TYPE TIMESTAMP WITH TIME ZONE + USING revoked_at AT TIME ZONE 'UTC'; + +ALTER TABLE tenant_api_keys + ALTER COLUMN created_at TYPE TIMESTAMP WITH TIME ZONE + USING created_at AT TIME ZONE 'UTC'; + +ALTER TABLE tenant_api_keys + ALTER COLUMN updated_at TYPE TIMESTAMP WITH TIME ZONE + USING updated_at AT TIME ZONE 'UTC'; + +ALTER TABLE resource_access_grants + ALTER COLUMN expires_at TYPE TIMESTAMP WITH TIME ZONE + USING expires_at AT TIME ZONE 'UTC'; + +ALTER TABLE resource_access_grants + ALTER COLUMN revoked_at TYPE TIMESTAMP WITH TIME ZONE + USING revoked_at AT TIME ZONE 'UTC'; + +ALTER TABLE resource_access_grants + ALTER COLUMN created_at TYPE TIMESTAMP WITH TIME ZONE + USING created_at AT TIME ZONE 'UTC'; + +DO $$ BEGIN RAISE NOTICE '[Migration 000072] Authorization timestamps ready'; END $$;