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
+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")
}
}