Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix: normalize API key expiry timestamps to UTC (#2137)

wizardchen0f2c6cee11a1
diff --git a/internal/application/repository/tenant_api_key.go b/internal/application/repository/tenant_api_key.go
index 61ab02295..1daff605a 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 000000000..c7a3a0cfe
--- /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 a837d70a6..0a3433006 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 e0eabdaf6..f6a187e6e 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 9c77c5f15..7c192f77e 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 b3ab7717e..eb0fee642 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 bae6d4f8e..c5a569645 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 000000000..07c797759
--- /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 000000000..40997840d
--- /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 $$;