refactor(api-keys): use role field and route-level API key guards

Replace scopes JSON with a viewer/contributor/admin role column, move
unsafe-method authorization from path-prefix middleware to declarative
APIKey* guards on routes, and close remaining KB-scope gaps in handlers.
This commit is contained in:
wizardchen
2026-07-06 13:23:55 +08:00
committed by lyingbug
parent 3ace6e657f
commit 9a76a24ce6
28 changed files with 678 additions and 438 deletions
+3 -22
View File
@@ -43,12 +43,12 @@ func (s *tenantAPIKeyService) CreateAPIKey(
Name: name,
KeyHash: hashTenantAPIKey(token),
APIKey: token,
Scopes: normalizeAPIKeyScopes(req.Scopes),
Role: types.NormalizeTenantAPIKeyRole(req.Role),
KnowledgeBaseIDs: normalizeAPIKeyIDs(req.KnowledgeBaseIDs),
ExpiresAt: req.ExpiresAt,
}
if len(key.Scopes) == 0 {
key.Scopes = types.StringArray{types.TenantAPIKeyScopeRead}
if key.Role == "" {
key.Role = types.TenantRoleViewer
}
if err := s.repo.CreateAPIKey(ctx, key); err != nil {
return nil, err
@@ -162,25 +162,6 @@ func (s *tenantAPIKeyService) ensureAPIKeyHash(ctx context.Context, key *types.T
return nil
}
func normalizeAPIKeyScopes(in []string) types.StringArray {
out := types.StringArray{}
seen := map[string]struct{}{}
for _, scope := range in {
scope = strings.ToLower(strings.TrimSpace(scope))
switch scope {
case types.TenantAPIKeyScopeRead, types.TenantAPIKeyScopeWrite, types.TenantAPIKeyScopeAdmin:
default:
continue
}
if _, ok := seen[scope]; ok {
continue
}
seen[scope] = struct{}{}
out = append(out, scope)
}
return out
}
func normalizeAPIKeyIDs(in []string) types.StringArray {
out := types.StringArray{}
seen := map[string]struct{}{}