feat(gateway): 多租户2b-A —— Task 加 owner/tenant 隔离 + 系统旁路修 admin 全局口径

- store.WithoutTenant(ctx):显式跨租户旁路,插件即使 ctx 带租户也不过滤。
  修复增量2 引入的回归:admin SystemCounts 数 KB 时被 admin 自己租户误过滤。
  AdminOverview 改用旁路 ctx → 任务/KB/Doc/Eval 恢复全平台口径。
- Task 加 TenantID(插件自动填) + Owner(提交者 user.id) + isTenantScoped()。
  SaveTask 记录 owner;RecentTasks/RecentRuns 按 owner+租户过滤"我的运行"。
  RecentRuns 是 raw Table 查询绕过插件,手动补 owner+tenant WHERE。

live 验证:A 提交任务 → 行 owner/tenant 自动填对 ✓;A 的 /runs 只见己方、
B 空、legacy 无 owner 行被排除 ✓;admin/overview tasks_total=39/kb_count=21
= DB 全局真值(旁路生效,回归已修)✓。

Eval/Doc/DocLink 的 tenant 传播见 2b-B。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Blizzard
2026-07-07 09:18:15 +08:00
parent 30d667954b
commit ee1e9cfdca
5 changed files with 46 additions and 19 deletions
@@ -16,6 +16,7 @@ type tenantScopedMarker interface{ isTenantScoped() }
// ---- 请求上下文携带 tenant_id(中间件注入 → 传到 store → 插件读取)----
type ctxKeyTenant struct{}
type ctxKeySystem struct{}
// WithTenant 把 tenant_id 放进 context(空则原样返回,避免污染系统/回填查询)。
func WithTenant(ctx context.Context, tenantID string) context.Context {
@@ -25,6 +26,20 @@ func WithTenant(ctx context.Context, tenantID string) context.Context {
return context.WithValue(ctx, ctxKeyTenant{}, tenantID)
}
// WithoutTenant 标记本次操作为「系统/跨租户」——即使 ctx 里带着某租户(如 admin 自己的),
// 插件也**不**加 tenant 过滤。用于 admin 系统级聚合、跨租户后台任务等需全平台可见的路径。
func WithoutTenant(ctx context.Context) context.Context {
return context.WithValue(ctx, ctxKeySystem{}, true)
}
func isSystemCtx(ctx context.Context) bool {
if ctx == nil {
return false
}
b, _ := ctx.Value(ctxKeySystem{}).(bool)
return b
}
func tenantFromCtx(ctx context.Context) string {
if ctx == nil {
return ""
@@ -53,7 +68,7 @@ func isTenantScopedStmt(db *gorm.DB) bool {
// addTenantWhere:受租户模型 + ctx 有 tenant → 追加 tenant_id 过滤。
// ctx 无 tenant(系统/回填/未登录)→ 不过滤(这些路径本就需跨租户;用户面由中间件保证有 tenant)。
func addTenantWhere(db *gorm.DB) {
if !isTenantScopedStmt(db) {
if !isTenantScopedStmt(db) || isSystemCtx(db.Statement.Context) {
return
}
if tid := tenantFromCtx(db.Statement.Context); tid != "" {
@@ -65,7 +80,7 @@ func addTenantWhere(db *gorm.DB) {
// setTenantOnCreate:受租户模型 + ctx 有 tenant → 强制把 tenant_id 设为 ctx 租户(防越权写他租)。
func setTenantOnCreate(db *gorm.DB) {
if !isTenantScopedStmt(db) {
if !isTenantScopedStmt(db) || isSystemCtx(db.Statement.Context) {
return
}
if tid := tenantFromCtx(db.Statement.Context); tid != "" {