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:
@@ -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))
|
||||
}
|
||||
Reference in New Issue
Block a user