diff --git a/internal/handler/tenant.go b/internal/handler/tenant.go index 4e3b8cca..88516195 100644 --- a/internal/handler/tenant.go +++ b/internal/handler/tenant.go @@ -576,7 +576,7 @@ func (h *TenantHandler) ResetAPIKey(c *gin.Context) { result, err := h.apiKeyService.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{ TenantID: id, Name: "Tenant API key", - Role: types.TenantRoleAdmin, + Role: types.TenantRoleOwner, }) if err != nil { if appErr, ok := errors.IsAppError(err); ok { diff --git a/internal/middleware/rbac.go b/internal/middleware/rbac.go index 2c104334..d4fdaec9 100644 --- a/internal/middleware/rbac.go +++ b/internal/middleware/rbac.go @@ -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) { diff --git a/internal/middleware/rbac_api_key_shortcircuit_test.go b/internal/middleware/rbac_api_key_shortcircuit_test.go index fc17b74f..c1852a7e 100644 --- a/internal/middleware/rbac_api_key_shortcircuit_test.go +++ b/internal/middleware/rbac_api_key_shortcircuit_test.go @@ -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) } } diff --git a/internal/router/router.go b/internal/router/router.go index 493b6916..0b982eba 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -1461,17 +1461,6 @@ func newFileServeHandler(globalFileService interfaces.FileService) gin.HandlerFu return } - // /files is registered on the engine root, outside the /api/v1 - // API-key gate. A KB-restricted API key must not fetch arbitrary - // tenant files: a raw storage path cannot be attributed to the - // key's KB allow-list, so serving it would bypass the KB scope. - if scope, ok := types.TenantAPIKeyScopeFromContext(c.Request.Context()); ok && scope.IsKnowledgeBaseRestricted() { - logger.Warnf(context.Background(), - "[Router] /files denied KB-restricted API key: tenant_id=%d file_path=%q", tenant.ID, filePath) - c.JSON(http.StatusForbidden, gin.H{"error": "forbidden: API key scope does not allow file access"}) - return - } - if err := secutils.ValidateStoragePathTenant(filePath, tenant.ID); err != nil { logger.Warnf(context.Background(), "[Router] /files denied cross-tenant or invalid path: tenant_id=%d file_path=%q err=%v", tenant.ID, filePath, err) c.JSON(http.StatusForbidden, gin.H{"error": "forbidden: file path not accessible"}) @@ -1529,7 +1518,10 @@ func newFileServeHandler(globalFileService interfaces.FileService) gin.HandlerFu func serveFiles(r getRouteRegistrar, globalFileService interfaces.FileService) { logger.Infof(context.Background(), "[Router] Serving files from /files") - r.GET("/files", newFileServeHandler(globalFileService)) + // /files sits outside the /api/v1 APIKeyGate; storage paths cannot be + // attributed to a key's KB allow-list, so API keys are denied outright + // (embed routes use their own /embed/.../files handler). + r.GET("/files", middleware.DenyAPIKeyPrincipal(), newFileServeHandler(globalFileService)) } // servePresignedFiles serves files via HMAC-signed URLs without requiring authentication. diff --git a/internal/router/router_api_key_management_test.go b/internal/router/router_api_key_management_test.go new file mode 100644 index 00000000..d9dac814 --- /dev/null +++ b/internal/router/router_api_key_management_test.go @@ -0,0 +1,97 @@ +package router + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/Tencent/WeKnora/internal/middleware" + "github.com/Tencent/WeKnora/internal/types" + "github.com/gin-gonic/gin" +) + +// TestAPIKeyGateDeniesTenantKeyManagementPaths guards the default-deny +// contract: tenant lifecycle, key management and API-principal config routes +// are registered without apiKeyRoute/apiKeyGroup, so even an Owner-role API +// key must receive 403 from the gate before JWT-only handlers run. +func TestAPIKeyGateDeniesTenantKeyManagementPaths(t *testing.T) { + gin.SetMode(gin.TestMode) + + gate := middleware.NewAPIKeyRouteAuthorizer() + engine := gin.New() + engine.Use(func(c *gin.Context) { + scope := types.TenantAPIKeyScope{Role: types.TenantRoleOwner} + c.Request = c.Request.WithContext(types.WithTenantAPIKeyScope(c.Request.Context(), scope)) + c.Next() + }) + engine.Use(gate.Middleware()) + + v1 := engine.Group("/api/v1") + tenantByID := v1.Group("/tenants/:id") + { + tenantByID.POST("/api-key", reachedOK) + tenantByID.GET("/api-keys", reachedOK) + tenantByID.POST("/api-keys", reachedOK) + tenantByID.DELETE("/api-keys/:key_id", reachedOK) + tenantByID.GET("/api-principal-config", reachedOK) + tenantByID.PUT("/api-principal-config", reachedOK) + tenantByID.POST("/api-principal-test-token", reachedOK) + } + tenantRoutes := v1.Group("/tenants") + { + tenantRoutes.POST("", reachedOK) + } + + cases := []struct { + method string + path string + }{ + {http.MethodPost, "/api/v1/tenants/42/api-key"}, + {http.MethodGet, "/api/v1/tenants/42/api-keys"}, + {http.MethodPost, "/api/v1/tenants/42/api-keys"}, + {http.MethodDelete, "/api/v1/tenants/42/api-keys/7"}, + {http.MethodGet, "/api/v1/tenants/42/api-principal-config"}, + {http.MethodPut, "/api/v1/tenants/42/api-principal-config"}, + {http.MethodPost, "/api/v1/tenants/42/api-principal-test-token"}, + {http.MethodPost, "/api/v1/tenants"}, + } + + for _, tc := range cases { + t.Run(tc.method+" "+tc.path, func(t *testing.T) { + w := httptest.NewRecorder() + engine.ServeHTTP(w, httptest.NewRequest(tc.method, tc.path, nil)) + if w.Code != http.StatusForbidden { + t.Fatalf("status = %d, want 403 body=%s", w.Code, w.Body.String()) + } + }) + } +} + +// TestAPIKeyGateAllowsDeclaredTenantKVRead confirms the gate still permits +// routes that are explicitly declared for Owner API keys (sanity check). +func TestAPIKeyGateAllowsDeclaredTenantKVRead(t *testing.T) { + gin.SetMode(gin.TestMode) + + g := &rbacGuards{} + v1 := gin.New().Group("/api/v1") + g.apiKeyRoute(v1.Group("/tenants"), http.MethodGet, "/kv/:key", apiKeyOwner(), reachedOK) + + engine := gin.New() + engine.Use(func(c *gin.Context) { + scope := types.TenantAPIKeyScope{Role: types.TenantRoleOwner} + c.Request = c.Request.WithContext(types.WithTenantAPIKeyScope(c.Request.Context(), scope)) + c.Next() + }) + engine.Use(g.apiKeyAuthorizer.Middleware()) + engine.GET("/api/v1/tenants/kv/:key", reachedOK) + + w := httptest.NewRecorder() + engine.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/tenants/kv/my-key", nil)) + if w.Code != http.StatusOK { + t.Fatalf("declared owner route status = %d, want 200 body=%s", w.Code, w.Body.String()) + } +} + +func reachedOK(c *gin.Context) { + c.Status(http.StatusOK) +} diff --git a/internal/router/router_files_test.go b/internal/router/router_files_test.go index f0eec566..3d5ff16f 100644 --- a/internal/router/router_files_test.go +++ b/internal/router/router_files_test.go @@ -153,6 +153,32 @@ func TestServeFilesRejectsPathWithoutTenantSegment(t *testing.T) { } } +func TestServeFilesRejectsAPIKeyPrincipal(t *testing.T) { + gin.SetMode(gin.TestMode) + t.Setenv("STORAGE_TYPE", "local") + + engine := gin.New() + serveFiles(engine, &stubFileService{ + getFile: func(ctx context.Context, filePath string) (io.ReadCloser, error) { + t.Fatalf("GetFile should not be called for API-key principal, got %q", filePath) + return nil, nil + }, + }) + + filePath := "local://42/docs/example.txt" + req := httptest.NewRequest(http.MethodGet, "/files?file_path="+url.QueryEscape(filePath), nil) + ctx := context.WithValue(req.Context(), types.TenantInfoContextKey, &types.Tenant{ID: 42}) + ctx = types.WithTenantAPIKeyScope(ctx, types.TenantAPIKeyScope{Role: types.TenantRoleOwner}) + req = req.WithContext(ctx) + + recorder := httptest.NewRecorder() + engine.ServeHTTP(recorder, req) + + if got, want := recorder.Code, http.StatusForbidden; got != want { + t.Fatalf("status = %d, want %d body=%s", got, want, recorder.Body.String()) + } +} + func TestServeFilesForcesActiveContentDownload(t *testing.T) { gin.SetMode(gin.TestMode) t.Setenv("STORAGE_TYPE", "local") diff --git a/migrations/versioned/000065_tenant_api_keys.up.sql b/migrations/versioned/000065_tenant_api_keys.up.sql index 84d70a55..33daf9f6 100644 --- a/migrations/versioned/000065_tenant_api_keys.up.sql +++ b/migrations/versioned/000065_tenant_api_keys.up.sql @@ -35,7 +35,7 @@ SELECT 'Tenant API key', 'migrated-tenant-' || id::text, api_key, - 'admin', + 'owner', '[]'::jsonb, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP