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()
+142 -3
View File
@@ -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
View File
@@ -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,
+4
View File
@@ -111,6 +111,10 @@ func IsTenantAccessible(
func RequireCrossTenantAccess(cfg *config.Config) gin.HandlerFunc {
return func(c *gin.Context) {
ctx := c.Request.Context()
if scope, ok := types.TenantAPIKeyScopeFromContext(ctx); ok && scope.IsPlatform() {
c.Next()
return
}
// First the cluster-wide flag — if it's off, nobody gets through,
// not even users with CanAccessAllTenants=true. This mirrors the
// "must require BOTH" rule that previously lived in tenant.go.
+10
View File
@@ -21,6 +21,10 @@ var errTenantAPIKeyScopeForbidden = stderrors.New("workspace API key scope forbi
// default (fail-closed), which removes the old "remember to add APIKeyDeny"
// footgun.
type APIKeyRoutePolicy struct {
// PlatformOnly rejects workspace-bound keys even when they are full-access.
// It is used for control-plane routes under /system/admin and cross-workspace
// tenant lifecycle APIs.
PlatformOnly bool
// RequireFullAccess admits only full-access tenant API keys unless one of
// the listed capabilities also matches. Routes with neither full-access
// requirement nor capabilities are open to any valid API key.
@@ -128,6 +132,12 @@ func (a *APIKeyRouteAuthorizer) authorize(scope types.TenantAPIKeyScope, method,
if !ok {
return errTenantAPIKeyScopeForbidden
}
if policy.PlatformOnly && !scope.IsPlatform() {
return errTenantAPIKeyScopeForbidden
}
if policy.PlatformOnly && len(policy.Capabilities) == 0 {
return errTenantAPIKeyScopeForbidden
}
if scope.FullAccess {
return nil
}
+29
View File
@@ -171,6 +171,35 @@ func TestGateKBScopeDoesNotBlockDataPlane(t *testing.T) {
}
}
func TestGatePlatformOnlyPolicyRejectsTenantKeyBeforeFullAccess(t *testing.T) {
a := NewAPIKeyRouteAuthorizer()
a.Register(http.MethodGet, "/api/v1/system/admin/settings",
APIKeyRoutePolicy{PlatformOnly: true}.
WithCapability(types.APIKeyCapabilitySystemSettingsRead))
tenantFull := &types.TenantAPIKeyScope{FullAccess: true}
platform := &types.TenantAPIKeyScope{
ScopeType: types.APIKeyScopePlatform,
Capabilities: types.StringArray{string(types.APIKeyCapabilitySystemSettingsRead)},
}
if runGate(t, a, tenantFull, http.MethodGet, "/api/v1/system/admin/settings") {
t.Fatal("tenant full-access key must not enter a platform-only route")
}
if !runGate(t, a, platform, http.MethodGet, "/api/v1/system/admin/settings") {
t.Fatal("platform key with the required capability should pass")
}
withoutCapability := NewAPIKeyRouteAuthorizer()
withoutCapability.Register(http.MethodGet, "/api/v1/system/admin/unsafe",
APIKeyRoutePolicy{PlatformOnly: true})
corruptPlatformFull := &types.TenantAPIKeyScope{
ScopeType: types.APIKeyScopePlatform,
FullAccess: true,
}
if runGate(t, withoutCapability, corruptPlatformFull, http.MethodGet, "/api/v1/system/admin/unsafe") {
t.Fatal("platform-only policy without an explicit capability must fail closed")
}
}
// runDenyAPIKey mounts DenyAPIKeyPrincipal ahead of a handler and reports
// whether the request reached the handler.
func runDenyAPIKey(t *testing.T, scope *types.TenantAPIKeyScope) (reached bool, status int) {
+125 -18
View File
@@ -337,7 +337,51 @@ func authenticateAPIKeyRequest(
return false
}
attachAPIKeyAuthContext(c, tenantService, userService, key.TenantID, key)
if key.IsPlatform() {
tenantHeader := strings.TrimSpace(c.GetHeader("X-Tenant-ID"))
if tenantHeader == "" {
if !isPlatformTenantOptionalAPI(c.Request.URL.Path, c.Request.Method) {
c.JSON(http.StatusConflict, gin.H{
"error": "Workspace required: platform API keys must send X-Tenant-ID",
"code": "TENANT_REQUIRED",
})
c.Abort()
return false
}
attachPlatformAPIKeyAuthContext(c, key)
} else {
targetTenantID, parseErr := strconv.ParseUint(tenantHeader, 10, 64)
if parseErr != nil || targetTenantID == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid X-Tenant-ID header"})
c.Abort()
return false
}
attachAPIKeyAuthContext(c, tenantService, userService, targetTenantID, key)
}
} else {
tenantID := key.TenantIDValue()
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: invalid API key scope"})
c.Abort()
return false
}
if tenantHeader := strings.TrimSpace(c.GetHeader("X-Tenant-ID")); tenantHeader != "" {
requestedTenantID, parseErr := strconv.ParseUint(tenantHeader, 10, 64)
if parseErr != nil || requestedTenantID == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid X-Tenant-ID header"})
c.Abort()
return false
}
if requestedTenantID != tenantID {
c.JSON(http.StatusForbidden, gin.H{
"error": "Forbidden: workspace API key cannot switch workspaces",
})
c.Abort()
return false
}
}
attachAPIKeyAuthContext(c, tenantService, userService, tenantID, key)
}
if c.IsAborted() {
return false
}
@@ -347,6 +391,55 @@ func authenticateAPIKeyRequest(
return true
}
func isPlatformTenantOptionalAPI(path, method string) bool {
path = strings.TrimSuffix(strings.TrimSpace(path), "/")
if strings.HasPrefix(path, "/api/v1/system/admin") {
return true
}
if method == http.MethodGet && (path == "/api/v1/tenants/all" || path == "/api/v1/tenants/search") {
return true
}
return method == http.MethodPost && path == "/api/v1/tenants"
}
func attachPlatformAPIKeyAuthContext(c *gin.Context, key *types.TenantAPIKey) {
principal, user := platformAPIKeyIdentity(key)
userID := user.ID
c.Set(types.UserContextKey.String(), user)
c.Set(types.UserIDContextKey.String(), userID)
c.Set(types.PrincipalContextKey.String(), principal)
c.Set(types.TenantRoleContextKey.String(), types.TenantRoleViewer)
c.Set(types.SystemAdminContextKey.String(), false)
ctx := c.Request.Context()
ctx = context.WithValue(ctx, types.UserContextKey, user)
ctx = context.WithValue(ctx, types.UserIDContextKey, userID)
ctx = types.WithPrincipal(ctx, principal)
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleViewer)
ctx = context.WithValue(ctx, types.SystemAdminContextKey, false)
ctx = types.WithTenantAPIKeyScope(ctx, types.TenantAPIKeyScope{
KeyID: key.ID,
ScopeType: types.APIKeyScopePlatform,
FullAccess: false,
Capabilities: key.Capabilities,
})
c.Request = c.Request.WithContext(ctx)
}
func platformAPIKeyIdentity(key *types.TenantAPIKey) (types.Principal, *types.User) {
keyID := uint64(0)
if key != nil {
keyID = key.ID
}
principal := types.Principal{Type: types.PrincipalAPIPlatform, ID: strconv.FormatUint(keyID, 10)}
userID := principal.StorageID()
return principal, &types.User{
ID: userID,
Username: userID,
Email: fmt.Sprintf("platform-api-key-%d@api-key.local", keyID),
IsActive: true,
}
}
func attachAPIKeyAuthContext(
c *gin.Context,
tenantService interfaces.TenantService,
@@ -369,32 +462,45 @@ func attachAPIKeyAuthContext(
types.TenantInfoContextKey, t,
)
user, err := userService.GetUserByTenantID(c.Request.Context(), tenantID)
if err != nil || user == nil {
user = &types.User{
ID: fmt.Sprintf("system-%d", tenantID),
Username: fmt.Sprintf("system-%d", tenantID),
Email: fmt.Sprintf("system-%d@api-key.local", tenantID),
TenantID: tenantID,
IsActive: true,
var user *types.User
var principal types.Principal
if key != nil && key.IsPlatform() {
// A platform key keeps one stable machine identity while selecting the
// target workspace through X-Tenant-ID. Tenant API-principal modes and
// tenant-owned synthetic users must not rewrite that identity.
principal, user = platformAPIKeyIdentity(key)
user.TenantID = tenantID
} else {
user, err = userService.GetUserByTenantID(c.Request.Context(), tenantID)
if err != nil || user == nil {
user = &types.User{
ID: fmt.Sprintf("system-%d", tenantID),
Username: fmt.Sprintf("system-%d", tenantID),
Email: fmt.Sprintf("system-%d@api-key.local", tenantID),
TenantID: tenantID,
IsActive: true,
}
log.Printf("No user found for tenant %d via API key, using synthetic system user %s", tenantID, user.ID)
}
var principalErr error
principal, principalErr = resolveAPIPrincipal(c.Request.Context(), t, c.Request.Header)
if principalErr != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": apiPrincipalAuthErrorMessage(principalErr)})
c.Abort()
return
}
log.Printf("No user found for tenant %d via API key, using synthetic system user %s", tenantID, user.ID)
}
c.Set(types.UserContextKey.String(), user)
c.Set(types.UserIDContextKey.String(), user.ID)
principal, principalErr := resolveAPIPrincipal(c.Request.Context(), t, c.Request.Header)
if principalErr != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": apiPrincipalAuthErrorMessage(principalErr)})
c.Abort()
return
}
c.Set(types.PrincipalContextKey.String(), principal)
// This role context exists only for legacy guard compatibility after
// RequireRole short-circuits API-key principals. The API key's real
// authority is FullAccess + Capabilities + KnowledgeBaseIDs.
apiKeyTenantRoleContext := types.TenantRoleViewer
if key != nil && key.FullAccess {
fullAccess := key != nil && key.FullAccess && !key.IsPlatform()
if fullAccess {
apiKeyTenantRoleContext = types.TenantRoleOwner
}
c.Set(types.TenantRoleContextKey.String(), apiKeyTenantRoleContext)
@@ -407,7 +513,8 @@ func attachAPIKeyAuthContext(
if key != nil {
ctx = types.WithTenantAPIKeyScope(ctx, types.TenantAPIKeyScope{
KeyID: key.ID,
FullAccess: key.FullAccess,
ScopeType: key.ScopeType,
FullAccess: fullAccess,
KnowledgeBaseIDs: key.KnowledgeBaseIDs,
Capabilities: key.Capabilities,
})
@@ -0,0 +1,95 @@
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
func TestPlatformTenantOptionalAPIs(t *testing.T) {
cases := []struct {
method string
path string
want bool
}{
{http.MethodGet, "/api/v1/system/admin/settings", true},
{http.MethodGet, "/api/v1/tenants/all", true},
{http.MethodGet, "/api/v1/tenants/search", true},
{http.MethodPost, "/api/v1/tenants", true},
{http.MethodGet, "/api/v1/knowledge-bases", false},
{http.MethodGet, "/api/v1/tenants", false},
}
for _, tc := range cases {
if got := isPlatformTenantOptionalAPI(tc.path, tc.method); got != tc.want {
t.Fatalf("isPlatformTenantOptionalAPI(%s, %s) = %v, want %v", tc.method, tc.path, got, tc.want)
}
}
}
func TestAttachPlatformAPIKeyAuthContext(t *testing.T) {
gin.SetMode(gin.TestMode)
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodGet, "/api/v1/system/admin/settings", nil)
attachPlatformAPIKeyAuthContext(c, &types.TenantAPIKey{
ID: 9, ScopeType: types.APIKeyScopePlatform,
Capabilities: types.StringArray{string(types.APIKeyCapabilitySystemSettingsRead)},
})
scope, ok := types.TenantAPIKeyScopeFromContext(c.Request.Context())
if !ok || !scope.IsPlatform() || scope.KeyID != 9 {
t.Fatalf("platform scope = %#v, ok=%v", scope, ok)
}
if _, ok := types.TenantIDFromContext(c.Request.Context()); ok {
t.Fatal("tenantless platform control-plane request must not have tenant context")
}
principal, ok := types.PrincipalFromContext(c.Request.Context())
if !ok || principal.Type != types.PrincipalAPIPlatform {
t.Fatalf("principal = %#v, ok=%v", principal, ok)
}
}
func TestPlatformAPIKeyIdentityIsStableAcrossTenants(t *testing.T) {
principal, user := platformAPIKeyIdentity(&types.TenantAPIKey{ID: 27})
if principal.Type != types.PrincipalAPIPlatform || principal.ID != "27" {
t.Fatalf("principal = %#v", principal)
}
if user.ID != "api_platform:27" || user.Username != user.ID {
t.Fatalf("user = %#v", user)
}
}
func TestAttachTargetedPlatformAPIKeyKeepsPlatformPrincipal(t *testing.T) {
gin.SetMode(gin.TestMode)
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodGet, "/api/v1/knowledge-bases", nil)
key := &types.TenantAPIKey{
ID: 27,
ScopeType: types.APIKeyScopePlatform,
FullAccess: true, // Corrupt/legacy data must still be capability-only at runtime.
Capabilities: types.StringArray{
string(types.APIKeyCapabilityRetrieve),
},
}
attachAPIKeyAuthContext(c, &fakeTenantService{tenant: &types.Tenant{ID: 42}}, nil, 42, key)
if c.IsAborted() {
t.Fatal("targeted platform API key context unexpectedly aborted")
}
principal, ok := types.PrincipalFromContext(c.Request.Context())
if !ok || principal.Type != types.PrincipalAPIPlatform || principal.ID != "27" {
t.Fatalf("principal = %#v, ok=%v", principal, ok)
}
tenantID, ok := types.TenantIDFromContext(c.Request.Context())
if !ok || tenantID != 42 {
t.Fatalf("tenant id = %d, ok=%v", tenantID, ok)
}
scope, ok := types.TenantAPIKeyScopeFromContext(c.Request.Context())
if !ok || !scope.IsPlatform() || scope.FullAccess {
t.Fatalf("scope = %#v, ok=%v", scope, ok)
}
user, ok := c.Request.Context().Value(types.UserContextKey).(*types.User)
if !ok || user.ID != "api_platform:27" || user.TenantID != 42 {
t.Fatalf("user = %#v, ok=%v", user, ok)
}
}
+8 -3
View File
@@ -148,9 +148,14 @@ func RequireSystemAdmin(cfg *config.Config) gin.HandlerFunc {
warnOnNilConfig(cfg)
return func(c *gin.Context) {
ctx := c.Request.Context()
// API-key principals must never reach system-admin routes, even if a
// future route registration mistakenly declares an apiKey* policy.
if _, ok := types.TenantAPIKeyScopeFromContext(ctx); ok {
// The API-key gate runs before this guard and default-denies undeclared
// routes. Only platform keys that passed an explicit platform capability
// policy may reuse the system-admin handlers below.
if scope, ok := types.TenantAPIKeyScopeFromContext(ctx); ok {
if scope.IsPlatform() {
c.Next()
return
}
logger.Warnf(ctx,
"[rbac] system admin required: API-key principal denied path=%s",
c.Request.URL.Path)
@@ -55,6 +55,17 @@ func TestRequireSystemAdmin_RejectsAPIKey(t *testing.T) {
}
}
func TestRequireSystemAdmin_AllowsPlatformAPIKeyAfterRouteGate(t *testing.T) {
w := apiKeyRBACHarness(
types.TenantAPIKeyScope{ScopeType: types.APIKeyScopePlatform},
types.TenantRoleViewer,
RequireSystemAdmin(cfgRBAC(true)),
)
if w.Code != http.StatusOK {
t.Fatalf("platform API key should pass the system-admin role guard after route authorization, got %d", w.Code)
}
}
// TestRequireOwnershipOrRole_ShortCircuitsAPIKey is the core regression for
// review #1: an API key writing to a KB it does not
// "own" (synthetic system user never matches creator_id) must not be 403'd by
+8
View File
@@ -231,6 +231,14 @@ func apiKeyFullAccess() middleware.APIKeyRoutePolicy {
return middleware.APIKeyRoutePolicy{RequireFullAccess: true}
}
func apiKeyPlatform(capabilities ...types.APIKeyCapability) middleware.APIKeyRoutePolicy {
policy := middleware.APIKeyRoutePolicy{PlatformOnly: true}
for _, capability := range capabilities {
policy = policy.WithCapability(capability)
}
return policy
}
// apiKeyRetrieve grants read/search access to knowledge-base data.
func apiKeyRetrieve(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
return base.WithCapability(types.APIKeyCapabilityRetrieve)
+44 -22
View File
@@ -654,10 +654,9 @@ func RegisterChatRoutes(r *gin.RouterGroup, handler *session.Handler, g *rbacGua
// EnableCrossTenantAccess flag, replacing the 12-line if-block that
// previously opened ListAllTenants and SearchTenants.
//
// POST /tenants and GET /tenants stay open to authenticated users —
// the previous handler comments claimed CanAccessAllTenants gating
// "is in the handler" but the bodies never enforced it; this PR is a
// pure refactor and does not introduce new gates.
// JWT behavior for POST /tenants and GET /tenants remains unchanged. Platform
// API keys may create tenants through system_tenants_manage; workspace keys
// remain default-denied on tenant-catalog operations.
func RegisterTenantRoutes(
r *gin.RouterGroup,
handler *handler.TenantHandler,
@@ -668,8 +667,12 @@ func RegisterTenantRoutes(
) {
// Cross-tenant superuser endpoints — promoted from handler if-blocks
// to middleware.RequireCrossTenantAccess at the route layer.
r.GET("/tenants/all", g.CrossTenant(), handler.ListAllTenants)
r.GET("/tenants/search", g.CrossTenant(), handler.SearchTenants)
g.apiKeyRoute(r, http.MethodGet, "/tenants/all",
apiKeyPlatform(types.APIKeyCapabilitySystemTenantsRead, types.APIKeyCapabilitySystemTenantsManage),
g.CrossTenant(), handler.ListAllTenants)
g.apiKeyRoute(r, http.MethodGet, "/tenants/search",
apiKeyPlatform(types.APIKeyCapabilitySystemTenantsRead, types.APIKeyCapabilitySystemTenantsManage),
g.CrossTenant(), handler.SearchTenants)
// 空间路由组
tenantRoutes := r.Group("/tenants")
@@ -682,7 +685,8 @@ func RegisterTenantRoutes(
// 不需要跨空间特权;handler 也不读写 X-Tenant-ID 指向的现有
// 空间,所以越过 PathTenantMatch 守卫不会扩大攻击面。
// 创建空间不对 API key 开放(注册在原始 group,默认拒绝)。
tenantRoutes.POST("", handler.CreateTenant)
g.apiKeyRoute(tenantRoutes, http.MethodPost, "",
apiKeyPlatform(types.APIKeyCapabilitySystemTenantsManage), handler.CreateTenant)
g.apiKeyRoute(tenantRoutes, http.MethodGet, "", apiKeyManageTenantSettings(apiKeyFullAccess()), handler.ListTenants)
// Generic KV configuration management (tenant-level). Tenant ID
@@ -700,9 +704,13 @@ func RegisterTenantRoutes(
// opts in below through the manage_members capability.
tenantByID := tenantRoutes.Group("/:id", g.PathTenantMatch())
{
tenantByID.GET("", g.Viewer(), handler.GetTenant)
tenantByID.PUT("", g.Owner(), handler.UpdateTenant)
tenantByID.DELETE("", g.Owner(), handler.DeleteTenant)
g.apiKeyRoute(tenantByID, http.MethodGet, "",
apiKeyPlatform(types.APIKeyCapabilitySystemTenantsRead, types.APIKeyCapabilitySystemTenantsManage),
g.Viewer(), handler.GetTenant)
g.apiKeyRoute(tenantByID, http.MethodPut, "",
apiKeyPlatform(types.APIKeyCapabilitySystemTenantsManage), g.Owner(), handler.UpdateTenant)
g.apiKeyRoute(tenantByID, http.MethodDelete, "",
apiKeyPlatform(types.APIKeyCapabilitySystemTenantsManage), g.Owner(), handler.DeleteTenant)
tenantByID.GET("/api-keys", g.Owner(), handler.ListAPIKeys)
tenantByID.POST("/api-keys", g.Owner(), handler.CreateAPIKey)
tenantByID.DELETE("/api-keys/:key_id", g.Owner(), handler.DeleteAPIKey)
@@ -948,30 +956,43 @@ func RegisterSystemAdminRoutes(
adminRoutes.POST("/revoke", handler.RevokeSystemAdmin)
adminRoutes.GET("/list", handler.ListSystemAdmins)
adminRoutes.POST("/users/reset-password", handler.ResetUserPassword)
adminRoutes.GET("/api-keys", handler.ListPlatformAPIKeys)
adminRoutes.POST("/api-keys", handler.CreatePlatformAPIKey)
adminRoutes.DELETE("/api-keys/:key_id", handler.DeletePlatformAPIKey)
// P1: platform-wide system settings (DB-backed runtime tunables).
// Reads return raw model rows / arrays (no `gin.H{"data":...}`
// wrapping), matching the project's axios interceptor convention
// — see frontend/src/utils/request.ts:97.
adminRoutes.GET("/settings", handler.ListSystemSettings)
adminRoutes.GET("/settings/:key", handler.GetSystemSetting)
adminRoutes.PUT("/settings/:key", handler.UpdateSystemSetting)
adminRoutes.DELETE("/settings/:key", handler.ResetSystemSetting)
g.apiKeyRoute(adminRoutes, http.MethodGet, "/settings",
apiKeyPlatform(types.APIKeyCapabilitySystemSettingsRead, types.APIKeyCapabilitySystemSettingsManage),
handler.ListSystemSettings)
g.apiKeyRoute(adminRoutes, http.MethodGet, "/settings/:key",
apiKeyPlatform(types.APIKeyCapabilitySystemSettingsRead, types.APIKeyCapabilitySystemSettingsManage),
handler.GetSystemSetting)
g.apiKeyRoute(adminRoutes, http.MethodPut, "/settings/:key",
apiKeyPlatform(types.APIKeyCapabilitySystemSettingsManage), handler.UpdateSystemSetting)
g.apiKeyRoute(adminRoutes, http.MethodDelete, "/settings/:key",
apiKeyPlatform(types.APIKeyCapabilitySystemSettingsManage), handler.ResetSystemSetting)
// Runtime operations: live asynq queue depths, safe task projections,
// and state-checked task actions for the SystemAdmin dashboard. Lite
// mode returns available=false.
adminRoutes.GET("/runtime/queues", handler.GetRuntimeQueues)
adminRoutes.GET("/runtime/queues/:queue/tasks", handler.ListRuntimeTasks)
adminRoutes.POST("/runtime/queues/:queue/tasks/:task_id/actions/:action", handler.MutateRuntimeTask)
g.apiKeyRoute(adminRoutes, http.MethodGet, "/runtime/queues",
apiKeyPlatform(types.APIKeyCapabilitySystemRuntimeRead, types.APIKeyCapabilitySystemRuntimeManage),
handler.GetRuntimeQueues)
g.apiKeyRoute(adminRoutes, http.MethodGet, "/runtime/queues/:queue/tasks",
apiKeyPlatform(types.APIKeyCapabilitySystemRuntimeRead, types.APIKeyCapabilitySystemRuntimeManage),
handler.ListRuntimeTasks)
g.apiKeyRoute(adminRoutes, http.MethodPost, "/runtime/queues/:queue/tasks/:task_id/actions/:action",
apiKeyPlatform(types.APIKeyCapabilitySystemRuntimeManage), handler.MutateRuntimeTask)
// Bulk action — write the current default-quota setting onto
// every existing tenant. Lives under /tenants instead of
// /settings because it changes tenants, not the setting row.
adminRoutes.POST(
"/tenants/apply-default-storage-quota",
handler.ApplyDefaultStorageQuotaToAllTenants,
)
g.apiKeyRoute(adminRoutes, http.MethodPost, "/tenants/apply-default-storage-quota",
apiKeyPlatform(types.APIKeyCapabilitySystemTenantsManage),
handler.ApplyDefaultStorageQuotaToAllTenants)
// Platform-wide audit feed (tenant_id=0 rows). Covers
// system.setting_changed / system.admin_promoted /
@@ -981,7 +1002,8 @@ func RegisterSystemAdminRoutes(
// out by tenant_id). Optional: skip when audit deps are
// absent, matching RegisterTenantRoutes' /audit-log handling.
if auditLogHandler != nil {
adminRoutes.GET("/audit-log", auditLogHandler.ListSystemAuditLog)
g.apiKeyRoute(adminRoutes, http.MethodGet, "/audit-log",
apiKeyPlatform(types.APIKeyCapabilitySystemAuditRead), auditLogHandler.ListSystemAuditLog)
}
}
}
@@ -47,6 +47,72 @@ func TestConversationRoutesDeclareChatCapability(t *testing.T) {
}
}
func TestPlatformControlPlaneRoutesDeclarePlatformCapabilities(t *testing.T) {
gin.SetMode(gin.TestMode)
g := &rbacGuards{}
v1 := gin.New().Group("/api/v1")
RegisterSystemAdminRoutes(v1, &handler.SystemHandler{}, nil, g)
cases := []struct {
method string
path string
capability types.APIKeyCapability
}{
{http.MethodGet, "/api/v1/system/admin/settings", types.APIKeyCapabilitySystemSettingsRead},
{http.MethodPut, "/api/v1/system/admin/settings/:key", types.APIKeyCapabilitySystemSettingsManage},
{http.MethodGet, "/api/v1/system/admin/runtime/queues", types.APIKeyCapabilitySystemRuntimeRead},
{http.MethodPost, "/api/v1/system/admin/runtime/queues/:queue/tasks/:task_id/actions/:action", types.APIKeyCapabilitySystemRuntimeManage},
}
for _, tc := range cases {
policy := mustLookupAPIKeyPolicy(t, g, tc.method, tc.path)
if !policy.PlatformOnly {
t.Fatalf("%s %s must be platform-only", tc.method, tc.path)
}
if !policyHasCapability(policy, tc.capability) {
t.Fatalf("%s %s capabilities = %#v, want %s", tc.method, tc.path, policy.Capabilities, tc.capability)
}
}
if _, ok := g.apiKeyAuthorizer.Lookup(http.MethodPost, "/api/v1/system/admin/api-keys"); ok {
t.Fatal("platform API keys must not create other platform API keys")
}
}
func TestPlatformTenantLifecycleRoutesDeclarePlatformCapabilities(t *testing.T) {
gin.SetMode(gin.TestMode)
g := &rbacGuards{}
v1 := gin.New().Group("/api/v1")
RegisterTenantRoutes(
v1,
&handler.TenantHandler{},
&handler.TenantMemberHandler{},
&handler.TenantInvitationHandler{},
nil,
g,
)
cases := []struct {
method string
path string
capability types.APIKeyCapability
}{
{http.MethodGet, "/api/v1/tenants/all", types.APIKeyCapabilitySystemTenantsRead},
{http.MethodGet, "/api/v1/tenants/search", types.APIKeyCapabilitySystemTenantsRead},
{http.MethodPost, "/api/v1/tenants", types.APIKeyCapabilitySystemTenantsManage},
{http.MethodGet, "/api/v1/tenants/:id", types.APIKeyCapabilitySystemTenantsRead},
{http.MethodPut, "/api/v1/tenants/:id", types.APIKeyCapabilitySystemTenantsManage},
{http.MethodDelete, "/api/v1/tenants/:id", types.APIKeyCapabilitySystemTenantsManage},
}
for _, tc := range cases {
policy := mustLookupAPIKeyPolicy(t, g, tc.method, tc.path)
if !policy.PlatformOnly {
t.Fatalf("%s %s must be platform-only", tc.method, tc.path)
}
if !policyHasCapability(policy, tc.capability) {
t.Fatalf("%s %s capabilities = %#v, want %s", tc.method, tc.path, policy.Capabilities, tc.capability)
}
}
}
func TestMessageHistoryRoutesDeclareMessageHistoryCapability(t *testing.T) {
gin.SetMode(gin.TestMode)
g := &rbacGuards{}
+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)