fix(rbac): propagate TenantRole through logger.CloneContext

logger.CloneContext rebuilds a fresh context.Background() and only
copies a hand-curated allow-list of context keys (LoggerContextKey,
TenantIDContextKey, UserContextKey, etc.) before passing it to
downstream handlers — the chat / agent QA pipelines all do
`ctx := logger.CloneContext(c.Request.Context())` at the top of
parseQARequest.

TenantRoleContextKey was missing from that allow-list. Any call site
that read the role via TenantRoleFromContext(reqCtx.ctx) saw the
type-zero TenantRole and the helper's least-privilege fallback
returned Viewer. The auth middleware had set role=Owner correctly
on the parent context, but the cloned context lost it.

Symptom: an Owner of their home tenant got 403 on POST /agent-chat
when the agent had runnable_by_viewer=false, because the gate at
session/qa.go:520 saw role=viewer despite middleware logging
role=owner two ms earlier.

Diagnostic log lines added in the previous commits (auth.go:145
"[auth] resolved role=...", auth.go:283 "[auth] resolveTenantRole
step1 hit row_role=...") made this immediately visible — a request
showed role=owner at the middleware layer and role=viewer at the
handler layer, which can only mean ctx propagation lost it. Keeping
the diagnostic logs in place so similar regressions surface fast.

Fix is one line: add TenantRoleContextKey to the CloneContext
allow-list, with a comment pinning it to the bug it fixes so a
future drive-by removal has to weigh that loss.
This commit is contained in:
wizardchen
2026-05-14 23:32:16 +08:00
committed by lyingbug
parent f832bce16d
commit 0e1482bc4c
2 changed files with 34 additions and 0 deletions
+9
View File
@@ -411,6 +411,15 @@ func CloneContext(ctx context.Context) context.Context {
types.TenantInfoContextKey,
types.UserIDContextKey,
types.UserContextKey,
// TenantRoleContextKey: the caller's resolved role in the
// active tenant (PR 2 #1303). Must be propagated for the same
// reason as TenantIDContextKey — any handler that does
// `ctx := logger.CloneContext(c.Request.Context())` and then
// reads role via TenantRoleFromContext (e.g. session/qa.go's
// "viewer cannot run runnable_by_viewer=false agent" gate)
// would otherwise see the type-zero TenantRole and fall back
// to Viewer, blocking even Owners.
types.TenantRoleContextKey,
types.LanguageContextKey,
types.SessionTenantIDContextKey,
types.EmbedQueryContextKey,