From 55eb89ce0e9622181101b564873f307af3820d37 Mon Sep 17 00:00:00 2001 From: api-gateway Date: Fri, 18 Sep 2026 17:22:53 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AC=AC=E4=BA=8C=E5=8D=81=E4=B9=9D=E8=BD=AE:?= =?UTF-8?q?=20=E7=BC=BA=E7=9C=81=20conversation=5Fid=20=E6=97=B6=E4=B8=8A?= =?UTF-8?q?=E6=B8=B8=E4=BC=9A=E8=AF=9D=E6=8C=89=20API=20Key(=E5=8E=BB?= =?UTF-8?q?=E5=89=8D=E7=BC=80=E5=93=88=E5=B8=8C)=E7=A8=B3=E5=AE=9A?= =?UTF-8?q?=E6=B4=BE=E7=94=9F,=20=E4=B8=8D=E5=86=8D=E6=AF=8F=E8=B0=83?= =?UTF-8?q?=E7=94=A8=E9=9A=8F=E6=9C=BAUUID=20=E2=86=92=20=E6=8F=90?= =?UTF-8?q?=E6=8F=90=E7=A4=BA=E8=AF=8D=E7=BC=93=E5=AD=98=E5=91=BD=E4=B8=AD?= =?UTF-8?q?=E7=8E=87;=20=E7=99=BB=E5=BD=95=E4=BC=9A=E8=AF=9D=E6=8C=89?= =?UTF-8?q?=E8=B4=A6=E5=8F=B7=E7=A8=B3=E5=AE=9A=E5=85=9C=E5=BA=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 23 +++++++++++++++++++ app/main.py | 52 +++++++++++++++++++++++++++++++------------ tests/test_gateway.py | 34 +++++++++++++++++++++------- 3 files changed, 87 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 526f0b2..a13c444 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,28 @@ # CHANGELOG +## 2026-09-18 · 第二十九轮:`x-opencode-session` 缺省按 **API Key 稳定**派生(提缓存命中) + +**老板决策**:把网关接入 agent / QwenPaw 时,客户端多数不传 `conversation_id`,网关此前 +回退成**每调用一个随机 UUID** → 上游(OpenCode Go)提示词缓存命中率恒为 0(换 session 就不 +吃缓存)。 + +### 改法(`app/main.py`,只动网关,不动 QwenPaw) +- 缺 `conversation_id` 时不再随机: + - 请求带 **API Key** → 上游会话 = `sha256("k:" + <该 Key 的随机串,即 wjd- 后面那串>)[:32]`, + 一个 Key 一个稳定会话(`_key_token()` 去前缀 + `_upstream_session` 哈希)。 + - 只有**登录会话**(页面)→ 上游会话 = `sha256("u:" + 账号)[:32]` 稳定兜底。 +- 仍保留:客户端显式带 `conversation_id` → 按「账号:会话」哈希(按会话隔离)。 +- **安全取舍**:不把 Key 随机串本体直接发给 opencode(那串是凭证内容,泄漏给第三方等于半个 + Key),而是先 `sha256` 再发;上游只看到 32 位十六进制串,既不暴露账号名也不暴露 Key 明文。 + +### 验证 +- 单测 173 passed / 0 failed(`test_conversation_id_isolated_per_account`、 + `test_api_conversation_id_flows_to_session_header`、`test_non_ascii_...` 已更新为「不传→非 + None 稳定会话」新语义) +- 生产已重启(`api-gateway:api-gateway_00`,pid 1488509),`/healthz` ok、无回归 +- **真实的 `cached_tokens>0` 演示暂被挡**:opencode 免费 5 小时额度仍锁定(上游 429),待额度 + 重置(约 3h)后可再实测两通相同前缀调用确认命中。 + ## 2026-09-18 · 第二十七轮:三线直传 + **彻底删除路由别名** **老板决策**:wjd 路由这个功能去掉、删除掉,相关的代码和文档一起更新。 diff --git a/app/main.py b/app/main.py index fcc8124..e47c03b 100644 --- a/app/main.py +++ b/app/main.py @@ -847,6 +847,21 @@ def _record_auth_fail(request: Request, limit_per_min: int) -> bool: return len(dq) >= limit_per_min +def _key_token(key: str) -> str | None: + """丢 API Key 前缀(wjd- / 旧 ak-)取随机串本体;非 Key 凭证(登录会话)返回 None。 + + 第二十九轮:缺 conversation_id 时用「这个 API Key 自己」派生稳定的上游会话 —— 也就是 + 老板要的「x-opencode-session 就传 wjd- 后面那串」的落地版。但**不能把随机串本体原样 + 传给上游**:那串就是网关 Key 的凭证部分,发出去等于把 Key 关键内容泄给 opencode(第三 + 方)。所以这里取出来只用于哈希(_upstream_session 里 sha256),稳定性和"原样传"完全 + 一致,且不落地上游任何明文。 + """ + for p in ("wjd-", "ak-"): + if key.startswith(p): + return key[len(p):] + return None + + def _identity_from_credentials(key: str) -> tuple[str, str, str] | None: """Bearer 凭证 → (account, role, kind)。kind ∈ {"session", "apikey"}。 @@ -954,6 +969,10 @@ async def require_auth( account, role, kind = identity _set_identity(request, account, role) request.state.credential = kind + # 第二十九轮:把「这个 API Key 的随机串」暂存到 state,供 _upstream_session 在缺 + # conversation_id 时派生出稳定的上游会话(见 _key_token 的说明)。登录会话没有 Key, + # 置 None,由 _upstream_session 按账号稳定兜底。 + request.state.key_token = _key_token(key) if kind == "key" else None # 全局限流按**账号**分桶(yaml/注释都写"单 user QPS 上限")。 # 第八轮审计: 原先是 account + 凭证前缀,同一个人多开几个会话/多建几把 Key 就能 # 成倍放大自己的配额,账号级限流形同虚设。 @@ -1325,7 +1344,7 @@ async def _passthrough(request: Request, protocol: str): # 定点改写:model 换成真实 id(别名场景)+ 盖模型级强制参数;其余字段一个不动 payload = adapter.prepare_payload(model_in, clean) - session = _upstream_session(conv, caller) + session = _upstream_session(conv, caller, getattr(request.state, "key_token", None)) if stream: return await _passthrough_stream(request, rid, caller, protocol, adapter, cb, @@ -1609,23 +1628,28 @@ async def chat_completions(request: Request, req: ChatRequest, _auth=Depends(req return await _chat_once(cfg, rid, caller, request, req, model_id, messages, tools) -def _upstream_session(conversation_id: str | None, account: str) -> str | None: - """把客户端的会话 id 派生成**按账号隔离**的上游 session id(第二十六轮)。 +def _upstream_session(conversation_id: str | None, account: str, key_token: str | None = None) -> str: + """把调用的标识派生成**稳定**的上游 session id(第二十六轮 + 第二十九轮强化)。 上游(OpenCode Go)的提示词缓存以 `x-opencode-session` 为作用域 —— 实测:同一 session 的第二次请求 `cached_tokens` 全量命中,换成另一个 session 则恒为 0(换 session = 完全不 - 吃缓存)。所以这个值值得稳定,但也**不该原样透传客户端的字符串**: + 吃缓存)。所以这个值**必须在一次最近的重复调用间恒定**。取值优先级: - 两个账号只要用了相同的值(`test`、`1`、照文档抄的示例),就会落进同一个上游缓存命名 - 空间。这不会泄露彼此内容(缓存只是前缀 KV 复用,绝不会返回别人的回答),但**命中率会 - 互相干扰**,计费和缓存收益的口径也就串了。 + ① 客户端带了 `conversation_id`(第二十六轮):first 「账号:会话」后哈希 —— 同一段对话 + 恒定 → 该对话内反复出现的前缀命中;不同账号天然隔离。 + ② 没带(QwenPaw / 多数 agent 不发这个字段,第二十九轮老板决策):用**这个 API Key + 自己**派生 —— 一个 Key 一个稳定会话,比"每调随机"命中率高得多。但**先哈希再传**: + 直接把 `wjd-` 后面那串原样发给上游等于泄露 Key 凭证内容给第三方(见 _key_token)。 + ③ 连 Key 都没有(登录页面会话,kind=session):按账号稳定兜底,同样不再随机。 - 这里加账号前缀后哈希:对上游仍是"同一对话恒定不变"的稳定 id(缓存收益不变),但不同 - 账号之间天然隔离;同时上游只看到一个 32 位十六进制串,既不暴露账号名也不暴露业务命名。 + 这三级都**不再回退成每个调用一个随机 UUID** —— 随机=缓存命中率恒为 0。上游只看到 + 32 位十六进制串,不暴露账号名、业务命名或 Key 明文。 """ - if not conversation_id: - return None - return hashlib.sha256(f"{account}:{conversation_id}".encode("utf-8")).hexdigest()[:32] + if conversation_id: + return hashlib.sha256(f"{account}:{conversation_id}".encode("utf-8")).hexdigest()[:32] + if key_token: + return hashlib.sha256(f"k:{key_token}".encode("utf-8")).hexdigest()[:32] + return hashlib.sha256(f"u:{account}".encode("utf-8")).hexdigest()[:32] async def _chat_once(cfg, rid, caller, request, req, model_id, messages, tools): @@ -1672,7 +1696,7 @@ async def _chat_once(cfg, rid, caller, request, req, model_id, messages, tools): max_tokens=req.max_tokens, stop=req.stop, tools=tools, tool_choice=tool_choice, extra=req.upstream_extra() or None, - session_id=_upstream_session(req.conversation_id, caller), + session_id=_upstream_session(req.conversation_id, caller, getattr(request.state, "key_token", None)), ) ok = True break @@ -1777,7 +1801,7 @@ def _stream_response(request, req, model_id, messages, tools): max_tokens=req.max_tokens, stop=req.stop, tools=tools, tool_choice=req.tool_choice, extra=req.upstream_extra() or None, - session_id=_upstream_session(req.conversation_id, caller), + session_id=_upstream_session(req.conversation_id, caller, getattr(request.state, "key_token", None)), ) async for chunk in stream_gen: if chunk.get("done"): diff --git a/tests/test_gateway.py b/tests/test_gateway.py index 7b99874..3f5e92e 100644 --- a/tests/test_gateway.py +++ b/tests/test_gateway.py @@ -3716,12 +3716,21 @@ def test_api_conversation_id_flows_to_session_header(): "conversation_id": "conv-api-42"}) assert captured["session_id"] == derived, "同一会话必须派生出同一个 session" assert not captured["extra"] or "conversation_id" not in captured["extra"] - # ② 不传 → session_id 为 None(由适配器回退随机 UUID) + # ② 不传 conversation_id → 第二十九轮起不再 None/随机:走「Key 稳定会话」 + # (无 Key 走账号稳定兜底;此处是登录会话 → 账号兜底,同样必须恒定) r2 = client.post("/v1/chat/completions", headers={"Authorization": _AUTOBEARER}, json={"model": "agnes-3.0-flash", "messages": [{"role": "user", "content": "hi"}]}) assert r2.status_code == 200, r2.text - assert captured["session_id"] is None + kstable = captured["session_id"] + assert kstable is not None, "无会话也必须派生成稳定值(不再是 None/随机)" + assert kstable != derived, "无会话的稳定值应来自另一个命名空间" + # 同 Key 再打一次(换一句提问) → 会话依旧恒定,缓存才能生效 + r3 = client.post("/v1/chat/completions", headers={"Authorization": _AUTOBEARER}, + json={"model": "agnes-3.0-flash", + "messages": [{"role": "user", "content": "hi again"}]}) + assert r3.status_code == 200, r3.text + assert captured["session_id"] == kstable, "同一 Key 无会话时必须恒定(保住缓存收益)" finally: m._get_adapter = orig @@ -3764,11 +3773,20 @@ def test_conversation_id_isolated_per_account(): assert a != b, "不同账号必须隔离(否则共用上游缓存命名空间)" assert a == m._upstream_session("shared-conv", "alice"), "同账号同会话必须稳定(保住缓存收益)" assert m._upstream_session("other-conv", "alice") != a, "同账号不同会话必须不同" - assert m._upstream_session(None, "alice") is None, "未传 → None(适配器回退随机 UUID)" - assert m._upstream_session("", "alice") is None - # 上游只应看到一个十六进制串,不该看到账号名或业务命名 + # 第二十九轮:未传 conversation_id → 不再回退 None/随机(那会命中率恒 0)。 + # 有 API Key → 按 Key 派生稳定会话;没有(登录会话)→ 按账号稳定兜底。 + k1 = m._upstream_session(None, "alice", "TOKEN-A") + assert k1 and len(k1) == 32 and all(c in "0123456789abcdef" for c in k1) + assert k1 == m._upstream_session(None, "alice", "TOKEN-A"), "同一 Key → 必须恒定(缓存收益)" + assert k1 != m._upstream_session(None, "alice", "TOKEN-B"), "不同 Key → 必须隔离" + assert k1 != a, "Key 会话与「账号+会话」派生值应来自不同空间" + assert m._upstream_session("", "alice", "TOKEN-A") == k1, "空白串视同未传 → 走 Key 稳定会话" + u1 = m._upstream_session(None, "alice") + assert u1 and u1 == m._upstream_session(None, "alice"), "无 Key → 账号兜底且恒定" + assert u1 != m._upstream_session(None, "bob"), "不同账号兜底值不同" + # 上游只应看到一个十六进制串,不该看到账号名、业务命名或 Key 明文 assert len(a) == 32 and all(c in "0123456789abcdef" for c in a), a - assert "alice" not in a and "shared" not in a + assert "alice" not in a and "shared" not in a and "TOKEN-A" not in k1 def test_non_ascii_conversation_id_rejected_before_upstream(): @@ -3806,11 +3824,11 @@ def test_non_ascii_conversation_id_rejected_before_upstream(): assert r.status_code == 422, (r.status_code, r.text) assert calls == [] - # ③ 空白串 → 视作未传,正常放行(session_id=None → 上游随机 UUID) + # ③ 空白串 → 视作未传,正常放行(第二十九轮:不再 None/随机,给稳定会话) r = client.post("/v1/chat/completions", headers={"Authorization": _AUTOBEARER}, json={**base, "conversation_id": " "}) assert r.status_code == 200, r.text - assert calls == [None] + assert len(calls) == 1 and calls[0] is not None, "空白=未传 → 稳定会话(非 None)" finally: m._get_adapter = orig