fix(reconciliation): 平台 Key 自动带工作空间访问租户资源 (CYWL-37)
build / build (push) Successful in 1m58s

WeKnora v0.9.1 的 /system/admin/runtime/* 由 apiKeyPlatform 声明为
PlatformOnly,租户 Key 即使在 capabilities 里带 system_runtime_read 也会
在网关被 403;要让运行时读与对账共用一把 Key,绑定页必须保存平台 Key,
而平台 Key 访问租户资源要求 X-Tenant-ID。

客户端在首次收到 409 TENANT_REQUIRED 时用同一把 Key 查
/api/v1/tenants/all,按工作空间逐个重试原请求;成功后缓存并在后续请求
带上 X-Tenant-ID。租户 Key 不触发该路径,普通 409(上传冲突)不受影响。
This commit is contained in:
Zhero & 助理
2026-12-02 16:20:10 +08:00
committed by Hermes Assistant
parent 7567159dc0
commit 5798183392
4 changed files with 241 additions and 7 deletions
+128 -5
View File
@@ -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 {
+96
View File
@@ -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")
}
}