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
+1 -1
View File
@@ -174,7 +174,7 @@ var (
// ErrPendingNotFound is returned when Resolve is called with an unknown id.
ErrPendingNotFound = errors.New("tool approval pending not found")
// ErrTenantMismatch is returned when Resolve tenant does not match the pending request.
ErrTenantMismatch = errors.New("tenant mismatch for tool approval")
ErrTenantMismatch = errors.New("workspace mismatch for tool approval")
// ErrAlreadyResolved is returned when Resolve loses the race against a
// timeout / cancellation: the waiter is still in the map but its decision
// channel was already consumed by the timer/ctx branch.
+3 -3
View File
@@ -144,11 +144,11 @@ func (t *WebSearchTool) Execute(ctx context.Context, args json.RawMessage) (*typ
}
if tenantID == 0 {
logger.Errorf(ctx, "[Tool][WebSearch] Tenant ID not found in context")
logger.Errorf(ctx, "[Tool][WebSearch] Workspace ID not found in context")
return &types.ToolResult{
Success: false,
Error: "tenant ID not found in context",
}, fmt.Errorf("tenant ID not found in context")
Error: "workspace ID not found in context",
}, fmt.Errorf("workspace ID not found in context")
}
// Get tenant info from context (same approach as search.go)
@@ -293,8 +293,8 @@ func (s *embedChannelService) chunkAllowedForEmbed(
if chunk == nil || chunk.KnowledgeBaseID == "" {
return false
}
// 显式重校验租户:GetChunkByIDOnly 无租户过滤,且 KBSelectionMode=="all"/默认
// 分支会无条件放行,必须在此挡住跨租户 chunk id 撞库读取他人知识库正文。
// 显式重校验空间:GetChunkByIDOnly 无空间过滤,且 KBSelectionMode=="all"/默认
// 分支会无条件放行,必须在此挡住跨空间 chunk id 撞库读取他人知识库正文。
if ch == nil || chunk.TenantID != ch.TenantID {
return false
}
+1 -1
View File
@@ -498,7 +498,7 @@ func (s *DataTableSummaryService) prepareResources(ctx context.Context, payload
return nil, fmt.Errorf("unsupported file type: %s", fileType)
}
// 获取租户信息
// 获取空间信息
tenantInfo, err := s.tenantService.GetTenantByID(ctx, payload.TenantID)
if err != nil {
logger.Errorf(ctx, "failed to get tenant: %v", err)
+6 -6
View File
@@ -414,11 +414,11 @@ func (s *knowledgeService) isKnowledgeAborted(
// checkStorageEngineConfigured verifies that the knowledge base has a storage engine configured
// (either at the KB level or via the tenant default).
//
// 内部版兜底语义:当 KB 与租户都未配置 storage provider 时,如果服务实例持有
// 内部版兜底语义:当 KB 与空间都未配置 storage provider 时,如果服务实例持有
// 全局 FileService(由容器按 STORAGE_TYPE 注入,默认 local),允许直接落到该
// 全局 fileSvc 上,不再硬性阻断。这与 resolveFileService / resolveFileServiceForPath
// 在 provider 为空时回退到 s.fileSvc 的行为保持一致,避免上层闸门和下游解析口径不一。
// 仅当 KB/租户/全局三处都拿不到任何可用 FileService 时才报错。
// 仅当 KB/空间/全局三处都拿不到任何可用 FileService 时才报错。
func (s *knowledgeService) checkStorageEngineConfigured(ctx context.Context, kb *types.KnowledgeBase) error {
provider := kb.GetStorageProvider()
if provider == "" {
@@ -498,7 +498,7 @@ func (s *knowledgeService) GetOwningKBCreatorID(ctx context.Context, knowledgeID
// minimal and tenant-scoped.
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
if !ok {
return "", werrors.NewUnauthorizedError("Tenant ID not found in context")
return "", werrors.NewUnauthorizedError("Workspace ID not found in context")
}
knowledge, err := s.repo.GetKnowledgeByID(ctx, tenantID, knowledgeID)
if err != nil {
@@ -791,11 +791,11 @@ func (s *knowledgeService) UpdateKnowledgeTagBatch(ctx context.Context, authoriz
}
tenantIDVal := ctx.Value(types.TenantIDContextKey)
if tenantIDVal == nil {
return werrors.NewUnauthorizedError("tenant ID not found in context")
return werrors.NewUnauthorizedError("workspace ID not found in context")
}
tenantID, ok := tenantIDVal.(uint64)
if !ok {
return werrors.NewUnauthorizedError("invalid tenant ID in context")
return werrors.NewUnauthorizedError("invalid workspace ID in context")
}
// Get all knowledge items in batch
@@ -882,7 +882,7 @@ func (s *knowledgeService) UpdateKnowledgeTagBatch(ctx context.Context, authoriz
func (s *knowledgeService) SearchKnowledge(ctx context.Context, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, int64, error) {
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
if !ok {
return nil, false, 0, werrors.NewUnauthorizedError("Tenant ID not found in context")
return nil, false, 0, werrors.NewUnauthorizedError("Workspace ID not found in context")
}
scopes := make([]types.KnowledgeSearchScope, 0)
@@ -1899,7 +1899,7 @@ func (s *knowledgeService) UpdateLastFAQImportResultDisplayStatus(ctx context.Co
return werrors.NewBadRequestError("invalid display status, must be 'open' or 'close'")
}
// 获取当前租户ID
// 获取当前空间ID
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
// 查找FAQ类型的knowledge
+4 -4
View File
@@ -167,8 +167,8 @@ func (s *messageService) GetRecentMessagesBySession(ctx context.Context,
tenantID, ok := sessionTenantIDForLookup(ctx)
if !ok {
logger.Error(ctx, "Tenant ID not found in context for session lookup")
return nil, errors.New("tenant ID not found in context")
logger.Error(ctx, "Workspace ID not found in context for session lookup")
return nil, errors.New("workspace ID not found in context")
}
logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID)
_, err := s.sessionRepo.Get(ctx, tenantID, sessionUserIDForLookup(ctx), sessionID)
@@ -200,8 +200,8 @@ func (s *messageService) GetMessagesBySessionBeforeTime(ctx context.Context,
tenantID, ok := sessionTenantIDForLookup(ctx)
if !ok {
logger.Error(ctx, "Tenant ID not found in context for session lookup")
return nil, errors.New("tenant ID not found in context")
logger.Error(ctx, "Workspace ID not found in context for session lookup")
return nil, errors.New("workspace ID not found in context")
}
logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID)
_, err := s.sessionRepo.Get(ctx, tenantID, sessionUserIDForLookup(ctx), sessionID)
+1 -1
View File
@@ -64,7 +64,7 @@ func (s *modelService) decryptAppSecret(encrypted string) string {
}
// resolveWeKnoraCloudCredentials 为 WeKnoraCloud 厂商模型补全 AppID/AppSecret。
// 当模型自身参数中未存储凭证时,自动从租户配置中获取(SaveCredentials 保存的凭证)。
// 当模型自身参数中未存储凭证时,自动从空间配置中获取(SaveCredentials 保存的凭证)。
func (s *modelService) resolveWeKnoraCloudCredentials(ctx context.Context, params *types.ModelParameters) (appID, appSecret string) {
appID = params.AppID
appSecret = s.decryptAppSecret(params.AppSecret)
+1 -1
View File
@@ -142,7 +142,7 @@ func (s *sessionService) GetSessionByID(ctx context.Context, tenantID uint64, id
return nil, stderrors.New("session id is required")
}
if tenantID == 0 {
return nil, stderrors.New("tenant id is required")
return nil, stderrors.New("workspace id is required")
}
return s.sessionRepo.GetByID(ctx, tenantID, id)
}
@@ -800,7 +800,7 @@ func (s *sessionService) SearchKnowledge(ctx context.Context,
tenantID, ok := types.TenantIDFromContext(ctx)
if !ok {
logger.Error(ctx, "Failed to get tenant ID from context")
return nil, fmt.Errorf("tenant ID not found in context")
return nil, fmt.Errorf("workspace ID not found in context")
}
// Build unified search targets (computed once, used throughout pipeline)
+10 -10
View File
@@ -141,8 +141,8 @@ var registry = map[string]settingSpec{
Default: "create_personal",
Enum: []string{"create_personal", "tenantless"},
Category: "auth",
Description: "公开注册成功后的默认租户策略。create_personal = 自动创建个人租户并设为 Owner;" +
"tenantless = 仅创建用户,等待接受邀请或主动创建租户。修改后只影响新注册用户。",
Description: "公开注册成功后的默认空间策略。create_personal = 自动创建个人空间并设为 Owner;" +
"tenantless = 仅创建用户,等待接受邀请或主动创建空间。修改后只影响新注册用户。",
},
// tenant.max_owned_per_user caps how many tenants a single non-superuser
// can create (and Own) via self-service POST /tenants. Read on every
@@ -156,7 +156,7 @@ var registry = map[string]settingSpec{
EnvName: "WEKNORA_TENANT_MAX_OWNED_PER_USER",
Default: int64(10),
Category: "tenant",
Description: "每个非超管用户通过自助创建可拥有的最大租户数。每次创建租户时实时读取," +
Description: "每个非超管用户通过自助创建可拥有的最大空间数。每次创建空间时实时读取," +
"修改后立即生效。0 表示使用内置默认值 10;负数表示完全关闭限制(不建议在公开部署使用)。",
},
"tenant.self_service_creation_enabled": {
@@ -164,8 +164,8 @@ var registry = map[string]settingSpec{
EnvName: "WEKNORA_TENANT_SELF_SERVICE_CREATION_ENABLED",
Default: true,
Category: "tenant",
Description: "是否允许非超管用户主动创建租户。关闭后,普通用户只能通过邀请加入已有租户;" +
"跨租户超管仍可创建。修改后立即生效。",
Description: "是否允许非超管用户主动创建空间。关闭后,普通用户只能通过邀请加入已有空间;" +
"跨空间超管仍可创建。修改后立即生效。",
},
// tenant.default_storage_quota_gb is the default storage quota (in GB)
// applied to a newly-created tenant when the caller doesn't specify
@@ -179,8 +179,8 @@ var registry = map[string]settingSpec{
EnvName: "WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_GB",
Default: int64(10),
Category: "tenant",
Description: "新建租户时默认分配的存储配额(GB),包含向量、原文、文本、索引等。" +
"仅在创建时读取,修改后只对之后新建的租户生效,不会回写已存在的租户。" +
Description: "新建空间时默认分配的存储配额(GB),包含向量、原文、文本、索引等。" +
"仅在创建时读取,修改后只对之后新建的空间生效,不会回写已存在的空间。" +
"0 或负数表示使用内置默认值 10GB。",
},
// tenant.auto_create_api_key restores the legacy behaviour where creating
@@ -196,9 +196,9 @@ var registry = map[string]settingSpec{
EnvName: "WEKNORA_TENANT_AUTO_CREATE_API_KEY",
Default: false,
Category: "tenant",
Description: "创建租户时是否自动生成一个全量权限(full_access)的 API Key,并在创建接口的响应中返回其明文 token。" +
"用于兼容旧版本「创建租户即下发默认 API Key」的行为(属于破坏性变更的回退开关)。" +
"每次创建租户时实时读取,修改后立即生效。默认 false(不自动创建,需通过 API Key 管理显式创建)。",
Description: "创建空间时是否自动生成一个全量权限(full_access)的 API Key,并在创建接口的响应中返回其明文 token。" +
"用于兼容旧版本「创建空间即下发默认 API Key」的行为(属于破坏性变更的回退开关)。" +
"每次创建空间时实时读取,修改后立即生效。默认 false(不自动创建,需通过 API Key 管理显式创建)。",
},
"asynq.core_concurrency": {
Type: "int",
+7 -7
View File
@@ -34,8 +34,8 @@ func (s *tenantService) CreateTenant(ctx context.Context, tenant *types.Tenant)
logger.Info(ctx, "Start creating tenant")
if tenant.Name == "" {
logger.Error(ctx, "Tenant name cannot be empty")
return nil, errors.New("tenant name cannot be empty")
logger.Error(ctx, "Workspace name cannot be empty")
return nil, errors.New("workspace name cannot be empty")
}
logger.Infof(ctx, "Creating tenant, name: %s", tenant.Name)
@@ -68,7 +68,7 @@ func (s *tenantService) CreateTenant(ctx context.Context, tenant *types.Tenant)
// GetTenantByID retrieves a tenant by their ID
func (s *tenantService) GetTenantByID(ctx context.Context, id uint64) (*types.Tenant, error) {
if id == 0 {
logger.Error(ctx, "Tenant ID cannot be 0")
logger.Error(ctx, "Workspace ID cannot be 0")
return nil, errors.New("tenant ID cannot be 0")
}
@@ -103,7 +103,7 @@ func (s *tenantService) ListTenants(ctx context.Context) ([]*types.Tenant, error
// UpdateTenant updates an existing tenant's information
func (s *tenantService) UpdateTenant(ctx context.Context, tenant *types.Tenant) (*types.Tenant, error) {
if tenant.ID == 0 {
logger.Error(ctx, "Tenant ID cannot be 0")
logger.Error(ctx, "Workspace ID cannot be 0")
return nil, errors.New("tenant ID cannot be 0")
}
@@ -135,7 +135,7 @@ func (s *tenantService) DeleteTenant(ctx context.Context, id uint64) error {
logger.Info(ctx, "Start deleting tenant")
if id == 0 {
logger.Error(ctx, "Tenant ID cannot be 0")
logger.Error(ctx, "Workspace ID cannot be 0")
return errors.New("tenant ID cannot be 0")
}
@@ -164,7 +164,7 @@ func (s *tenantService) DeleteTenant(ctx context.Context, id uint64) error {
return err
}
logger.Infof(ctx, "Tenant deleted successfully, ID: %d", id)
logger.Infof(ctx, "Workspace deleted successfully, ID: %d", id)
return nil
}
@@ -324,7 +324,7 @@ func (s *tenantService) validateStorageBucketUniqueness(ctx context.Context, ten
oldB := oldBuckets[p]
if b != oldB { // User is trying to change their bucket name or set a new one
if usedByOthers[p] != nil && usedByOthers[p][b] {
return werrors.NewBadRequestError("存储桶名称「" + b + "」已被其他租户使用,为保证数据隔离,请使用其他名称")
return werrors.NewBadRequestError("存储桶名称「" + b + "」已被其他空间使用,为保证数据隔离,请使用其他名称")
}
}
}
+5 -5
View File
@@ -154,7 +154,7 @@ func (s *userService) Register(ctx context.Context, req *types.RegisterRequest)
createdTenant, err = s.tenantService.CreateTenant(ctx, tenant)
if err != nil {
logger.Errorf(ctx, "Failed to create tenant")
logger.Errorf(ctx, "Failed to create workspace")
return nil, errors.New("failed to create workspace")
}
}
@@ -931,14 +931,14 @@ func (s *userService) SwitchTenant(
return nil, errors.New("user is required")
}
if targetTenantID == 0 {
return nil, errors.New("target tenant ID is required")
return nil, errors.New("target workspace ID is required")
}
// Verify membership unless the caller is a cross-tenant superuser
// switching outside their home tenant.
if !user.CanAccessAllTenants || targetTenantID == user.TenantID {
if s.memberService == nil {
return nil, errors.New("tenant membership service unavailable")
return nil, errors.New("workspace membership service unavailable")
}
member, err := s.memberService.GetMembership(ctx, user.ID, targetTenantID)
if err != nil {
@@ -951,7 +951,7 @@ func (s *userService) SwitchTenant(
tenant, err := s.tenantService.GetTenantByID(ctx, targetTenantID)
if err != nil {
return nil, fmt.Errorf("load target tenant: %w", err)
return nil, fmt.Errorf("load target workspace: %w", err)
}
accessToken, refreshToken, err := s.generateTokensForTenant(ctx, user, targetTenantID)
@@ -972,7 +972,7 @@ func (s *userService) SwitchTenant(
return &types.LoginResponse{
Success: true,
Message: "Tenant switched",
Message: "Workspace switched",
User: user,
ActiveTenant: tenant,
Memberships: memberships,
+1 -1
View File
@@ -94,7 +94,7 @@ func (s *WebSearchService) resolveProvider(
if providerID != "" {
tenantID, ok := types.TenantIDFromContext(ctx)
if !ok {
return nil, fmt.Errorf("tenant ID not found in context")
return nil, fmt.Errorf("workspace ID not found in context")
}
entity, err := s.providerRepo.GetByID(ctx, tenantID, providerID)
+1 -1
View File
@@ -116,7 +116,7 @@ func (s *weKnoraCloudService) CheckStatus(ctx context.Context) (*types.WeKnoraCl
return &types.WeKnoraCloudStatusResult{HasModels: true, NeedsReinit: false}, nil
}
// updateTenantCredentials 更新租户的 WeKnoraCloud 凭证
// updateTenantCredentials 更新空间的 WeKnoraCloud 凭证
func (s *weKnoraCloudService) updateTenantCredentials(ctx context.Context, tenantID uint64, appID, appSecret string) error {
if s.tenantRepo == nil {
return fmt.Errorf("tenant repository is required")
+1 -1
View File
@@ -195,7 +195,7 @@ type ImageProcessingConfig struct {
EnableMultimodal bool `yaml:"enable_multimodal" json:"enable_multimodal"`
}
// TenantConfig 租户配置
// TenantConfig 空间配置
type TenantConfig struct {
DefaultSessionName string `yaml:"default_session_name" json:"default_session_name"`
DefaultSessionTitle string `yaml:"default_session_title" json:"default_session_title"`
+4 -4
View File
@@ -162,7 +162,7 @@ func NewValidationError(message string) *AppError {
func NewTenantNotFoundError() *AppError {
return &AppError{
Code: ErrTenantNotFound,
Message: "租户不存在",
Message: "空间不存在",
HTTPCode: http.StatusNotFound,
}
}
@@ -171,7 +171,7 @@ func NewTenantNotFoundError() *AppError {
func NewTenantAlreadyExistsError() *AppError {
return &AppError{
Code: ErrTenantAlreadyExists,
Message: "租户已存在",
Message: "空间已存在",
HTTPCode: http.StatusConflict,
}
}
@@ -180,7 +180,7 @@ func NewTenantAlreadyExistsError() *AppError {
func NewTenantInactiveError() *AppError {
return &AppError{
Code: ErrTenantInactive,
Message: "租户已停用",
Message: "空间已停用",
HTTPCode: http.StatusForbidden,
}
}
@@ -190,7 +190,7 @@ func NewTenantInactiveError() *AppError {
func NewTenantCreationDisabledError() *AppError {
return &AppError{
Code: ErrTenantCreationDisabled,
Message: "self-service tenant creation is disabled; join a workspace by invitation",
Message: "self-service workspace creation is disabled; join a workspace by invitation",
HTTPCode: http.StatusForbidden,
}
}
+3 -3
View File
@@ -35,11 +35,11 @@ type auditLogListResponse struct {
}
// ListTenantAuditLog godoc
// @Summary 获取租户审计日志
// @Description 返回该租户最近的审计事件,按 id 倒序。游标分页:将上次响应的 next_cursor 作为下一次请求的 after_id。
// @Summary 获取空间审计日志
// @Description 返回该空间最近的审计事件,按 id 倒序。游标分页:将上次响应的 next_cursor 作为下一次请求的 after_id。
// @Tags 审计日志
// @Produce json
// @Param id path string true "租户ID"
// @Param id path string true "空间ID"
// @Param after_id query int false "游标:返回 id 小于此值的记录(默认从最新开始)"
// @Param limit query int false "页大小,1-100,默认 50"
// @Param action query string false "按 action 精确过滤(如 rbac.member_added / rbac.access_denied)"
+7 -7
View File
@@ -586,7 +586,7 @@ type updateMyPreferencesRequest struct {
EnableMemory *bool `json:"enable_memory"`
// LastActiveTenantID lets the SPA persist "after a fresh login,
// drop me back into this workspace" across devices. Send a positive
// tenant id to set / replace, or 0 to clear. Membership is validated
// workspace id to set / replace, or 0 to clear. Membership is validated
// at next login, not here. Nil = field omitted from the PATCH and
// stays untouched.
LastActiveTenantID *uint64 `json:"last_active_tenant_id"`
@@ -717,15 +717,15 @@ func (h *AuthHandler) GetAuthConfig(c *gin.Context) {
}
// SwitchTenant godoc
// @Summary 切换激活租户
// @Description 为当前用户在目标租户重新签发访问令牌;要求该用户在目标租户存在 active 成员关系
// @Summary 切换激活空间
// @Description 为当前用户在目标空间重新签发访问令牌;要求该用户在目标空间存在 active 成员关系
// @Tags 认证
// @Accept json
// @Produce json
// @Param request body object{tenant_id=integer,refresh_token=string} true "切换请求"
// @Success 200 {object} types.LoginResponse
// @Failure 400 {object} errors.AppError "参数错误"
// @Failure 403 {object} errors.AppError "无该租户成员关系"
// @Failure 403 {object} errors.AppError "无该空间成员关系"
// @Security Bearer
// @Router /auth/switch-tenant [post]
//
@@ -740,7 +740,7 @@ func (h *AuthHandler) SwitchTenant(c *gin.Context) {
RefreshToken string `json:"refresh_token"`
}
if err := c.ShouldBindJSON(&req); err != nil {
appErr := errors.NewValidationError("Invalid switch-tenant request").WithDetails(err.Error())
appErr := errors.NewValidationError("Invalid workspace switch request").WithDetails(err.Error())
c.Error(appErr)
return
}
@@ -755,7 +755,7 @@ func (h *AuthHandler) SwitchTenant(c *gin.Context) {
resp, err := h.userService.SwitchTenant(ctx, user, req.TenantID, req.RefreshToken)
if err != nil {
logger.Errorf(ctx, "SwitchTenant failed user=%s target=%d: %v", user.ID, req.TenantID, err)
appErr := errors.NewForbiddenError("switch tenant failed").WithDetails(err.Error())
appErr := errors.NewForbiddenError("workspace switch failed").WithDetails(err.Error())
c.Error(appErr)
return
}
@@ -764,7 +764,7 @@ func (h *AuthHandler) SwitchTenant(c *gin.Context) {
}
// @Summary 自动初始化(Lite 桌面版)
// @Description Lite 版专用:首次启动时自动创建默认用户和租户并返回令牌,后续启动直接签发令牌,免除手动注册/登录流程
// @Description Lite 版专用:首次启动时自动创建默认用户和空间并返回令牌,后续启动直接签发令牌,免除手动注册/登录流程
// @Tags 认证
// @Accept json
// @Produce json
+2 -2
View File
@@ -49,7 +49,7 @@ type invitationLookupRequest struct {
// LookupInvitationByToken godoc
// @Summary 解析共享邀请链接 token
// @Description 根据邀请链接中的 token 返回邀请上下文(租户名 / 角色 / 过期时间),
// @Description 根据邀请链接中的 token 返回邀请上下文(空间名 / 角色 / 过期时间),
// @Description 供注册页展示。无认证;token 无效或被撤销返回 410。
// @Description 使用 POST + body 而非 GET + path,避免 token 落入访问日志 / 浏览器历史 / tracing。
// @Tags 认证
@@ -107,7 +107,7 @@ func (h *AuthHandler) LookupInvitationByToken(c *gin.Context) {
// RegisterByInvite godoc
// @Summary 使用共享链接注册
// @Description 通过 Owner 生成的共享邀请链接 token 完成注册,绕过 invite_only 模式拦截。
// @Description 注册者自填邮箱(与 token 不绑定);注册成功后自动加入对应租户。
// @Description 注册者自填邮箱(与 token 不绑定);注册成功后自动加入对应空间。
// @Tags 认证
// @Accept json
// @Produce json
+5 -5
View File
@@ -171,7 +171,7 @@ func (h *CustomAgentHandler) GetAgent(c *gin.Context) {
// ListAgents godoc
// @Summary 获取智能体列表
// @Description 获取当前租户的所有智能体(包括内置智能体)
// @Description 获取当前空间的所有智能体(包括内置智能体)
// @Tags 智能体
// @Accept json
// @Produce json
@@ -222,14 +222,14 @@ func (h *CustomAgentHandler) ListAgents(c *gin.Context) {
// Per-tenant "disabled by me" for own agents (only affects this tenant's conversation dropdown)
tenantIDVal, exists := c.Get(types.TenantIDContextKey.String())
if !exists {
logger.Error(ctx, "Tenant ID not found in context")
c.Error(errors.NewUnauthorizedError("Missing tenant context"))
logger.Error(ctx, "Workspace ID not found in context")
c.Error(errors.NewUnauthorizedError("Missing workspace context"))
return
}
tenantID, ok := tenantIDVal.(uint64)
if !ok {
logger.Errorf(ctx, "Tenant ID has unexpected type %T in context", tenantIDVal)
c.Error(errors.NewInternalServerError("Invalid tenant context type"))
c.Error(errors.NewInternalServerError("Invalid workspace context type"))
return
}
disabledOwnIDs, err := h.disabledRepo.ListDisabledOwnAgentIDs(ctx, tenantID)
@@ -241,7 +241,7 @@ func (h *CustomAgentHandler) ListAgents(c *gin.Context) {
return
}
// 批量回填 creator_name,作用同 KB 列表:让前端能区分「我创建」与「同租户其他成员」。
// 批量回填 creator_name,作用同 KB 列表:让前端能区分「我创建」与「同空间其他成员」。
// 内建 agent(IsBuiltin=true, CreatedBy="")不会有 creator_name,前端按 builtin
// 分支单独渲染。
enrichAgentCreatorNames(ctx, h.userService, agents)
+2 -2
View File
@@ -94,7 +94,7 @@ func (h *DataSourceHandler) CreateDataSource(c *gin.Context) {
// Extract tenant ID from context (set by auth middleware)
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized: tenant context missing"})
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized: workspace context missing"})
return
}
@@ -164,7 +164,7 @@ func (h *DataSourceHandler) ListDataSources(c *gin.Context) {
// Extract tenant ID from context
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized: tenant context missing"})
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized: workspace context missing"})
return
}
+1 -1
View File
@@ -38,7 +38,7 @@ func (h *DataSourceCredentialsHandler) ownDataSource(c *gin.Context) (*types.Dat
ctx := c.Request.Context()
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
c.Error(errors.NewBadRequestError("Workspace ID cannot be empty"))
return nil, false
}
id := c.Param("id")
+5 -5
View File
@@ -362,7 +362,7 @@ func (h *InitializationHandler) UpdateKBConfig(c *gin.Context) {
kb.VLMConfig.CustomInstructions = strings.TrimSpace(req.VLMConfig.CustomInstructions)
}
// 存储引擎:仅写入 provider 到新字段,参数从租户全局 StorageEngineConfig 读取
// 存储引擎:仅写入 provider 到新字段,参数从空间全局 StorageEngineConfig 读取
provider := strings.ToLower(strings.TrimSpace(req.StorageProvider))
if provider == "" {
provider = "local"
@@ -1696,7 +1696,7 @@ func (h *InitializationHandler) buildTestModel(
}
}
// resolveTenantWeKnoraCloudCreds 从当前租户上下文里取出 WeKnoraCloud 凭证,
// resolveTenantWeKnoraCloudCreds 从当前空间上下文里取出 WeKnoraCloud 凭证,
// 供测试连接端点补齐 appID/appSecret。与 service.resolveWeKnoraCloudCredentials
// 对应,但因为 handler 还没有被注入 tenantService(历史原因),暂时从
// TenantInfoFromContext 读取,等效果相同。
@@ -1751,7 +1751,7 @@ func (h *InitializationHandler) CheckRemoteModel(c *gin.Context) {
appID, appSecret, ok := h.resolveTenantWeKnoraCloudCreds(ctx)
if !ok {
logger.Error(ctx, "Tenant info not found")
c.Error(errors.NewBadRequestError("租户信息未找到"))
c.Error(errors.NewBadRequestError("空间信息未找到"))
return
}
@@ -1825,7 +1825,7 @@ func (h *InitializationHandler) TestEmbeddingModel(c *gin.Context) {
appID, appSecret, ok := h.resolveTenantWeKnoraCloudCreds(ctx)
if !ok {
logger.Error(ctx, "Tenant info not found")
c.Error(errors.NewBadRequestError("租户信息未找到"))
c.Error(errors.NewBadRequestError("空间信息未找到"))
return
}
@@ -1977,7 +1977,7 @@ func (h *InitializationHandler) CheckRerankModel(c *gin.Context) {
appID, appSecret, ok := h.resolveTenantWeKnoraCloudCreds(ctx)
if !ok {
logger.Error(ctx, "Tenant info not found")
c.Error(errors.NewBadRequestError("租户信息未找到"))
c.Error(errors.NewBadRequestError("空间信息未找到"))
return
}
+5 -5
View File
@@ -1002,7 +1002,7 @@ func (h *KnowledgeHandler) DeleteKnowledge(c *gin.Context) {
effectiveTenantID, _ := effCtx.Value(types.TenantIDContextKey).(uint64)
if effectiveTenantID == 0 {
logger.Error(ctx, "Effective tenant ID missing after access validation")
c.Error(errors.NewInternalServerError("tenant context unavailable"))
c.Error(errors.NewInternalServerError("workspace context unavailable"))
return
}
@@ -1341,13 +1341,13 @@ type GetKnowledgeBatchRequest struct {
// GetKnowledgeBatch godoc
// @Summary 批量获取知识
// @Description 根据ID列表批量获取知识条目。可选 kb_id:指定时按该知识库校验权限并用于共享知识库的租户解析;可选 agent_id:使用共享智能体时传此参数,后端按智能体所属租户查询(用于刷新后恢复共享知识库下的文件)
// @Description 根据ID列表批量获取知识条目。可选 kb_id:指定时按该知识库校验权限并用于共享知识库的空间解析;可选 agent_id:使用共享智能体时传此参数,后端按智能体所属空间查询(用于刷新后恢复共享知识库下的文件)
// @Tags 知识管理
// @Accept json
// @Produce json
// @Param ids query []string true "知识ID列表"
// @Param kb_id query string false "可选,知识库ID(用于共享知识库时指定范围)"
// @Param agent_id query string false "可选,共享智能体ID(用于按智能体租户批量拉取文件详情)"
// @Param agent_id query string false "可选,共享智能体ID(用于按智能体空间批量拉取文件详情)"
// @Success 200 {object} map[string]interface{} "知识列表"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
@@ -1709,7 +1709,7 @@ type knowledgeTagBatchRequest struct {
// UpdateKnowledgeTagBatch godoc
// @Summary 批量更新知识标签
// @Description 批量更新知识条目的标签。可选 kb_id:指定时按该知识库校验编辑权限并用于共享知识库的租户解析
// @Description 批量更新知识条目的标签。可选 kb_id:指定时按该知识库校验编辑权限并用于共享知识库的空间解析
// @Tags 知识管理
// @Accept json
// @Produce json
@@ -1898,7 +1898,7 @@ func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) {
_ = userIDVal
currentTenantID := c.GetUint64(types.TenantIDContextKey.String())
if currentTenantID == 0 {
c.Error(errors.NewUnauthorizedError("tenant ID not found"))
c.Error(errors.NewUnauthorizedError("workspace ID not found"))
return
}
callerTenantRole := types.TenantRoleFromContext(ctx)
+4 -4
View File
@@ -472,7 +472,7 @@ func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*typ
agent, err := h.agentShareService.GetSharedAgentForTenant(ctx, currentTenantID, callerTenantRole, agentID)
if err == nil && agent != nil {
if kb.TenantID != agent.TenantID {
logger.Warnf(ctx, "Shared agent tenant mismatch, KB %s tenant: %d, agent tenant: %d", id, kb.TenantID, agent.TenantID)
logger.Warnf(ctx, "Shared agent workspace mismatch, KB %s tenant: %d, agent tenant: %d", id, kb.TenantID, agent.TenantID)
} else {
mode := agent.Config.KBSelectionMode
if mode == "none" {
@@ -549,7 +549,7 @@ func (h *KnowledgeBaseHandler) GetKnowledgeBase(c *gin.Context) {
// ListKnowledgeBases godoc
// @Summary 获取知识库列表
// @Description 获取当前租户的所有知识库;或当传入 agent_id(共享智能体)时,校验权限后返回该智能体配置的知识库范围(用于 @ 提及)
// @Description 获取当前空间的所有知识库;或当传入 agent_id(共享智能体)时,校验权限后返回该智能体配置的知识库范围(用于 @ 提及)
// @Tags 知识库
// @Accept json
// @Produce json
@@ -572,7 +572,7 @@ func (h *KnowledgeBaseHandler) ListKnowledgeBases(c *gin.Context) {
_ = userIDVal
currentTenantID := c.GetUint64(types.TenantIDContextKey.String())
if currentTenantID == 0 {
c.Error(apperrors.NewUnauthorizedError("tenant ID not found"))
c.Error(apperrors.NewUnauthorizedError("workspace ID not found"))
return
}
callerTenantRole := types.TenantRoleFromContext(ctx)
@@ -700,7 +700,7 @@ func (h *KnowledgeBaseHandler) ListKnowledgeBases(c *gin.Context) {
}
}
// 批量回填 creator_name,让前端列表能区分「我创建」与「同租户其他成员创建」。
// 批量回填 creator_name,让前端列表能区分「我创建」与「同空间其他成员创建」。
// 仅在 list 接口里回填,详情 / 编辑场景不依赖这个字段;解析失败(用户已删除、
// CreatorID 为空的老数据)就让字段为空,前端按 fallback 渲染。
enrichKBCreatorNames(ctx, h.userService, kbs)
+2 -2
View File
@@ -68,7 +68,7 @@ func (h *MCPCredentialsHandler) Put(c *gin.Context) {
serviceID := c.Param("id")
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
c.Error(errors.NewBadRequestError("Workspace ID cannot be empty"))
return
}
@@ -135,7 +135,7 @@ func (h *MCPCredentialsHandler) DeleteField(c *gin.Context) {
field := c.Param("field")
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
c.Error(errors.NewBadRequestError("Workspace ID cannot be empty"))
return
}
if field != "api_key" && field != "token" {
+3 -3
View File
@@ -286,7 +286,7 @@ func (h *MCPOAuthHandler) ResolveMCPOAuth(c *gin.Context) {
case stderrors.Is(err, approval.ErrAlreadyResolved):
c.Error(errors.NewBadRequestError("pending authorization already resolved (timeout / cancel raced your action)"))
case stderrors.Is(err, approval.ErrTenantMismatch):
c.Error(errors.NewBadRequestError("tenant mismatch"))
c.Error(errors.NewBadRequestError("workspace mismatch"))
case stderrors.Is(err, approval.ErrUserMismatch):
c.Error(errors.NewBadRequestError("user mismatch: only the session owner may resolve this prompt"))
default:
@@ -325,7 +325,7 @@ func (h *MCPOAuthHandler) ResolveMCPOAuth(c *gin.Context) {
case stderrors.Is(err, approval.ErrAlreadyResolved):
c.Error(errors.NewBadRequestError("pending authorization already resolved (timeout / cancel raced your action)"))
case stderrors.Is(err, approval.ErrTenantMismatch):
c.Error(errors.NewBadRequestError("tenant mismatch"))
c.Error(errors.NewBadRequestError("workspace mismatch"))
case stderrors.Is(err, approval.ErrUserMismatch):
c.Error(errors.NewBadRequestError("user mismatch: only the session owner may resolve this prompt"))
default:
@@ -376,7 +376,7 @@ func (h *MCPOAuthHandler) CancelMCPOAuth(c *gin.Context) {
case stderrors.Is(err, approval.ErrAlreadyResolved):
c.Error(errors.NewBadRequestError("pending authorization already resolved (timeout / cancel raced your action)"))
case stderrors.Is(err, approval.ErrTenantMismatch):
c.Error(errors.NewBadRequestError("tenant mismatch"))
c.Error(errors.NewBadRequestError("workspace mismatch"))
case stderrors.Is(err, approval.ErrUserMismatch):
c.Error(errors.NewBadRequestError("user mismatch: only the session owner may resolve this prompt"))
default:
+13 -13
View File
@@ -61,7 +61,7 @@ func (h *MCPServiceHandler) CreateMCPService(c *gin.Context) {
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
logger.Error(ctx, "Tenant ID is empty")
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
c.Error(errors.NewBadRequestError("Workspace ID cannot be empty"))
return
}
service.TenantID = tenantID
@@ -91,7 +91,7 @@ func (h *MCPServiceHandler) CreateMCPService(c *gin.Context) {
// ListMCPServices godoc
// @Summary 获取MCP服务列表
// @Description 获取当前租户的所有MCP服务
// @Description 获取当前空间的所有MCP服务
// @Tags MCP服务
// @Accept json
// @Produce json
@@ -106,7 +106,7 @@ func (h *MCPServiceHandler) ListMCPServices(c *gin.Context) {
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
logger.Error(ctx, "Tenant ID is empty")
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
c.Error(errors.NewBadRequestError("Workspace ID cannot be empty"))
return
}
@@ -142,7 +142,7 @@ func (h *MCPServiceHandler) GetMCPService(c *gin.Context) {
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
logger.Error(ctx, "Tenant ID is empty")
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
c.Error(errors.NewBadRequestError("Workspace ID cannot be empty"))
return
}
@@ -182,7 +182,7 @@ func (h *MCPServiceHandler) UpdateMCPService(c *gin.Context) {
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
logger.Error(ctx, "Tenant ID is empty")
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
c.Error(errors.NewBadRequestError("Workspace ID cannot be empty"))
return
}
@@ -374,7 +374,7 @@ func (h *MCPServiceHandler) DeleteMCPService(c *gin.Context) {
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
logger.Error(ctx, "Tenant ID is empty")
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
c.Error(errors.NewBadRequestError("Workspace ID cannot be empty"))
return
}
@@ -410,7 +410,7 @@ func (h *MCPServiceHandler) TestMCPService(c *gin.Context) {
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
logger.Error(ctx, "Tenant ID is empty")
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
c.Error(errors.NewBadRequestError("Workspace ID cannot be empty"))
return
}
@@ -455,7 +455,7 @@ func (h *MCPServiceHandler) GetMCPServiceTools(c *gin.Context) {
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
logger.Error(ctx, "Tenant ID is empty")
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
c.Error(errors.NewBadRequestError("Workspace ID cannot be empty"))
return
}
@@ -491,7 +491,7 @@ func (h *MCPServiceHandler) GetMCPServiceResources(c *gin.Context) {
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
logger.Error(ctx, "Tenant ID is empty")
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
c.Error(errors.NewBadRequestError("Workspace ID cannot be empty"))
return
}
@@ -514,7 +514,7 @@ func (h *MCPServiceHandler) ListMCPToolApprovals(c *gin.Context) {
serviceID := secutils.SanitizeForLog(c.Param("id"))
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
c.Error(errors.NewBadRequestError("Workspace ID cannot be empty"))
return
}
if h.mcpToolApprovalService == nil {
@@ -565,7 +565,7 @@ func (h *MCPServiceHandler) SetMCPToolApproval(c *gin.Context) {
toolName := c.Param("tool_name")
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
c.Error(errors.NewBadRequestError("Workspace ID cannot be empty"))
return
}
if h.mcpToolApprovalService == nil {
@@ -611,7 +611,7 @@ func (h *MCPServiceHandler) ResolveToolApproval(c *gin.Context) {
pendingID := c.Param("pending_id")
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
c.Error(errors.NewBadRequestError("Workspace ID cannot be empty"))
return
}
if h.toolApprovalGate == nil {
@@ -661,7 +661,7 @@ func (h *MCPServiceHandler) ResolveToolApproval(c *gin.Context) {
case stderrors.Is(err, approval.ErrAlreadyResolved):
c.Error(errors.NewBadRequestError("pending approval already resolved (timeout / cancel raced your action)"))
case stderrors.Is(err, approval.ErrTenantMismatch):
c.Error(errors.NewBadRequestError("tenant mismatch"))
c.Error(errors.NewBadRequestError("workspace mismatch"))
case stderrors.Is(err, approval.ErrUserMismatch):
c.Error(errors.NewBadRequestError("user mismatch: only the session owner may resolve this approval"))
default:
+3 -3
View File
@@ -77,7 +77,7 @@ func (h *ModelHandler) CreateModel(c *gin.Context) {
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
logger.Error(ctx, "Tenant ID is empty")
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
c.Error(errors.NewBadRequestError("Workspace ID cannot be empty"))
return
}
@@ -169,7 +169,7 @@ func (h *ModelHandler) GetModel(c *gin.Context) {
// ListModels godoc
// @Summary 获取模型列表
// @Description 获取当前租户的所有模型
// @Description 获取当前空间的所有模型
// @Tags 模型管理
// @Accept json
// @Produce json
@@ -186,7 +186,7 @@ func (h *ModelHandler) ListModels(c *gin.Context) {
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
logger.Error(ctx, "Tenant ID is empty")
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
c.Error(errors.NewBadRequestError("Workspace ID cannot be empty"))
return
}
+2 -2
View File
@@ -36,7 +36,7 @@ func (h *ModelCredentialsHandler) Put(c *gin.Context) {
id := c.Param("id")
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
c.Error(errors.NewBadRequestError("Workspace ID cannot be empty"))
return
}
@@ -90,7 +90,7 @@ func (h *ModelCredentialsHandler) DeleteField(c *gin.Context) {
field := c.Param("field")
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
c.Error(errors.NewBadRequestError("Workspace ID cannot be empty"))
return
}
if field != "api_key" && field != "app_secret" {
+20 -20
View File
@@ -148,7 +148,7 @@ func (h *OrganizationHandler) GetOrganization(c *gin.Context) {
// ListMyOrganizations lists organizations that the current tenant belongs to.
// Response includes resource_counts (per-org KB/agent counts) for list sidebar so frontend does not need a separate GET /me/resource-counts.
// @Summary 获取我的组织列表
// @Description 获取当前租户所属的所有组织,并附带各空间内知识库/智能体数量
// @Description 获取当前空间所属的所有组织,并附带各空间内知识库/智能体数量
// @Tags 组织管理
// @Produce json
// @Success 200 {object} types.ListOrganizationsResponse
@@ -370,7 +370,7 @@ func (h *OrganizationHandler) DeleteOrganization(c *gin.Context) {
// ListMembers lists all tenant-members of an organization
// @Summary 获取组织成员列表
// @Description 获取组织的所有成员(按租户)
// @Description 获取组织的所有成员(按空间)
// @Tags 组织管理
// @Produce json
// @Param id path string true "组织ID"
@@ -389,7 +389,7 @@ func (h *OrganizationHandler) ListMembers(c *gin.Context) {
// get 403 — mirrors ListOrgShares / ListOrgAgentShares which already
// gate on GetTenantMember.
if _, err := h.orgService.GetTenantMember(ctx, orgID, tenantID); err != nil {
c.Error(apperrors.NewForbiddenError("Your tenant is not a member of this organization"))
c.Error(apperrors.NewForbiddenError("Your workspace is not a member of this organization"))
return
}
@@ -439,12 +439,12 @@ func (h *OrganizationHandler) ListMembers(c *gin.Context) {
// UpdateMemberRole updates a tenant-member's role
// @Summary 更新成员角色
// @Description 更新组织成员(租户)的角色(需要管理员权限)
// @Description 更新组织成员(空间)的角色(需要管理员权限)
// @Tags 组织管理
// @Accept json
// @Produce json
// @Param id path string true "组织ID"
// @Param tenant_id path string true "成员租户ID"
// @Param tenant_id path string true "成员空间ID"
// @Param request body types.UpdateMemberRoleRequest true "角色信息"
// @Success 200 {object} map[string]interface{}
// @Failure 403 {object} apperrors.AppError
@@ -457,7 +457,7 @@ func (h *OrganizationHandler) UpdateMemberRole(c *gin.Context) {
memberTenantIDStr := c.Param("tenant_id")
memberTenantID, err := strconv.ParseUint(memberTenantIDStr, 10, 64)
if err != nil {
c.Error(apperrors.NewValidationError("Invalid tenant ID"))
c.Error(apperrors.NewValidationError("Invalid workspace ID"))
return
}
operatorUserID := c.GetString(types.UserIDContextKey.String())
@@ -483,10 +483,10 @@ func (h *OrganizationHandler) UpdateMemberRole(c *gin.Context) {
// RemoveMember removes a tenant-member from an organization
// @Summary 移除成员
// @Description 从组织中移除成员租户(需要管理员权限)
// @Description 从组织中移除成员空间(需要管理员权限)
// @Tags 组织管理
// @Param id path string true "组织ID"
// @Param tenant_id path string true "成员租户ID"
// @Param tenant_id path string true "成员空间ID"
// @Success 200 {object} map[string]interface{}
// @Failure 403 {object} apperrors.AppError
// @Security Bearer
@@ -498,7 +498,7 @@ func (h *OrganizationHandler) RemoveMember(c *gin.Context) {
memberTenantIDStr := c.Param("tenant_id")
memberTenantID, err := strconv.ParseUint(memberTenantIDStr, 10, 64)
if err != nil {
c.Error(apperrors.NewValidationError("Invalid tenant ID"))
c.Error(apperrors.NewValidationError("Invalid workspace ID"))
return
}
operatorUserID := c.GetString(types.UserIDContextKey.String())
@@ -681,7 +681,7 @@ func (h *OrganizationHandler) SubmitJoinRequest(c *gin.Context) {
// Check if caller's tenant is already a member
_, memberErr := h.orgService.GetTenantMember(ctx, org.ID, tenantID)
if memberErr == nil {
c.Error(apperrors.NewValidationError("Your tenant is already a member of this organization"))
c.Error(apperrors.NewValidationError("Your workspace is already a member of this organization"))
return
}
@@ -1225,7 +1225,7 @@ func (h *OrganizationHandler) ListOrgShares(c *gin.Context) {
// Check if caller's tenant is a member and get its role for effective-permission calculation
member, err := h.orgService.GetTenantMember(ctx, orgID, tenantID)
if err != nil {
c.Error(apperrors.NewForbiddenError("Your tenant is not a member of this organization"))
c.Error(apperrors.NewForbiddenError("Your workspace is not a member of this organization"))
return
}
myRoleInOrg := member.Role
@@ -1436,7 +1436,7 @@ func (h *OrganizationHandler) ListOrgAgentShares(c *gin.Context) {
tenantID := c.GetUint64(types.TenantIDContextKey.String())
member, err := h.orgService.GetTenantMember(ctx, orgID, tenantID)
if err != nil {
c.Error(apperrors.NewForbiddenError("Your tenant is not a member of this organization"))
c.Error(apperrors.NewForbiddenError("Your workspace is not a member of this organization"))
return
}
myRoleInOrg := member.Role
@@ -1622,7 +1622,7 @@ func (h *OrganizationHandler) listSpaceKnowledgeBasesInOrganization(ctx context.
SourceTenantID: sourceTenantID,
SharedAt: agentItem.SharedAt,
},
// 即便 KB 是「被共享智能体捎带进来」的,只要它属于当前租户
// 即便 KB 是「被共享智能体捎带进来」的,只要它属于当前空间
// 就应该归到「我共享的」分组——否则用户会在共享空间里看到
// 自己的 KB 出现在「共享给我·仅查看」组里,非常迷惑。
IsMine: sourceTenantID == tenantID,
@@ -1656,7 +1656,7 @@ func (h *OrganizationHandler) ListOrganizationSharedKnowledgeBases(c *gin.Contex
list, err := h.listSpaceKnowledgeBasesInOrganization(ctx, orgID, tenantID, callerTenantRole)
if err != nil {
if errors.Is(err, service.ErrTenantNotInOrg) {
c.Error(apperrors.NewForbiddenError("Your tenant is not a member of this organization"))
c.Error(apperrors.NewForbiddenError("Your workspace is not a member of this organization"))
return
}
logger.Errorf(ctx, "Failed to list organization shared knowledge bases: %v", err)
@@ -1703,7 +1703,7 @@ func (h *OrganizationHandler) ListOrganizationSharedAgents(c *gin.Context) {
list, err := h.agentShareService.ListSharedAgentsInOrganization(ctx, orgID, tenantID, callerTenantRole)
if err != nil {
if errors.Is(err, service.ErrTenantNotInOrg) {
c.Error(apperrors.NewForbiddenError("Your tenant is not a member of this organization"))
c.Error(apperrors.NewForbiddenError("Your workspace is not a member of this organization"))
return
}
logger.Errorf(ctx, "Failed to list organization shared agents: %v", err)
@@ -1833,12 +1833,12 @@ func (h *OrganizationHandler) toOrgResponse(ctx context.Context, org *types.Orga
// canonical name, filters out tenants already in the org, and returns one row
// per candidate tenant with one representative user attached for display.
//
// @Summary 搜索可邀请的租户
// @Description 搜索租户(排除已加入的租户)用于邀请加入组织;按租户去重,附带代表用户
// @Summary 搜索可邀请的空间
// @Description 搜索空间(排除已加入的空间)用于邀请加入组织;按空间去重,附带代表用户
// @Tags 组织管理
// @Produce json
// @Param id path string true "组织ID"
// @Param q query string true "搜索关键词(租户名、用户名或邮箱)"
// @Param q query string true "搜索关键词(空间名、用户名或邮箱)"
// @Param limit query int false "返回数量限制" default(10)
// @Success 200 {object} map[string]interface{}
// @Failure 403 {object} apperrors.AppError
@@ -2048,7 +2048,7 @@ func (h *OrganizationHandler) InviteMember(c *gin.Context) {
// Tenant-id path: validate the tenant exists; pick a sensible
// representative when the caller didn't pin one.
if _, err := h.tenantService.GetTenantByID(ctx, targetTenantID); err != nil {
c.Error(apperrors.NewNotFoundError("Tenant not found"))
c.Error(apperrors.NewNotFoundError("Workspace not found"))
return
}
if representativeUserID == "" {
@@ -2086,7 +2086,7 @@ func (h *OrganizationHandler) InviteMember(c *gin.Context) {
// Check if target tenant is already a member of this org.
if _, memberErr := h.orgService.GetTenantMember(ctx, orgID, targetTenantID); memberErr == nil {
c.Error(apperrors.NewValidationError("Tenant is already a member of this organization"))
c.Error(apperrors.NewValidationError("Workspace is already a member of this organization"))
return
}
+11 -11
View File
@@ -39,9 +39,9 @@ func (h *KnowledgeBaseHandler) KBCreatorLookup(c *gin.Context) (string, error) {
ctx := c.Request.Context()
tenantID, ok := types.TenantIDFromContext(ctx)
if !ok {
// 没有租户上下文意味着 auth 中间件未完成;当作 lookup 失败让上层 503,
// 没有空间上下文意味着 auth 中间件未完成;当作 lookup 失败让上层 503,
// 而不是 silently 走 fail-open 给一个不该有的访问。
return "", errors.New("tenant context missing")
return "", errors.New("workspace context missing")
}
kb, err := h.service.GetKnowledgeBaseByID(ctx, id)
if err != nil {
@@ -53,8 +53,8 @@ func (h *KnowledgeBaseHandler) KBCreatorLookup(c *gin.Context) (string, error) {
if kb == nil {
return "", middleware.ErrResourceNotFound
}
// 显式重校验租户:repo.GetKnowledgeBaseByID 不带 tenant 过滤,
// 万一未来 :id 被攻击者从他人租户 UUID 试探到,也不会借由
// 显式重校验空间:repo.GetKnowledgeBaseByID 不带 tenant 过滤,
// 万一未来 :id 被攻击者从他人空间 UUID 试探到,也不会借由
// "ownership match" 通过中间件。
if kb.TenantID != tenantID {
return "", middleware.ErrResourceNotFound
@@ -77,7 +77,7 @@ func (h *KnowledgeBaseHandler) KBCreatorLookupFromKbIDParam(c *gin.Context) (str
ctx := c.Request.Context()
tenantID, ok := types.TenantIDFromContext(ctx)
if !ok {
return "", errors.New("tenant context missing")
return "", errors.New("workspace context missing")
}
kb, err := h.service.GetKnowledgeBaseByID(ctx, id)
if err != nil {
@@ -112,7 +112,7 @@ func (h *CustomAgentHandler) AgentCreatorLookup(c *gin.Context) (string, error)
ctx := c.Request.Context()
tenantID, ok := types.TenantIDFromContext(ctx)
if !ok {
return "", errors.New("tenant context missing")
return "", errors.New("workspace context missing")
}
agent, err := h.service.GetAgentByID(ctx, id)
if err != nil {
@@ -195,7 +195,7 @@ func (h *ChunkHandler) KBCreatorLookupFromChunkIDParam(c *gin.Context) (string,
ctx := c.Request.Context()
tenantID, ok := types.TenantIDFromContext(ctx)
if !ok {
return "", errors.New("tenant context missing")
return "", errors.New("workspace context missing")
}
chunk, err := h.service.GetChunkByIDOnly(ctx, chunkID)
if err != nil {
@@ -207,7 +207,7 @@ func (h *ChunkHandler) KBCreatorLookupFromChunkIDParam(c *gin.Context) (string,
if chunk == nil {
return "", middleware.ErrResourceNotFound
}
// 显式重校验租户:GetChunkByIDOnly 无租户过滤,必须在此挡住跨租户 chunk
// 显式重校验空间:GetChunkByIDOnly 无空间过滤,必须在此挡住跨空间 chunk
// id 撞库通过 ownership 匹配获取本不该有的访问。
if chunk.TenantID != tenantID {
return "", middleware.ErrResourceNotFound
@@ -229,7 +229,7 @@ func (h *WikiPageHandler) KBCreatorLookupFromKBPath(c *gin.Context) (string, err
ctx := c.Request.Context()
tenantID, ok := types.TenantIDFromContext(ctx)
if !ok {
return "", errors.New("tenant context missing")
return "", errors.New("workspace context missing")
}
kb, err := h.kbService.GetKnowledgeBaseByID(ctx, kbID)
if err != nil {
@@ -258,7 +258,7 @@ func resolveKBCreatorByKBID(
ctx := c.Request.Context()
tenantID, ok := types.TenantIDFromContext(ctx)
if !ok {
return "", errors.New("tenant context missing")
return "", errors.New("workspace context missing")
}
kb, err := kbService.GetKnowledgeBaseByID(ctx, kbID)
if err != nil {
@@ -291,7 +291,7 @@ func resolveKBCreatorByKnowledgeID(
// Same fail-closed reasoning as KBCreatorLookup: no tenant
// context means auth didn't complete, and we'd rather have the
// caller see a 503 than a silent fail-open.
return "", errors.New("tenant context missing")
return "", errors.New("workspace context missing")
}
creatorID, err := kgService.GetOwningKBCreatorID(ctx, knowledgeID)
if err != nil {
+2 -2
View File
@@ -103,7 +103,7 @@ func TestKBCreatorLookup_MissingTenantContext(t *testing.T) {
}}
_, err := h.KBCreatorLookup(c)
if err == nil {
t.Fatalf("expected error when tenant context missing")
t.Fatalf("expected error when workspace context missing")
}
if errors.Is(err, middleware.ErrResourceNotFound) {
t.Fatalf("missing tenant must not be reported as not-found: %v", err)
@@ -279,7 +279,7 @@ func TestKBCreatorLookupFromKnowledgeID_MissingTenantContext(t *testing.T) {
}}
_, err := h.KBCreatorLookupFromKnowledgeID(c)
if err == nil {
t.Fatalf("expected error when tenant context missing")
t.Fatalf("expected error when workspace context missing")
}
if errors.Is(err, middleware.ErrResourceNotFound) {
t.Fatalf("missing tenant must not be reported as not-found: %v", err)
+2 -2
View File
@@ -191,7 +191,7 @@ func (h *Handler) GetSession(c *gin.Context) {
// GetSessionsByTenant godoc
// @Summary 获取会话列表
// @Description 获取当前租户的会话列表,支持分页、关键字搜索、按来源/Agent 筛选
// @Description 获取当前空间的会话列表,支持分页、关键字搜索、按来源/Agent 筛选
// @Tags 会话
// @Accept json
// @Produce json
@@ -405,7 +405,7 @@ type batchDeleteRequest struct {
// BatchDeleteSessions godoc
// @Summary 批量删除会话
// @Description 根据ID列表批量删除对话会话,或设置 delete_all=true 删除当前租户的所有会话
// @Description 根据ID列表批量删除对话会话,或设置 delete_all=true 删除当前空间的所有会话
// @Tags 会话
// @Accept json
// @Produce json
+1 -1
View File
@@ -46,7 +46,7 @@ type CreateKnowledgeQARequest struct {
KnowledgeBaseIDs []string `json:"knowledge_base_ids"` // Selected knowledge base ID for this request
KnowledgeIds []string `json:"knowledge_ids"` // Selected knowledge ID for this request
AgentEnabled bool `json:"agent_enabled"` // Whether agent mode is enabled for this request
AgentID string `json:"agent_id"` // Selected custom agent ID (backend resolves shared agent and its tenant from share relation)
AgentID string `json:"agent_id"` // Selected custom agent ID (backend resolves shared agent and its workspace from share relation)
WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search is enabled for this request
SummaryModelID string `json:"summary_model_id"` // Optional summary model ID for this request (overrides session default)
MCPServiceIDs []string `json:"mcp_service_ids"` // Per-request MCP services selected via @mention
+3 -3
View File
@@ -1453,7 +1453,7 @@ func (h *SystemHandler) ResetUserPassword(c *gin.Context) {
// ListSystemSettings godoc
// @Summary List all system settings
// @Description Return every row in the system_settings table (system-scope,
// @Description not tenant-scope). SystemAdmin only.
// @Description not workspace-scoped). SystemAdmin only.
// @Tags System Admin
// @Produce json
// @Success 200 {array} types.SystemSetting "list of settings"
@@ -2015,11 +2015,11 @@ func (h *SystemHandler) UpdateSystemSetting(c *gin.Context) {
}
// ApplyDefaultStorageQuotaToAllTenants godoc
// @Summary Apply the default storage quota to every existing tenant
// @Summary Apply the default storage quota to every existing workspace
// @Description Reads the current value of `tenant.default_storage_quota_gb`
// @Description (3-tier resolver: DB > ENV > default) and writes that many
// @Description GiB into storage_quota for every row in tenants. Bypasses
// @Description the per-tenant PUT whitelist, which forbids storage_quota
// @Description the per-workspace PUT whitelist, which forbids storage_quota
// @Description edits by Owners. SystemAdmin only.
// @Description Idempotent — running twice with the same setting is a no-op.
// @Tags System Admin
+114 -114
View File
@@ -199,17 +199,17 @@ func (h *TenantHandler) resolveMaxOwnedTenantsPerUser(ctx context.Context) int {
}
// CreateTenant godoc
// @Summary 创建租户
// @Description 创建新的租户。任意已登录用户均可调用以建立自己的新工作区,
// @Description 调用方会被自动设为该租户的 Owner。跨租户超管仍可像以前一样
// @Description 通过本接口创建任意租户。
// @Summary 创建空间
// @Description 创建新的空间。任意已登录用户均可调用以建立自己的新工作区,
// @Description 调用方会被自动设为该空间的 Owner。跨空间超管仍可像以前一样
// @Description 通过本接口创建任意空间。
// @Description 当 tenant.auto_create_api_key(或 WEKNORA_TENANT_AUTO_CREATE_API_KEY)
// @Description 开启时,会自动创建一个 full_access API Key,并在响应体的 data.api_key 字段返回其明文 token。
// @Tags 租户管理
// @Tags 空间管理
// @Accept json
// @Produce json
// @Param request body handler.createTenantRequest true "租户信息"
// @Success 201 {object} map[string]interface{} "创建的租户(可选含 api_key)"
// @Param request body handler.createTenantRequest true "空间信息"
// @Success 201 {object} map[string]interface{} "创建的空间(可选含 api_key)"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Router /tenants [post]
@@ -278,7 +278,7 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
memberships, listErr := h.memberService.ListByUser(ctx, caller.ID)
if listErr != nil {
logger.Errorf(ctx, "Failed to count owned tenants for user %s: %v", caller.ID, listErr)
c.Error(errors.NewInternalServerError("Failed to validate tenant quota").WithDetails(listErr.Error()))
c.Error(errors.NewInternalServerError("Failed to validate workspace quota").WithDetails(listErr.Error()))
return
}
ownedCount := 0
@@ -294,7 +294,7 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
caller.ID, ownedCount, cap,
)
c.Error(errors.NewTooManyRequestsError(
"reached self-service tenant quota; contact an administrator to raise the limit",
"reached self-service workspace quota; contact an administrator to raise the limit",
))
return
}
@@ -335,11 +335,11 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
if err != nil {
// Check if this is an application-specific error
if appErr, ok := errors.IsAppError(err); ok {
logger.Error(ctx, "Failed to create tenant: application error", appErr)
logger.Error(ctx, "Failed to create workspace: application error", appErr)
c.Error(appErr)
} else {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to create tenant").WithDetails(err.Error()))
c.Error(errors.NewInternalServerError("Failed to create workspace").WithDetails(err.Error()))
}
return
}
@@ -363,7 +363,7 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
createdTenant.ID, delErr,
)
}
c.Error(errors.NewInternalServerError("Failed to finalise tenant ownership").WithDetails(err.Error()))
c.Error(errors.NewInternalServerError("Failed to finalise workspace ownership").WithDetails(err.Error()))
return
}
@@ -405,7 +405,7 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
)
}
c.Error(errors.NewTooManyRequestsError(
"reached self-service tenant quota; contact an administrator to raise the limit",
"reached self-service workspace quota; contact an administrator to raise the limit",
))
return
}
@@ -425,7 +425,7 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
_ = h.memberService.RemoveMember(ctx, caller.ID, createdTenant.ID)
}
_ = h.service.DeleteTenant(ctx, createdTenant.ID)
c.Error(errors.NewInternalServerError("Failed to finalise default tenant").WithDetails(err.Error()))
c.Error(errors.NewInternalServerError("Failed to finalise default workspace").WithDetails(err.Error()))
return
}
}
@@ -510,15 +510,15 @@ func (h *TenantHandler) autoCreateTenantAPIKey(ctx context.Context) bool {
}
// GetTenant godoc
// @Summary 获取租户详情
// @Description 根据ID获取租户详情
// @Tags 租户管理
// @Summary 获取空间详情
// @Description 根据ID获取空间详情
// @Tags 空间管理
// @Accept json
// @Produce json
// @Param id path int true "租户ID"
// @Success 200 {object} map[string]interface{} "租户详情"
// @Param id path int true "空间ID"
// @Success 200 {object} map[string]interface{} "空间详情"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 404 {object} errors.AppError "租户不存在"
// @Failure 404 {object} errors.AppError "空间不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /tenants/{id} [get]
@@ -527,19 +527,19 @@ func (h *TenantHandler) GetTenant(c *gin.Context) {
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
logger.Errorf(ctx, "Invalid tenant ID: %s", secutils.SanitizeForLog(c.Param("id")))
c.Error(errors.NewBadRequestError("Invalid tenant ID"))
logger.Errorf(ctx, "Invalid workspace ID: %s", secutils.SanitizeForLog(c.Param("id")))
c.Error(errors.NewBadRequestError("Invalid workspace ID"))
return
}
tenant, err := h.service.GetTenantByID(ctx, id)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
logger.Error(ctx, "Failed to retrieve tenant: application error", appErr)
logger.Error(ctx, "Failed to retrieve workspace: application error", appErr)
c.Error(appErr)
} else {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to retrieve tenant").WithDetails(err.Error()))
c.Error(errors.NewInternalServerError("Failed to retrieve workspace").WithDetails(err.Error()))
}
return
}
@@ -551,14 +551,14 @@ func (h *TenantHandler) GetTenant(c *gin.Context) {
}
// UpdateTenant godoc
// @Summary 更新租户
// @Description 更新租户信息
// @Tags 租户管理
// @Summary 更新空间
// @Description 更新空间信息
// @Tags 空间管理
// @Accept json
// @Produce json
// @Param id path int true "租户ID"
// @Param request body types.Tenant true "租户信息"
// @Success 200 {object} map[string]interface{} "更新后的租户"
// @Param id path int true "空间ID"
// @Param request body types.Tenant true "空间信息"
// @Success 200 {object} map[string]interface{} "更新后的空间"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Router /tenants/{id} [put]
@@ -569,8 +569,8 @@ func (h *TenantHandler) UpdateTenant(c *gin.Context) {
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
logger.Errorf(ctx, "Invalid tenant ID: %s", secutils.SanitizeForLog(c.Param("id")))
c.Error(errors.NewBadRequestError("Invalid tenant ID"))
logger.Errorf(ctx, "Invalid workspace ID: %s", secutils.SanitizeForLog(c.Param("id")))
c.Error(errors.NewBadRequestError("Invalid workspace ID"))
return
}
@@ -598,7 +598,7 @@ func (h *TenantHandler) UpdateTenant(c *gin.Context) {
c.Error(appErr)
} else {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to load tenant").WithDetails(err.Error()))
c.Error(errors.NewInternalServerError("Failed to load workspace").WithDetails(err.Error()))
}
return
}
@@ -620,11 +620,11 @@ func (h *TenantHandler) UpdateTenant(c *gin.Context) {
updatedTenant, err := h.service.UpdateTenant(ctx, existing)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
logger.Error(ctx, "Failed to update tenant: application error", appErr)
logger.Error(ctx, "Failed to update workspace: application error", appErr)
c.Error(appErr)
} else {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to update tenant").WithDetails(err.Error()))
c.Error(errors.NewInternalServerError("Failed to update workspace").WithDetails(err.Error()))
}
return
}
@@ -645,7 +645,7 @@ func (h *TenantHandler) ListAPIKeys(c *gin.Context) {
ctx := c.Request.Context()
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
c.Error(errors.NewBadRequestError("Invalid tenant ID"))
c.Error(errors.NewBadRequestError("Invalid workspace ID"))
return
}
keys, err := h.apiKeyService.ListAPIKeys(ctx, id)
@@ -664,7 +664,7 @@ func (h *TenantHandler) CreateAPIKey(c *gin.Context) {
ctx := c.Request.Context()
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
c.Error(errors.NewBadRequestError("Invalid tenant ID"))
c.Error(errors.NewBadRequestError("Invalid workspace ID"))
return
}
var req tenantAPIKeyCreateRequest
@@ -710,7 +710,7 @@ func (h *TenantHandler) DeleteAPIKey(c *gin.Context) {
ctx := c.Request.Context()
tenantID, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
c.Error(errors.NewBadRequestError("Invalid tenant ID"))
c.Error(errors.NewBadRequestError("Invalid workspace ID"))
return
}
keyID, err := strconv.ParseUint(c.Param("key_id"), 10, 64)
@@ -776,7 +776,7 @@ func validateTenantAPIKeyRequest(
return errors.NewValidationError("knowledge_base_ids contains an unknown knowledge base")
}
if kb.TenantID != tenantID {
return errors.NewForbiddenError("knowledge_base_ids contains a knowledge base outside this tenant")
return errors.NewForbiddenError("knowledge_base_ids contains a knowledge base outside this workspace")
}
}
return nil
@@ -800,12 +800,12 @@ func apiPrincipalConfigForResponse(cfg *types.APIPrincipalConfig) apiPrincipalCo
}
// GetAPIPrincipalConfig godoc
// @Summary 获取租户 API Key 用户身份配置
// @Summary 获取空间 API Key 用户身份配置
// @Description 返回 X-API-Key 请求如何映射为终端 Principal 的配置(Owner)
// @Tags 租户管理
// @Tags 空间管理
// @Accept json
// @Produce json
// @Param id path int true "租户ID"
// @Param id path int true "空间ID"
// @Success 200 {object} map[string]interface{} "API principal 配置"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 403 {object} errors.AppError "权限不足"
@@ -815,7 +815,7 @@ func (h *TenantHandler) GetAPIPrincipalConfig(c *gin.Context) {
ctx := c.Request.Context()
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
c.Error(errors.NewBadRequestError("Invalid tenant ID"))
c.Error(errors.NewBadRequestError("Invalid workspace ID"))
return
}
tenant, err := h.service.GetTenantByID(ctx, id)
@@ -823,7 +823,7 @@ func (h *TenantHandler) GetAPIPrincipalConfig(c *gin.Context) {
if appErr, ok := errors.IsAppError(err); ok {
c.Error(appErr)
} else {
c.Error(errors.NewInternalServerError("Failed to load tenant").WithDetails(err.Error()))
c.Error(errors.NewInternalServerError("Failed to load workspace").WithDetails(err.Error()))
}
return
}
@@ -834,12 +834,12 @@ func (h *TenantHandler) GetAPIPrincipalConfig(c *gin.Context) {
}
// UpdateAPIPrincipalConfig godoc
// @Summary 更新租户 API Key 用户身份配置
// @Summary 更新空间 API Key 用户身份配置
// @Description 配置 X-API-Key 请求如何映射为终端 Principal(Owner)
// @Tags 租户管理
// @Tags 空间管理
// @Accept json
// @Produce json
// @Param id path int true "租户ID"
// @Param id path int true "空间ID"
// @Param request body handler.apiPrincipalConfigRequest true "API principal 配置"
// @Success 200 {object} map[string]interface{} "更新后的配置"
// @Failure 400 {object} errors.AppError "请求参数错误"
@@ -850,7 +850,7 @@ func (h *TenantHandler) UpdateAPIPrincipalConfig(c *gin.Context) {
ctx := c.Request.Context()
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
c.Error(errors.NewBadRequestError("Invalid tenant ID"))
c.Error(errors.NewBadRequestError("Invalid workspace ID"))
return
}
var req apiPrincipalConfigRequest
@@ -873,7 +873,7 @@ func (h *TenantHandler) UpdateAPIPrincipalConfig(c *gin.Context) {
if appErr, ok := errors.IsAppError(err); ok {
c.Error(appErr)
} else {
c.Error(errors.NewInternalServerError("Failed to load tenant").WithDetails(err.Error()))
c.Error(errors.NewInternalServerError("Failed to load workspace").WithDetails(err.Error()))
}
return
}
@@ -923,11 +923,11 @@ func (h *TenantHandler) UpdateAPIPrincipalConfig(c *gin.Context) {
// CreateAPIPrincipalTestToken godoc
// @Summary 生成 API Playground 测试 JWT
// @Description 使用租户已保存的 HMAC 密钥签发短期外部用户 JWT(Owner)
// @Tags 租户管理
// @Description 使用空间已保存的 HMAC 密钥签发短期外部用户 JWT(Owner)
// @Tags 空间管理
// @Accept json
// @Produce json
// @Param id path int true "租户ID"
// @Param id path int true "空间ID"
// @Param request body handler.apiPrincipalTestTokenRequest true "测试 Token 参数"
// @Success 200 {object} map[string]interface{} "短期 JWT"
// @Failure 400 {object} errors.AppError "请求参数错误"
@@ -938,7 +938,7 @@ func (h *TenantHandler) CreateAPIPrincipalTestToken(c *gin.Context) {
ctx := c.Request.Context()
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
c.Error(errors.NewBadRequestError("Invalid tenant ID"))
c.Error(errors.NewBadRequestError("Invalid workspace ID"))
return
}
@@ -959,7 +959,7 @@ func (h *TenantHandler) CreateAPIPrincipalTestToken(c *gin.Context) {
if appErr, ok := errors.IsAppError(err); ok {
c.Error(appErr)
} else {
c.Error(errors.NewInternalServerError("Failed to load tenant").WithDetails(err.Error()))
c.Error(errors.NewInternalServerError("Failed to load workspace").WithDetails(err.Error()))
}
return
}
@@ -1026,12 +1026,12 @@ func validateAPIPrincipalExternalUserID(id string) error {
}
// DeleteTenant godoc
// @Summary 删除租户
// @Description 删除指定的租户
// @Tags 租户管理
// @Summary 删除空间
// @Description 删除指定的空间
// @Tags 空间管理
// @Accept json
// @Produce json
// @Param id path int true "租户ID"
// @Param id path int true "空间ID"
// @Success 200 {object} map[string]interface{} "删除成功"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
@@ -1043,8 +1043,8 @@ func (h *TenantHandler) DeleteTenant(c *gin.Context) {
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
logger.Errorf(ctx, "Invalid tenant ID: %s", secutils.SanitizeForLog(c.Param("id")))
c.Error(errors.NewBadRequestError("Invalid tenant ID"))
logger.Errorf(ctx, "Invalid workspace ID: %s", secutils.SanitizeForLog(c.Param("id")))
c.Error(errors.NewBadRequestError("Invalid workspace ID"))
return
}
@@ -1052,29 +1052,29 @@ func (h *TenantHandler) DeleteTenant(c *gin.Context) {
if err := h.service.DeleteTenant(ctx, id); err != nil {
if appErr, ok := errors.IsAppError(err); ok {
logger.Error(ctx, "Failed to delete tenant: application error", appErr)
logger.Error(ctx, "Failed to delete workspace: application error", appErr)
c.Error(appErr)
} else {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to delete tenant").WithDetails(err.Error()))
c.Error(errors.NewInternalServerError("Failed to delete workspace").WithDetails(err.Error()))
}
return
}
logger.Infof(ctx, "Tenant deleted successfully, ID: %d", id)
logger.Infof(ctx, "Workspace deleted successfully, ID: %d", id)
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Tenant deleted successfully",
"message": "Workspace deleted successfully",
})
}
// ListTenants godoc
// @Summary 获取租户列表
// @Description 获取当前用户可访问的租户列表
// @Tags 租户管理
// @Summary 获取空间列表
// @Description 获取当前用户可访问的空间列表
// @Tags 空间管理
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "租户列表"
// @Success 200 {object} map[string]interface{} "空间列表"
// @Failure 500 {object} errors.AppError "服务器错误"
// @Security Bearer
// @Router /tenants [get]
@@ -1096,12 +1096,12 @@ func (h *TenantHandler) ListTenants(c *gin.Context) {
}
// ListAllTenants godoc
// @Summary 获取所有租户列表
// @Description 获取系统中所有租户(需要跨租户访问权限)
// @Tags 租户管理
// @Summary 获取所有空间列表
// @Description 获取系统中所有空间(需要跨空间访问权限)
// @Tags 空间管理
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "所有租户列表"
// @Success 200 {object} map[string]interface{} "所有空间列表"
// @Failure 403 {object} errors.AppError "权限不足"
// @Security Bearer
// @Router /tenants/all [get]
@@ -1115,11 +1115,11 @@ func (h *TenantHandler) ListAllTenants(c *gin.Context) {
if err != nil {
// Check if this is an application-specific error
if appErr, ok := errors.IsAppError(err); ok {
logger.Error(ctx, "Failed to retrieve all tenants list: application error", appErr)
logger.Error(ctx, "Failed to retrieve all workspaces list: application error", appErr)
c.Error(appErr)
} else {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to retrieve all tenants list").WithDetails(err.Error()))
c.Error(errors.NewInternalServerError("Failed to retrieve all workspaces list").WithDetails(err.Error()))
}
return
}
@@ -1133,13 +1133,13 @@ func (h *TenantHandler) ListAllTenants(c *gin.Context) {
}
// SearchTenants godoc
// @Summary 搜索租户
// @Description 分页搜索租户(需要跨租户访问权限)
// @Tags 租户管理
// @Summary 搜索空间
// @Description 分页搜索空间(需要跨空间访问权限)
// @Tags 空间管理
// @Accept json
// @Produce json
// @Param keyword query string false "搜索关键词"
// @Param tenant_id query int false "租户ID筛选"
// @Param tenant_id query int false "空间ID筛选"
// @Param page query int false "页码" default(1)
// @Param page_size query int false "每页数量" default(20)
// @Success 200 {object} map[string]interface{} "搜索结果"
@@ -1185,11 +1185,11 @@ func (h *TenantHandler) SearchTenants(c *gin.Context) {
if err != nil {
// Check if this is an application-specific error
if appErr, ok := errors.IsAppError(err); ok {
logger.Error(ctx, "Failed to search tenants: application error", appErr)
logger.Error(ctx, "Failed to search workspaces: application error", appErr)
c.Error(appErr)
} else {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to search tenants").WithDetails(err.Error()))
c.Error(errors.NewInternalServerError("Failed to search workspaces").WithDetails(err.Error()))
}
return
}
@@ -1206,9 +1206,9 @@ func (h *TenantHandler) SearchTenants(c *gin.Context) {
}
// GetTenantKV godoc
// @Summary 获取租户KV配置
// @Description 获取租户级别的KV配置(支持web-search-config、prompt-templates、parser-engine-config、storage-engine-config、chat-history-config、retrieval-config)
// @Tags 租户管理
// @Summary 获取空间KV配置
// @Description 获取空间级别的KV配置(支持web-search-config、prompt-templates、parser-engine-config、storage-engine-config、chat-history-config、retrieval-config)
// @Tags 空间管理
// @Accept json
// @Produce json
// @Param key path string true "配置键名"
@@ -1256,9 +1256,9 @@ func (h *TenantHandler) GetTenantKV(c *gin.Context) {
}
// UpdateTenantKV godoc
// @Summary 更新租户KV配置
// @Description 更新租户级别的KV配置(支持web-search-config、parser-engine-config、storage-engine-config、chat-history-config、retrieval-config)
// @Tags 租户管理
// @Summary 更新空间KV配置
// @Description 更新空间级别的KV配置(支持web-search-config、parser-engine-config、storage-engine-config、chat-history-config、retrieval-config)
// @Tags 空间管理
// @Accept json
// @Produce json
// @Param key path string true "配置键名"
@@ -1317,8 +1317,8 @@ func (h *TenantHandler) updateTenantWebSearchConfigInternal(c *gin.Context) {
tenant, _ := types.TenantInfoFromContext(ctx)
if tenant == nil {
logger.Error(ctx, "Tenant is empty")
c.Error(errors.NewBadRequestError("Tenant is empty"))
logger.Error(ctx, "Workspace is empty")
c.Error(errors.NewBadRequestError("Workspace is empty"))
return
}
@@ -1334,11 +1334,11 @@ func (h *TenantHandler) updateTenantWebSearchConfigInternal(c *gin.Context) {
updatedTenant, err := h.service.UpdateTenant(ctx, tenant)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
logger.Error(ctx, "Failed to update tenant: application error", appErr)
logger.Error(ctx, "Failed to update workspace: application error", appErr)
c.Error(appErr)
} else {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to update tenant web search config").WithDetails(err.Error()))
c.Error(errors.NewInternalServerError("Failed to update workspace web search config").WithDetails(err.Error()))
}
return
}
@@ -1350,9 +1350,9 @@ func (h *TenantHandler) updateTenantWebSearchConfigInternal(c *gin.Context) {
}
// GetTenantWebSearchConfig godoc
// @Summary 获取租户网络搜索配置
// @Description 获取租户的网络搜索配置
// @Tags 租户管理
// @Summary 获取空间网络搜索配置
// @Description 获取空间的网络搜索配置
// @Tags 空间管理
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "网络搜索配置"
@@ -1366,8 +1366,8 @@ func (h *TenantHandler) GetTenantWebSearchConfig(c *gin.Context) {
// Get tenant
tenant, _ := types.TenantInfoFromContext(ctx)
if tenant == nil {
logger.Error(ctx, "Tenant is empty")
c.Error(errors.NewBadRequestError("Tenant is empty"))
logger.Error(ctx, "Workspace is empty")
c.Error(errors.NewBadRequestError("Workspace is empty"))
return
}
@@ -1383,8 +1383,8 @@ func (h *TenantHandler) GetTenantParserEngineConfig(c *gin.Context) {
ctx := c.Request.Context()
tenant, _ := types.TenantInfoFromContext(ctx)
if tenant == nil {
logger.Error(ctx, "Tenant is empty")
c.Error(errors.NewBadRequestError("Tenant is empty"))
logger.Error(ctx, "Workspace is empty")
c.Error(errors.NewBadRequestError("Workspace is empty"))
return
}
data := types.ParserEngineConfigForResponse(tenant.ParserEngineConfig, true)
@@ -1408,8 +1408,8 @@ func (h *TenantHandler) updateTenantParserEngineConfigInternal(c *gin.Context) {
}
tenant, _ := types.TenantInfoFromContext(ctx)
if tenant == nil {
logger.Error(ctx, "Tenant is empty")
c.Error(errors.NewBadRequestError("Tenant is empty"))
logger.Error(ctx, "Workspace is empty")
c.Error(errors.NewBadRequestError("Workspace is empty"))
return
}
merged := types.MergeParserEngineConfigForUpdate(&cfg, tenant.ParserEngineConfig)
@@ -1424,7 +1424,7 @@ func (h *TenantHandler) updateTenantParserEngineConfigInternal(c *gin.Context) {
c.Error(appErr)
} else {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to update tenant parser engine config").WithDetails(err.Error()))
c.Error(errors.NewInternalServerError("Failed to update workspace parser engine config").WithDetails(err.Error()))
}
return
}
@@ -1440,8 +1440,8 @@ func (h *TenantHandler) GetTenantStorageEngineConfig(c *gin.Context) {
ctx := c.Request.Context()
tenant, _ := types.TenantInfoFromContext(ctx)
if tenant == nil {
logger.Error(ctx, "Tenant is empty")
c.Error(errors.NewBadRequestError("Tenant is empty"))
logger.Error(ctx, "Workspace is empty")
c.Error(errors.NewBadRequestError("Workspace is empty"))
return
}
data := types.StorageEngineConfigForResponse(tenant.StorageEngineConfig, true)
@@ -1478,8 +1478,8 @@ func (h *TenantHandler) updateTenantStorageEngineConfigInternal(c *gin.Context)
cfg.DefaultProvider = provider
tenant, _ := types.TenantInfoFromContext(ctx)
if tenant == nil {
logger.Error(ctx, "Tenant is empty")
c.Error(errors.NewBadRequestError("Tenant is empty"))
logger.Error(ctx, "Workspace is empty")
c.Error(errors.NewBadRequestError("Workspace is empty"))
return
}
merged := types.MergeStorageEngineConfigForUpdate(&cfg, tenant.StorageEngineConfig)
@@ -1490,7 +1490,7 @@ func (h *TenantHandler) updateTenantStorageEngineConfigInternal(c *gin.Context)
c.Error(appErr)
} else {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to update tenant storage engine config").WithDetails(err.Error()))
c.Error(errors.NewInternalServerError("Failed to update workspace storage engine config").WithDetails(err.Error()))
}
return
}
@@ -1504,7 +1504,7 @@ func (h *TenantHandler) updateTenantStorageEngineConfigInternal(c *gin.Context)
// GetPromptTemplates godoc
// @Summary 获取提示词模板
// @Description 获取系统配置的提示词模板列表
// @Tags 租户管理
// @Tags 空间管理
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "提示词模板配置"
@@ -1546,8 +1546,8 @@ func (h *TenantHandler) GetTenantChatHistoryConfig(c *gin.Context) {
ctx := c.Request.Context()
tenant, _ := types.TenantInfoFromContext(ctx)
if tenant == nil {
logger.Error(ctx, "Tenant is empty")
c.Error(errors.NewBadRequestError("Tenant is empty"))
logger.Error(ctx, "Workspace is empty")
c.Error(errors.NewBadRequestError("Workspace is empty"))
return
}
data := tenant.ChatHistoryConfig
@@ -1576,8 +1576,8 @@ func (h *TenantHandler) updateTenantChatHistoryConfigInternal(c *gin.Context) {
tenant, _ := types.TenantInfoFromContext(ctx)
if tenant == nil {
logger.Error(ctx, "Tenant is empty")
c.Error(errors.NewBadRequestError("Tenant is empty"))
logger.Error(ctx, "Workspace is empty")
c.Error(errors.NewBadRequestError("Workspace is empty"))
return
}
@@ -1643,8 +1643,8 @@ func (h *TenantHandler) GetTenantRetrievalConfig(c *gin.Context) {
ctx := c.Request.Context()
tenant, _ := types.TenantInfoFromContext(ctx)
if tenant == nil {
logger.Error(ctx, "Tenant is empty")
c.Error(errors.NewBadRequestError("Tenant is empty"))
logger.Error(ctx, "Workspace is empty")
c.Error(errors.NewBadRequestError("Workspace is empty"))
return
}
data := tenant.RetrievalConfig
@@ -1692,8 +1692,8 @@ func (h *TenantHandler) updateTenantRetrievalConfigInternal(c *gin.Context) {
tenant, _ := types.TenantInfoFromContext(ctx)
if tenant == nil {
logger.Error(ctx, "Tenant is empty")
c.Error(errors.NewBadRequestError("Tenant is empty"))
logger.Error(ctx, "Workspace is empty")
c.Error(errors.NewBadRequestError("Workspace is empty"))
return
}
+11 -11
View File
@@ -187,11 +187,11 @@ func (h *TenantInvitationHandler) hydrateTenants(c *gin.Context, invs []*types.T
}
// ListTenantInvitations godoc
// @Summary 列出租户邀请
// @Description 按 tenant 列出待接受 / 历史邀请。query include_terminal=true 时附带 accepted/declined/revoked/expired。
// @Tags 租户邀请
// @Summary 列出空间邀请
// @Description 按空间列出待接受 / 历史邀请。query include_terminal=true 时附带 accepted/declined/revoked/expired。
// @Tags 空间邀请
// @Produce json
// @Param id path string true "租户 ID"
// @Param id path string true "空间 ID"
// @Param include_terminal query bool false "是否包含终止态行(默认 false)"
// @Param page query int false "页码(从 1 起)" default(1)
// @Param page_size query int false "每页数量" default(20)
@@ -244,12 +244,12 @@ func (h *TenantInvitationHandler) ListTenantInvitations(c *gin.Context) {
}
// CreateInvitation godoc
// @Summary 发出租户邀请
// @Description Owner 通过邮箱邀请已注册用户加入当前租户;被邀请人需要在 /me/invitations 接受后才会成为成员。
// @Tags 租户邀请
// @Summary 发出空间邀请
// @Description Owner 通过邮箱邀请已注册用户加入当前空间;被邀请人需要在 /me/invitations 接受后才会成为成员。
// @Tags 空间邀请
// @Accept json
// @Produce json
// @Param id path string true "租户 ID"
// @Param id path string true "空间 ID"
// @Param request body createInvitationRequest true "邀请请求"
// @Success 201 {object} map[string]interface{}
// @Security Bearer
@@ -325,9 +325,9 @@ func (h *TenantInvitationHandler) CreateInvitation(c *gin.Context) {
// RevokeInvitation godoc
// @Summary 撤销待接受邀请
// @Description Owner 取消一条还在 pending 的邀请;已 accepted/declined/revoked/expired 的行不可再撤销。
// @Tags 租户邀请
// @Tags 空间邀请
// @Produce json
// @Param id path string true "租户 ID"
// @Param id path string true "空间 ID"
// @Param inv_id path string true "邀请 ID"
// @Success 200 {object} map[string]interface{}
// @Security Bearer
@@ -498,7 +498,7 @@ func (h *TenantInvitationHandler) AcceptMyInvitation(c *gin.Context) {
if updateErr := h.userService.UpdateUser(ctx, user); updateErr != nil {
logger.Errorf(ctx, "AcceptMyInvitation failed to set default tenant: user=%s tenant=%d err=%v",
caller, member.TenantID, updateErr)
c.Error(apperrors.NewInternalServerError("invitation accepted but default tenant update failed").WithDetails(updateErr.Error()))
c.Error(apperrors.NewInternalServerError("invitation accepted but default workspace update failed").WithDetails(updateErr.Error()))
return
}
}
+3 -3
View File
@@ -54,12 +54,12 @@ type createInviteLinkRequest struct {
// CreateInviteLink godoc
// @Summary 生成共享邀请链接
// @Description 生成一条多次使用的共享邀请链接:谁拿到链接谁就能注册并加入当前租户。
// @Description 生成一条多次使用的共享邀请链接:谁拿到链接谁就能注册并加入当前空间。
// @Description 链接持续有效,直到过期或被撤销。
// @Tags 租户邀请
// @Tags 空间邀请
// @Accept json
// @Produce json
// @Param id path string true "租户 ID"
// @Param id path string true "空间 ID"
// @Param request body createInviteLinkRequest true "共享链接配置"
// @Success 201 {object} map[string]interface{}
// @Security Bearer
+26 -26
View File
@@ -73,23 +73,23 @@ type updateMemberRoleRequest struct {
func parseTenantIDFromPath(c *gin.Context) (uint64, bool) {
raw := strings.TrimSpace(c.Param("id"))
if raw == "" {
c.Error(apperrors.NewValidationError("tenant id is required"))
c.Error(apperrors.NewValidationError("workspace id is required"))
return 0, false
}
v, err := strconv.ParseUint(raw, 10, 64)
if err != nil || v == 0 {
c.Error(apperrors.NewValidationError("tenant id must be a positive integer"))
c.Error(apperrors.NewValidationError("workspace id must be a positive integer"))
return 0, false
}
return v, true
}
// ListMembers godoc
// @Summary 列出租户成员
// @Description 分页返回当前租户内 active 成员(含每位成员的角色、邮箱、头像);支持 q 按邮箱/用户名筛选
// @Tags 租户成员
// @Summary 列出空间成员
// @Description 分页返回当前空间内 active 成员(含每位成员的角色、邮箱、头像);支持 q 按邮箱/用户名筛选
// @Tags 空间成员
// @Produce json
// @Param id path string true "租户 ID"
// @Param id path string true "空间 ID"
// @Param q query string false "按邮箱/用户名模糊筛选"
// @Param page query int false "页码(从 1 起)" default(1)
// @Param page_size query int false "每页数量(最大 100)" default(20)
@@ -162,15 +162,15 @@ func (h *TenantMemberHandler) ListMembers(c *gin.Context) {
}
// AddMember godoc
// @Summary 直接添加租户成员(直加路径)
// @Summary 直接添加空间成员(直加路径)
// @Description
//
// Owner 通过 email 直接把用户作为 active 成员添加进当前租户。
// Owner 通过 email 直接把用户作为 active 成员添加进当前空间。
//
// 这是【直加路径】,被加入的用户没有任何确认机会就出现在租户里——
// 这是【直加路径】,被加入的用户没有任何确认机会就出现在空间里——
// 保留它是为了三类不需要走邀请确认的场景:
// 1. 自动化脚本 / 平台运维 / 数据迁移;
// 2. 跨租户超管 (CanAccessAllTenants) 的批量编排;
// 2. 跨空间超管 (CanAccessAllTenants) 的批量编排;
// 3. 对接外部 IdP 时由身份源单向同步成员。
//
// 所有由 UI 触发的「邀请伙伴加入」交互应改走
@@ -178,10 +178,10 @@ func (h *TenantMemberHandler) ListMembers(c *gin.Context) {
// 人在 /me/invitations 主动接受后再写 tenant_members 行(PR #1303 后续)。
// 这条路径与 invitations 路径共存而不互相替代。
//
// @Tags 租户成员
// @Tags 空间成员
// @Accept json
// @Produce json
// @Param id path string true "租户 ID"
// @Param id path string true "空间 ID"
// @Param request body addMemberRequest true "邀请请求"
// @Success 201 {object} map[string]interface{}
// @Security Bearer
@@ -271,12 +271,12 @@ func (h *TenantMemberHandler) AddMember(c *gin.Context) {
}
// UpdateMemberRole godoc
// @Summary 修改租户成员角色
// @Description Owner 修改某位成员在当前租户内的角色;不能将最后一位 Owner 降级
// @Tags 租户成员
// @Summary 修改空间成员角色
// @Description Owner 修改某位成员在当前空间内的角色;不能将最后一位 Owner 降级
// @Tags 空间成员
// @Accept json
// @Produce json
// @Param id path string true "租户 ID"
// @Param id path string true "空间 ID"
// @Param user_id path string true "用户 ID"
// @Param request body updateMemberRoleRequest true "目标角色"
// @Success 200 {object} map[string]interface{}
@@ -324,11 +324,11 @@ func (h *TenantMemberHandler) UpdateMemberRole(c *gin.Context) {
}
// RemoveMember godoc
// @Summary 移除租户成员
// @Description Owner 将某位成员从当前租户中移除(软删除 tenant_members 行);不能移除最后一位 Owner
// @Tags 租户成员
// @Summary 移除空间成员
// @Description Owner 将某位成员从当前空间中移除(软删除 tenant_members 行);不能移除最后一位 Owner
// @Tags 空间成员
// @Produce json
// @Param id path string true "租户 ID"
// @Param id path string true "空间 ID"
// @Param user_id path string true "用户 ID"
// @Success 200 {object} map[string]interface{}
// @Security Bearer
@@ -363,15 +363,15 @@ func (h *TenantMemberHandler) RemoveMember(c *gin.Context) {
}
// LeaveTenant godoc
// @Summary 退出当前租户
// @Description 调用方主动退出当前租户。等价于以自己的 user_id 调 RemoveMember,
// @Summary 退出当前空间
// @Description 调用方主动退出当前空间。等价于以自己的 user_id 调 RemoveMember,
//
// 但不需要 Owner 权限——非 Owner 也可以自助离开。最后一位 Owner 仍然不能离开
// (需先把其他成员提升为 Owner),由服务层 ErrLastOwner 拦截。
//
// @Tags 租户成员
// @Tags 空间成员
// @Produce json
// @Param id path string true "租户 ID"
// @Param id path string true "空间 ID"
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Router /tenants/{id}/leave [post]
@@ -390,13 +390,13 @@ func (h *TenantMemberHandler) LeaveTenant(c *gin.Context) {
if err := h.memberService.RemoveMember(ctx, caller, tenantID); err != nil {
switch {
case errors.Is(err, service.ErrMembershipNotFound):
c.Error(apperrors.NewNotFoundError("you are not a member of this tenant"))
c.Error(apperrors.NewNotFoundError("you are not a member of this workspace"))
case errors.Is(err, service.ErrLastOwner):
c.Error(apperrors.NewConflictError(err.Error()))
default:
logger.Errorf(ctx, "LeaveTenant failed: user=%s tenant=%d err=%v",
caller, tenantID, err)
c.Error(apperrors.NewInternalServerError("failed to leave tenant").WithDetails(err.Error()))
c.Error(apperrors.NewInternalServerError("failed to leave workspace").WithDetails(err.Error()))
}
return
}
+2 -2
View File
@@ -44,7 +44,7 @@ func favoriteContext(c *gin.Context) (string, uint64, bool) {
}
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
c.Error(apperrors.NewUnauthorizedError("tenant ID not found"))
c.Error(apperrors.NewUnauthorizedError("workspace ID not found"))
return "", 0, false
}
return userID, tenantID, true
@@ -52,7 +52,7 @@ func favoriteContext(c *gin.Context) (string, uint64, bool) {
// ListFavorites godoc
// @Summary List my favorites
// @Description Lists this user's starred resources in the current tenant for a given type
// @Description Lists this user's starred resources in the current workspace for a given type
// @Tags User
// @Param type query string true "Resource type (kb | agent)"
// @Success 200 {object} map[string]interface{}
+9 -9
View File
@@ -79,7 +79,7 @@ func envStoreReadonlyError() gin.H {
// CreateStore godoc
// @Summary Create vector store
// @Description Create a new vector store configuration for the current tenant
// @Description Create a new vector store configuration for the current workspace
// @Tags VectorStore
// @Accept json
// @Produce json
@@ -96,7 +96,7 @@ func (h *VectorStoreHandler) CreateStore(c *gin.Context) {
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: tenant context missing"})
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: workspace context missing"})
return
}
@@ -129,7 +129,7 @@ func (h *VectorStoreHandler) CreateStore(c *gin.Context) {
// ListStores godoc
// @Summary List vector stores
// @Description List all vector stores for the current tenant, including environment-configured and user-created stores
// @Description List all vector stores for the current workspace, including environment-configured and user-created stores
// @Tags VectorStore
// @Produce json
// @Success 200 {object} map[string]interface{} "List of vector stores (env + DB)"
@@ -142,7 +142,7 @@ func (h *VectorStoreHandler) ListStores(c *gin.Context) {
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: tenant context missing"})
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: workspace context missing"})
return
}
@@ -189,7 +189,7 @@ func (h *VectorStoreHandler) GetStore(c *gin.Context) {
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: tenant context missing"})
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: workspace context missing"})
return
}
@@ -242,7 +242,7 @@ func (h *VectorStoreHandler) UpdateStore(c *gin.Context) {
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: tenant context missing"})
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: workspace context missing"})
return
}
@@ -311,7 +311,7 @@ func (h *VectorStoreHandler) DeleteStore(c *gin.Context) {
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: tenant context missing"})
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: workspace context missing"})
return
}
@@ -369,7 +369,7 @@ func (h *VectorStoreHandler) TestStoreByID(c *gin.Context) {
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: tenant context missing"})
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: workspace context missing"})
return
}
@@ -434,7 +434,7 @@ func (h *VectorStoreHandler) TestStoreRaw(c *gin.Context) {
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: tenant context missing"})
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: workspace context missing"})
return
}
+6 -6
View File
@@ -80,7 +80,7 @@ func (h *WebSearchProviderHandler) CreateProvider(c *gin.Context) {
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: tenant context missing"})
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: workspace context missing"})
return
}
@@ -121,7 +121,7 @@ func (h *WebSearchProviderHandler) ListProviders(c *gin.Context) {
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: tenant context missing"})
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: workspace context missing"})
return
}
@@ -156,7 +156,7 @@ func (h *WebSearchProviderHandler) GetProvider(c *gin.Context) {
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: tenant context missing"})
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: workspace context missing"})
return
}
@@ -194,7 +194,7 @@ func (h *WebSearchProviderHandler) UpdateProvider(c *gin.Context) {
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: tenant context missing"})
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: workspace context missing"})
return
}
@@ -287,7 +287,7 @@ func (h *WebSearchProviderHandler) DeleteProvider(c *gin.Context) {
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: tenant context missing"})
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: workspace context missing"})
return
}
@@ -344,7 +344,7 @@ func (h *WebSearchProviderHandler) TestProviderByID(c *gin.Context) {
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: tenant context missing"})
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "unauthorized: workspace context missing"})
return
}
@@ -41,7 +41,7 @@ func (h *WebSearchProviderCredentialsHandler) Put(c *gin.Context) {
ctx := c.Request.Context()
tenantID := h.tenantID(c)
if tenantID == 0 {
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
c.Error(errors.NewBadRequestError("Workspace ID cannot be empty"))
return
}
id := c.Param("id")
@@ -83,7 +83,7 @@ func (h *WebSearchProviderCredentialsHandler) DeleteField(c *gin.Context) {
ctx := c.Request.Context()
tenantID := h.tenantID(c)
if tenantID == 0 {
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
c.Error(errors.NewBadRequestError("Workspace ID cannot be empty"))
return
}
id := c.Param("id")
+4 -4
View File
@@ -23,11 +23,11 @@ type weKnoraCloudCredentialsRequest struct {
}
// SaveCredentials POST /api/v1/weknoracloud/credentials
// 仅保存 APPID/APPSECRET 凭证到租户配置,不自动创建模型
// 仅保存 APPID/APPSECRET 凭证到空间配置,不自动创建模型
//
// SaveCredentials godoc
// @Summary 保存 WeKnoraCloud 凭证
// @Description 保存 APPID/APPSECRET 到当前租户配置(不自动创建模型)
// @Description 保存 APPID/APPSECRET 到当前空间配置(不自动创建模型)
// @Tags WeKnoraCloud
// @Accept json
// @Produce json
@@ -53,11 +53,11 @@ func (h *WeKnoraCloudHandler) SaveCredentials(c *gin.Context) {
}
// Status GET /api/v1/models/weknoracloud/status
// 检查当前租户的 WeKnoraCloud 凭证是否完好,如需重新初始化则返回 needs_reinit=true
// 检查当前空间的 WeKnoraCloud 凭证是否完好,如需重新初始化则返回 needs_reinit=true
//
// Status godoc
// @Summary 检查 WeKnoraCloud 凭证状态
// @Description 检查当前租户的 WeKnoraCloud 凭证是否完好;needs_reinit=true 表示需要重新保存
// @Description 检查当前空间的 WeKnoraCloud 凭证是否完好;needs_reinit=true 表示需要重新保存
// @Tags WeKnoraCloud
// @Produce json
// @Success 200 {object} map[string]interface{} "凭证状态"
+1 -1
View File
@@ -2890,7 +2890,7 @@ func (s *Service) processFileToKnowledgeBase(ctx context.Context, msg *IncomingM
tenant, err := s.tenantService.GetTenantByID(ctx, tenantID)
if err != nil {
logger.Errorf(ctx, "[IM] Failed to get tenant %d for file processing: %v", tenantID, err)
s.sendFileResult(ctx, adapter, msg, msg.FileName, false, "获取租户信息失败", channel)
s.sendFileResult(ctx, adapter, msg, msg.FileName, false, "获取空间信息失败", channel)
return
}
kbCtx := context.WithValue(ctx, types.TenantIDContextKey, tenantID)
+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
+23 -23
View File
@@ -408,7 +408,7 @@ func RegisterKnowledgeBaseRoutes(r *gin.RouterGroup, handler *handler.KnowledgeB
// 由 RegisterKnowledgeRoutes/FAQ/Tag/Wiki 等子路由的 ingest 能力控制;
// KB 自身的元数据/生命周期管理需要 full access 或 manage_kbs。创建/拷贝
// KB 没有单个目标 KB 可约束,因此不对 scoped key 开放(capability 无法
// 把它约束到某个 KB 上);但 full-access key 是租户级全权,与它已能
// 把它约束到某个 KB 上);但 full-access key 是空间级全权,与它已能
// 更新/删除/管理 KB 对齐,允许其创建 KB,消除"能删不能建"的不一致。
kbgrp := r.Group("/knowledge-bases")
kb := g.apiKeyGroup(kbgrp, apiKeyRetrieve(apiKeyFullAccess()))
@@ -568,7 +568,7 @@ func RegisterChatRoutes(r *gin.RouterGroup, handler *session.Handler, g *rbacGua
}
}
// RegisterTenantRoutes 注册租户相关的路由
// RegisterTenantRoutes 注册空间相关的路由
//
// Tenant-internal RBAC for /tenants/:id:
// - GET /:id Viewer+ (read tenant settings)
@@ -612,17 +612,17 @@ func RegisterTenantRoutes(
r.GET("/tenants/all", g.CrossTenant(), handler.ListAllTenants)
r.GET("/tenants/search", g.CrossTenant(), handler.SearchTenants)
// 租户路由组
// 空间路由组
tenantRoutes := r.Group("/tenants")
{
// 创建租户对所有已登录用户开放:用户可以为自己再开一个工作区,
// handler 内部会调 EnsureOwner 把调用者写成新租户的 Owner。
// 跨租户超管走同一个端点,但能携带 storage_quota / status 等
// 创建空间对所有已登录用户开放:用户可以为自己再开一个工作区,
// handler 内部会调 EnsureOwner 把调用者写成新空间的 Owner。
// 跨空间超管走同一个端点,但能携带 storage_quota / status 等
// 全字段(见 handler.CreateTenant 内部分支)。
// 安全说明:这里不挂 g.CrossTenant(),因为 self-service 创建
// 不需要跨租户特权;handler 也不读写 X-Tenant-ID 指向的现有
// 租户,所以越过 PathTenantMatch 守卫不会扩大攻击面。
// 创建租户不对 API key 开放(注册在原始 group,默认拒绝)。
// 不需要跨空间特权;handler 也不读写 X-Tenant-ID 指向的现有
// 空间,所以越过 PathTenantMatch 守卫不会扩大攻击面。
// 创建空间不对 API key 开放(注册在原始 group,默认拒绝)。
tenantRoutes.POST("", handler.CreateTenant)
g.apiKeyRoute(tenantRoutes, http.MethodGet, "", apiKeyManageTenantSettings(apiKeyFullAccess()), handler.ListTenants)
@@ -706,7 +706,7 @@ func RegisterModelRoutes(
credHandler *handler.ModelCredentialsHandler,
g *rbacGuards,
) {
// 模型路由组。租户级基础设施:仅完全访问(Owner)API key 可访问。
// 模型路由组。空间级基础设施:仅完全访问(Owner)API key 可访问。
models := g.apiKeyGroup(r.Group("/models"), apiKeyManageModels(apiKeyFullAccess()))
{
// 获取模型厂商列表 — Viewer+
@@ -810,8 +810,8 @@ func RegisterInitializationRoutes(r *gin.RouterGroup, handler *handler.Initializ
apiKeyManageKnowledgeBases(apiKeyFullAccess()), g.OwnedKBOrAdminFromKbIDParam(), g.KBAccessWrite("kbId"), handler.UpdateKBConfig)
// Ollama / 远程 API / 抽取等系统级检测/下载操作。这些不绑某个 KB,
// 会改租户级模型配置或拉远端模型;JWT 侧只读探测 Viewer+、变更 Admin+。
// 对 API key 均为租户级:full-access key 可用,scoped key 需要 manage_models。
// 会改空间级模型配置或拉远端模型;JWT 侧只读探测 Viewer+、变更 Admin+。
// 对 API key 均为空间级:full-access key 可用,scoped key 需要 manage_models。
g.apiKeyRoute(r, http.MethodGet, "/initialization/ollama/status", apiKeyManageModels(apiKeyFullAccess()), g.Viewer(), handler.CheckOllamaStatus)
g.apiKeyRoute(r, http.MethodGet, "/initialization/ollama/models", apiKeyManageModels(apiKeyFullAccess()), g.Viewer(), handler.ListOllamaModels)
g.apiKeyRoute(r, http.MethodPost, "/initialization/ollama/models/check", apiKeyManageModels(apiKeyFullAccess()), g.Admin(), handler.CheckOllamaModels)
@@ -1205,10 +1205,10 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza
// Knowledge base sharing routes (add to existing kb routes).
// 分享 KB 到组织 = 让组织里所有人能读这个 KB;这跟"修改 KB 元信息"
// 同等敏感,所以挂同款 OwnedKBOrAdmin 矩阵。Viewer 在自己租户里
// 同等敏感,所以挂同款 OwnedKBOrAdmin 矩阵。Viewer 在自己空间里
// 也不能私自把 KB 暴露出去。
// 分享管理不通过 capability 授予(manage_spaces 也不含);仅 full-access
// key(租户级全权)可管理分享,scoped key 保持 default-deny。
// key(空间级全权)可管理分享,scoped key 保持 default-deny。
kbShares := g.apiKeyGroup(r.Group("/knowledge-bases/:id/shares"), apiKeyFullAccess())
{
// Share knowledge base
@@ -1226,10 +1226,10 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza
//
// GET 走 OwnedAgentOrAdmin 作为 JWT 侧的 owner 校验;service 层
// ListSharesByAgent 现在也强制 tenant 归属(与 ListSharesByKnowledgeBase
// 对齐),这样 full-access API key(会短路路由 guard)也无法跨租户
// 对齐),这样 full-access API key(会短路路由 guard)也无法跨空间
// 枚举他人 agent 的分享。
// 同 KB 分享:分享管理不通过 capability 授予;仅 full-access key
// (租户级全权)可管理 agent 分享,scoped key 保持 default-deny。
// (空间级全权)可管理 agent 分享,scoped key 保持 default-deny。
agentShares := g.apiKeyGroup(r.Group("/agents/:id/shares"), apiKeyFullAccess())
{
agentShares.POST("", g.OwnedAgentOrAdmin(), orgHandler.ShareAgent)
@@ -1241,9 +1241,9 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza
g.apiKeyRoute(r, http.MethodGet, "/shared-knowledge-bases", apiKeyManageSpaces(apiKeyFullAccess()), g.Viewer(), orgHandler.ListSharedKnowledgeBases)
// Shared agents route — Viewer+
g.apiKeyRoute(r, http.MethodGet, "/shared-agents", apiKeyManageSpaces(apiKeyFullAccess()), g.Viewer(), orgHandler.ListSharedAgents)
// "Disable by me" 是租户级偏好(写到 tenant_disabled_shared_agents),
// 影响整个租户在会话下拉里看到的 agent 列表。任何 Viewer 改这个表就
// 等于替整个租户做决定 — 必须 Admin+ 才允许调整。
// "Disable by me" 是空间级偏好(写到 tenant_disabled_shared_agents),
// 影响整个空间在会话下拉里看到的 agent 列表。任何 Viewer 改这个表就
// 等于替整个空间做决定 — 必须 Admin+ 才允许调整。
g.apiKeyRoute(r, http.MethodPost, "/shared-agents/disabled", apiKeyManageSpaces(apiKeyFullAccess()), g.Admin(), orgHandler.SetSharedAgentDisabledByMe)
}
@@ -1529,7 +1529,7 @@ func newFileServeHandler(globalFileService interfaces.FileService) gin.HandlerFu
tenant, _ := c.Request.Context().Value(types.TenantInfoContextKey).(*types.Tenant)
if tenant == nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized: tenant context missing"})
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized: workspace context missing"})
return
}
@@ -1661,7 +1661,7 @@ func newKBScopedFileServeHandler(
// storage objects, so the requested path must belong to it.
ownerTenantID, ok := types.TenantIDFromContext(ctx)
if !ok || ownerTenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized: tenant context missing"})
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized: workspace context missing"})
return
}
@@ -1889,7 +1889,7 @@ func servePresignedPreview(r *gin.Engine, cfg *config.Config) {
tenant, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
if tenant == nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized: tenant context missing"})
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized: workspace context missing"})
return
}
@@ -1899,7 +1899,7 @@ func servePresignedPreview(r *gin.Engine, cfg *config.Config) {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
"provider": provider,
"hint": "tenant storage config is missing or incomplete for this provider",
"hint": "workspace storage config is missing or incomplete for this provider",
})
return
}
+1 -1
View File
@@ -96,7 +96,7 @@ const (
// {key, value_type, old_value, new_value} — sensitive values are
// redacted server-side before logging when is_secret=true (P3+;
// for now no setting is marked secret). Audit rows always have
// tenant_id=0 because the change is system-scope, not tenant-scope.
// tenant_id=0 because the change is system-scope, not workspace-scoped.
AuditActionSystemSettingChanged AuditAction = "system.setting_changed"
// AuditActionSystemAdminPromoted fires when a SystemAdmin grants
+4 -4
View File
@@ -87,7 +87,7 @@ type CustomAgent struct {
DeletedAt gorm.DeletedAt `yaml:"deleted_at" json:"deleted_at" gorm:"index"`
// CreatorName 由 list handler 在返回前批量回填,作用同 KnowledgeBase.CreatorName:
// 让前端列表卡片区分「我创建」与「同租户其他成员创建」。不落库,内建 agent / 老数据
// 让前端列表卡片区分「我创建」与「同空间其他成员创建」。不落库,内建 agent / 老数据
// 仍可能为空。
CreatorName string `yaml:"-" json:"creator_name,omitempty" gorm:"-"`
}
@@ -162,14 +162,14 @@ type CustomAgentConfig struct {
// ===== Image Upload / Multimodal Settings =====
// Whether image upload is enabled for this agent (default: false)
ImageUploadEnabled bool `yaml:"image_upload_enabled" json:"image_upload_enabled"`
// VLM model ID for image analysis (optional, falls back to tenant-level VLM)
// VLM model ID for image analysis (optional, falls back to workspace-level VLM)
VLMModelID string `yaml:"vlm_model_id" json:"vlm_model_id"`
// Whether audio upload (ASR transcription) is enabled for this agent (default: false)
AudioUploadEnabled bool `yaml:"audio_upload_enabled" json:"audio_upload_enabled"`
// ASR model ID for audio transcription (optional)
ASRModelID string `yaml:"asr_model_id" json:"asr_model_id"`
// Storage provider for image uploads: "local", "minio", "cos", "tos", "s3", "oss", "ks3".
// Empty means use the global/tenant default provider.
// Empty means use the global/workspace default provider.
ImageStorageProvider string `yaml:"image_storage_provider" json:"image_storage_provider"`
// ===== File Type Restriction Settings =====
@@ -199,7 +199,7 @@ type CustomAgentConfig struct {
// Maximum web search results
WebSearchMaxResults int `yaml:"web_search_max_results" json:"web_search_max_results"`
// WebSearchProviderID references a specific WebSearchProviderEntity.
// If empty, the tenant's default provider (is_default=true) is used.
// If empty, the workspace's default provider (is_default=true) is used.
WebSearchProviderID string `yaml:"web_search_provider_id" json:"web_search_provider_id,omitempty"`
// Whether to auto-fetch full page content for reranked web search results
WebFetchEnabled bool `yaml:"web_fetch_enabled" json:"web_fetch_enabled"`
+3 -3
View File
@@ -54,7 +54,7 @@ type DataSource struct {
// Unique identifier
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
// Tenant ID for multi-tenancy
// Workspace ID for multi-workspace isolation
TenantID uint64 `json:"tenant_id" gorm:"index"`
// Target knowledge base ID
@@ -137,7 +137,7 @@ type SyncLog struct {
// Reference to the data source
DataSourceID string `json:"data_source_id" gorm:"index"`
// Tenant ID
// Workspace ID
TenantID uint64 `json:"tenant_id" gorm:"index"`
// Sync status: running, success, partial, failed, canceled
@@ -369,7 +369,7 @@ type DataSourceSyncPayload struct {
// Data source ID to sync
DataSourceID string `json:"data_source_id"`
// Tenant ID
// Workspace ID
TenantID uint64 `json:"tenant_id"`
// Sync log ID (for tracking)
+2 -2
View File
@@ -8,9 +8,9 @@ import (
// WeKnoraCloudService 处理 WeKnoraCloud 凭证管理
type WeKnoraCloudService interface {
// SaveCredentials 仅保存 APPID/APPSECRET 凭证到租户配置,不自动创建模型
// SaveCredentials 仅保存 APPID/APPSECRET 凭证到空间配置,不自动创建模型
SaveCredentials(ctx context.Context, appID, appSecret string) error
// CheckStatus 检查当前租户的 WeKnoraCloud 凭证是否可正常解密
// CheckStatus 检查当前空间的 WeKnoraCloud 凭证是否可正常解密
// needsReinit=true 表示加密状态已损坏(salt 变更等),需要用户重新填写凭证
CheckStatus(ctx context.Context) (*types.WeKnoraCloudStatusResult, error)
}
+1 -1
View File
@@ -112,7 +112,7 @@ type KnowledgeListFilter struct {
type Knowledge struct {
// Unique identifier of the knowledge
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
// Tenant ID
// Workspace ID
TenantID uint64 `json:"tenant_id"`
// ID of the knowledge base
KnowledgeBaseID string `json:"knowledge_base_id"`
+1 -1
View File
@@ -11,7 +11,7 @@ type KnowledgeProcessOverrides struct {
GraphEnabled *bool `json:"graph_enabled,omitempty"`
ExtractConfig *ExtractConfig `json:"extract_config,omitempty"`
// ParserEngineOverrides passes key-value configuration to docreader parsers
// (e.g. pdf_force_scanned=true). Merged with tenant-level overrides in the
// (e.g. pdf_force_scanned=true). Merged with workspace-level overrides in the
// parse pipeline; per-upload values take priority on conflict.
ParserEngineOverrides map[string]string `json:"parser_engine_overrides,omitempty"`
}
+7 -7
View File
@@ -49,13 +49,13 @@ type KnowledgeBase struct {
IsTemporary bool `yaml:"is_temporary" json:"is_temporary" gorm:"default:false"`
// Description of the knowledge base
Description string `yaml:"description" json:"description"`
// Tenant ID
// Workspace ID
TenantID uint64 `yaml:"tenant_id" json:"tenant_id"`
// CreatorID records the user ID of whoever originally created the KB.
// Used by the tenant-level RBAC middleware to let Contributors edit
// Used by the workspace-level RBAC middleware to let Contributors edit
// their own KBs without granting them access to everyone else's.
// Nullable for backward compatibility with rows created before the
// RBAC migration backfilled the column to the tenant Owner.
// RBAC migration backfilled the column to the workspace Owner.
CreatorID string `yaml:"creator_id" json:"creator_id" gorm:"type:varchar(36);index"`
// Chunking configuration
ChunkingConfig ChunkingConfig `yaml:"chunking_config" json:"chunking_config" gorm:"type:json"`
@@ -69,12 +69,12 @@ type KnowledgeBase struct {
VLMConfig VLMConfig `yaml:"vlm_config" json:"vlm_config" gorm:"type:json"`
// ASR config (Automatic Speech Recognition)
ASRConfig ASRConfig `yaml:"asr_config" json:"asr_config" gorm:"type:json"`
// Storage provider config (new): only stores provider selection; credentials from tenant StorageEngineConfig
// Storage provider config (new): only stores provider selection; credentials from workspace StorageEngineConfig
StorageProviderConfig *StorageProviderConfig `yaml:"storage_provider_config" json:"storage_provider_config" gorm:"column:storage_provider_config;type:jsonb"`
// Deprecated: legacy COS config column. Kept for backward compatibility with old data.
StorageConfig StorageConfig `yaml:"-" json:"storage_config" gorm:"column:cos_config;type:json"`
// VectorStoreID references the VectorStore this knowledge base is bound to.
// When nil, the KB falls back to the tenant's effective engines derived from
// When nil, the KB falls back to the workspace's effective engines derived from
// the RETRIEVE_DRIVER environment variable (env store flow).
// This field is set once at creation time and must not be modified afterwards;
// enforcement lives at the GORM layer (`<-:create`) plus the service-layer
@@ -93,7 +93,7 @@ type KnowledgeBase struct {
IndexingStrategy IndexingStrategy `yaml:"indexing_strategy" json:"indexing_strategy" gorm:"column:indexing_strategy;type:json"`
// IsPinned and PinnedAt are computed per-caller from user_kb_pins
// (see migration 000050). They used to be stored on the row itself,
// which made pinning a tenant-wide ordering decision gated behind
// which made pinning a workspace-wide ordering decision gated behind
// the kb-edit RBAC guard. The columns are still present in legacy
// schemas for rollback safety but are no longer read or written by
// the application — both fields are tagged `gorm:"-"` so GORM
@@ -121,7 +121,7 @@ type KnowledgeBase struct {
ShareCount int64 `yaml:"share_count" json:"share_count" gorm:"-"`
// CreatorName 是 CreatorID 对应用户的展示名(username / email 等),
// 仅在列表场景由 handler 批量回填,不落库;为空表示创建者无法解析(用户已删除、
// CreatorID 为空的老数据等)。前端用它在卡片来源徽章上做 mine vs tenant 的二分。
// CreatorID 为空的老数据等)。前端用它在卡片来源徽章上做 mine vs workspace 的二分。
CreatorName string `yaml:"-" json:"creator_name,omitempty" gorm:"-"`
}
+1 -1
View File
@@ -34,7 +34,7 @@ type MCPService struct {
AdvancedConfig *MCPAdvancedConfig `json:"advanced_config" gorm:"type:json"`
StdioConfig *MCPStdioConfig `json:"stdio_config,omitempty" gorm:"type:json"` // Required for stdio transport
EnvVars MCPEnvVars `json:"env_vars,omitempty" gorm:"type:json"` // Environment variables for stdio
IsBuiltin bool `json:"is_builtin" gorm:"default:false"` // Whether this is a builtin MCP service (visible to all tenants)
IsBuiltin bool `json:"is_builtin" gorm:"default:false"` // Whether this is a builtin MCP service (visible to all workspaces)
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
+1 -1
View File
@@ -115,7 +115,7 @@ type Model struct {
// GORM's struct tag is documented to match so AutoMigrate paths
// produce the same shape.
ID string `yaml:"id" json:"id" gorm:"type:varchar(64);primaryKey"`
// Tenant ID
// Workspace ID
TenantID uint64 `yaml:"tenant_id" json:"tenant_id"`
// Name of the model
Name string `yaml:"name" json:"name"`
+29 -29
View File
@@ -122,8 +122,8 @@ type OrganizationTenantMember struct {
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Organization *Organization `json:"organization,omitempty" gorm:"foreignKey:OrganizationID"`
RepresentativeUser *User `json:"representative_user,omitempty" gorm:"foreignKey:RepresentativeUserID"`
Organization *Organization `json:"organization,omitempty" gorm:"foreignKey:OrganizationID"`
RepresentativeUser *User `json:"representative_user,omitempty" gorm:"foreignKey:RepresentativeUserID"`
}
// TableName returns the table name for GORM
@@ -256,15 +256,15 @@ func (AgentShare) TableName() string {
// SharedAgentInfo represents a shared agent with additional sharing info
type SharedAgentInfo struct {
Agent *CustomAgent `json:"agent"`
ShareID string `json:"share_id"`
OrganizationID string `json:"organization_id"`
OrgName string `json:"org_name"`
Permission OrgMemberRole `json:"permission"`
SourceTenantID uint64 `json:"source_tenant_id"`
SharedAt time.Time `json:"shared_at"`
SharedByUserID string `json:"shared_by_user_id,omitempty"`
SharedByUsername string `json:"shared_by_username,omitempty"`
Agent *CustomAgent `json:"agent"`
ShareID string `json:"share_id"`
OrganizationID string `json:"organization_id"`
OrgName string `json:"org_name"`
Permission OrgMemberRole `json:"permission"`
SourceTenantID uint64 `json:"source_tenant_id"`
SharedAt time.Time `json:"shared_at"`
SharedByUserID string `json:"shared_by_user_id,omitempty"`
SharedByUsername string `json:"shared_by_username,omitempty"`
// DisabledByMe: current tenant has hidden this shared agent from their conversation dropdown (per-user preference)
DisabledByMe bool `json:"disabled_by_me"`
}
@@ -280,7 +280,7 @@ type SourceFromAgentInfo struct {
// When SourceFromAgent is set, the KB is from a shared agent's config (no direct KB share); show as read-only and "来自智能体 XXX".
type OrganizationSharedKnowledgeBaseItem struct {
SharedKnowledgeBaseInfo
IsMine bool `json:"is_mine"`
IsMine bool `json:"is_mine"`
SourceFromAgent *SourceFromAgentInfo `json:"source_from_agent,omitempty"`
}
@@ -363,20 +363,20 @@ type RequestRoleUpgradeRequest struct {
Message string `json:"message" binding:"max=500"` // Optional message explaining the reason
}
// InviteMemberRequest represents a request to directly invite a tenant to organization.
// InviteMemberRequest represents a request to directly invite a workspace to an organization.
//
// Plan 3 (#1303) moved membership to the tenant level: an invitation enrols a whole
// tenant into the organization, with one user attached purely as the representative
// Plan 3 (#1303) moved membership to the workspace level: an invitation enrols a whole
// workspace into the organization, with one user attached purely as the representative
// (display/audit). Callers SHOULD set TenantID and optionally
// RepresentativeUserID. For backward compatibility with older SDK callers that
// still send UserID alone, the handler resolves that user's TenantID and uses
// the user as the representative.
type InviteMemberRequest struct {
// TenantID is the tenant to enrol as an org member. Preferred field.
// TenantID is the workspace to enrol as an org member. Preferred field.
TenantID uint64 `json:"tenant_id"`
// RepresentativeUserID identifies the user attached to the OTM row for
// display/audit. Optional: when unset, the handler picks a stable default
// (the user from the legacy UserID field, or the tenant's owner).
// (the user from the legacy UserID field, or the workspace's owner).
RepresentativeUserID string `json:"representative_user_id"`
// UserID is retained for backward compatibility. When set without
// TenantID, the handler resolves the user's TenantID and uses this
@@ -403,9 +403,9 @@ type OrganizationResponse struct {
Description string `json:"description"`
Avatar string `json:"avatar,omitempty"`
OwnerID string `json:"owner_id"`
// OwnerTenantID is the persisted owner tenant of the organization
// OwnerTenantID is the persisted owner workspace of the organization
// (Plan 3, migration 000046). Frontend uses this to identify the
// "owner row" in the tenant-keyed members list — comparing
// "owner row" in the workspace-keyed members list — comparing
// member.tenant_id against owner_tenant_id is the post-Plan-3
// equivalent of the old member.user_id == owner_id check.
OwnerTenantID uint64 `json:"owner_tenant_id"`
@@ -453,12 +453,12 @@ type OrganizationMemberResponse struct {
// caused this tenant to show up in the search). Multiple users may belong
// to the same tenant; deduplication is by TenantID.
type TenantInviteCandidate struct {
TenantID uint64 `json:"tenant_id"`
TenantName string `json:"tenant_name"`
RepresentativeUserID string `json:"representative_user_id"`
RepresentativeUsername string `json:"representative_username"`
RepresentativeEmail string `json:"representative_email"`
RepresentativeAvatar string `json:"representative_avatar,omitempty"`
TenantID uint64 `json:"tenant_id"`
TenantName string `json:"tenant_name"`
RepresentativeUserID string `json:"representative_user_id"`
RepresentativeUsername string `json:"representative_username"`
RepresentativeEmail string `json:"representative_email"`
RepresentativeAvatar string `json:"representative_avatar,omitempty"`
}
// KnowledgeBaseShareResponse represents a share record in API responses
@@ -496,10 +496,10 @@ type AgentShareResponse struct {
MyPermission string `json:"my_permission,omitempty"`
CreatedAt time.Time `json:"created_at"`
// Agent scope summary for list display (from agent config when available)
ScopeKB string `json:"scope_kb,omitempty"` // "all" | "selected" | "none"
ScopeKB string `json:"scope_kb,omitempty"` // "all" | "selected" | "none"
ScopeKBCount int `json:"scope_kb_count,omitempty"` // when selected
ScopeWebSearch bool `json:"scope_web_search,omitempty"`
ScopeMCP string `json:"scope_mcp,omitempty"` // "all" | "selected" | "none"
ScopeMCP string `json:"scope_mcp,omitempty"` // "all" | "selected" | "none"
ScopeMCPCount int `json:"scope_mcp_count,omitempty"` // when selected
// Agent avatar (emoji or icon name) for list display
AgentAvatar string `json:"agent_avatar,omitempty"`
@@ -507,8 +507,8 @@ type AgentShareResponse struct {
// ListOrganizationsResponse represents the response for listing organizations
type ListOrganizationsResponse struct {
Organizations []OrganizationResponse `json:"organizations"`
Total int64 `json:"total"`
Organizations []OrganizationResponse `json:"organizations"`
Total int64 `json:"total"`
ResourceCounts *ResourceCountsByOrgResponse `json:"resource_counts,omitempty"` // 各空间内知识库/智能体数量,供列表侧栏展示
}
+1 -1
View File
@@ -79,7 +79,7 @@ type Session struct {
Title string `json:"title"`
// Description
Description string `json:"description"`
// Tenant ID
// Workspace ID
TenantID uint64 `json:"tenant_id" gorm:"index"`
// UserID is the owner scope for this session. WeKnora user UUIDs, API
// external-user principals, and embed visitor principals all use this column.
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"time"
)
// SystemSetting is a platform-wide (NOT tenant-scoped) tunable that
// SystemSetting is a platform-wide (NOT workspace-scoped) tunable that
// SystemAdmins can edit at runtime via the management UI without
// restarting the service. Persisted in the system_settings table
// (migration 000053).
+1 -1
View File
@@ -14,7 +14,7 @@ type KnowledgeTag struct {
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
// SeqID is an auto-increment integer ID for external API usage
SeqID int64 `json:"seq_id" gorm:"type:bigint;uniqueIndex;autoIncrement"`
// Tenant ID
// Workspace ID
TenantID uint64 `json:"tenant_id"`
// Knowledge base ID that this tag belongs to
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"type:varchar(36);index"`
+2 -2
View File
@@ -100,9 +100,9 @@ type Tenant struct {
StorageQuota int64 `yaml:"storage_quota" json:"storage_quota" gorm:"default:10737418240"`
// Storage used (Bytes)
StorageUsed int64 `yaml:"storage_used" json:"storage_used" gorm:"default:0"`
// Global Context configuration for this tenant (default for all sessions)
// Global Context configuration for this workspace (default for all sessions)
ContextConfig *ContextConfig `yaml:"context_config" json:"context_config" gorm:"type:jsonb"`
// Global WebSearch configuration for this tenant
// Global WebSearch configuration for this workspace
WebSearchConfig *WebSearchConfig `yaml:"web_search_config" json:"web_search_config" gorm:"type:jsonb"`
// Parser engine config overrides (MinerU endpoint, API key, etc.). Used when parsing documents; overrides env.
ParserEngineConfig *ParserEngineConfig `yaml:"parser_engine_config" json:"parser_engine_config" gorm:"type:jsonb"`
+12 -12
View File
@@ -27,11 +27,11 @@ type UserPreferences struct {
// *false / *true = user explicitly set the toggle.
EnableMemory *bool `json:"enable_memory,omitempty"`
// LastActiveTenantID remembers the last tenant the user actively
// LastActiveTenantID remembers the last workspace the user actively
// switched into, so a fresh login (new device, cleared browser, new
// refresh token) lands them back in that workspace instead of always
// bouncing to their home tenant. Login / RefreshToken validate that
// the tenant still exists and the user still has an active membership
// bouncing to their home workspace. Login / RefreshToken validate that
// the workspace still exists and the user still has an active membership
// (or CanAccessAllTenants) before honouring this preference; an
// invalid pointer is best-effort cleared and the user falls back to
// home.
@@ -40,7 +40,7 @@ type UserPreferences struct {
// *0 = "clear preference" sentinel for the partial-update endpoint
// (UpdateUserPreferences turns this into nil). Otherwise treat
// a stored *0 the same as nil.
// *N = preferred tenant id.
// *N = preferred workspace id.
LastActiveTenantID *uint64 `json:"last_active_tenant_id,omitempty"`
}
@@ -87,13 +87,13 @@ type User struct {
PasswordHash string `json:"-" gorm:"type:varchar(255);not null"`
// Avatar URL of the user
Avatar string `json:"avatar" gorm:"type:varchar(500)"`
// Tenant ID that the user belongs to
// Workspace ID that the user belongs to
TenantID uint64 `json:"tenant_id" gorm:"index"`
// Whether the user is active
IsActive bool `json:"is_active" gorm:"default:true"`
// Whether the user can access all tenants (cross-tenant access)
// Whether the user can access all workspaces (cross-workspace access)
CanAccessAllTenants bool `json:"can_access_all_tenants" gorm:"default:false"`
// Whether the user is a system administrator (independent of tenant roles)
// Whether the user is a system administrator (independent of workspace roles)
IsSystemAdmin bool `json:"is_system_admin" gorm:"default:false;index"`
// Per-user UI/feature preferences (memory toggle, future knobs).
// Stored as JSON (jsonb on Postgres, TEXT on SQLite) via the
@@ -213,14 +213,14 @@ type LoginResponse struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
User *User `json:"user,omitempty"`
// ActiveTenant is the tenant whose ID is encoded in the issued JWT;
// ActiveTenant is the workspace whose ID is encoded in the issued JWT;
// future requests are scoped to it until the client calls /auth/switch-tenant.
// Defaults to the user's home tenant on a fresh login.
// Defaults to the user's home workspace on a fresh login.
ActiveTenant *Tenant `json:"active_tenant,omitempty"`
// Memberships lists every tenant the user can authenticate into,
// Memberships lists every workspace the user can authenticate into,
// along with their role in each. Always populated (length 1 for users
// who only belong to their home tenant) so frontends can render a
// tenant switcher without a follow-up request. Serialised without
// who only belong to their home workspace) so frontends can render a
// workspace switcher without a follow-up request. Serialised without
// omitempty so the field is always present as a JSON array (possibly
// empty) — the "always populated" contract relies on the server side
// guaranteeing a non-nil slice.
+3 -3
View File
@@ -33,13 +33,13 @@ func IsEnvStoreID(id string) bool {
// In production: os.Getenv, in tests: custom lookup function.
type EnvLookupFunc func(string) string
// VectorStore represents a configured vector database instance for a tenant.
// Each tenant can register multiple VectorStore entries (even of the same engine type)
// VectorStore represents a configured vector database instance for a workspace.
// Each workspace can register multiple VectorStore entries (even of the same engine type)
// to support multi-store scenarios (e.g., ES-hot + ES-warm clusters).
type VectorStore struct {
// Unique identifier (UUID, auto-generated)
ID string `yaml:"id" json:"id" gorm:"type:varchar(36);primaryKey"`
// Tenant ID for scoping
// Workspace ID for scoping
TenantID uint64 `yaml:"tenant_id" json:"tenant_id"`
// User-friendly name, e.g., "elasticsearch-hot"
Name string `yaml:"name" json:"name" gorm:"type:varchar(255);not null"`
+4 -4
View File
@@ -25,14 +25,14 @@ const (
WebSearchProviderTypeKeenable WebSearchProviderType = "keenable"
)
// WebSearchProviderEntity represents a configured web search provider instance for a tenant.
// WebSearchProviderEntity represents a configured web search provider instance for a workspace.
// This is a CRUD entity stored in the database, similar to the Model entity.
// Each tenant can create multiple provider configurations (e.g., "Production Bing", "Test Google").
// Each workspace can create multiple provider configurations (e.g., "Production Bing", "Test Google").
// Agents reference these by ID.
type WebSearchProviderEntity struct {
// Unique identifier (UUID, auto-generated)
ID string `yaml:"id" json:"id" gorm:"type:varchar(36);primaryKey"`
// Tenant ID for scoping
// Workspace ID for scoping
TenantID uint64 `yaml:"tenant_id" json:"tenant_id"`
// User-friendly name, e.g., "Production Bing Search"
Name string `yaml:"name" json:"name" gorm:"type:varchar(255);not null"`
@@ -42,7 +42,7 @@ type WebSearchProviderEntity struct {
Description string `yaml:"description" json:"description" gorm:"type:text"`
// Provider-specific parameters (API key, engine ID, etc.) stored as encrypted JSON
Parameters WebSearchProviderParameters `yaml:"parameters" json:"parameters" gorm:"type:json"`
// Whether this is the default provider for the tenant
// Whether this is the default provider for the workspace
IsDefault bool `yaml:"is_default" json:"is_default" gorm:"default:false"`
// Timestamps
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
+1 -1
View File
@@ -79,7 +79,7 @@ type WikiLogEntry struct {
// frontend pagination uses it as a stable cursor without needing to
// disambiguate identical created_at values.
ID uint64 `json:"id" gorm:"primaryKey;autoIncrement"`
// Tenant scope, mirrored from the enclosing knowledge base.
// Workspace scope, mirrored from the enclosing knowledge base.
TenantID uint64 `json:"tenant_id" gorm:"index"`
// Knowledge base this event belongs to.
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"type:varchar(36);index"`
+1 -1
View File
@@ -146,7 +146,7 @@ const (
type WikiPage struct {
// Unique identifier (UUID)
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
// Tenant ID for multi-tenant isolation
// Workspace ID for multi-workspace isolation
TenantID uint64 `json:"tenant_id" gorm:"index"`
// Knowledge base this page belongs to
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"type:varchar(36);index"`
+1 -1
View File
@@ -111,7 +111,7 @@ func ValidateStoragePathTenant(filePath string, tenantID uint64) error {
return fmt.Errorf("storage path has no tenant segment")
}
if pathTenant != tenantID {
return fmt.Errorf("storage path tenant mismatch")
return fmt.Errorf("storage path workspace mismatch")
}
return nil
}