diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e5cc18..9b5dcc6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## 开发快照 0.1.427(导入对账:平台 Key 自动带工作空间) + +### Added + +- **WeKnora 客户端支持平台 Key**:绑定页保存的 Key 若是 platform scope,上游的租户接口会回 `409 TENANT_REQUIRED`;客户端此时用同一把 Key 查 `/api/v1/tenants/all`,按工作空间逐个重试原请求,成功后缓存 ID 并在后续请求带上 `X-Tenant-ID`。租户 Key 不触发该路径,行为不变;JSON 请求体在重试时会被重放(上限 1 MiB),上传流式接口不走这条路径。 +- 覆盖三种情形:平台 Key 首次拒绝后重放成功、租户 Key 从不发 `X-Tenant-ID`、普通 409(上传冲突)不被误判成 `TENANT_REQUIRED`。 + +### Changed + +- **为什么需要这一步**:WeKnora v0.9.1 把 `/api/v1/system/admin/runtime/*` 声明为 `apiKeyPlatform`,网关在能力判定之前就拒绝租户 Key,`system_runtime_read` 授给租户 Key 也无效。要想「运行时读与对账共用一把 Key」,绑定里必须是平台 Key,而平台 Key 访问租户资源必须点名工作空间。 +- 同步 `docs/IMPORT_RECONCILIATION_REQUIREMENTS.md` §5/Q7:写清平台 Key 约束、工作空间自动识别,以及建议的最小能力集。 + ## 开发快照 0.1.426(导入对账:运行时读复用知识库绑定 Key) ### Changed diff --git a/docs/IMPORT_RECONCILIATION_REQUIREMENTS.md b/docs/IMPORT_RECONCILIATION_REQUIREMENTS.md index 690859d..598e397 100644 --- a/docs/IMPORT_RECONCILIATION_REQUIREMENTS.md +++ b/docs/IMPORT_RECONCILIATION_REQUIREMENTS.md @@ -118,12 +118,15 @@ WeKnora v0.9.1 新增了系统管理员「任务队列」(CHANGELOG #4732、#5 **列表的盲区**:不传 `parse_status` 时上游隐藏 `deleting` 行(`repository/knowledge.go:176`),所以“列表里没有”不等于“已删除”,R1 必须单条 GET 复核。 -**运行时读 Key 的配置契约(Q7,2026-12-02 改判)** +**运行时读 Key 的配置契约(Q7,2026-12-02 改判,同日修正)** - 不再单独维护平台级只读 Key:「导入对账」的 `runtime/queues` 与 `runtime/documents/{id}`(以及页面上的「WeKnora 处理详情」)直接使用「系统设置 → 知识库绑定」测试环境保存的地址与 Key,与对账扫描共用同一个 resolver。 +- **绑定里的 Key 必须是平台 Key**:WeKnora v0.9.1 的 `/api/v1/system/admin/runtime/*` 由 `apiKeyPlatform` 声明为 `PlatformOnly`,`internal/middleware/api_key_gate.go` 在能力判定之前就先拒绝非 platform scope 的 Key,所以租户 Key 即使授予 `system_runtime_read` 也会得到 403。改动前实测:租户 Key 打 queues 403、打 `knowledge-bases` 200;平台 Key 反之。 +- **平台 Key 访问租户资源要带工作空间**:缺少 `X-Tenant-ID` 时上游返回 `409 TENANT_REQUIRED`。平台在首次遇到该响应时用同一把 Key 请求 `/api/v1/tenants/all`,按返回的工作空间逐个重试原请求,成功后缓存该 ID 并在后续请求带上 `X-Tenant-ID`;租户 Key 不会触发这条路径,行为与之前一致。 +- 绑定 Key 建议按最小权限配置(`system_runtime_read` + `retrieve`,需要列库时再加 `manage_kbs`),不要保存带租户管理/写能力的全权限 Key。 - 每次请求解析绑定;管理员换 Key 保存后,下一次请求即生效,不需要重启 API。不再读取任何 Key 文件。 - 绑定未配置或无法解密 → 503 `runtime_read_unavailable`,页面指向绑定页;上游 401/403 → 502 `runtime_key_forbidden`,页面提示去 WeKnora 授权 `system_runtime_read`;连接或运行时读失败 → 502 `runtime_unreachable`,页面提示连不上 WeKnora。 -- `/monitor/overview` 的 `weknora_queues` 不可用时为 `null`,并用 `weknora_queue_error` 携带上述原因码;三种情况都不影响对账批次本身(对账只用租户 Key 列库与读单条)。 +- `/monitor/overview` 的 `weknora_queues` 不可用时为 `null`,并用 `weknora_queue_error` 携带上述原因码;三种情况都不影响对账批次本身。 ## 6. 运行方式 diff --git a/internal/platform/weknora/client.go b/internal/platform/weknora/client.go index 726558c..590bb47 100644 --- a/internal/platform/weknora/client.go +++ b/internal/platform/weknora/client.go @@ -12,6 +12,7 @@ import ( "net/http" "net/url" "strings" + "sync" "time" ) @@ -102,6 +103,13 @@ type Client struct { apiKey string httpClient *http.Client maxResponseBytes int64 + + // tenantMu guards tenantID: a platform-scoped key must name the workspace + // it acts on (X-Tenant-ID), so the first call that is refused with + // TENANT_REQUIRED discovers the workspace once and every later call reuses + // it. Tenant keys never trigger this path. + tenantMu sync.Mutex + tenantID string } func NewClient(config ClientConfig) (*Client, error) { @@ -446,25 +454,140 @@ func (c *Client) doJSON(ctx context.Context, method, path string, body io.Reader return c.doJSONQuery(ctx, method, path, nil, body, target) } +// maxJSONRequestBody bounds the buffered request body a retry can replay. +// Every JSON call here carries a small filter object; uploads stream through +// UploadFile and never reach this path. +const maxJSONRequestBody int64 = 1 << 20 + func (c *Client) doJSONQuery(ctx context.Context, method, path string, query url.Values, body io.Reader, target any) error { + var payload []byte + if body != nil { + read, err := io.ReadAll(io.LimitReader(body, maxJSONRequestBody+1)) + if err != nil { + return errors.New("read WeKnora request body") + } + if int64(len(read)) > maxJSONRequestBody { + return errors.New("WeKnora request body exceeds size limit") + } + payload = read + } + response, err := c.send(ctx, method, path, query, payload) + if err != nil { + return err + } + if tenantRequired(response) { + // A platform-scoped key is refused until it names its workspace. The + // binding page stores whichever key the operator saved, so discover the + // workspace from the same key instead of asking for a second setting. + tenants, err := c.platformTenants(ctx) + if err != nil { + return err + } + for _, tenant := range tenants { + c.rememberTenant(tenant) + response, err = c.send(ctx, method, path, query, payload) + if err != nil { + return err + } + if !tenantRequired(response) { + break + } + } + } + if response.status < 200 || response.status >= 300 { + return &HTTPError{StatusCode: response.status} + } + if err := json.Unmarshal(response.body, target); err != nil { + return errors.New("decode WeKnora response") + } + return nil +} + +type rawResponse struct { + status int + body []byte +} + +// send performs one request with the currently known workspace header. +func (c *Client) send(ctx context.Context, method, path string, query url.Values, payload []byte) (*rawResponse, error) { endpoint := c.endpoint(path) if len(query) > 0 { endpoint += "?" + query.Encode() } - req, err := http.NewRequestWithContext(ctx, method, endpoint, body) + var reader io.Reader + if payload != nil { + reader = bytes.NewReader(payload) + } + req, err := http.NewRequestWithContext(ctx, method, endpoint, reader) if err != nil { - return errors.New("create WeKnora request") + return nil, errors.New("create WeKnora request") } req.Header.Set("Accept", "application/json") - if body != nil { + if payload != nil { req.Header.Set("Content-Type", "application/json") } req.Header.Set("X-API-Key", c.apiKey) + if tenant := c.currentTenant(); tenant != "" { + req.Header.Set("X-Tenant-ID", tenant) + } resp, err := c.httpClient.Do(req) if err != nil { - return fmt.Errorf("send WeKnora request: %w", err) + return nil, fmt.Errorf("send WeKnora request: %w", err) } - return c.decodeResponse(resp, target) + defer resp.Body.Close() + body, err := io.ReadAll(io.LimitReader(resp.Body, c.maxResponseBytes+1)) + if err != nil { + return nil, errors.New("read WeKnora response") + } + if int64(len(body)) > c.maxResponseBytes { + return nil, errors.New("WeKnora response exceeds size limit") + } + return &rawResponse{status: resp.StatusCode, body: body}, nil +} + +// tenantRequired reports WeKnora's 409 TENANT_REQUIRED refusal, which is +// distinct from an upload conflict despite sharing the status code. +func tenantRequired(response *rawResponse) bool { + return response != nil && response.status == http.StatusConflict && + bytes.Contains(response.body, []byte(`"TENANT_REQUIRED"`)) +} + +// platformTenants lists the workspaces a platform-scoped key may act on. The +// route is tenant-optional, so it answers before any workspace is known. +func (c *Client) platformTenants(ctx context.Context) ([]string, error) { + var response struct { + Success bool `json:"success"` + Data struct { + Items []struct { + ID uint64 `json:"id"` + } `json:"items"` + } `json:"data"` + } + if err := c.doJSONQuery(ctx, http.MethodGet, "/api/v1/tenants/all", nil, nil, &response); err != nil { + return nil, err + } + tenants := make([]string, 0, len(response.Data.Items)) + for _, item := range response.Data.Items { + if item.ID != 0 { + tenants = append(tenants, fmt.Sprint(item.ID)) + } + } + if len(tenants) == 0 { + return nil, errors.New("WeKnora platform key has no workspace to act on") + } + return tenants, nil +} + +func (c *Client) currentTenant() string { + c.tenantMu.Lock() + defer c.tenantMu.Unlock() + return c.tenantID +} + +func (c *Client) rememberTenant(tenant string) { + c.tenantMu.Lock() + defer c.tenantMu.Unlock() + c.tenantID = tenant } func (c *Client) decodeResponse(resp *http.Response, target any) error { diff --git a/internal/platform/weknora/client_test.go b/internal/platform/weknora/client_test.go index 45ccb2b..f082d2e 100644 --- a/internal/platform/weknora/client_test.go +++ b/internal/platform/weknora/client_test.go @@ -469,3 +469,99 @@ func TestClientClassifiesTimeoutAsRetryable(t *testing.T) { t.Fatalf("GetKnowledge() error = %v, want retryable timeout", err) } } + +// A platform-scoped key is refused with TENANT_REQUIRED until it names a +// workspace. The client must discover that workspace with the same key and +// replay the call, then reuse the header for later calls. +func TestClientResolvesWorkspaceForPlatformKey(t *testing.T) { + const apiKey = "platform" + "-key" + var listCalls, tenantCalls atomic.Int64 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/v1/tenants/all": + tenantCalls.Add(1) + if got := r.Header.Get("X-API-Key"); got != apiKey { + t.Fatalf("tenants X-API-Key = %q", got) + } + _, _ = w.Write([]byte(`{"success":true,"data":{"items":[{"id":10000,"name":"workspace"}]}}`)) + case "/api/v1/knowledge-bases": + listCalls.Add(1) + if r.Header.Get("X-Tenant-ID") != "10000" { + w.WriteHeader(http.StatusConflict) + _, _ = w.Write([]byte(`{"code":"TENANT_REQUIRED","error":"Workspace required: platform API keys must send X-Tenant-ID"}`)) + return + } + _, _ = w.Write([]byte(`{"success":true,"data":[{"id":"kb-1","name":"测试库","knowledge_count":1,"chunk_count":2,"tenant_id":10000}]}`)) + case "/api/v1/knowledge/knowledge-1": + if r.Header.Get("X-Tenant-ID") != "10000" { + w.WriteHeader(http.StatusConflict) + _, _ = w.Write([]byte(`{"code":"TENANT_REQUIRED"}`)) + return + } + _, _ = w.Write([]byte(`{"success":true,"data":{"id":"knowledge-1","knowledge_base_id":"kb-1","parse_status":"completed"}}`)) + default: + t.Fatalf("unexpected path %s", r.URL.Path) + } + })) + defer server.Close() + + client, err := NewClient(ClientConfig{BaseURL: server.URL, APIKey: apiKey, Timeout: time.Second}) + if err != nil { + t.Fatal(err) + } + bases, err := client.ListKnowledgeBases(context.Background()) + if err != nil { + t.Fatalf("ListKnowledgeBases() error = %v", err) + } + if len(bases) != 1 || bases[0].ID != "kb-1" { + t.Fatalf("bases = %#v", bases) + } + if _, err := client.GetKnowledge(context.Background(), "knowledge-1"); err != nil { + t.Fatalf("GetKnowledge() after discovery error = %v", err) + } + if tenantCalls.Load() != 1 { + t.Fatalf("tenant discovery calls = %d, want 1", tenantCalls.Load()) + } + if listCalls.Load() != 2 { + t.Fatalf("knowledge-base calls = %d, want 2 (refused + replay)", listCalls.Load()) + } +} + +// A tenant key never sends X-Tenant-ID and never asks for the workspace list. +func TestClientTenantKeyNeverSendsWorkspaceHeader(t *testing.T) { + const apiKey = "tenant" + "-key" + var tenantCalls atomic.Int64 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/tenants/all" { + tenantCalls.Add(1) + t.Fatalf("tenant key must not query the workspace list") + } + if got := r.Header.Get("X-Tenant-ID"); got != "" { + t.Fatalf("X-Tenant-ID = %q, want empty for a tenant key", got) + } + _, _ = w.Write([]byte(`{"success":true,"data":[{"id":"kb-1","name":"测试库","knowledge_count":1,"chunk_count":2,"tenant_id":10000}]}`)) + })) + defer server.Close() + + client, err := NewClient(ClientConfig{BaseURL: server.URL, APIKey: apiKey, Timeout: time.Second}) + if err != nil { + t.Fatal(err) + } + if _, err := client.ListKnowledgeBases(context.Background()); err != nil { + t.Fatalf("ListKnowledgeBases() error = %v", err) + } + if tenantCalls.Load() != 0 { + t.Fatalf("tenant discovery calls = %d", tenantCalls.Load()) + } +} + +// An upload conflict keeps its own meaning: 409 without TENANT_REQUIRED is not +// treated as a workspace refusal. +func TestTenantRequiredIgnoresPlainConflict(t *testing.T) { + if tenantRequired(&rawResponse{status: http.StatusConflict, body: []byte(`{"error":"already exists"}`)}) { + t.Fatal("plain 409 must not be classified as TENANT_REQUIRED") + } + if !tenantRequired(&rawResponse{status: http.StatusConflict, body: []byte(`{"code":"TENANT_REQUIRED"}`)}) { + t.Fatal("TENANT_REQUIRED 409 must be classified") + } +}