refactor(api-keys): update role handling and enhance API key restrictions

Change the default role for tenant API keys from 'admin' to 'owner' to align with the new authorization model. Update related tests to reflect this change, ensuring that API keys with the owner role are correctly denied access to management paths and system-admin routes. Introduce new tests to validate that API keys are properly restricted from accessing sensitive endpoints, reinforcing the security measures in place.
This commit is contained in:
wizardchen
2026-07-06 18:13:37 +08:00
committed by lyingbug
parent a6759d61b5
commit 1d1e1e3d25
7 changed files with 143 additions and 25 deletions
+9 -6
View File
@@ -128,13 +128,16 @@ func RequireSystemAdmin(cfg *config.Config) gin.HandlerFunc {
warnOnNilConfig(cfg)
return func(c *gin.Context) {
ctx := c.Request.Context()
// API-key principals never gain system-admin authority, but the
// APIKeyGate is the single place that decides which routes they may
// reach. System routes are simply not declared there, so an API key
// is already rejected by default-deny before this guard runs. Short-
// circuit to avoid a misleading "system administrator required" 403.
// 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 {
c.Next()
logger.Warnf(ctx,
"[rbac] system admin required: API-key principal denied path=%s",
c.Request.URL.Path)
c.JSON(http.StatusForbidden, gin.H{
"error": "Forbidden: API keys cannot access this endpoint",
})
c.Abort()
return
}
if types.IsSystemAdminFromContext(ctx) {
@@ -44,14 +44,14 @@ func TestRequireRole_ShortCircuitsAPIKey(t *testing.T) {
}
}
func TestRequireSystemAdmin_ShortCircuitsAPIKey(t *testing.T) {
func TestRequireSystemAdmin_RejectsAPIKey(t *testing.T) {
w := apiKeyRBACHarness(
types.TenantAPIKeyScope{Role: types.TenantRoleAdmin},
types.TenantRoleAdmin,
types.TenantAPIKeyScope{Role: types.TenantRoleOwner},
types.TenantRoleOwner,
RequireSystemAdmin(cfgRBAC(true)),
)
if w.Code != http.StatusOK {
t.Fatalf("API-key principal should short-circuit RequireSystemAdmin, got %d", w.Code)
if w.Code != http.StatusForbidden {
t.Fatalf("API-key principal must be rejected by RequireSystemAdmin, got %d", w.Code)
}
}