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
+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