feat(api-keys): add platform-scoped API keys for control-plane automation

Introduce platform API keys with capability-based access to tenant management,
system settings, runtime queues, and audit logs, plus admin UI for key lifecycle
and system audit log viewing.
This commit is contained in:
wizardchen
2026-07-21 15:05:57 +08:00
committed by lyingbug
parent c695125dce
commit 23db592c4a
42 changed files with 2967 additions and 1083 deletions
@@ -47,6 +47,15 @@ func (r *tenantAPIKeyRepository) ListAPIKeys(ctx context.Context, tenantID uint6
return keys, err
}
func (r *tenantAPIKeyRepository) ListPlatformAPIKeys(ctx context.Context) ([]*types.TenantAPIKey, error) {
var keys []*types.TenantAPIKey
err := r.db.WithContext(ctx).
Where("scope_type = ? AND revoked_at IS NULL", types.APIKeyScopePlatform).
Order("created_at DESC").
Find(&keys).Error
return keys, err
}
func (r *tenantAPIKeyRepository) RevokeAPIKey(ctx context.Context, tenantID uint64, id uint64) error {
now := time.Now()
res := r.db.WithContext(ctx).
@@ -62,6 +71,21 @@ func (r *tenantAPIKeyRepository) RevokeAPIKey(ctx context.Context, tenantID uint
return nil
}
func (r *tenantAPIKeyRepository) RevokePlatformAPIKey(ctx context.Context, id uint64) error {
now := time.Now()
res := r.db.WithContext(ctx).
Model(&types.TenantAPIKey{}).
Where("id = ? AND scope_type = ? AND revoked_at IS NULL", id, types.APIKeyScopePlatform).
Update("revoked_at", &now)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return ErrTenantAPIKeyNotFound
}
return nil
}
func (r *tenantAPIKeyRepository) UpdateAPIKeyHash(ctx context.Context, id uint64, hash string) error {
return r.db.WithContext(ctx).
Model(&types.TenantAPIKey{}).
+24 -3
View File
@@ -34,9 +34,17 @@ func NewTenantAPIKeyService(repo interfaces.TenantAPIKeyRepository) interfaces.T
func (s *tenantAPIKeyService) CreateAPIKey(
ctx context.Context, req interfaces.TenantAPIKeyCreateRequest,
) (*interfaces.TenantAPIKeyCreateResult, error) {
if req.TenantID == 0 {
scopeType := types.NormalizeAPIKeyScopeType(req.ScopeType)
if scopeType == types.APIKeyScopeTenant && req.TenantID == 0 {
return nil, errors.New("tenant_id is required")
}
if scopeType == types.APIKeyScopePlatform && req.FullAccess {
return nil, errors.New("platform API keys require explicit capabilities")
}
capabilities := types.NormalizeAPIKeyCapabilities(types.StringArray(req.Capabilities))
if scopeType == types.APIKeyScopePlatform && len(capabilities) == 0 {
return nil, errors.New("platform API keys require at least one capability")
}
name := strings.TrimSpace(req.Name)
if name == "" {
return nil, errors.New("name is required")
@@ -45,14 +53,19 @@ func (s *tenantAPIKeyService) CreateAPIKey(
if err != nil {
return nil, err
}
var tenantID *uint64
if scopeType == types.APIKeyScopeTenant {
tenantID = &req.TenantID
}
key := &types.TenantAPIKey{
TenantID: req.TenantID,
TenantID: tenantID,
ScopeType: scopeType,
Name: name,
KeyHash: hashTenantAPIKey(token),
APIKey: token,
FullAccess: req.FullAccess,
KnowledgeBaseIDs: normalizeAPIKeyIDs(req.KnowledgeBaseIDs),
Capabilities: types.NormalizeAPIKeyCapabilities(types.StringArray(req.Capabilities)),
Capabilities: capabilities,
ExpiresAt: req.ExpiresAt,
}
if key.FullAccess {
@@ -108,10 +121,18 @@ func (s *tenantAPIKeyService) ListAPIKeys(ctx context.Context, tenantID uint64)
return s.repo.ListAPIKeys(ctx, tenantID)
}
func (s *tenantAPIKeyService) ListPlatformAPIKeys(ctx context.Context) ([]*types.TenantAPIKey, error) {
return s.repo.ListPlatformAPIKeys(ctx)
}
func (s *tenantAPIKeyService) RevokeAPIKey(ctx context.Context, tenantID uint64, id uint64) error {
return s.repo.RevokeAPIKey(ctx, tenantID, id)
}
func (s *tenantAPIKeyService) RevokePlatformAPIKey(ctx context.Context, id uint64) error {
return s.repo.RevokePlatformAPIKey(ctx, id)
}
func (s *tenantAPIKeyService) BackfillMissingKeyHashes(ctx context.Context) (int, error) {
has, err := s.repo.HasKeysWithPlaceholderHash(ctx)
if err != nil {
@@ -66,7 +66,18 @@ func (r *fakeTenantAPIKeyRepo) GetAPIKeyByHash(_ context.Context, hash string) (
func (r *fakeTenantAPIKeyRepo) ListAPIKeys(_ context.Context, tenantID uint64) ([]*types.TenantAPIKey, error) {
out := []*types.TenantAPIKey{}
for _, key := range r.byHash {
if key.TenantID == tenantID && key.RevokedAt == nil {
if key.TenantIDValue() == tenantID && key.RevokedAt == nil {
cp := *key
out = append(out, &cp)
}
}
return out, nil
}
func (r *fakeTenantAPIKeyRepo) ListPlatformAPIKeys(_ context.Context) ([]*types.TenantAPIKey, error) {
out := []*types.TenantAPIKey{}
for _, key := range r.byHash {
if key.IsPlatform() && key.RevokedAt == nil {
cp := *key
out = append(out, &cp)
}
@@ -77,7 +88,18 @@ func (r *fakeTenantAPIKeyRepo) ListAPIKeys(_ context.Context, tenantID uint64) (
func (r *fakeTenantAPIKeyRepo) RevokeAPIKey(_ context.Context, tenantID uint64, id uint64) error {
now := time.Now()
for _, key := range r.byHash {
if key.ID == id && key.TenantID == tenantID && key.RevokedAt == nil {
if key.ID == id && key.TenantIDValue() == tenantID && key.RevokedAt == nil {
key.RevokedAt = &now
return nil
}
}
return apprepo.ErrTenantAPIKeyNotFound
}
func (r *fakeTenantAPIKeyRepo) RevokePlatformAPIKey(_ context.Context, id uint64) error {
now := time.Now()
for _, key := range r.byHash {
if key.ID == id && key.IsPlatform() && key.RevokedAt == nil {
key.RevokedAt = &now
return nil
}
@@ -134,7 +156,7 @@ func TestTenantAPIKeyServiceBackfillMissingKeyHashes(t *testing.T) {
token := "sk-legacy-token-value"
legacy := &types.TenantAPIKey{
TenantID: 7,
TenantID: uint64Pointer(7),
Name: "legacy",
KeyHash: "migrated-tenant-7",
APIKey: token,
@@ -159,6 +181,38 @@ func TestTenantAPIKeyServiceBackfillMissingKeyHashes(t *testing.T) {
}
}
func uint64Pointer(value uint64) *uint64 { return &value }
func TestTenantAPIKeyServiceCreatesPlatformKeyWithoutTenant(t *testing.T) {
repo := newFakeTenantAPIKeyRepo()
svc := NewTenantAPIKeyService(repo)
created, err := svc.CreateAPIKey(context.Background(), interfaces.TenantAPIKeyCreateRequest{
ScopeType: types.APIKeyScopePlatform,
Name: "automation",
Capabilities: []string{string(types.APIKeyCapabilityRetrieve)},
})
if err != nil {
t.Fatalf("CreateAPIKey returned error: %v", err)
}
if !created.APIKey.IsPlatform() || created.APIKey.TenantID != nil {
t.Fatalf("created key scope = %q tenant=%v, want platform with nil tenant", created.APIKey.ScopeType, created.APIKey.TenantID)
}
if created.APIKey.FullAccess {
t.Fatal("platform API key must not be full-access")
}
}
func TestTenantAPIKeyServiceRejectsFullAccessPlatformKey(t *testing.T) {
svc := NewTenantAPIKeyService(newFakeTenantAPIKeyRepo())
_, err := svc.CreateAPIKey(context.Background(), interfaces.TenantAPIKeyCreateRequest{
ScopeType: types.APIKeyScopePlatform,
Name: "unsafe", FullAccess: true,
})
if err == nil {
t.Fatal("full-access platform key should be rejected")
}
}
func TestTenantAPIKeyServiceRevokeAPIKey(t *testing.T) {
ctx := context.Background()
repo := newFakeTenantAPIKeyRepo()