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
+2
View File
@@ -121,6 +121,8 @@ const (
// another user's local password. Details identify the target and record
// session revocation, but never contain the old or new password.
AuditActionSystemUserPasswordReset AuditAction = "system.user_password_reset"
AuditActionSystemAPIKeyCreated AuditAction = "system.api_key_created"
AuditActionSystemAPIKeyRevoked AuditAction = "system.api_key_revoked"
// Runtime queue mutations are privileged SystemAdmin actions. Retrying an
// archived task can repeat its original side effects; deleting one removes
+5
View File
@@ -64,6 +64,7 @@ type TenantRepository interface {
type TenantAPIKeyCreateRequest struct {
TenantID uint64
ScopeType types.APIKeyScopeType
Name string
FullAccess bool
KnowledgeBaseIDs []string
@@ -80,7 +81,9 @@ type TenantAPIKeyRepository interface {
CreateAPIKey(ctx context.Context, key *types.TenantAPIKey) error
GetAPIKeyByHash(ctx context.Context, hash string) (*types.TenantAPIKey, error)
ListAPIKeys(ctx context.Context, tenantID uint64) ([]*types.TenantAPIKey, error)
ListPlatformAPIKeys(ctx context.Context) ([]*types.TenantAPIKey, error)
RevokeAPIKey(ctx context.Context, tenantID uint64, id uint64) error
RevokePlatformAPIKey(ctx context.Context, id uint64) error
UpdateAPIKeyHash(ctx context.Context, id uint64, hash string) error
UpdateAPIKeyLastUsed(ctx context.Context, id uint64, at time.Time) error
// ListKeysWithPlaceholderHash returns keys whose key_hash is still the
@@ -96,7 +99,9 @@ type TenantAPIKeyService interface {
CreateAPIKey(ctx context.Context, req TenantAPIKeyCreateRequest) (*TenantAPIKeyCreateResult, error)
AuthenticateAPIKey(ctx context.Context, token string) (*types.TenantAPIKey, error)
ListAPIKeys(ctx context.Context, tenantID uint64) ([]*types.TenantAPIKey, error)
ListPlatformAPIKeys(ctx context.Context) ([]*types.TenantAPIKey, error)
RevokeAPIKey(ctx context.Context, tenantID uint64, id uint64) error
RevokePlatformAPIKey(ctx context.Context, id uint64) error
// BackfillMissingKeyHashes computes and persists the SHA-256 key_hash
// for legacy keys still carrying the migration placeholder.
// Returns the number of keys backfilled.
+1
View File
@@ -9,6 +9,7 @@ import (
const (
PrincipalWebUser = "web_user"
PrincipalAPITenant = "api_tenant"
PrincipalAPIPlatform = "api_platform"
PrincipalAPIExternalUser = "api_external_user"
PrincipalIMUser = "im_user"
PrincipalEmbedChannel = "embed_channel"
+66 -10
View File
@@ -11,17 +11,19 @@ import (
"gorm.io/gorm"
)
// TenantAPIKey is a revocable, per-tenant API key. KeyHash is used for
// authentication lookup; APIKey is stored encrypted when SYSTEM_AES_KEY is set
// and returned by owner-only management APIs.
// TenantAPIKey is a revocable machine credential. Tenant-scoped and platform
// keys intentionally share one table; platform keys have tenant_id=NULL and
// choose a target workspace per request. KeyHash is used for authentication
// lookup; APIKey is stored encrypted when SYSTEM_AES_KEY is set.
type TenantAPIKey struct {
ID uint64 `json:"id" gorm:"primaryKey;autoIncrement"`
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
Name string `json:"name" gorm:"type:varchar(128);not null"`
KeyHash string `json:"-" gorm:"type:varchar(64);not null;uniqueIndex"`
APIKey string `json:"api_key" gorm:"column:api_key;type:text;not null;default:''"`
FullAccess bool `json:"full_access" gorm:"not null;default:false"`
KnowledgeBaseIDs StringArray `json:"knowledge_base_ids" gorm:"type:jsonb;not null;default:'[]'"`
ID uint64 `json:"id" gorm:"primaryKey;autoIncrement"`
TenantID *uint64 `json:"tenant_id,omitempty" gorm:"index"`
ScopeType APIKeyScopeType `json:"scope_type" gorm:"type:varchar(16);not null;default:tenant;index"`
Name string `json:"name" gorm:"type:varchar(128);not null"`
KeyHash string `json:"-" gorm:"type:varchar(64);not null;uniqueIndex"`
APIKey string `json:"api_key" gorm:"column:api_key;type:text;not null;default:''"`
FullAccess bool `json:"full_access" gorm:"not null;default:false"`
KnowledgeBaseIDs StringArray `json:"knowledge_base_ids" gorm:"type:jsonb;not null;default:'[]'"`
// Capabilities are bounded grants for non-full-access keys. Each
// capability maps to an integration persona (retrieval, chat, ingest,
// tenant infrastructure management, and history access). KB scoping
@@ -35,6 +37,33 @@ type TenantAPIKey struct {
UpdatedAt time.Time `json:"updated_at"`
}
type APIKeyScopeType string
const (
APIKeyScopeTenant APIKeyScopeType = "tenant"
APIKeyScopePlatform APIKeyScopeType = "platform"
)
func NormalizeAPIKeyScopeType(scope APIKeyScopeType) APIKeyScopeType {
switch APIKeyScopeType(strings.ToLower(strings.TrimSpace(string(scope)))) {
case APIKeyScopePlatform:
return APIKeyScopePlatform
default:
return APIKeyScopeTenant
}
}
func (k *TenantAPIKey) IsPlatform() bool {
return k != nil && NormalizeAPIKeyScopeType(k.ScopeType) == APIKeyScopePlatform
}
func (k *TenantAPIKey) TenantIDValue() uint64 {
if k == nil || k.TenantID == nil {
return 0
}
return *k.TenantID
}
func (TenantAPIKey) TableName() string {
return "tenant_api_keys"
}
@@ -126,6 +155,13 @@ const (
// principal mode, request headers, and tenant KV. It does not include API
// key management, member management, tenant deletion, or ownership transfer.
APIKeyCapabilityManageTenantSettings APIKeyCapability = "manage_tenant_settings"
APIKeyCapabilitySystemTenantsRead APIKeyCapability = "system_tenants_read"
APIKeyCapabilitySystemTenantsManage APIKeyCapability = "system_tenants_manage"
APIKeyCapabilitySystemSettingsRead APIKeyCapability = "system_settings_read"
APIKeyCapabilitySystemSettingsManage APIKeyCapability = "system_settings_manage"
APIKeyCapabilitySystemRuntimeRead APIKeyCapability = "system_runtime_read"
APIKeyCapabilitySystemRuntimeManage APIKeyCapability = "system_runtime_manage"
APIKeyCapabilitySystemAuditRead APIKeyCapability = "system_audit_read"
)
// NormalizeAPIKeyCapability maps an input capability string to a known
@@ -168,6 +204,20 @@ func NormalizeAPIKeyCapability(c APIKeyCapability) APIKeyCapability {
return APIKeyCapabilityManageSpaces
case APIKeyCapabilityManageTenantSettings:
return APIKeyCapabilityManageTenantSettings
case APIKeyCapabilitySystemTenantsRead:
return APIKeyCapabilitySystemTenantsRead
case APIKeyCapabilitySystemTenantsManage:
return APIKeyCapabilitySystemTenantsManage
case APIKeyCapabilitySystemSettingsRead:
return APIKeyCapabilitySystemSettingsRead
case APIKeyCapabilitySystemSettingsManage:
return APIKeyCapabilitySystemSettingsManage
case APIKeyCapabilitySystemRuntimeRead:
return APIKeyCapabilitySystemRuntimeRead
case APIKeyCapabilitySystemRuntimeManage:
return APIKeyCapabilitySystemRuntimeManage
case APIKeyCapabilitySystemAuditRead:
return APIKeyCapabilitySystemAuditRead
default:
return ""
}
@@ -218,6 +268,7 @@ func (k *TenantAPIKey) AfterFind(tx *gorm.DB) error {
// TenantAPIKeyScope is the request-context projection used by middleware.
type TenantAPIKeyScope struct {
KeyID uint64
ScopeType APIKeyScopeType
FullAccess bool
KnowledgeBaseIDs StringArray
Capabilities StringArray
@@ -241,12 +292,17 @@ func TenantAPIKeyScopeFromContext(ctx context.Context) (TenantAPIKeyScope, bool)
func (s TenantAPIKeyScope) Normalize() TenantAPIKeyScope {
return TenantAPIKeyScope{
KeyID: s.KeyID,
ScopeType: NormalizeAPIKeyScopeType(s.ScopeType),
FullAccess: s.FullAccess,
KnowledgeBaseIDs: normalizeIDArray(s.KnowledgeBaseIDs),
Capabilities: NormalizeAPIKeyCapabilities(s.Capabilities),
}
}
func (s TenantAPIKeyScope) IsPlatform() bool {
return NormalizeAPIKeyScopeType(s.ScopeType) == APIKeyScopePlatform
}
// HasCapability reports whether the scope carries the given additive grant.
func (s TenantAPIKeyScope) HasCapability(c APIKeyCapability) bool {
c = NormalizeAPIKeyCapability(c)