From a40ef46635930a013062e4f194a39a1646089dde Mon Sep 17 00:00:00 2001 From: MidoriKurage Date: Tue, 1 Sep 2026 15:43:40 +0800 Subject: [PATCH] fix(auth): record last-active-tenant preference on SwitchTenant (#2922) * fix(auth): record last-active-tenant preference on SwitchTenant * docs(auth): note SwitchTenant updating last-active-tenant preference * fix(auth): persist last-active tenant before SwitchTenant tokens RefreshToken re-resolves from this preference because refresh JWTs omit tenant_id. Fail the switch if the write fails so a 200 never returns a token pair whose later refresh would land in a different workspace. * fix(cli): align HybridSearch interfaces with SDK variadic options Client.HybridSearch gained ResourceURLOptions; CLI ChunksService and MCP knowledgeService still used the old signature, so *Client no longer satisfied those interfaces. * style(cli): wrap HybridSearch signatures under the 120-column lint --------- Co-authored-by: wizardchen --- .golangci.yml | 4 + cli/cmd/search/chunks.go | 9 +- cli/cmd/search/chunks_test.go | 8 +- cli/internal/mcp/server.go | 3 + cli/internal/mcp/tools.go | 7 +- cli/internal/mcp/tools_test.go | 4 +- client/README.md | 1 + client/README_EN.md | 1 + client/auth.go | 30 ++- docs/api/auth.md | 61 ++++- docs/docs.go | 8 +- docs/swagger.json | 8 +- docs/swagger.yaml | 26 +- internal/application/service/user.go | 36 +++ .../service/user_switch_tenant_test.go | 240 ++++++++++++++++++ internal/handler/auth.go | 18 +- internal/types/interfaces/user.go | 3 + internal/types/user.go | 7 +- website-docs/03-features/01-tenant-auth.md | 2 +- website-docs/04-api/02-api-auth.md | 4 +- 20 files changed, 444 insertions(+), 36 deletions(-) create mode 100644 internal/application/service/user_switch_tenant_test.go diff --git a/.golangci.yml b/.golangci.yml index 63b35f01..86a59075 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -8,6 +8,10 @@ linters: lll: line-length: 120 tab-width: 4 + exclusions: + paths: + # swag embeds OpenAPI as single-line JSON strings; line-length is not meaningful. + - docs/docs\.go$ formatters: enable: - gofmt diff --git a/cli/cmd/search/chunks.go b/cli/cmd/search/chunks.go index c862ab07..8701721a 100644 --- a/cli/cmd/search/chunks.go +++ b/cli/cmd/search/chunks.go @@ -37,9 +37,16 @@ type ChunksOptions struct { // ChunksService is the narrow SDK surface used by runChunks. *sdk.Client // satisfies it; tests inject fakes via Factory.Client. type ChunksService interface { - HybridSearch(ctx context.Context, kbID string, params *sdk.SearchParams) ([]*sdk.SearchResult, error) + HybridSearch( + ctx context.Context, + kbID string, + params *sdk.SearchParams, + opts ...sdk.ResourceURLOptions, + ) ([]*sdk.SearchResult, error) } +var _ ChunksService = (*sdk.Client)(nil) + // NewCmdChunks builds `weknora search chunks "" --kb `. // Uses a positional query argument with the KB selected via flag. // diff --git a/cli/cmd/search/chunks_test.go b/cli/cmd/search/chunks_test.go index 5b708e40..5a62c63a 100644 --- a/cli/cmd/search/chunks_test.go +++ b/cli/cmd/search/chunks_test.go @@ -21,7 +21,9 @@ type fakeChunksSvc struct { gotQ string } -func (f *fakeChunksSvc) HybridSearch(_ context.Context, kbID string, p *sdk.SearchParams) ([]*sdk.SearchResult, error) { +func (f *fakeChunksSvc) HybridSearch( + _ context.Context, kbID string, p *sdk.SearchParams, _ ...sdk.ResourceURLOptions, +) ([]*sdk.SearchResult, error) { f.gotKB = kbID f.gotQ = p.QueryText return f.results, f.err @@ -239,7 +241,9 @@ type capturingChunksSvc struct { capture func(*sdk.SearchParams) } -func (c *capturingChunksSvc) HybridSearch(_ context.Context, _ string, p *sdk.SearchParams) ([]*sdk.SearchResult, error) { +func (c *capturingChunksSvc) HybridSearch( + _ context.Context, _ string, p *sdk.SearchParams, _ ...sdk.ResourceURLOptions, +) ([]*sdk.SearchResult, error) { c.capture(p) return nil, nil } diff --git a/cli/internal/mcp/server.go b/cli/internal/mcp/server.go index 39301186..94bf8528 100644 --- a/cli/internal/mcp/server.go +++ b/cli/internal/mcp/server.go @@ -25,6 +25,7 @@ import ( mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/Tencent/WeKnora/cli/internal/build" + sdk "github.com/Tencent/WeKnora/client" ) // ServiceClient bundles the SDK methods the tool registry needs. *sdk.Client @@ -41,6 +42,8 @@ type ServiceClient interface { chunkListService } +var _ ServiceClient = (*sdk.Client)(nil) + // RunStdio constructs the MCP server, registers the curated 10 tools, and // blocks reading JSON-RPC from stdin until the client disconnects or ctx // is cancelled. Returns the underlying transport error (if any); the cobra diff --git a/cli/internal/mcp/tools.go b/cli/internal/mcp/tools.go index f08432d9..72f2a49a 100644 --- a/cli/internal/mcp/tools.go +++ b/cli/internal/mcp/tools.go @@ -86,7 +86,12 @@ type knowledgeService interface { ListKnowledgeWithFilter(ctx context.Context, kbID string, page, pageSize int, filter sdk.KnowledgeListFilter) ([]sdk.Knowledge, int64, error) GetKnowledge(ctx context.Context, knowledgeID string) (*sdk.Knowledge, error) OpenKnowledgeFile(ctx context.Context, knowledgeID string) (string, io.ReadCloser, error) - HybridSearch(ctx context.Context, kbID string, params *sdk.SearchParams) ([]*sdk.SearchResult, error) + HybridSearch( + ctx context.Context, + kbID string, + params *sdk.SearchParams, + opts ...sdk.ResourceURLOptions, + ) ([]*sdk.SearchResult, error) } type chatService interface { diff --git a/cli/internal/mcp/tools_test.go b/cli/internal/mcp/tools_test.go index 96eebe25..b5919866 100644 --- a/cli/internal/mcp/tools_test.go +++ b/cli/internal/mcp/tools_test.go @@ -91,7 +91,9 @@ func (f *fakeSvc) OpenKnowledgeFile(_ context.Context, id string) (string, io.Re f.calls.openDocID = id return f.openDocName, f.openDocBody, f.openDocErr } -func (f *fakeSvc) HybridSearch(_ context.Context, kbID string, p *sdk.SearchParams) ([]*sdk.SearchResult, error) { +func (f *fakeSvc) HybridSearch( + _ context.Context, kbID string, p *sdk.SearchParams, _ ...sdk.ResourceURLOptions, +) ([]*sdk.SearchResult, error) { f.calls.hybridKBID, f.calls.hybridParams = kbID, p return f.hybridResults, f.hybridErr } diff --git a/client/README.md b/client/README.md index 7b1c0456..c8b3446f 100644 --- a/client/README.md +++ b/client/README.md @@ -16,6 +16,7 @@ 8. **消息管理**:获取和删除会话消息 9. **模型管理**:创建、获取、更新和删除模型 10. **沙箱技能**:向沙箱配置安装技能(zip 上传,或从 ClawHub / SkillHub / GitHub 等来源),并配置技能所需的环境变量 +11. **认证**:登录、刷新令牌、切换激活空间(`SwitchTenant` 会写入最近活跃租户偏好) ## 使用方法 diff --git a/client/README_EN.md b/client/README_EN.md index 2527fe2a..11456a18 100644 --- a/client/README_EN.md +++ b/client/README_EN.md @@ -16,6 +16,7 @@ The client includes the following main functional modules: 8. **Model Management**: Create, retrieve, update, and delete models 9. **Evaluation Function**: Start evaluation tasks and get evaluation results 10. **Sandbox skills**: Install a skill onto a sandbox config (zip upload, or ClawHub / SkillHub / GitHub source) and configure the environment variables it needs +11. **Auth**: Login, refresh tokens, and switch the active workspace (`SwitchTenant` records the last-active-tenant preference) ## Usage diff --git a/client/auth.go b/client/auth.go index ef32a140..97bbac6a 100644 --- a/client/auth.go +++ b/client/auth.go @@ -18,6 +18,8 @@ type LoginRequest struct { // Token is the JWT access token; RefreshToken renews it via Auth.Refresh. // ActiveTenant is the tenant whose ID is encoded in the JWT — every // subsequent request is scoped to it until /auth/switch-tenant is called. +// A successful switch also records that tenant as the user's last-active +// preference, so the next login and refresh land in the same workspace. // Memberships lists every tenant the user can access along with their // role in each, so callers can build a tenant switcher UI without a // follow-up request. @@ -104,8 +106,9 @@ type CurrentUserResponse struct { // HTTP middleware (e.g. the CLI's 401-retry transport) can classify // requests without re-hardcoding the literals. const ( - PathAuthLogin = "/api/v1/auth/login" - PathAuthRefresh = "/api/v1/auth/refresh" + PathAuthLogin = "/api/v1/auth/login" + PathAuthRefresh = "/api/v1/auth/refresh" + PathAuthSwitchTenant = "/api/v1/auth/switch-tenant" ) // RefreshTokenResponse is the body of POST /api/v1/auth/refresh. @@ -135,6 +138,29 @@ func (c *Client) Login(ctx context.Context, req LoginRequest) (*LoginResponse, e return &out, nil } +// SwitchTenantRequest is the body for POST /api/v1/auth/switch-tenant. +type SwitchTenantRequest struct { + TenantID uint64 `json:"tenant_id"` + RefreshToken string `json:"refresh_token,omitempty"` +} + +// SwitchTenant re-issues a token pair scoped to TenantID and records that +// tenant as the user's last-active preference (next login and refresh land +// there). A preference-write failure fails the whole call — no new tokens +// are issued. Maps to POST /api/v1/auth/switch-tenant. +func (c *Client) SwitchTenant(ctx context.Context, req SwitchTenantRequest) (*LoginResponse, error) { + resp, err := c.doRequest(ctx, http.MethodPost, PathAuthSwitchTenant, req, nil) + if err != nil { + return nil, fmt.Errorf("switch tenant: %w", err) + } + var out LoginResponse + if err := parseResponse(resp, &out); err != nil { + return nil, err + } + out.Tenant = out.ActiveTenant + return &out, nil +} + // GetCurrentUser returns the currently authenticated principal and the // tenant projection. Maps to GET /api/v1/auth/me; the bearer token must // already be set on the client (use WithBearerToken). diff --git a/docs/api/auth.md b/docs/api/auth.md index 79f9e54b..a18a08db 100644 --- a/docs/api/auth.md +++ b/docs/api/auth.md @@ -13,7 +13,7 @@ WeKnora 的 `/auth/*` 端点本身**不需要 X-API-Key**,但部分端点需 | `/auth/register` `/auth/login` `/auth/config` | 无 | | `/auth/oidc/config` `/auth/oidc/url` `/auth/oidc/callback` | 无 | | `/auth/refresh` | refresh_token(请求体携带) | -| `/auth/validate` `/auth/me` `/auth/logout` `/auth/change-password` | Bearer JWT | +| `/auth/validate` `/auth/me` `/auth/logout` `/auth/change-password` `/auth/switch-tenant` `/auth/me/preferences` | Bearer JWT | 注册接口可通过环境变量 `DISABLE_REGISTRATION=true` 关闭。密码策略默认 8–32 位且同时包含字母与数字;部署可通过环境变量 `WEKNORA_AUTH_COMPLEX_PASSWORD_ENABLED` 或系统设置 `auth.complex_password_enabled` 要求额外包含大小写字母与特殊字符。当前策略见 `GET /auth/config`。 @@ -31,6 +31,8 @@ WeKnora 的 `/auth/*` 端点本身**不需要 X-API-Key**,但部分端点需 | GET | `/auth/validate` | 验证 JWT 有效性 | | POST | `/auth/logout` | 退出登录 | | GET | `/auth/me` | 获取当前用户信息 | +| PUT | `/auth/me/preferences` | 更新最近活跃空间等个人偏好 | +| POST | `/auth/switch-tenant` | 切换激活空间并换发 token | | POST | `/auth/change-password` | 修改密码 | --- @@ -356,6 +358,63 @@ curl --location 'http://localhost:8080/api/v1/auth/me' \ --- +## POST `/auth/switch-tenant` - 切换激活空间 + +为当前用户在目标空间重新签发 access / refresh token 对。调用者须在目标空间有 **active** 成员关系(`CanAccessAllTenants` 超级用户切到非 home 空间除外)。 + +成功换签会把目标空间写入账号级「最近活跃租户」偏好(`users.preferences.last_active_tenant_id`)。refresh JWT **不含** `tenant_id`,因此 **下次登录与 refresh 都按该偏好落点**;一次换签会改变该用户所有设备的落点。偏好写入失败则整次换签失败,**不会**发出新 token。 + +切回 home 时服务端写入 home ID(与 SPA 发送 `0` 清偏好在当前落点语义上等价)。Web UI 切空间走 `X-Tenant-ID` + `PUT /auth/me/preferences`,不调用本接口。 + +**参数说明(请求体)**: + +| 字段 | 类型 | 必填 | 说明 | +| ------------- | ------ | ---- | ---------------------------- | +| tenant_id | uint64 | 是 | 目标空间 ID | +| refresh_token | string | 否 | 当前 refresh token,成功后撤销 | + +**请求**: + +```curl +curl --location --request POST 'http://localhost:8080/api/v1/auth/switch-tenant' \ +--header 'Authorization: Bearer eyJhbGciOi...' \ +--header 'Content-Type: application/json' \ +--data '{ + "tenant_id": 2 +}' +``` + +**响应**: 与登录相同的 `LoginResponse`(`user` / `active_tenant` / `memberships` / `token` / `refresh_token`)。`user.preferences.last_active_tenant_id` 与目标空间一致。 + +**错误**: 无成员关系或偏好写入失败 → 403;参数校验失败 → 400。 + +--- + +## PUT `/auth/me/preferences` - 更新个人偏好 + +按 PATCH 语义合并 `users.preferences`(仅覆盖请求体里出现的字段)。SPA 在 UI 切空间后用此接口记住落点;`POST /auth/switch-tenant` 会在服务端写同一字段,API 客户端不必再补发本请求。 + +**参数说明(请求体)**: + +| 字段 | 类型 | 必填 | 说明 | +| ---------------------- | ------- | ---- | ---- | +| last_active_tenant_id | *uint64 | 否 | 正整数 = 设置/替换;`0` = 清除(下次登录回 home);省略 = 不改 | + +**请求**: + +```curl +curl --location --request PUT 'http://localhost:8080/api/v1/auth/me/preferences' \ +--header 'Authorization: Bearer eyJhbGciOi...' \ +--header 'Content-Type: application/json' \ +--data '{ + "last_active_tenant_id": 2 +}' +``` + +**响应**: `{ "success": true, "data": { "last_active_tenant_id": 2 } }` + +--- + ## POST `/auth/change-password` - 修改密码 修改当前用户的登录密码。新密码须满足 **8–32 位**且**同时包含字母与数字**;当 `GET /auth/config` 的 `complex_password_enabled` 为 true 时,还须包含大小写字母与特殊字符。不能与当前密码相同。成功后**所有会话被撤销**,需使用新密码重新登录。 diff --git a/docs/docs.go b/docs/docs.go index 0e42773c..6ec42a53 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -1370,7 +1370,7 @@ const docTemplate = `{ "Bearer": [] } ], - "description": "为当前用户在目标空间重新签发访问令牌;要求该用户在目标空间存在 active 成员关系", + "description": "为当前用户在目标空间重新签发访问令牌;要求该用户在目标空间存在 active 成员关系(跨租户超级用户除外)。\n成功换签会把目标空间写入「最近活跃租户」偏好,下次登录与 refresh 都落在该空间(refresh JWT 不含 tenant_id)。\n该偏好是账号级的:一次换签会改变该用户所有设备的下次登录/refresh 落点。偏好写入失败则整次换签失败,不会发出新 token。", "consumes": [ "application/json" ], @@ -1414,7 +1414,7 @@ const docTemplate = `{ } }, "403": { - "description": "无该空间成员关系", + "description": "无该空间成员关系或偏好写入失败", "schema": { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" } @@ -22018,7 +22018,7 @@ const docTemplate = `{ "type": "object", "properties": { "last_active_tenant_id": { - "description": "LastActiveTenantID remembers the last workspace the user actively\nswitched into, so a fresh login (new device, cleared browser, new\nrefresh token) lands them back in that workspace instead of always\nbouncing to their home workspace. Login / RefreshToken validate that\nthe workspace still exists and the user still has an active membership\n(or CanAccessAllTenants) before honouring this preference; an\ninvalid pointer is best-effort cleared and the user falls back to\nhome.\n\nnil = no preference (use user.TenantID, i.e. home)\n*0 = \"clear preference\" sentinel for the partial-update endpoint\n (UpdateUserPreferences turns this into nil). Otherwise treat\n a stored *0 the same as nil.\n*N = preferred workspace id.", + "description": "LastActiveTenantID remembers the last workspace the user actively\nswitched into, so a fresh login (new device, cleared browser, new\nrefresh token) lands them back in that workspace instead of always\nbouncing to their home workspace. Written by the SPA's preferences\nPUT and by service-level SwitchTenant (including when switching\nhome, which stores the home ID). Login / RefreshToken validate that\nthe workspace still exists and the user still has an active membership\n(or CanAccessAllTenants) before honouring this preference; an\ninvalid pointer is best-effort cleared and the user falls back to\nhome. Refresh JWT claims have no tenant_id, so RefreshToken\nre-resolves from this field.\n\nnil = no preference (use user.TenantID, i.e. home)\n*0 = \"clear preference\" sentinel for the partial-update endpoint\n (UpdateUserPreferences turns this into nil). Otherwise treat\n a stored *0 the same as nil.\n*N = preferred workspace id.", "type": "integer" }, "oidc_only_login": { @@ -24769,7 +24769,7 @@ const docTemplate = `{ "type": "object", "properties": { "last_active_tenant_id": { - "description": "LastActiveTenantID lets the SPA persist \"after a fresh login,\ndrop me back into this workspace\" across devices. Send a positive\nworkspace id to set / replace, or 0 to clear. Membership is validated\nat next login, not here. Nil = field omitted from the PATCH and\nstays untouched.", + "description": "LastActiveTenantID lets clients persist \"after a fresh login,\ndrop me back into this workspace\" across devices. The SPA sends\nthis after every tenant switch; POST /auth/switch-tenant records\nthe same preference server-side. Send a positive workspace id to\nset / replace, or 0 to clear. Membership is validated at next\nlogin, not here. Nil = field omitted from the PATCH and stays\nuntouched.", "type": "integer" } } diff --git a/docs/swagger.json b/docs/swagger.json index e7f9e01e..8ee20c3c 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -1363,7 +1363,7 @@ "Bearer": [] } ], - "description": "为当前用户在目标空间重新签发访问令牌;要求该用户在目标空间存在 active 成员关系", + "description": "为当前用户在目标空间重新签发访问令牌;要求该用户在目标空间存在 active 成员关系(跨租户超级用户除外)。\n成功换签会把目标空间写入「最近活跃租户」偏好,下次登录与 refresh 都落在该空间(refresh JWT 不含 tenant_id)。\n该偏好是账号级的:一次换签会改变该用户所有设备的下次登录/refresh 落点。偏好写入失败则整次换签失败,不会发出新 token。", "consumes": [ "application/json" ], @@ -1407,7 +1407,7 @@ } }, "403": { - "description": "无该空间成员关系", + "description": "无该空间成员关系或偏好写入失败", "schema": { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" } @@ -22011,7 +22011,7 @@ "type": "object", "properties": { "last_active_tenant_id": { - "description": "LastActiveTenantID remembers the last workspace the user actively\nswitched into, so a fresh login (new device, cleared browser, new\nrefresh token) lands them back in that workspace instead of always\nbouncing to their home workspace. Login / RefreshToken validate that\nthe workspace still exists and the user still has an active membership\n(or CanAccessAllTenants) before honouring this preference; an\ninvalid pointer is best-effort cleared and the user falls back to\nhome.\n\nnil = no preference (use user.TenantID, i.e. home)\n*0 = \"clear preference\" sentinel for the partial-update endpoint\n (UpdateUserPreferences turns this into nil). Otherwise treat\n a stored *0 the same as nil.\n*N = preferred workspace id.", + "description": "LastActiveTenantID remembers the last workspace the user actively\nswitched into, so a fresh login (new device, cleared browser, new\nrefresh token) lands them back in that workspace instead of always\nbouncing to their home workspace. Written by the SPA's preferences\nPUT and by service-level SwitchTenant (including when switching\nhome, which stores the home ID). Login / RefreshToken validate that\nthe workspace still exists and the user still has an active membership\n(or CanAccessAllTenants) before honouring this preference; an\ninvalid pointer is best-effort cleared and the user falls back to\nhome. Refresh JWT claims have no tenant_id, so RefreshToken\nre-resolves from this field.\n\nnil = no preference (use user.TenantID, i.e. home)\n*0 = \"clear preference\" sentinel for the partial-update endpoint\n (UpdateUserPreferences turns this into nil). Otherwise treat\n a stored *0 the same as nil.\n*N = preferred workspace id.", "type": "integer" }, "oidc_only_login": { @@ -24762,7 +24762,7 @@ "type": "object", "properties": { "last_active_tenant_id": { - "description": "LastActiveTenantID lets the SPA persist \"after a fresh login,\ndrop me back into this workspace\" across devices. Send a positive\nworkspace id to set / replace, or 0 to clear. Membership is validated\nat next login, not here. Nil = field omitted from the PATCH and\nstays untouched.", + "description": "LastActiveTenantID lets clients persist \"after a fresh login,\ndrop me back into this workspace\" across devices. The SPA sends\nthis after every tenant switch; POST /auth/switch-tenant records\nthe same preference server-side. Send a positive workspace id to\nset / replace, or 0 to clear. Membership is validated at next\nlogin, not here. Nil = field omitted from the PATCH and stays\nuntouched.", "type": "integer" } } diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 49ed133c..285c3a3b 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -4069,11 +4069,14 @@ definitions: 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 workspace. Login / RefreshToken validate that + bouncing to their home workspace. Written by the SPA's preferences + PUT and by service-level SwitchTenant (including when switching + home, which stores the home ID). 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. + home. Refresh JWT claims have no tenant_id, so RefreshToken + re-resolves from this field. nil = no preference (use user.TenantID, i.e. home) *0 = "clear preference" sentinel for the partial-update endpoint @@ -6095,11 +6098,13 @@ definitions: properties: last_active_tenant_id: description: |- - LastActiveTenantID lets the SPA persist "after a fresh login, - drop me back into this workspace" across devices. Send a positive - 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 lets clients persist "after a fresh login, + drop me back into this workspace" across devices. The SPA sends + this after every tenant switch; POST /auth/switch-tenant records + the same preference server-side. Send a positive 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. type: integer type: object internal_handler_session.AttachmentUpload: @@ -7176,7 +7181,10 @@ paths: post: consumes: - application/json - description: 为当前用户在目标空间重新签发访问令牌;要求该用户在目标空间存在 active 成员关系 + description: |- + 为当前用户在目标空间重新签发访问令牌;要求该用户在目标空间存在 active 成员关系(跨租户超级用户除外)。 + 成功换签会把目标空间写入「最近活跃租户」偏好,下次登录与 refresh 都落在该空间(refresh JWT 不含 tenant_id)。 + 该偏好是账号级的:一次换签会改变该用户所有设备的下次登录/refresh 落点。偏好写入失败则整次换签失败,不会发出新 token。 parameters: - description: 切换请求 in: body @@ -7201,7 +7209,7 @@ paths: schema: $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' "403": - description: 无该空间成员关系 + description: 无该空间成员关系或偏好写入失败 schema: $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' security: diff --git a/internal/application/service/user.go b/internal/application/service/user.go index 8696d4c5..d557119b 100644 --- a/internal/application/service/user.go +++ b/internal/application/service/user.go @@ -1099,6 +1099,13 @@ func (s *userService) generateTokensForTenant( // The previous refresh token (if provided) is revoked so the old session // can no longer roll forward into the source tenant. // +// On success the target is also recorded as the user's last-active- +// tenant preference. Refresh tokens do not carry tenant_id, so +// RefreshToken / the next login re-resolve from this preference; +// a successful switch therefore has to persist it before minting +// tokens. A write failure aborts the switch so we never return a +// token pair whose later refresh would bounce to a different workspace. +// // Returns ErrMembershipNotFound when the user is not a member of the // target tenant. Cross-tenant superuser access (CanAccessAllTenants) // is allowed without a membership row, mirroring the auth middleware's @@ -1136,6 +1143,14 @@ func (s *userService) SwitchTenant( return nil, fmt.Errorf("load target workspace: %w", err) } + // Persist before minting tokens so a 200 response is also a + // durable landing-preference update. RefreshToken re-reads this + // field; writing after issue would leave a window where access + // is scoped to targetTenantID but refresh falls back to home. + if err := s.recordLastActiveTenant(ctx, user, targetTenantID); err != nil { + return nil, fmt.Errorf("record last-active-tenant preference: %w", err) + } + accessToken, refreshToken, err := s.generateTokensForTenant(ctx, user, targetTenantID) if err != nil { return nil, fmt.Errorf("generate tokens: %w", err) @@ -1163,6 +1178,27 @@ func (s *userService) SwitchTenant( }, nil } +// recordLastActiveTenant records tenantID as the user's last-active- +// tenant preference so fresh logins and refresh-token rotations land +// in the last activated workspace. Switching home writes the home ID +// rather than clearing; resolveLoginTenantID treats *home the same as +// nil today. (The SPA still sends 0 when switching home — landing is +// equivalent unless home tenant_id is later rewritten while the old +// home membership remains.) Errors are returned to the caller. +func (s *userService) recordLastActiveTenant(ctx context.Context, user *types.User, tenantID uint64) error { + if user == nil || tenantID == 0 { + return nil + } + patch := types.UserPreferences{LastActiveTenantID: &tenantID} + merged, err := s.UpdateUserPreferences(ctx, user.ID, patch) + if err != nil { + return err + } + // Reflect the persisted preferences in the switch response. + user.Preferences = merged + return nil +} + // ValidateToken validates an access token. The second return value is // the JWT's `tenant_id` claim — i.e. the tenant the token was minted // for, which may differ from user.TenantID after a /auth/switch-tenant diff --git a/internal/application/service/user_switch_tenant_test.go b/internal/application/service/user_switch_tenant_test.go new file mode 100644 index 00000000..0f1d8d77 --- /dev/null +++ b/internal/application/service/user_switch_tenant_test.go @@ -0,0 +1,240 @@ +package service + +import ( + "context" + "errors" + "testing" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" +) + +// switchTenantUserRepo stores users by value so UpdateUser behaves like +// a real persistence round-trip: a change written by the service is only +// visible to later reads once UpdateUser succeeds. +type switchTenantUserRepo struct { + interfaces.UserRepository + users map[string]types.User + failUpdates bool + updateCalls int +} + +func (r *switchTenantUserRepo) GetUserByID(_ context.Context, id string) (*types.User, error) { + stored, ok := r.users[id] + if !ok { + return nil, errors.New("user not found") + } + user := stored + return &user, nil +} + +func (r *switchTenantUserRepo) UpdateUser(_ context.Context, user *types.User) error { + r.updateCalls++ + if r.failUpdates { + return errors.New("simulated update failure") + } + r.users[user.ID] = *user + return nil +} + +type countingAuthTokenRepo struct { + stubAuthTokenRepo + createCalls int +} + +func (s *countingAuthTokenRepo) CreateToken(context.Context, *types.AuthToken) error { + s.createCalls++ + return nil +} + +func newSwitchTenantTestService(repo *switchTenantUserRepo, memberSvc interfaces.TenantMemberService) *userService { + return &userService{ + userRepo: repo, + tokenRepo: &stubAuthTokenRepo{}, + tenantService: &provisioningTenantService{}, + memberService: memberSvc, + } +} + +// TestSwitchTenantRecordsLastActiveTenantPreference pins the landing +// contract for non-SPA switch paths (server-to-server re-signs, API +// clients): a successful switch persists the target workspace as the +// user's "last active tenant" preference, the response agrees with it, +// and a fresh login resolves back to the switched workspace. +func TestSwitchTenantRecordsLastActiveTenantPreference(t *testing.T) { + ctx := context.Background() + repo := &switchTenantUserRepo{users: map[string]types.User{ + "alice": {ID: "alice", TenantID: 7}, + }} + memberSvc := &membershipLookupService{ + byTenant: map[uint64]*types.TenantMember{ + 42: {TenantID: 42, Status: types.TenantMemberStatusActive}, + }, + } + svc := newSwitchTenantTestService(repo, memberSvc) + user, _ := repo.GetUserByID(ctx, "alice") + + resp, err := svc.SwitchTenant(ctx, user, 42, "") + if err != nil { + t.Fatalf("SwitchTenant: %v", err) + } + + stored, _ := repo.GetUserByID(ctx, "alice") + if stored.Preferences.LastActiveTenantID == nil || *stored.Preferences.LastActiveTenantID != 42 { + t.Fatalf("persisted LastActiveTenantID = %v, want 42", stored.Preferences.LastActiveTenantID) + } + if resp.User.Preferences.LastActiveTenantID == nil || *resp.User.Preferences.LastActiveTenantID != 42 { + t.Fatalf("response LastActiveTenantID = %v, want 42 (response must agree with the active workspace)", + resp.User.Preferences.LastActiveTenantID) + } + if got := svc.resolveLoginTenantID(ctx, stored); got != 42 { + t.Fatalf("fresh login after switch resolves to %d, want 42", got) + } +} + +// TestSwitchTenantBackToHomeWritesHomePreference pins the unconditional +// write: switching back to home records the home ID instead of clearing. +// resolveLoginTenantID treats *home == cleared, so landing semantics are +// identical without a server-side clear sentinel. +func TestSwitchTenantBackToHomeWritesHomePreference(t *testing.T) { + ctx := context.Background() + repo := &switchTenantUserRepo{users: map[string]types.User{ + "alice": {ID: "alice", TenantID: 7}, + }} + memberSvc := &membershipLookupService{ + byTenant: map[uint64]*types.TenantMember{ + 7: {TenantID: 7, Status: types.TenantMemberStatusActive}, + }, + } + svc := newSwitchTenantTestService(repo, memberSvc) + user, _ := repo.GetUserByID(ctx, "alice") + + if _, err := svc.SwitchTenant(ctx, user, 7, ""); err != nil { + t.Fatalf("SwitchTenant back to home: %v", err) + } + + stored, _ := repo.GetUserByID(ctx, "alice") + want := uint64(7) + if stored.Preferences.LastActiveTenantID == nil || *stored.Preferences.LastActiveTenantID != want { + t.Fatalf("persisted LastActiveTenantID = %v, want %d (unconditional write)", + stored.Preferences.LastActiveTenantID, want) + } +} + +// TestSwitchTenantPreferenceWriteFailureAbortsSwitch pins the +// fail-closed contract: RefreshToken re-resolves from last-active, so +// a switch that cannot persist the preference must not issue tokens +// whose later refresh would bounce to a different workspace. +func TestSwitchTenantPreferenceWriteFailureAbortsSwitch(t *testing.T) { + ctx := context.Background() + repo := &switchTenantUserRepo{ + users: map[string]types.User{"alice": {ID: "alice", TenantID: 7}}, + failUpdates: true, + } + memberSvc := &membershipLookupService{ + byTenant: map[uint64]*types.TenantMember{ + 7: {TenantID: 7, Status: types.TenantMemberStatusActive}, + 42: {TenantID: 42, Status: types.TenantMemberStatusActive}, + }, + } + tokens := &countingAuthTokenRepo{} + svc := newSwitchTenantTestService(repo, memberSvc) + svc.tokenRepo = tokens + user, _ := repo.GetUserByID(ctx, "alice") + + resp, err := svc.SwitchTenant(ctx, user, 42, "") + if err == nil { + t.Fatal("SwitchTenant must fail when the preference write fails") + } + if resp != nil { + t.Fatal("failed switch must not return a login response") + } + if tokens.createCalls != 0 { + t.Fatalf("CreateToken calls = %d, want 0 (no tokens before preference persists)", tokens.createCalls) + } + stored, _ := repo.GetUserByID(ctx, "alice") + if stored.Preferences.LastActiveTenantID != nil { + t.Fatalf("LastActiveTenantID = %v, want nil after failed write", stored.Preferences.LastActiveTenantID) + } + if got := svc.resolveLoginTenantID(ctx, stored); got != 7 { + t.Fatalf("fresh login after failed switch resolves to %d, want home 7", got) + } +} + +// TestSwitchTenantSuperuserRecordsPreferenceWithoutMembership covers +// CanAccessAllTenants switching into a tenant with no membership row: +// the preference still has to persist so refresh/login follow the switch. +func TestSwitchTenantSuperuserRecordsPreferenceWithoutMembership(t *testing.T) { + ctx := context.Background() + repo := &switchTenantUserRepo{users: map[string]types.User{ + "alice": {ID: "alice", TenantID: 7, CanAccessAllTenants: true}, + }} + svc := newSwitchTenantTestService(repo, &membershipLookupService{byTenant: map[uint64]*types.TenantMember{}}) + user, _ := repo.GetUserByID(ctx, "alice") + + resp, err := svc.SwitchTenant(ctx, user, 42, "") + if err != nil { + t.Fatalf("SwitchTenant superuser: %v", err) + } + stored, _ := repo.GetUserByID(ctx, "alice") + if stored.Preferences.LastActiveTenantID == nil || *stored.Preferences.LastActiveTenantID != 42 { + t.Fatalf("persisted LastActiveTenantID = %v, want 42", stored.Preferences.LastActiveTenantID) + } + if resp.User.Preferences.LastActiveTenantID == nil || *resp.User.Preferences.LastActiveTenantID != 42 { + t.Fatalf("response LastActiveTenantID = %v, want 42", resp.User.Preferences.LastActiveTenantID) + } +} + +// TestSwitchTenantPreservesOidcOnlyLogin proves the preference write +// goes through the PATCH merge, not a blob overwrite. +func TestSwitchTenantPreservesOidcOnlyLogin(t *testing.T) { + ctx := context.Background() + oidcOnly := true + repo := &switchTenantUserRepo{users: map[string]types.User{ + "alice": { + ID: "alice", + TenantID: 7, + Preferences: types.UserPreferences{ + OidcOnlyLogin: &oidcOnly, + }, + }, + }} + memberSvc := &membershipLookupService{ + byTenant: map[uint64]*types.TenantMember{ + 42: {TenantID: 42, Status: types.TenantMemberStatusActive}, + }, + } + svc := newSwitchTenantTestService(repo, memberSvc) + user, _ := repo.GetUserByID(ctx, "alice") + + if _, err := svc.SwitchTenant(ctx, user, 42, ""); err != nil { + t.Fatalf("SwitchTenant: %v", err) + } + stored, _ := repo.GetUserByID(ctx, "alice") + if stored.Preferences.OidcOnlyLogin == nil || !*stored.Preferences.OidcOnlyLogin { + t.Fatal("OidcOnlyLogin was dropped by the last-active write") + } + if stored.Preferences.LastActiveTenantID == nil || *stored.Preferences.LastActiveTenantID != 42 { + t.Fatalf("LastActiveTenantID = %v, want 42", stored.Preferences.LastActiveTenantID) + } +} + +// TestSwitchTenantNonMemberWritesNoPreference guards the write +// placement: the preference is only recorded after membership +// validation passes, so a rejected switch leaves the user's state +// untouched. +func TestSwitchTenantNonMemberWritesNoPreference(t *testing.T) { + ctx := context.Background() + repo := &switchTenantUserRepo{users: map[string]types.User{ + "alice": {ID: "alice", TenantID: 7}, + }} + svc := newSwitchTenantTestService(repo, &membershipLookupService{byTenant: map[uint64]*types.TenantMember{}}) + user, _ := repo.GetUserByID(ctx, "alice") + + if _, err := svc.SwitchTenant(ctx, user, 42, ""); !errors.Is(err, ErrMembershipNotFound) { + t.Fatalf("SwitchTenant for non-member: err = %v, want ErrMembershipNotFound", err) + } + if repo.updateCalls != 0 { + t.Fatalf("UpdateUser calls = %d, want 0 (no preference write before validation)", repo.updateCalls) + } +} diff --git a/internal/handler/auth.go b/internal/handler/auth.go index 38c52b30..aa0930d2 100644 --- a/internal/handler/auth.go +++ b/internal/handler/auth.go @@ -672,11 +672,13 @@ func (h *AuthHandler) GetCurrentUser(c *gin.Context) { // (preserve existing value) from "explicit false". See // types.UserPreferences for the persistence-layer counterpart. type updateMyPreferencesRequest struct { - // LastActiveTenantID lets the SPA persist "after a fresh login, - // drop me back into this workspace" across devices. Send a positive - // 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 lets clients persist "after a fresh login, + // drop me back into this workspace" across devices. The SPA sends + // this after every tenant switch; POST /auth/switch-tenant records + // the same preference server-side. Send a positive 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"` } @@ -832,14 +834,16 @@ func (h *AuthHandler) GetAuthConfig(c *gin.Context) { // SwitchTenant godoc // @Summary 切换激活空间 -// @Description 为当前用户在目标空间重新签发访问令牌;要求该用户在目标空间存在 active 成员关系 +// @Description 为当前用户在目标空间重新签发访问令牌;要求该用户在目标空间存在 active 成员关系(跨租户超级用户除外)。 +// @Description 成功换签会把目标空间写入「最近活跃租户」偏好,下次登录与 refresh 都落在该空间(refresh JWT 不含 tenant_id)。 +// @Description 该偏好是账号级的:一次换签会改变该用户所有设备的下次登录/refresh 落点。偏好写入失败则整次换签失败,不会发出新 token。 // @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] // diff --git a/internal/types/interfaces/user.go b/internal/types/interfaces/user.go index f39da46d..25f8cfd0 100644 --- a/internal/types/interfaces/user.go +++ b/internal/types/interfaces/user.go @@ -55,6 +55,9 @@ type UserService interface { // returns the corresponding LoginResponse. The caller's previous // refresh token (passed in for revocation) is invalidated. Membership // is verified via the TenantMember service before tokens are issued. + // On success the target is recorded as the user's last-active-tenant + // preference (next login and refresh land there). A preference-write + // failure fails the switch so no token pair is issued. SwitchTenant(ctx context.Context, user *types.User, targetTenantID uint64, currentRefreshToken string) (*types.LoginResponse, error) // ValidateToken validates an access token. It returns the user // referenced by the token plus the active tenant ID encoded in the diff --git a/internal/types/user.go b/internal/types/user.go index 454d19f7..8a94fed3 100644 --- a/internal/types/user.go +++ b/internal/types/user.go @@ -25,11 +25,14 @@ type UserPreferences struct { // 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 workspace. Login / RefreshToken validate that + // bouncing to their home workspace. Written by the SPA's preferences + // PUT and by service-level SwitchTenant (including when switching + // home, which stores the home ID). 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. + // home. Refresh JWT claims have no tenant_id, so RefreshToken + // re-resolves from this field. // // nil = no preference (use user.TenantID, i.e. home) // *0 = "clear preference" sentinel for the partial-update endpoint diff --git a/website-docs/03-features/01-tenant-auth.md b/website-docs/03-features/01-tenant-auth.md index 7bde66a1..2a7451ff 100644 --- a/website-docs/03-features/01-tenant-auth.md +++ b/website-docs/03-features/01-tenant-auth.md @@ -310,7 +310,7 @@ refreshClaims := jwt.MapClaims{ 3. 查 `auth_tokens` 表检查 `IsRevoked`(登出 = 撤销记录); 4. 从 claims 提取 `user_id` 加载用户、`tenant_id` 作为激活租户。 -**租户切换即换发 token**:`SwitchTenant` 校验目标租户的 active 成员资格(跨租户超级用户除外)后,签发携带新 `tenant_id` claim 的新 token 对,并尽力撤销旧 refresh token。 +**租户切换即换发 token**:`SwitchTenant` 校验目标租户的 active 成员资格(跨租户超级用户除外)后,先把目标空间写入「最近活跃租户」偏好(`Preferences.LastActiveTenantID`),再签发携带新 `tenant_id` claim 的 token 对,并尽力撤销旧 refresh token。refresh JWT 不含 `tenant_id`,下次登录与 refresh 都按该偏好落点;偏好写入失败则整次换签失败。切回 home 时写入 home ID(与 SPA 发送 `0` 清偏好在当前落点语义上等价)。该偏好是账号级的,一次换签会改变所有设备的下次落点。 ## 4. API Key 体系 diff --git a/website-docs/04-api/02-api-auth.md b/website-docs/04-api/02-api-auth.md index f045222f..53bf8151 100644 --- a/website-docs/04-api/02-api-auth.md +++ b/website-docs/04-api/02-api-auth.md @@ -102,6 +102,8 @@ curl $BASE/api/v1/auth/config 响应:200,同 Login。 +换签成功会把目标空间写入账号级「最近活跃租户」偏好,下次登录(密码/OIDC/换设备)与 refresh 都回到该空间。refresh JWT 不含 `tenant_id`,因此偏好写入失败则整次换签失败、不会发出新 token。API 客户端无需再补发 `PUT /auth/me/preferences`。Web UI 切空间不走本接口。一次换签会改变该用户所有设备的下次落点。 + ```bash curl -X POST $BASE/api/v1/auth/switch-tenant -H "Authorization: Bearer $TOKEN" \ -H 'Content-Type: application/json' -d '{"tenant_id":2}' @@ -193,7 +195,7 @@ curl $BASE/api/v1/auth/me -H "X-API-Key: $API_KEY" | 字段 | 类型 | 必填 | 说明 | | --- | --- | --- | --- | -| `last_active_tenant_id` | *uint64 | 否 | 最近活跃空间 ID,null 清除 | +| `last_active_tenant_id` | *uint64 | 否 | 正整数设置/替换;`0` 清除(下次登录回 home);省略则不改。`POST /auth/switch-tenant` 成功时服务端会写同一字段。 | 响应:200 `{"success":true,"data":{UserPreferences}}`