fix(api-keys): harden scoped key auth after code review

Revoke existing keys on reset, unify scope enforcement, default empty
scopes to read-only, map API key scopes to tenant roles, and remove dead
key-generation helpers left over from the tenant api_key column removal.
This commit is contained in:
wizardchen
2026-07-05 10:40:49 +08:00
committed by lyingbug
parent 505bc7ddec
commit 3f516d7f31
17 changed files with 231 additions and 203 deletions
+7 -25
View File
@@ -110,31 +110,6 @@ func (s *tenantAPIKeyService) AuthenticateTenantAPIKey(
return nil, apprepo.ErrTenantAPIKeyNotFound
}
func (s *tenantAPIKeyService) EnsureTenantAPIKey(ctx context.Context, tenantID uint64, apiKey string) error {
if tenantID == 0 || strings.TrimSpace(apiKey) == "" {
return nil
}
token := strings.TrimSpace(apiKey)
hash := hashTenantAPIKey(token)
if existing, err := s.repo.GetAPIKeyByHash(ctx, hash); err == nil && existing != nil {
return nil
} else if err != nil && !errors.Is(err, apprepo.ErrTenantAPIKeyNotFound) {
return err
}
key := &types.TenantAPIKey{
TenantID: tenantID,
Name: "Tenant API key",
KeyHash: hash,
APIKey: token,
Scopes: types.StringArray{
types.TenantAPIKeyScopeRead,
types.TenantAPIKeyScopeWrite,
types.TenantAPIKeyScopeAdmin,
},
}
return s.repo.CreateAPIKey(ctx, key)
}
func (s *tenantAPIKeyService) ListAPIKeys(ctx context.Context, tenantID uint64) ([]*types.TenantAPIKey, error) {
keys, err := s.repo.ListAPIKeys(ctx, tenantID)
if err != nil {
@@ -152,6 +127,13 @@ func (s *tenantAPIKeyService) RevokeAPIKey(ctx context.Context, tenantID uint64,
return s.repo.RevokeAPIKey(ctx, tenantID, id)
}
func (s *tenantAPIKeyService) RevokeAllAPIKeys(ctx context.Context, tenantID uint64) error {
if tenantID == 0 {
return nil
}
return s.repo.RevokeAllAPIKeys(ctx, tenantID)
}
func generateTenantAPIKeyToken() (string, error) {
var b [32]byte
if _, err := rand.Read(b[:]); err != nil {