feat(knowledge-base): validate vector store bindings on create, copy, and delete

Wires KnowledgeBase.VectorStoreID and the ownership-aware retrieve factory
into the user-facing knowledge-base lifecycle:

- POST /knowledge-bases validates the requested vector_store_id against
  the caller's tenant scope and the engine registry. New error codes
  ErrVectorStoreBindingInvalid (2200) and ErrVectorStoreUnavailable (2201)
  distinguish the typed branches without echoing UUIDs to the client.
- GET / POST / PUT / PUT-pin responses embed the bound store's display
  metadata (name, source, engine_type, status) without exposing any
  connection credentials. Cross-tenant shared KBs receive a suppressed
  payload (vector_store_id stripped, source="shared") so operator-chosen
  store names cannot be enumerated across tenants.
- POST /knowledge-bases/copy synchronously rejects clones whose target
  has a different embedding model or vector store, before the async
  clone task is enqueued. The async clone worker re-applies the same
  checks for defense in depth.
- DELETE /vector-stores/:id refuses to remove a store with bound KBs,
  inside a transaction that row-locks the store on PostgreSQL and
  serializes via WAL on SQLite. unregister-from-registry is wrapped in
  defer/recover so a panic surfaces as a structured warning instead of
  silently leaking a stale engine.
- vector_store_id is immutable after creation. The GORM <-:create tag
  blocks every ORM update path; the service-layer DTO omits the field
  entirely; a reflection-based regression test catches any future
  maintainer who adds it back to either layer.
- Empty-string vector_store_id is normalized to nil at both the create
  path and inside SharesStoreWith, so rows persisted by callers that
  did not run Normalize first cannot trip false same-store comparisons.

Part of #993. Depends on #994 and #1310.
This commit is contained in:
ochan.kwon
2026-05-18 10:10:01 +09:00
committed by lyingbug
parent 7611d59d71
commit 0e8de6192c
23 changed files with 2420 additions and 164 deletions
+40 -4
View File
@@ -8,6 +8,7 @@
- JSON 中对象存储相关字段:**`storage_config`** 为序列化字段名(对应数据库列 `cos_config`,兼容旧数据)。旧客户端若仍发送或接收 `cos_config`,服务端会兼容解析;新集成请使用 **`storage_config`**。
- **`storage_provider_config`** 为新版存储提供者选择(如 `{"provider": "local"}`),与租户级存储引擎凭证配合使用;无配置时可为 `null`。
- 嵌套配置对象:`chunking_config`、`image_processing_config`、`vlm_config`、`asr_config`、`extract_config`、`faq_config`、`question_generation_config`。其中 `extract_config`、`faq_config`、`question_generation_config` 允许为 `null`。
- **`vector_store_id`** 为知识库绑定的向量存储 ID(参见 [vector-store.md](./vector-store.md))。未指定(或 `null`/`""`)时使用租户级默认的环境变量存储;一旦创建即不可修改。详情接口返回时会附带 `vector_store_name` / `vector_store_source` / `vector_store_engine_type` / `vector_store_status` 四个只读元数据字段,用于前端展示。
| 方法 | 路径 | 描述 |
| ------ | ----------------------------------------- | ------------------------ |
@@ -43,6 +44,7 @@
| extract_config | object | 否 | 图谱抽取配置;`enabled=true` 时需提供 `text`/`tags`/`nodes`/`relations` |
| faq_config | object | 否 | FAQ 配置(仅 FAQ 类型知识库需要) |
| question_generation_config | object | 否 | 问题生成配置 |
| vector_store_id | string | 否 | 绑定的向量存储 ID。不传或为空字符串等同于 `null`(使用环境变量默认存储)。指定时必须是调用者所在租户拥有的向量存储 UUID;创建后不可修改。无效 UUID / 跨租户 / 未注册到引擎的 ID 会返回 `400` |
**请求**:
@@ -102,7 +104,8 @@ curl --location 'http://localhost:8080/api/v1/knowledge-bases' \
"question_generation_config": {
"enabled": false,
"question_count": 3
}
},
"vector_store_id": "550e8400-e29b-41d4-a716-446655440000"
}'
```
@@ -170,6 +173,11 @@ curl --location 'http://localhost:8080/api/v1/knowledge-bases' \
"knowledge_count": 0,
"chunk_count": 0,
"processing_count": 0,
"vector_store_id": "550e8400-e29b-41d4-a716-446655440000",
"vector_store_name": "elasticsearch-hot",
"vector_store_source": "user",
"vector_store_engine_type": "elasticsearch",
"vector_store_status": "available",
"created_at": "2025-08-12T11:30:09.206238645+08:00",
"updated_at": "2025-08-12T11:30:09.206238854+08:00",
"deleted_at": null
@@ -178,6 +186,23 @@ curl --location 'http://localhost:8080/api/v1/knowledge-bases' \
}
```
**`vector_store_*` 响应字段说明**:
| 字段 | 类型 | 说明 |
| -------------------------- | ------ | ---------------------------------------------------------------------------------------------------------- |
| `vector_store_id` | string | 绑定的向量存储 ID(创建时未指定时为 `null`,从响应中省略) |
| `vector_store_name` | string | 绑定存储的展示名。未绑定时返回 `"System default"`;跨租户共享 KB 视图中被隐藏 |
| `vector_store_source` | string | `"user"`(DB 中创建的存储)/ `"env"`(环境变量虚拟存储)/ `"shared"`(跨租户共享 KB)/ `"unavailable"`(绑定的存储已不可解析) |
| `vector_store_engine_type` | string | 引擎类型(`elasticsearch` / `qdrant` / `milvus` 等)。`shared` / `unavailable` 时为空 |
| `vector_store_status` | string | `"available"` / `"unavailable"`。`unavailable` 表示绑定的存储已被删除或不在内存注册表中,UI 可据此提示用户重新绑定 |
**错误码(Phase 2 新增)**:
| HTTP | code | 说明 |
| ---- | ---- | ----------------------------------------------------------------- |
| 400 | 2200 | `vector_store_id` 无效:格式错误、不存在或属于其他租户(统一返回,避免枚举泄漏) |
| 400 | 2201 | 指定的向量存储当前不可用:存在于数据库但未注册到引擎注册表,请检查 connection_config |
## GET `/knowledge-bases` - 获取知识库列表
返回当前租户拥有的全部知识库。当传入 `agent_id` 时,校验调用者对该共享智能体的访问权限后,返回该智能体配置可见的知识库范围(用于 `@` 提及)。
@@ -198,6 +223,8 @@ curl --location 'http://localhost:8080/api/v1/knowledge-bases' \
**响应**: `data` 为数组,每个元素的字段结构同 `POST /knowledge-bases` 响应,并额外携带 `knowledge_count` / `chunk_count` / `processing_count` / `share_count` / `is_pinned` / `pinned_at` 这些聚合与状态字段。
> **注意(Phase 2)**:列表接口不包含 `vector_store_name` / `vector_store_source` / `vector_store_engine_type` / `vector_store_status` 这四个解析后的元数据字段(避免 N+1 查询);仅 `vector_store_id` 来自数据库本身。需要展示存储名称时请单独调用详情接口或 `/vector-stores/:id`。
## GET `/knowledge-bases/:id` - 获取知识库详情
根据 ID 获取知识库详情。当通过共享智能体访问时,可传 `agent_id` 进行权限校验;此时返回对象会附加 `my_permission` 字段以指示当前用户对该知识库的角色(如 `viewer`)。
@@ -222,7 +249,7 @@ curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001' \
--header 'X-API-Key: sk-xxxxx'
```
**响应**: 字段结构同 `POST /knowledge-bases` 响应,并附 `is_pinned` / `pinned_at` / `knowledge_count` / `chunk_count` / `processing_count` 状态字段。通过共享智能体访问时还会附加 `my_permission`。
**响应**: 字段结构同 `POST /knowledge-bases` 响应(包含 Phase 2 的 `vector_store_*` 元数据字段),并附 `is_pinned` / `pinned_at` / `knowledge_count` / `chunk_count` / `processing_count` 状态字段。通过共享智能体访问时还会附加 `my_permission`;同时 `vector_store_name` / `vector_store_engine_type` 会被隐藏(`vector_store_source` 返回 `"shared"`),避免跨租户泄漏存储展示名。
## PUT `/knowledge-bases/:id` - 更新知识库
@@ -282,7 +309,7 @@ curl --location --request PUT 'http://localhost:8080/api/v1/knowledge-bases/b582
}'
```
**响应**: 字段结构同 `POST /knowledge-bases` 响应(返回更新后的完整知识库对象)。
**响应**: 字段结构同 `POST /knowledge-bases` 响应(返回更新后的完整知识库对象,包含 Phase 2 的 `vector_store_*` 元数据字段。`vector_store_id` 与创建时保持一致,无法通过该接口更改)。
## DELETE `/knowledge-bases/:id` - 删除知识库
@@ -329,7 +356,7 @@ curl --location --request PUT 'http://localhost:8080/api/v1/knowledge-bases/kb-0
--header 'Content-Type: application/json'
```
**响应**: 字段结构同 `POST /knowledge-bases` 响应,本接口操作后 `is_pinned` 翻转、`pinned_at` 同步更新。
**响应**: 字段结构同 `POST /knowledge-bases` 响应(包含 Phase 2 的 `vector_store_*` 元数据字段),本接口操作后 `is_pinned` 翻转、`pinned_at` 同步更新。
## GET `/knowledge-bases/:id/hybrid-search` - 混合搜索
@@ -404,6 +431,15 @@ curl --location --request GET 'http://localhost:8080/api/v1/knowledge-bases/kb-0
**约束**:源知识库 `source_id` 必须属于调用者所在租户;若指定 `target_id`,目标知识库同样必须属于调用者租户,否则返回 `403 Forbidden`。
**Phase 2 同步预检(当 `target_id` 非空时)**:
| 检查 | 失败时响应 |
| -------------- | ----------------------------------------------------------------------------- |
| 嵌入模型一致性 | `400` `source and target knowledge bases use different embedding models; clone into a target with the same embedding model` |
| 向量存储一致性 | `400` `source and target knowledge bases are bound to different vector stores; cross-store cloning is not yet supported` |
预检失败时任务不会入队、不会生成 `task_id`,调用方直接收到 `400`;这两个检查在异步 worker 中会再次执行(defense in depth),但在握手时即时拒绝是为了避免用户需要轮询 `progress` 才能看到错误。当 `target_id` 为空(新建目标库)时,目标库会自动复制源库的 `vector_store_id` 与 `embedding_model_id`,因此预检不会触发。
**参数说明(请求体)**:
| 字段 | 类型 | 必填 | 说明 |
+31 -8
View File
@@ -332,6 +332,10 @@ curl --location --request PUT 'http://localhost:8080/api/v1/vector-stores/550e84
对 DB 中的存储执行软删除。环境变量存储不可删除(返回 `400`)。
**Phase 2 — 绑定保护**:
删除请求在事务中执行,并按 `(tenant_id, vector_store_id)` 复合索引统计当前租户中仍绑定到该存储的活跃知识库数量。**只要存在任意绑定的知识库(已软删除的 KB 不计入),删除即被拒绝**,调用者必须先解绑或删除这些知识库才能继续。在 PostgreSQL 上,事务期间会对 `vector_stores` 行加 `SELECT … FOR UPDATE` 行锁,阻止并发的知识库创建请求悄悄落到正在被删除的存储上(SQLite 上则依赖 WAL + 单写入序列化达成同样语义)。
**路径参数**:
| 字段 | 类型 | 必填 | 说明 |
@@ -345,7 +349,7 @@ curl --location --request DELETE 'http://localhost:8080/api/v1/vector-stores/550
--header 'X-API-Key: sk-xxxxx'
```
**响应**:
**响应(成功)**:
```json
{
@@ -353,6 +357,20 @@ curl --location --request DELETE 'http://localhost:8080/api/v1/vector-stores/550
}
```
**响应(绑定保护触发)**:
```json
{
"success": false,
"error": {
"code": 1000,
"message": "vector store still has 3 knowledge base(s) bound to it; unbind or delete them before removing the store"
}
}
```
HTTP `400`。错误消息中包含具体的知识库数量(便于运营定位),但不包含任何 KB 的 ID/名称,以避免跨租户信息泄漏。删除被拒绝时,DB 中的存储行保持原状,进程内引擎注册表也不会被清除。
## POST `/vector-stores/:id/test` - 测试已保存或环境变量存储的连接
对已保存的 DB 存储或环境变量虚拟存储执行一次连接测试。成功时返回检测到的服务器版本;对 DB 存储,检测到的版本会被自动写回 `connection_config.version`,环境变量存储不会更新。
@@ -399,13 +417,18 @@ curl --location --request POST 'http://localhost:8080/api/v1/vector-stores/550e8
- **readonly**:`true`
- **不可修改/删除**:`PUT` 和 `DELETE` 返回 `400`
- **可测试连通性**:`POST /vector-stores/:id/test` 正常工作
- **被知识库绑定时**:未指定 `vector_store_id` 创建的知识库默认使用环境变量存储;这种知识库在响应中显示为 `vector_store_name="System default"` + `vector_store_source="env"`。
## 错误码
| HTTP 状态码 | 含义 |
| ----------- | --------------------------------------------------- |
| 400 | 请求参数错误、校验失败、尝试修改环境变量存储 |
| 401 | 未认证(缺少租户上下文或 API Key) |
| 404 | 向量存储不存在 |
| 409 | 同一 endpoint + index 组合已存在 |
| 500 | 内部服务器错误 |
| HTTP 状态码 | code | 含义 |
| ----------- | ---- | --------------------------------------------------- |
| 400 | 1000 | 请求参数错误、校验失败、尝试修改环境变量存储、删除时仍有知识库绑定 |
| 400 | 2200 | 知识库创建时引用的 `vector_store_id` 无效(不存在或属于其他租户) |
| 400 | 2201 | 知识库创建时引用的存储当前不可用(DB 中存在但未注册到引擎) |
| 401 | 1001 | 未认证(缺少租户上下文或 API Key) |
| 404 | 1003 | 向量存储不存在 |
| 409 | 1005 | 同一 endpoint + index 组合已存在 |
| 500 | 1007 | 内部服务器错误 |
> `2200` / `2201` 由 `POST /knowledge-bases` 等知识库创建路径返回(详见 [knowledge-base.md](./knowledge-base.md)),列于此处仅为完整覆盖与向量存储相关的所有错误码。