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.
This commit is contained in:
wizardchen
2026-07-21 18:24:16 +08:00
committed by lyingbug
parent 59fed12643
commit 0f2c6cee11
9 changed files with 150 additions and 12 deletions
@@ -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).
@@ -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))
}
+3 -3
View File
@@ -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
}
@@ -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
@@ -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")
}
}
+2 -2
View File
@@ -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
}
+2 -2
View File
@@ -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
}
@@ -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 $$;
@@ -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 $$;