fix(rbac): plug ungated mutating routes; log RBAC state at startup
Sweep over the route table found four classes of mutating endpoints
that had no role guard:
- POST /tenants — creating a brand-new tenant. Now g.CrossTenant():
only org-level superusers may create tenants, matching /tenants/all
and /tenants/search.
- POST /initialization/initialize/:kbId, PUT /initialization/config/:kbId
— these change a KB's embedding/parser/storage configuration, which
is at least as sensitive as PUT /knowledge-bases/:id. New
KBCreatorLookupFromKbIDParam (sister of KBCreatorLookup but reading
:kbId) lets us reuse the OwnedKBOrAdmin matrix; routes now use the
new g.OwnedKBOrAdminFromKbIDParam() guard.
- POST /initialization/{ollama,remote,embedding,rerank,asr,multimodal,
extract}/* — system-level model probes / downloads / extraction
pipelines. These trigger LLM calls and outbound network fanout
with tenant credentials; gated to Admin+. The corresponding GETs
(status / list / progress) drop to Viewer+ since they're read-only
observability.
- POST /system/{parser-engines,docreader,storage-engine}/* — same
pattern: GETs that report state are Viewer+, the *-check /
/reconnect actions are Admin+.
POST /evaluation/ runs the eval harness which fans out LLM calls
across the tenant — gated to Admin+.
Operational improvement: log the resolved tenant RBAC state at
LoadConfig completion. air's hot-reload only rebuilds the binary on
Go-source changes; it does NOT re-source .env, so flipping
WEKNORA_TENANT_ENABLE_RBAC=true while the dev loop is already
running has no effect until the parent dev-app process restarts.
This was a real diagnostic loop in PR review — printing the value at
startup makes the "I edited .env but the gates still aren't firing"
trap obvious from the first console line.
The Printf includes both the resolved cfg.Tenant.EnableRBAC value
and the raw env var, so a mismatch between "what the .env file
says" and "what this process actually inherited" is one glance.
This commit is contained in:
@@ -477,6 +477,24 @@ func LoadConfig() (*Config, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Surface RBAC enforcement state at startup. air's hot-reload only
|
||||
// rebuilds the binary on Go-source changes; it does NOT re-source
|
||||
// .env, so a `WEKNORA_TENANT_ENABLE_RBAC=true` flip while the dev
|
||||
// loop is already running silently has no effect until the dev
|
||||
// script restarts. Logging this once at startup makes the
|
||||
// "I edited .env but the gates still aren't firing" trap obvious
|
||||
// from the first console line. Printf rather than logger because
|
||||
// LoadConfig runs before the logger sink is wired in the dig graph.
|
||||
rbacOn := cfg.Tenant != nil && cfg.Tenant.EnableRBAC
|
||||
xtAccess := cfg.Tenant != nil && cfg.Tenant.EnableCrossTenantAccess
|
||||
fmt.Printf(
|
||||
"[config] tenant RBAC enforcement: enable_rbac=%v cross_tenant_access=%v "+
|
||||
"(env: WEKNORA_TENANT_ENABLE_RBAC=%q WEKNORA_TENANT_ENABLE_CROSS_TENANT_ACCESS=%q)\n",
|
||||
rbacOn, xtAccess,
|
||||
os.Getenv("WEKNORA_TENANT_ENABLE_RBAC"),
|
||||
os.Getenv("WEKNORA_TENANT_ENABLE_CROSS_TENANT_ACCESS"),
|
||||
)
|
||||
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -62,6 +62,39 @@ func (h *KnowledgeBaseHandler) KBCreatorLookup(c *gin.Context) (string, error) {
|
||||
return kb.CreatorID, nil
|
||||
}
|
||||
|
||||
// KBCreatorLookupFromKbIDParam is the same lookup as KBCreatorLookup
|
||||
// but reads `:kbId` instead of `:id`. Used by the /initialization
|
||||
// routes (POST /initialization/initialize/:kbId, PUT
|
||||
// /initialization/config/:kbId), which are KB-scoped mutating ops:
|
||||
// changing a KB's embedding/parser/storage configuration is at least
|
||||
// as sensitive as updating the KB itself, so it must follow the same
|
||||
// "creator OR Admin+" matrix.
|
||||
func (h *KnowledgeBaseHandler) KBCreatorLookupFromKbIDParam(c *gin.Context) (string, error) {
|
||||
id := c.Param("kbId")
|
||||
if id == "" {
|
||||
return "", errors.New("missing :kbId param for KB creator lookup")
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
tenantID, ok := types.TenantIDFromContext(ctx)
|
||||
if !ok {
|
||||
return "", errors.New("tenant context missing")
|
||||
}
|
||||
kb, err := h.service.GetKnowledgeBaseByID(ctx, id)
|
||||
if err != nil {
|
||||
if errors.Is(err, apprepo.ErrKnowledgeBaseNotFound) {
|
||||
return "", middleware.ErrResourceNotFound
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
if kb == nil {
|
||||
return "", middleware.ErrResourceNotFound
|
||||
}
|
||||
if kb.TenantID != tenantID {
|
||||
return "", middleware.ErrResourceNotFound
|
||||
}
|
||||
return kb.CreatorID, nil
|
||||
}
|
||||
|
||||
// AgentCreatorLookup resolves :id -> CustomAgent.CreatedBy. Built-in
|
||||
// agents (IsBuiltin == true) are tenant-owned across the board: they
|
||||
// belong to the tenant rather than to any one user, so we return
|
||||
@@ -105,6 +138,7 @@ func (h *CustomAgentHandler) AgentCreatorLookup(c *gin.Context) (string, error)
|
||||
// so route wiring stays type-safe even if a signature drifts.
|
||||
var (
|
||||
_ middleware.CreatorLookup = (*KnowledgeBaseHandler)(nil).KBCreatorLookup
|
||||
_ middleware.CreatorLookup = (*KnowledgeBaseHandler)(nil).KBCreatorLookupFromKbIDParam
|
||||
_ middleware.CreatorLookup = (*CustomAgentHandler)(nil).AgentCreatorLookup
|
||||
_ middleware.CreatorLookup = (*KnowledgeHandler)(nil).KBCreatorLookupFromKnowledgeID
|
||||
_ middleware.CreatorLookup = (*ChunkHandler)(nil).KBCreatorLookupFromKnowledgeIDParam
|
||||
|
||||
@@ -31,6 +31,9 @@ type rbacGuards struct {
|
||||
// to be exported into every Register* function as well.
|
||||
kbCreator middleware.CreatorLookup
|
||||
agentCreator middleware.CreatorLookup
|
||||
// kbCreatorFromKbIDParam reads :kbId (not :id) for the
|
||||
// /initialization/* routes whose KB is addressed by :kbId.
|
||||
kbCreatorFromKbIDParam middleware.CreatorLookup
|
||||
// Per-KB-ownership lookups for knowledge / chunk / wiki page routes
|
||||
// (PR 5, #1303). They walk the URL param back to KB.CreatorID so a
|
||||
// Contributor who owns the KB can edit/delete its sub-resources
|
||||
@@ -54,6 +57,7 @@ func newRBACGuards(
|
||||
g := &rbacGuards{cfg: cfg}
|
||||
if kbHandler != nil {
|
||||
g.kbCreator = kbHandler.KBCreatorLookup
|
||||
g.kbCreatorFromKbIDParam = kbHandler.KBCreatorLookupFromKbIDParam
|
||||
}
|
||||
if agentHandler != nil {
|
||||
g.agentCreator = agentHandler.AgentCreatorLookup
|
||||
@@ -100,6 +104,15 @@ func (g *rbacGuards) OwnedKBOrAdmin() gin.HandlerFunc {
|
||||
return middleware.RequireOwnershipOrRole(types.TenantRoleAdmin, g.kbCreator, g.cfg)
|
||||
}
|
||||
|
||||
// OwnedKBOrAdminFromKbIDParam is the same matrix as OwnedKBOrAdmin but
|
||||
// addresses the KB via :kbId (used by /initialization/* routes). KB
|
||||
// configuration changes — picking the embedding/parser/storage
|
||||
// engine, materialising indexes — are at least as sensitive as
|
||||
// updating the KB itself, so they share the "creator OR Admin+" rule.
|
||||
func (g *rbacGuards) OwnedKBOrAdminFromKbIDParam() gin.HandlerFunc {
|
||||
return middleware.RequireOwnershipOrRole(types.TenantRoleAdmin, g.kbCreatorFromKbIDParam, g.cfg)
|
||||
}
|
||||
|
||||
// OwnedAgentOrAdmin: same shape as OwnedKBOrAdmin but for CustomAgent.
|
||||
// Built-in agents (IsBuiltin=true) are tenant-owned; their creator
|
||||
// lookup returns "" and only Admin+ may mutate them.
|
||||
|
||||
+52
-33
@@ -176,9 +176,9 @@ func NewRouter(params RouterParams) *gin.Engine {
|
||||
RegisterChatRoutes(v1, params.SessionHandler, rbacGuards)
|
||||
RegisterMessageRoutes(v1, params.MessageHandler, rbacGuards)
|
||||
RegisterModelRoutes(v1, params.ModelHandler, params.ModelCredentialsHandler, rbacGuards)
|
||||
RegisterEvaluationRoutes(v1, params.EvaluationHandler)
|
||||
RegisterInitializationRoutes(v1, params.InitializationHandler)
|
||||
RegisterSystemRoutes(v1, params.SystemHandler)
|
||||
RegisterEvaluationRoutes(v1, params.EvaluationHandler, rbacGuards)
|
||||
RegisterInitializationRoutes(v1, params.InitializationHandler, rbacGuards)
|
||||
RegisterSystemRoutes(v1, params.SystemHandler, rbacGuards)
|
||||
RegisterMCPServiceRoutes(v1, params.MCPServiceHandler, params.MCPCredentialsHandler, rbacGuards)
|
||||
RegisterWebSearchRoutes(v1, params.WebSearchHandler, rbacGuards)
|
||||
RegisterWebSearchProviderRoutes(v1, params.WebSearchProviderHandler, params.WebSearchCredentialsHandler, rbacGuards)
|
||||
@@ -473,7 +473,11 @@ func RegisterTenantRoutes(
|
||||
// 租户路由组
|
||||
tenantRoutes := r.Group("/tenants")
|
||||
{
|
||||
tenantRoutes.POST("", handler.CreateTenant)
|
||||
// 创建租户是组织级管理动作(建一个新租户只有 cross-tenant
|
||||
// 超管可以做),所以挂 g.CrossTenant() — 与 /tenants/all、
|
||||
// /tenants/search 保持一致。普通用户的租户在登录/auto-setup
|
||||
// 链路里隐式创建,不走这个端点。
|
||||
tenantRoutes.POST("", g.CrossTenant(), handler.CreateTenant)
|
||||
tenantRoutes.GET("", handler.ListTenants)
|
||||
|
||||
// Generic KV configuration management (tenant-level). Tenant ID
|
||||
@@ -548,11 +552,15 @@ func RegisterModelRoutes(
|
||||
}
|
||||
}
|
||||
|
||||
func RegisterEvaluationRoutes(r *gin.RouterGroup, handler *handler.EvaluationHandler) {
|
||||
// RegisterEvaluationRoutes registers evaluation endpoints. Running an
|
||||
// evaluation drives LLM calls (cost) and reads from KBs across the
|
||||
// tenant; gate to Admin+ until product asks for a finer-grained
|
||||
// matrix.
|
||||
func RegisterEvaluationRoutes(r *gin.RouterGroup, handler *handler.EvaluationHandler, g *rbacGuards) {
|
||||
evaluationRoutes := r.Group("/evaluation")
|
||||
{
|
||||
evaluationRoutes.POST("/", handler.Evaluation)
|
||||
evaluationRoutes.GET("/", handler.GetEvaluationResult)
|
||||
evaluationRoutes.POST("/", g.Admin(), handler.Evaluation)
|
||||
evaluationRoutes.GET("/", g.Viewer(), handler.GetEvaluationResult)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -573,42 +581,53 @@ func RegisterAuthRoutes(r *gin.RouterGroup, handler *handler.AuthHandler) {
|
||||
r.POST("/auth/change-password", handler.ChangePassword)
|
||||
}
|
||||
|
||||
func RegisterInitializationRoutes(r *gin.RouterGroup, handler *handler.InitializationHandler) {
|
||||
func RegisterInitializationRoutes(r *gin.RouterGroup, handler *handler.InitializationHandler, g *rbacGuards) {
|
||||
// 初始化接口
|
||||
r.GET("/initialization/config/:kbId", handler.GetCurrentConfigByKB)
|
||||
r.POST("/initialization/initialize/:kbId", handler.InitializeByKB)
|
||||
r.PUT("/initialization/config/:kbId", handler.UpdateKBConfig) // 新的简化版接口,只传模型ID
|
||||
// GetCurrentConfigByKB 是只读,Viewer+ 即可。
|
||||
r.GET("/initialization/config/:kbId", g.Viewer(), handler.GetCurrentConfigByKB)
|
||||
// InitializeByKB / UpdateKBConfig 都是改 KB 的核心模型/storage 配置 —
|
||||
// 跟 PUT /knowledge-bases/:id 同等敏感,挂同款 OwnedKB 矩阵。
|
||||
r.POST("/initialization/initialize/:kbId", g.OwnedKBOrAdminFromKbIDParam(), handler.InitializeByKB)
|
||||
r.PUT("/initialization/config/:kbId", g.OwnedKBOrAdminFromKbIDParam(), handler.UpdateKBConfig)
|
||||
|
||||
// Ollama相关接口
|
||||
r.GET("/initialization/ollama/status", handler.CheckOllamaStatus)
|
||||
r.GET("/initialization/ollama/models", handler.ListOllamaModels)
|
||||
r.POST("/initialization/ollama/models/check", handler.CheckOllamaModels)
|
||||
r.POST("/initialization/ollama/models/download", handler.DownloadOllamaModel)
|
||||
r.GET("/initialization/ollama/download/progress/:taskId", handler.GetDownloadProgress)
|
||||
r.GET("/initialization/ollama/download/tasks", handler.ListDownloadTasks)
|
||||
// Ollama / 远程 API / 抽取等系统级检测/下载操作。这些不绑某个 KB,
|
||||
// 但会改租户级模型配置或拉远端模型 — 一律 Admin+。Viewer+ 的检测
|
||||
// 入口已经在 settings 页面隐藏,但服务端仍要兜底。
|
||||
r.GET("/initialization/ollama/status", g.Viewer(), handler.CheckOllamaStatus)
|
||||
r.GET("/initialization/ollama/models", g.Viewer(), handler.ListOllamaModels)
|
||||
r.POST("/initialization/ollama/models/check", g.Admin(), handler.CheckOllamaModels)
|
||||
r.POST("/initialization/ollama/models/download", g.Admin(), handler.DownloadOllamaModel)
|
||||
r.GET("/initialization/ollama/download/progress/:taskId", g.Viewer(), handler.GetDownloadProgress)
|
||||
r.GET("/initialization/ollama/download/tasks", g.Viewer(), handler.ListDownloadTasks)
|
||||
|
||||
// 远程API相关接口
|
||||
r.POST("/initialization/remote/check", handler.CheckRemoteModel)
|
||||
r.POST("/initialization/embedding/test", handler.TestEmbeddingModel)
|
||||
r.POST("/initialization/rerank/check", handler.CheckRerankModel)
|
||||
r.POST("/initialization/asr/check", handler.CheckASRModel)
|
||||
r.POST("/initialization/multimodal/test", handler.TestMultimodalFunction)
|
||||
r.POST("/initialization/remote/check", g.Admin(), handler.CheckRemoteModel)
|
||||
r.POST("/initialization/embedding/test", g.Admin(), handler.TestEmbeddingModel)
|
||||
r.POST("/initialization/rerank/check", g.Admin(), handler.CheckRerankModel)
|
||||
r.POST("/initialization/asr/check", g.Admin(), handler.CheckASRModel)
|
||||
r.POST("/initialization/multimodal/test", g.Admin(), handler.TestMultimodalFunction)
|
||||
|
||||
r.POST("/initialization/extract/text-relation", handler.ExtractTextRelations)
|
||||
r.POST("/initialization/extract/fabri-tag", handler.FabriTag)
|
||||
r.POST("/initialization/extract/fabri-text", handler.FabriText)
|
||||
r.POST("/initialization/extract/text-relation", g.Admin(), handler.ExtractTextRelations)
|
||||
r.POST("/initialization/extract/fabri-tag", g.Admin(), handler.FabriTag)
|
||||
r.POST("/initialization/extract/fabri-text", g.Admin(), handler.FabriText)
|
||||
}
|
||||
|
||||
// RegisterSystemRoutes registers system information routes
|
||||
func RegisterSystemRoutes(r *gin.RouterGroup, handler *handler.SystemHandler) {
|
||||
//
|
||||
// Reads (GetSystemInfo / ListParserEngines / GetStorageEngineStatus)
|
||||
// are gated to Viewer+ — any tenant member can see "is the parser
|
||||
// reachable". The /*-check / /reconnect endpoints actively probe
|
||||
// remote services with tenant credentials and could trigger network
|
||||
// fanout, so they're Admin+.
|
||||
func RegisterSystemRoutes(r *gin.RouterGroup, handler *handler.SystemHandler, g *rbacGuards) {
|
||||
systemRoutes := r.Group("/system")
|
||||
{
|
||||
systemRoutes.GET("/info", handler.GetSystemInfo)
|
||||
systemRoutes.GET("/parser-engines", handler.ListParserEngines)
|
||||
systemRoutes.POST("/parser-engines/check", handler.CheckParserEngines)
|
||||
systemRoutes.POST("/docreader/reconnect", handler.ReconnectDocReader)
|
||||
systemRoutes.GET("/storage-engine-status", handler.GetStorageEngineStatus)
|
||||
systemRoutes.POST("/storage-engine-check", handler.CheckStorageEngine)
|
||||
systemRoutes.GET("/info", g.Viewer(), handler.GetSystemInfo)
|
||||
systemRoutes.GET("/parser-engines", g.Viewer(), handler.ListParserEngines)
|
||||
systemRoutes.POST("/parser-engines/check", g.Admin(), handler.CheckParserEngines)
|
||||
systemRoutes.POST("/docreader/reconnect", g.Admin(), handler.ReconnectDocReader)
|
||||
systemRoutes.GET("/storage-engine-status", g.Viewer(), handler.GetStorageEngineStatus)
|
||||
systemRoutes.POST("/storage-engine-check", g.Admin(), handler.CheckStorageEngine)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user