refactor(terminology): rename user-facing tenant labels to workspace

Align product copy, API docs, Swagger descriptions, and i18n strings
with workspace terminology while keeping internal tenant identifiers
and headers unchanged for API compatibility.
This commit is contained in:
wizardchen
2026-07-14 16:13:49 +08:00
committed by lyingbug
parent e1572b71b9
commit 41975abcc5
161 changed files with 1865 additions and 1770 deletions
+7 -7
View File
@@ -106,7 +106,7 @@ func IsTenantAccessible(
// rather than inside one.
//
// Unlike RequireRole this is NOT modulated by cfg.Tenant.EnableRBAC:
// cross-tenant operations are always sensitive regardless of whether
// cross-workspace operations are always sensitive regardless of whether
// per-tenant RBAC is being enforced, so we never log-and-pass.
func RequireCrossTenantAccess(cfg *config.Config) gin.HandlerFunc {
return func(c *gin.Context) {
@@ -119,7 +119,7 @@ func RequireCrossTenantAccess(cfg *config.Config) gin.HandlerFunc {
logger.Warnf(ctx,
"[rbac] cross-tenant route blocked (EnableCrossTenantAccess=false): user=%s path=%s",
uid, c.Request.URL.Path)
_ = c.Error(apperrors.NewForbiddenError("Cross-tenant access is disabled"))
_ = c.Error(apperrors.NewForbiddenError("Cross-workspace access is disabled"))
c.Abort()
return
}
@@ -130,7 +130,7 @@ func RequireCrossTenantAccess(cfg *config.Config) gin.HandlerFunc {
"[rbac] cross-tenant route blocked (not a superuser): user=%s path=%s",
uid, c.Request.URL.Path)
_ = c.Error(apperrors.NewForbiddenError(
"Insufficient permissions for cross-tenant operation"))
"Insufficient permissions for cross-workspace operation"))
c.Abort()
return
}
@@ -156,13 +156,13 @@ func RequirePathTenantMatch(cfg *config.Config) gin.HandlerFunc {
ctx := c.Request.Context()
raw := strings.TrimSpace(c.Param("id"))
if raw == "" {
_ = c.Error(apperrors.NewValidationError("tenant id is required"))
_ = c.Error(apperrors.NewValidationError("workspace id is required"))
c.Abort()
return
}
pathTenantID, err := strconv.ParseUint(raw, 10, 64)
if err != nil || pathTenantID == 0 {
_ = c.Error(apperrors.NewValidationError("tenant id must be a positive integer"))
_ = c.Error(apperrors.NewValidationError("workspace id must be a positive integer"))
c.Abort()
return
}
@@ -172,7 +172,7 @@ func RequirePathTenantMatch(cfg *config.Config) gin.HandlerFunc {
// fail closed rather than silently treating "no context" as
// a match.
logger.Warnf(ctx, "[rbac] path-tenant-match: no tenant in ctx, path=%s", c.Request.URL.Path)
_ = c.Error(apperrors.NewUnauthorizedError("tenant context missing"))
_ = c.Error(apperrors.NewUnauthorizedError("workspace context missing"))
c.Abort()
return
}
@@ -189,7 +189,7 @@ func RequirePathTenantMatch(cfg *config.Config) gin.HandlerFunc {
"[rbac] path-tenant-match rejected: user=%s ctx_tenant=%d path_tenant=%d path=%s",
uid, ctxTenantID, pathTenantID, c.Request.URL.Path)
_ = c.Error(apperrors.NewForbiddenError(
"Access denied: URL tenant does not match the active tenant"))
"Access denied: URL workspace does not match the active workspace"))
c.Abort()
}
}
+1 -1
View File
@@ -9,7 +9,7 @@ import (
"github.com/gin-gonic/gin"
)
var errTenantAPIKeyScopeForbidden = stderrors.New("tenant api key scope forbidden")
var errTenantAPIKeyScopeForbidden = stderrors.New("workspace API key scope forbidden")
// APIKeyRoutePolicy declares how an X-API-Key caller may use a single route.
//
+21 -21
View File
@@ -155,8 +155,8 @@ func Auth(
crossTenantSwitch := targetTenantID != user.TenantID
tenantHeader := c.GetHeader("X-Tenant-ID")
if tenantHeader != "" {
// 解析目标租户ID。畸形 / 零值必须显式拒绝:静默忽略会让坏掉的
// 前端/SDK 悄悄写错租户,反而看不到问题。与 RequirePathTenantMatch
// 解析目标空间ID。畸形 / 零值必须显式拒绝:静默忽略会让坏掉的
// 前端/SDK 悄悄写错空间,反而看不到问题。与 RequirePathTenantMatch
// 中对 :id 的校验保持一致(非空、可解析、>0)。
parsedTenantID, err := strconv.ParseUint(tenantHeader, 10, 64)
if err != nil || parsedTenantID == 0 {
@@ -169,11 +169,11 @@ func Auth(
c.Abort()
return
}
// 检查用户是否有权限访问目标租户:自家租户、跨租户超管、或
// 检查用户是否有权限访问目标空间:自家空间、跨空间超管、或
// 有 active membership 行——三选一,由 IsTenantAccessible
// 统一判定。
if IsTenantAccessible(c.Request.Context(), user, parsedTenantID, memberService, cfg) {
// 验证目标租户是否存在
// 验证目标空间是否存在
targetTenant, err := tenantService.GetTenantByID(c.Request.Context(), parsedTenantID)
if err == nil && targetTenant != nil {
targetTenantID = parsedTenantID
@@ -182,16 +182,16 @@ func Auth(
} else {
log.Printf("Error getting target tenant by ID: %v, tenantID: %d", err, parsedTenantID)
c.JSON(http.StatusBadRequest, gin.H{
"error": "Invalid target tenant ID",
"error": "Invalid target workspace ID",
})
c.Abort()
return
}
} else {
// 用户没有权限访问目标租户
// 用户没有权限访问目标空间
log.Printf("User %s attempted to access tenant %d without permission", user.ID, parsedTenantID)
c.JSON(http.StatusForbidden, gin.H{
"error": "Forbidden: insufficient permissions to access target tenant",
"error": "Forbidden: insufficient permissions to access target workspace",
})
c.Abort()
return
@@ -210,25 +210,25 @@ func Auth(
return
}
c.JSON(http.StatusConflict, gin.H{
"error": "Tenant required",
"error": "Workspace required",
"code": "TENANT_REQUIRED",
})
c.Abort()
return
}
// 获取租户信息(使用目标租户ID)
// 获取空间信息(使用目标空间ID)
tenant, err := tenantService.GetTenantByID(c.Request.Context(), targetTenantID)
if err != nil {
log.Printf("Error getting tenant by ID: %v, tenantID: %d, userID: %s", err, targetTenantID, user.ID)
c.JSON(http.StatusUnauthorized, gin.H{
"error": "Unauthorized: invalid tenant",
"error": "Unauthorized: invalid workspace",
})
c.Abort()
return
}
// 解析当前租户内的角色 (issue #1303)
// 解析当前空间内的角色 (issue #1303)
role, ok := resolveTenantRole(c.Request.Context(), memberService, user, targetTenantID, crossTenantSwitch, cfg)
if !ok {
// 强制 RBAC 时,缺少 active membership 即拒绝;fail-open 路径已在
@@ -236,13 +236,13 @@ func Auth(
logger.Warnf(c.Request.Context(),
"User %s has no active membership in tenant %d", user.ID, targetTenantID)
c.JSON(http.StatusForbidden, gin.H{
"error": "Forbidden: not a member of the target tenant",
"error": "Forbidden: not a member of the target workspace",
})
c.Abort()
return
}
// 存储用户和租户信息到上下文
// 存储用户和空间信息到上下文
logger.Infof(c.Request.Context(),
"[auth] resolved role=%s for user=%s in tenant=%d (jwt_tenant=%d, header=%q, cross_switch=%v)",
role, user.ID, targetTenantID, jwtTenantID, tenantHeader, crossTenantSwitch)
@@ -503,7 +503,7 @@ func verifyExternalUserJWT(tokenString string, tenantID uint64, secret string) (
return "", errors.New("token not yet valid")
}
if got := principalTenantIDFromClaims(claims); got != tenantID {
return "", fmt.Errorf("tenant mismatch: got %d want %d", got, tenantID)
return "", fmt.Errorf("workspace mismatch: got %d want %d", got, tenantID)
}
sub, _ := claims["sub"].(string)
sub = strings.TrimSpace(sub)
@@ -637,8 +637,8 @@ func resolveTenantRole(
user.ID, targetTenantID, statusInfo)
}
// 2. 跨租户超管直通:CanAccessAllTenants 用户切到别的租户时不强制要求 membership。
// 注意:这里只授予临时 Admin 角色,不写入 tenant_members,避免"看一眼别人租户"
// 2. 跨空间超管直通:CanAccessAllTenants 用户切到别的空间时不强制要求 membership。
// 注意:这里只授予临时 Admin 角色,不写入 tenant_members,避免"看一眼别人空间"
// 意外升级为持久化所有权。
if crossTenantSwitch && user.CanAccessAllTenants {
logger.Infof(ctx,
@@ -647,9 +647,9 @@ func resolveTenantRole(
return types.TenantRoleAdmin, true
}
// 3. 孤儿租户自愈:仅当用户登录的是自己的 home tenant、且该租户尚无任何活跃成员时
// 允许自动晋升为 Owner。跨租户 switch / JWT 指向他人租户的场景一律不进入此分支,
// 防止越权获得他人租户的 Owner 权限。
// 3. 孤儿空间自愈:仅当用户登录的是自己的 home tenant、且该空间尚无任何活跃成员时
// 允许自动晋升为 Owner。跨空间 switch / JWT 指向他人空间的场景一律不进入此分支,
// 防止越权获得他人空间的 Owner 权限。
isHomeTenant := !crossTenantSwitch && targetTenantID == user.TenantID
if isHomeTenant {
hasAny, anyErr := memberService.HasAnyMembers(ctx, targetTenantID)
@@ -679,7 +679,7 @@ func resolveTenantRole(
logger.Warnf(ctx,
"[auth] resolveTenantRole step4 fail-open (EnableRBAC=false) -> Admin: user=%s tenant=%d",
user.ID, targetTenantID)
// fail-open 期间保持现有行为(每个登录用户在自己租户里都是"管理员")。
// fail-open 期间保持现有行为(每个登录用户在自己空间里都是"管理员")。
return types.TenantRoleAdmin, true
}
@@ -687,7 +687,7 @@ func resolveTenantRole(
func GetTenantIDFromContext(ctx context.Context) (uint64, error) {
tenantID, ok := ctx.Value("tenantID").(uint64)
if !ok {
return 0, errors.New("tenant ID not found in context")
return 0, errors.New("workspace ID not found in context")
}
return tenantID, nil
}
+5 -5
View File
@@ -160,7 +160,7 @@ func TestResolveTenantRole_ActiveMembershipWins(t *testing.T) {
}
func TestResolveTenantRole_CrossTenantSuperuserGetsAdmin_NoAutoPromote(t *testing.T) {
// 回归 H1:跨租户超管 switch 到他人租户时,绝对不能写入 tenant_members。
// 回归 H1:跨空间超管 switch 到他人空间时,绝对不能写入 tenant_members。
svc := newFakeMemberService()
user := &types.User{ID: "super", TenantID: 1, CanAccessAllTenants: true}
@@ -174,9 +174,9 @@ func TestResolveTenantRole_CrossTenantSuperuserGetsAdmin_NoAutoPromote(t *testin
}
func TestResolveTenantRole_AutoPromoteRequiresHomeTenant(t *testing.T) {
// 回归 H1:即便 target 是孤儿租户,只要不是用户自己的 home tenant,
// 回归 H1:即便 target 是孤儿空间,只要不是用户自己的 home tenant,
// 就不能 auto-promote 为 Owner。
svc := newFakeMemberService() // 空 — 任何租户都是孤儿
svc := newFakeMemberService() // 空 — 任何空间都是孤儿
user := &types.User{ID: "u1", TenantID: 1, CanAccessAllTenants: true}
got, ok := resolveTenantRole(context.Background(), svc, user, 42, true, cfgWithRBAC(true))
@@ -189,7 +189,7 @@ func TestResolveTenantRole_AutoPromoteRequiresHomeTenant(t *testing.T) {
}
func TestResolveTenantRole_AutoPromoteHomeTenant(t *testing.T) {
// home tenant + 孤儿租户 + 非 switch → 允许 auto-promote 为 Owner。
// home tenant + 孤儿空间 + 非 switch → 允许 auto-promote 为 Owner。
svc := newFakeMemberService()
user := &types.User{ID: "u1", TenantID: 7}
@@ -242,7 +242,7 @@ func TestResolveTenantRole_LookupErrorFailsOpenWhenRBACDisabled(t *testing.T) {
// 选与 home 不同的值,避免进入 home-tenant auto-promote 分支。
svc := newFakeMemberService()
svc.failGet = errors.New("transient db failure")
// 让 HasAnyMembers 返回 true,关闭孤儿租户自愈路径。
// 让 HasAnyMembers 返回 true,关闭孤儿空间自愈路径。
svc.seedActive("placeholder", 8, types.TenantRoleAdmin)
user := &types.User{ID: "u1", TenantID: 7}
+1 -1
View File
@@ -150,7 +150,7 @@ func EmbedAuth(
tenant, err := tenantSvc.GetTenantByID(c.Request.Context(), ch.TenantID)
if err != nil || tenant == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "tenant unavailable"})
c.JSON(http.StatusInternalServerError, gin.H{"error": "workspace unavailable"})
c.Abort()
return
}
+1 -1
View File
@@ -404,7 +404,7 @@ func resolveSharedAgentAccess(
return nil
}
if kb.TenantID != agent.TenantID {
logger.Warnf(ctx, "[kb_access] shared agent tenant mismatch: kb=%s kb.tenant=%d agent.tenant=%d",
logger.Warnf(ctx, "[kb_access] shared agent workspace mismatch: kb=%s kb.tenant=%d agent.tenant=%d",
kb.ID, kb.TenantID, agent.TenantID)
return nil
}
+2 -2
View File
@@ -104,7 +104,7 @@ func RequireRole(min types.TenantRole, cfg *config.Config) gin.HandlerFunc {
_ = svc.LogDenied(ctx, c, tenantID, uid, string(role), min)
}
c.JSON(http.StatusForbidden, gin.H{
"error": "Forbidden: insufficient tenant role",
"error": "Forbidden: insufficient workspace role",
})
c.Abort()
}
@@ -137,7 +137,7 @@ func RequireRoleOrSystemAdmin(min types.TenantRole, cfg *config.Config) gin.Hand
// System administrators operate independently of tenant-scoped roles and
// are not bound by the per-tenant RBAC matrix. Use this guard for
// platform-wide administrative endpoints (managing other system admins,
// editing global settings, cross-tenant operations) where the per-tenant
// editing global settings, cross-workspace operations) where the per-tenant
// Owner/Admin/Contributor/Viewer ladder does not apply.
//
// Unlike tenant-role guards, this check is always enforced. The