Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(gateway): 拒绝头体身份冲突的聊天请求

NickFuryXXX88be5723cc1e
diff --git a/jiuwenswarm/gateway/channel_manager/web/web_http_app.py b/jiuwenswarm/gateway/channel_manager/web/web_http_app.py
index 6513f32c02..c7dd56ed3a 100644
--- a/jiuwenswarm/gateway/channel_manager/web/web_http_app.py
+++ b/jiuwenswarm/gateway/channel_manager/web/web_http_app.py
@@ -795,6 +795,35 @@ async def _history_json(
logger.debug("[WebHTTP] unregister_request_outbound failed", exc_info=True)
+def _chat_identity_error(
+ request: Request, method: str, params: dict[str, Any], request_id: str,
+) -> JSONResponse | None:
+ """Check history-writing chat methods before dispatch or opening SSE."""
+ if method not in ("chat.send", "chat.resume", "chat.user_answer"):
+ return None
+ for field in ("user_id", "group_id", "bot_id", "gateway_id"):
+ header = (request.headers.get("x-" + field.replace("_", "-")) or "").strip()
+ value = params.get(field)
+ body_value = str(value).strip() if value is not None else ""
+ # Match routing normalization: missing/null/blank identity is unset.
+ if header and body_value and body_value != header:
+ return JSONResponse(
+ {
+ "request_id": request_id,
+ "ok": False,
+ "error": {
+ "code": "IDENTITY_CONFLICT",
+ "message": "Request header and body identity must match",
+ "details": {"field": field},
+ },
+ "metadata": _web_http_metadata(method),
+ },
+ status_code=400,
+ headers=_response_headers(request_id, method),
+ )
+ return None
+
+
async def _unary(
request: Request,
channel: Any,
@@ -807,6 +836,9 @@ async def _unary(
) -> JSONResponse:
outbound = None
req_id = request.headers.get("x-request-id") or uuid.uuid4().hex
+ error = _chat_identity_error(request, method, params, req_id)
+ if error is not None:
+ return error
try:
outbound, req_id, _sid = await dispatch_http_request(
channel,
@@ -858,8 +890,11 @@ async def _stream(
channel: Any,
method: str,
params: dict[str, Any],
-) -> StreamingResponse:
+) -> Response:
req_id = request.headers.get("x-request-id") or uuid.uuid4().hex
+ error = _chat_identity_error(request, method, params, req_id)
+ if error is not None:
+ return error
async def gen() -> AsyncIterator[str]:
outbound = None
diff --git a/tests/unit_tests/test_web_http.py b/tests/unit_tests/test_web_http.py
index 7807356278..18d4e95f59 100644
--- a/tests/unit_tests/test_web_http.py
+++ b/tests/unit_tests/test_web_http.py
@@ -489,6 +489,53 @@ def test_sessions_list_create_delete(app_with_mock):
assert r.json()["ok"] is True
+ "/api/v1/chat/completions", "/api/v1/chat/send", "/api/v1/chat/resume",
+ "/api/v1/chat/sess_1/actions/user_answer", "/api/v1/chat/sess_1/actions/answer",
+])
[email protected]("stream,accept", [(True, "application/json"), (False, "application/json"), (False, "text/event-stream")])
[email protected]("field", ["user_id", "group_id", "bot_id", "gateway_id"])
+def test_chat_rejects_conflicting_identity_before_dispatch(app_with_mock, path, stream, accept, field):
+ app, dispatch = app_with_mock
+ response = TestClient(app).post(
+ path,
+ json={"session_id": "sess_1", "query": "probe", "user_id": "A", field: "B", "enable_streaming": stream},
+ headers={"X-" + field.replace("_", "-"): "A", "X-Request-Id": "conflict", "Accept": accept},
+ )
+ assert response.status_code == 400
+ assert response.json()["error"]["code"] == "IDENTITY_CONFLICT"
+ assert response.headers["x-request-id"] == "conflict"
+ dispatch.assert_not_called()
+
+
+ "/api/v1/chat/completions", "/api/v1/chat/resume",
+ "/api/v1/chat/sess_1/actions/user_answer",
+])
[email protected]("body_identity", [
+ {}, {"bot_id": "A"}, {"bot_id": " A "}, {"bot_id": None},
+ {"bot_id": ""}, {"bot_id": " "},
+ {"user_id": "A", "user": "B"}, # user is not a routing identity field.
+])
+def test_chat_accepts_matching_or_header_only_identity(app_with_mock, body_identity, path):
+ app, dispatch = app_with_mock
+
+ async def _disp(*args, **kwargs):
+ rid = kwargs["request_id"]
+ return _FakePeer([
+ {"type": "res", "id": rid, "ok": True, "payload": {"accepted": True}},
+ ]), rid, "sess_1"
+
+ dispatch.side_effect = _disp
+ response = TestClient(app).post(
+ path,
+ json={"session_id": "sess_1", "query": "probe", "enable_streaming": False, **body_identity},
+ headers={"X-Bot-Id": "A", "X-User-Id": "A"},
+ )
+ assert response.status_code == 200
+ dispatch.assert_awaited_once()
+
+
def test_chat_completions_sse(app_with_mock):
app, dispatch = app_with_mock