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:
+142
-3
@@ -45,6 +45,7 @@ type SystemHandler struct {
|
||||
tenantSvc interfaces.TenantService
|
||||
userSvc interfaces.UserService
|
||||
systemSettingSvc interfaces.SystemSettingService
|
||||
apiKeySvc interfaces.TenantAPIKeyService
|
||||
// auditSvc is optional — when nil, emitAdminAudit no-ops so unit
|
||||
// tests that wire a partial container still compile. In production
|
||||
// the dig graph always provides one.
|
||||
@@ -72,6 +73,7 @@ func NewSystemHandler(cfg *config.Config,
|
||||
tenantSvc interfaces.TenantService,
|
||||
userSvc interfaces.UserService,
|
||||
systemSettingSvc interfaces.SystemSettingService,
|
||||
apiKeySvc interfaces.TenantAPIKeyService,
|
||||
auditSvc interfaces.AuditLogService,
|
||||
taskInspector interfaces.TaskInspector,
|
||||
knowledgeSvc interfaces.KnowledgeService,
|
||||
@@ -84,6 +86,7 @@ func NewSystemHandler(cfg *config.Config,
|
||||
tenantSvc: tenantSvc,
|
||||
userSvc: userSvc,
|
||||
systemSettingSvc: systemSettingSvc,
|
||||
apiKeySvc: apiKeySvc,
|
||||
auditSvc: auditSvc,
|
||||
taskInspector: taskInspector,
|
||||
knowledgeSvc: knowledgeSvc,
|
||||
@@ -91,6 +94,142 @@ func NewSystemHandler(cfg *config.Config,
|
||||
}
|
||||
}
|
||||
|
||||
type platformAPIKeyCreateRequest struct {
|
||||
Name string `json:"name"`
|
||||
Capabilities []string `json:"capabilities"`
|
||||
ExpiresAt *int64 `json:"expires_at_unix"`
|
||||
}
|
||||
|
||||
// ListPlatformAPIKeys godoc
|
||||
// @Summary List platform API keys
|
||||
// @Description Lists non-workspace API keys. Full tokens are always masked. Human SystemAdmin only.
|
||||
// @Tags System Admin
|
||||
// @Produce json
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Security Bearer
|
||||
// @Router /system/admin/api-keys [get]
|
||||
func (h *SystemHandler) ListPlatformAPIKeys(c *gin.Context) {
|
||||
keys, err := h.apiKeySvc.ListPlatformAPIKeys(c.Request.Context())
|
||||
if err != nil {
|
||||
c.Error(apperrors.NewInternalServerError("Failed to list platform API keys").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
response := make([]tenantAPIKeyResponse, 0, len(keys))
|
||||
for _, key := range keys {
|
||||
item := tenantAPIKeyForResponse(key)
|
||||
item.APIKey = maskManagedAPIKey(key.APIKey)
|
||||
response = append(response, item)
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": response})
|
||||
}
|
||||
|
||||
// CreatePlatformAPIKey godoc
|
||||
// @Summary Create a platform API key
|
||||
// @Description Creates a capability-scoped key that may target any workspace through X-Tenant-ID. The plaintext token is returned once. Human SystemAdmin only.
|
||||
// @Tags System Admin
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body platformAPIKeyCreateRequest true "Platform API key"
|
||||
// @Success 201 {object} map[string]interface{}
|
||||
// @Security Bearer
|
||||
// @Router /system/admin/api-keys [post]
|
||||
func (h *SystemHandler) CreatePlatformAPIKey(c *gin.Context) {
|
||||
var req platformAPIKeyCreateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.Error(apperrors.NewValidationError("Invalid request data").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(req.Name) == "" {
|
||||
c.Error(apperrors.NewValidationError("name is required"))
|
||||
return
|
||||
}
|
||||
capabilities := types.NormalizeAPIKeyCapabilities(types.StringArray(req.Capabilities))
|
||||
if len(capabilities) == 0 || len(capabilities) != len(req.Capabilities) {
|
||||
c.Error(apperrors.NewValidationError("valid capabilities are required"))
|
||||
return
|
||||
}
|
||||
var expiresAt *time.Time
|
||||
if req.ExpiresAt != nil {
|
||||
value := time.Unix(*req.ExpiresAt, 0)
|
||||
if !value.After(time.Now()) {
|
||||
c.Error(apperrors.NewValidationError("expires_at_unix must be in the future"))
|
||||
return
|
||||
}
|
||||
expiresAt = &value
|
||||
}
|
||||
result, err := h.apiKeySvc.CreateAPIKey(c.Request.Context(), interfaces.TenantAPIKeyCreateRequest{
|
||||
ScopeType: types.APIKeyScopePlatform,
|
||||
Name: req.Name,
|
||||
Capabilities: []string(capabilities),
|
||||
ExpiresAt: expiresAt,
|
||||
})
|
||||
if err != nil {
|
||||
c.Error(apperrors.NewInternalServerError("Failed to create platform API key").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
item := tenantAPIKeyForResponse(result.APIKey)
|
||||
item.APIKey = maskManagedAPIKey(result.Token)
|
||||
h.emitAPIKeyAudit(c.Request.Context(), types.AuditActionSystemAPIKeyCreated, result.APIKey)
|
||||
c.JSON(http.StatusCreated, gin.H{
|
||||
"success": true,
|
||||
"data": tenantAPIKeyCreateResponse{tenantAPIKeyResponse: item, Token: result.Token},
|
||||
})
|
||||
}
|
||||
|
||||
// DeletePlatformAPIKey godoc
|
||||
// @Summary Revoke a platform API key
|
||||
// @Description Immediately revokes a platform API key. Human SystemAdmin only.
|
||||
// @Tags System Admin
|
||||
// @Produce json
|
||||
// @Param key_id path int true "API key ID"
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Security Bearer
|
||||
// @Router /system/admin/api-keys/{key_id} [delete]
|
||||
func (h *SystemHandler) DeletePlatformAPIKey(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("key_id"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
c.Error(apperrors.NewBadRequestError("Invalid API key ID"))
|
||||
return
|
||||
}
|
||||
if err := h.apiKeySvc.RevokePlatformAPIKey(c.Request.Context(), id); err != nil {
|
||||
c.Error(apperrors.NewNotFoundError("Platform API key not found"))
|
||||
return
|
||||
}
|
||||
h.emitAPIKeyAudit(c.Request.Context(), types.AuditActionSystemAPIKeyRevoked, &types.TenantAPIKey{ID: id})
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
}
|
||||
|
||||
func maskManagedAPIKey(token string) string {
|
||||
token = strings.TrimSpace(token)
|
||||
if len(token) <= 12 {
|
||||
return "***"
|
||||
}
|
||||
return token[:7] + "..." + token[len(token)-4:]
|
||||
}
|
||||
|
||||
func (h *SystemHandler) emitAPIKeyAudit(ctx context.Context, action types.AuditAction, key *types.TenantAPIKey) {
|
||||
if h.auditSvc == nil || key == nil {
|
||||
return
|
||||
}
|
||||
actorID, _ := types.UserIDFromContext(ctx)
|
||||
details, _ := json.Marshal(map[string]any{
|
||||
"scope_type": types.APIKeyScopePlatform,
|
||||
"capabilities": key.Capabilities,
|
||||
})
|
||||
_ = h.auditSvc.Log(ctx, &types.AuditLog{
|
||||
TenantID: 0, ActorUserID: actorID, ActorRole: systemAuditActorRole(ctx),
|
||||
Action: action, TargetType: "api_key", TargetID: strconv.FormatUint(key.ID, 10),
|
||||
Outcome: types.AuditOutcomeSuccess, Details: types.JSON(details),
|
||||
})
|
||||
}
|
||||
|
||||
func systemAuditActorRole(ctx context.Context) string {
|
||||
if scope, ok := types.TenantAPIKeyScopeFromContext(ctx); ok && scope.IsPlatform() {
|
||||
return "platform_api_key"
|
||||
}
|
||||
return "system_admin"
|
||||
}
|
||||
|
||||
// emitAdminAudit writes one audit row for a system-admin lifecycle event
|
||||
// (promote / revoke). Best-effort — a nil audit service or a write
|
||||
// failure does not bubble up to the caller. Mirrors the failure
|
||||
@@ -120,7 +259,7 @@ func (h *SystemHandler) emitAdminAudit(
|
||||
// events (matches AuditActionSystemSettingChanged).
|
||||
TenantID: 0,
|
||||
ActorUserID: actorID,
|
||||
ActorRole: "system_admin",
|
||||
ActorRole: systemAuditActorRole(ctx),
|
||||
Action: action,
|
||||
TargetType: "user",
|
||||
Outcome: types.AuditOutcomeSuccess,
|
||||
@@ -1773,7 +1912,7 @@ func (h *SystemHandler) emitQueueTaskAudit(
|
||||
_ = h.auditSvc.Log(ctx, &types.AuditLog{
|
||||
TenantID: 0,
|
||||
ActorUserID: actorID,
|
||||
ActorRole: "system_admin",
|
||||
ActorRole: systemAuditActorRole(ctx),
|
||||
Action: action,
|
||||
TargetType: targetType,
|
||||
TargetID: targetID,
|
||||
@@ -2122,7 +2261,7 @@ func (h *SystemHandler) ApplyDefaultStorageQuotaToAllTenants(c *gin.Context) {
|
||||
_ = h.auditSvc.Log(ctx, &types.AuditLog{
|
||||
TenantID: 0,
|
||||
ActorUserID: actorID,
|
||||
ActorRole: "system_admin",
|
||||
ActorRole: systemAuditActorRole(ctx),
|
||||
Action: types.AuditActionSystemSettingChanged,
|
||||
TargetType: "tenant_storage_quota",
|
||||
TargetID: "all",
|
||||
|
||||
+22
-14
@@ -144,15 +144,16 @@ type tenantAPIKeyCreateRequest struct {
|
||||
}
|
||||
|
||||
type tenantAPIKeyResponse struct {
|
||||
ID uint64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
APIKey string `json:"api_key"`
|
||||
FullAccess bool `json:"full_access"`
|
||||
KnowledgeBaseIDs types.StringArray `json:"knowledge_base_ids"`
|
||||
Capabilities types.StringArray `json:"capabilities"`
|
||||
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
|
||||
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ID uint64 `json:"id"`
|
||||
ScopeType types.APIKeyScopeType `json:"scope_type"`
|
||||
Name string `json:"name"`
|
||||
APIKey string `json:"api_key"`
|
||||
FullAccess bool `json:"full_access"`
|
||||
KnowledgeBaseIDs types.StringArray `json:"knowledge_base_ids"`
|
||||
Capabilities types.StringArray `json:"capabilities"`
|
||||
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
|
||||
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type tenantAPIKeyCreateResponse struct {
|
||||
@@ -227,12 +228,15 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
|
||||
c.Error(errors.NewUnauthorizedError("authentication required"))
|
||||
return
|
||||
}
|
||||
apiKeyScope, hasAPIKeyScope := types.TenantAPIKeyScopeFromContext(ctx)
|
||||
platformCaller := hasAPIKeyScope && apiKeyScope.IsPlatform()
|
||||
catalogManager := caller.CanAccessAllTenants || platformCaller
|
||||
|
||||
// Deployment-level policy: ordinary users may be restricted to joining
|
||||
// existing workspaces by invitation. This check is authoritative; the
|
||||
// frontend capability only improves UX and cannot bypass it. Cross-tenant
|
||||
// superusers retain the catalog-management create path.
|
||||
if !caller.CanAccessAllTenants &&
|
||||
if !catalogManager &&
|
||||
!resolveTenantSelfServiceCreationEnabled(ctx, h.config, h.systemSettingSvc) {
|
||||
logger.Warnf(ctx, "Self-service tenant creation denied by policy for user %s", caller.ID)
|
||||
c.Error(errors.NewTenantCreationDisabledError())
|
||||
@@ -241,7 +245,7 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
|
||||
|
||||
var tenantData types.Tenant
|
||||
|
||||
if caller.CanAccessAllTenants {
|
||||
if catalogManager {
|
||||
// Backward-compatible path for cross-tenant superusers: accept
|
||||
// the full Tenant payload (status, storage_quota, retriever
|
||||
// engines, configs...) so existing tooling keeps working.
|
||||
@@ -352,7 +356,7 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
|
||||
// yet still occupies storage_bucket / name uniqueness slots.
|
||||
// Idempotent: EnsureOwner is a no-op when the row already exists,
|
||||
// so cross-tenant superusers create-and-own through the same path.
|
||||
if h.memberService != nil {
|
||||
if h.memberService != nil && !platformCaller {
|
||||
if _, err := h.memberService.EnsureOwner(ctx, caller.ID, createdTenant.ID); err != nil {
|
||||
logger.Errorf(ctx,
|
||||
"Failed to bootstrap owner membership for user %s tenant %d: %v — rolling back tenant",
|
||||
@@ -416,7 +420,7 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
|
||||
// When a tenantless user creates their first workspace, make it their
|
||||
// default login tenant. Roll the just-created resources back if this
|
||||
// finalisation fails so the user is not left with an unreachable tenant.
|
||||
if caller.TenantID == 0 {
|
||||
if caller.TenantID == 0 && !platformCaller {
|
||||
caller.TenantID = createdTenant.ID
|
||||
if err := h.userService.UpdateUser(ctx, caller); err != nil {
|
||||
logger.Errorf(ctx, "Failed to set first tenant %d as default for user %s: %v",
|
||||
@@ -450,7 +454,10 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
|
||||
// tenant_api_keys. Failing to create the convenience key must NOT fail
|
||||
// the whole tenant creation (the tenant is fully usable without a key);
|
||||
// we log a warning and return the tenant as usual.
|
||||
if h.autoCreateTenantAPIKey(ctx) && h.apiKeyService != nil {
|
||||
// A platform key with system_tenants_manage may create workspaces, but it
|
||||
// must not bootstrap a full-access workspace key and escalate beyond its
|
||||
// own explicit capabilities.
|
||||
if !platformCaller && h.autoCreateTenantAPIKey(ctx) && h.apiKeyService != nil {
|
||||
result, keyErr := h.apiKeyService.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
||||
TenantID: createdTenant.ID,
|
||||
Name: "default",
|
||||
@@ -731,6 +738,7 @@ func tenantAPIKeyForResponse(key *types.TenantAPIKey) tenantAPIKeyResponse {
|
||||
}
|
||||
return tenantAPIKeyResponse{
|
||||
ID: key.ID,
|
||||
ScopeType: types.NormalizeAPIKeyScopeType(key.ScopeType),
|
||||
Name: key.Name,
|
||||
APIKey: key.APIKey,
|
||||
FullAccess: key.FullAccess,
|
||||
|
||||
Reference in New Issue
Block a user