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
审计日志:修复file_upload和http_agent_send可能没有UID的问题
hanjiahui4c23b5a70bb2
diff --git a/jiuwenswarm/channels/web/frontend/src/services/obsUpload.ts b/jiuwenswarm/channels/web/frontend/src/services/obsUpload.tsindex ba1eab68f2..42eb6fdb11 100644--- a/jiuwenswarm/channels/web/frontend/src/services/obsUpload.ts+++ b/jiuwenswarm/channels/web/frontend/src/services/obsUpload.ts@@ -1,3 +1,5 @@+import { buildRuntimeIdentityHeaders } from './runtimeScope';+const MAX_UPLOAD_BYTES = 50 * 1024 * 1024;export interface ObsUploadResult {@@ -31,6 +33,13 @@ function fileToBase64(file: File): Promise<string> {});}+function newUploadRequestId(): string {+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {+ return `req_obs_${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`;+ }+ return `req_obs_${Date.now().toString(36)}`;+}+/** Upload a browser File to Gateway MinIO via POST /file-api/upload-obs. */export async function uploadFileToObs(file: File): Promise<ObsUploadResult> {if (file.size <= 0) {@@ -41,9 +50,14 @@ export async function uploadFileToObs(file: File): Promise<ObsUploadResult> {}const content_base64 = await fileToBase64(file);+ const requestId = newUploadRequestId();const response = await fetch('/file-api/upload-obs', {method: 'POST',- headers: { 'Content-Type': 'application/json' },+ headers: {+ 'Content-Type': 'application/json',+ // 与 webRequest 对齐:Gateway 审计/路由从 X-User-Id 等头取身份+ ...buildRuntimeIdentityHeaders(requestId, {}),+ },body: JSON.stringify({filename: file.name,content_base64,diff --git a/jiuwenswarm/common/audit_emit.py b/jiuwenswarm/common/audit_emit.pyindex 26317a8b65..111883ec4e 100644--- a/jiuwenswarm/common/audit_emit.py+++ b/jiuwenswarm/common/audit_emit.py@@ -74,16 +74,26 @@ def emit_audit(keyword = str(event_type or "").strip().upper()success = keyword != "EVT"desc = fields.get("UA") or fields.get("EVT") or fields.get("MSG")+ # UID/uid 必须进 audit_claw_log(uid=),不能只塞 extra(否则无 ContextVar+ # 时顶层 UID/user_id 仍为空,仅靠 extra 覆盖占位符,桥接 user_id 仍可能丢)。+ rest = {+ k: v+ for k, v in fields.items()+ if k not in ("UA", "EVT", "MSG", "UID", "uid")+ }+ raw_uid = fields.get("UID", fields.get("uid"))+ uid = str(raw_uid).strip() if raw_uid is not None else ""audit_claw_log(submdl=SUBMDL,proc=PROC,success=success,+ uid=uid or None,rspcd=RSPCD,desc=str(desc) if desc is not None else None,message=str(fields.get("MSG") or ""),level=level,caller=caller,- extra={k: v for k, v in fields.items() if k not in ("UA", "EVT", "MSG")},+ extra=rest,)returnexcept Exception: # noqa: BLE001diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex 72e50d335f..16a8b82ec7 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -7510,7 +7510,9 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:channel.register_method("permissions.owner_scopes.get", _permissions_owner_scopes_get)channel.register_method("permissions.owner_scopes.set", _permissions_owner_scopes_set)- async def _forward_permissions_to_agent(ws, req_id, params, session_id, *, req_method):+ async def _forward_permissions_to_agent(+ ws, req_id, params, session_id, *, req_method, user_id=None+ ):"""permissions.*:优先经 E2A 转发到 AgentServer;Agent 未就绪时本地执行(与 config_rpc 同源)。"""from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fieldsfrom jiuwenswarm.common.schema.agent import AgentRequest@@ -7520,6 +7522,8 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:await channel.send_response(ws, req_id, ok=False, error="invalid req_method", code="INTERNAL_ERROR")return+ authenticated_user_id = str(user_id or "").strip() or None+synthetic = AgentRequest(request_id=str(req_id) if req_id else "",channel_id="",@@ -7566,6 +7570,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:session_id=session_id,req_method=req_method,params=dict(params) if isinstance(params, dict) else {},+ user_id=authenticated_user_id,)try:resp = await ac.send_request(env)@@ -7589,8 +7594,10 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:from jiuwenswarm.common.schema.message import ReqMethod as _PermReqdef _register_perm(method_name: str, rm: Any) -> None:- async def _handler(ws, req_id, params, session_id):- await _forward_permissions_to_agent(ws, req_id, params, session_id, req_method=rm)+ async def _handler(ws, req_id, params, session_id, user_id=None):+ await _forward_permissions_to_agent(+ ws, req_id, params, session_id, req_method=rm, user_id=user_id+ )channel.register_method(method_name, _handler)@@ -7628,7 +7635,9 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:channel.register_method("memory.forbidden.get", _memory_forbidden_get)channel.register_method("memory.forbidden.set", _memory_forbidden_set)- async def _forward_harness_to_agent(ws, req_id, params, session_id, *, req_method):+ async def _forward_harness_to_agent(+ ws, req_id, params, session_id, *, req_method, user_id=None+ ):"""harness.*:优先经 E2A 转发到 AgentServer;Agent 未就绪时本地执行(无 agent 实例)。"""from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fieldsfrom jiuwenswarm.common.schema.message import ReqMethod@@ -7637,6 +7646,8 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:await channel.send_response(ws, req_id, ok=False, error="invalid req_method", code="INTERNAL_ERROR")return+ authenticated_user_id = str(user_id or "").strip() or None+ac = _resolve(agent_client)if ac is None or not getattr(ac, "server_ready", False):# Agent 未就绪时本地处理(无 agent 实例可用)@@ -7695,6 +7706,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:session_id=session_id,req_method=req_method,params=dict(params) if isinstance(params, dict) else {},+ user_id=authenticated_user_id,)try:resp = await ac.send_request(env)@@ -7718,8 +7730,10 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:from jiuwenswarm.common.schema.message import ReqMethod as _HarnessReqdef _register_harness(method_name: str, rm: Any) -> None:- async def _handler(ws, req_id, params, session_id):- await _forward_harness_to_agent(ws, req_id, params, session_id, req_method=rm)+ async def _handler(ws, req_id, params, session_id, user_id=None):+ await _forward_harness_to_agent(+ ws, req_id, params, session_id, req_method=rm, user_id=user_id+ )channel.register_method(method_name, _handler)diff --git a/jiuwenswarm/gateway/channel_manager/web/file_http.py b/jiuwenswarm/gateway/channel_manager/web/file_http.pyindex 7231c93ca3..de0e61ce36 100644--- a/jiuwenswarm/gateway/channel_manager/web/file_http.py+++ b/jiuwenswarm/gateway/channel_manager/web/file_http.py@@ -409,6 +409,7 @@ def save_pushed_file(file_bytes: bytes,filename: str,session_id: str,+ user_id: str | None = None,) -> dict[str, Any]:"""Persist upload and return download metadata (3-A: no Web Pod push)."""from jiuwenswarm.agents.harness.common.tools.web_file_download import (@@ -417,6 +418,8 @@ def save_pushed_file(from jiuwenswarm.common.audit_emit import emit_audit_evt, emit_audit_ua+ uid = str(user_id or "").strip()+ audit_uid = {"UID": uid} if uid else {}clean_name = safe_filename(filename)safe_name = f"{int(time.time())}_{clean_name}"local_path = resolve_path_under_directory(received_files_dir(), safe_name)@@ -427,6 +430,7 @@ def save_pushed_file(MSG="invalid_filename",EVT="invalid_filename",session_id=session_id,+ **audit_uid,)raise ValueError("invalid_filename")local_path.write_bytes(file_bytes)@@ -440,6 +444,7 @@ def save_pushed_file(PROC="file_upload",session_id=session_id,filename=clean_name,+ **audit_uid,)return {"success": True,@@ -450,9 +455,15 @@ def save_pushed_file(}-def process_obs_upload_body(raw: bytes) -> tuple[int, dict[str, Any]]:+def process_obs_upload_body(+ raw: bytes,+ *,+ user_id: str | None = None,+) -> tuple[int, dict[str, Any]]:from jiuwenswarm.common.audit_emit import emit_audit_evt, emit_audit_ua+ uid = str(user_id or "").strip()+ audit_uid = {"UID": uid} if uid else {}try:payload = json.loads(raw.decode("utf-8") if raw else "{}")except json.JSONDecodeError:@@ -461,6 +472,7 @@ def process_obs_upload_body(raw: bytes) -> tuple[int, dict[str, Any]]:PROC="file_upload",MSG="invalid_json",EVT="invalid_json",+ **audit_uid,)return 400, {"ok": False, "error": "invalid_json"}if not isinstance(payload, dict):@@ -469,6 +481,7 @@ def process_obs_upload_body(raw: bytes) -> tuple[int, dict[str, Any]]:PROC="file_upload",MSG="invalid_payload",EVT="invalid_payload",+ **audit_uid,)return 400, {"ok": False, "error": "invalid_payload"}filename = str(payload.get("filename") or "upload.bin")@@ -480,6 +493,7 @@ def process_obs_upload_body(raw: bytes) -> tuple[int, dict[str, Any]]:SUBMDL="file",PROC="file_upload",filename=str(result.get("name") or filename),+ **audit_uid,)return 200, resultexcept Exception as exc:@@ -490,6 +504,7 @@ def process_obs_upload_body(raw: bytes) -> tuple[int, dict[str, Any]]:MSG=str(exc)[:512],EVT="file_upload_failed",filename=filename,+ **audit_uid,)return 500, {"ok": False, "error": str(exc)}diff --git a/jiuwenswarm/gateway/channel_manager/web/web_http_file_compat.py b/jiuwenswarm/gateway/channel_manager/web/web_http_file_compat.pyindex f176cda799..5f46c02f08 100644--- a/jiuwenswarm/gateway/channel_manager/web/web_http_file_compat.py+++ b/jiuwenswarm/gateway/channel_manager/web/web_http_file_compat.py@@ -70,6 +70,19 @@ def _json(status: int, payload: dict[str, Any]) -> JSONResponse:return JSONResponse(payload, status_code=status)+def _request_user_id(request: Request) -> str | None:+ """企业上传审计 UID:可信客户端时取 ``X-User-Id``(对齐 Web HTTP 租户头策略)。"""+ from jiuwenswarm.gateway.channel_manager.web.web_http_dispatch import (+ _trust_client_tenant_headers,+ )++ client_host = request.client.host if request.client else None+ if not _trust_client_tenant_headers(client_host):+ return None+ text = str(request.headers.get("x-user-id") or "").strip()+ return text or None++def catalog_file_compat_entries() -> list[dict[str, Any]]:paths = [("GET", "/file-api/list-files", "列目录"),@@ -380,7 +393,10 @@ def register_file_compat_routes(app: FastAPI) -> None:if not is_enterprise():return _json(404, {"error": "not_available"})raw = await request.body()- status, payload = process_obs_upload_body(raw)+ status, payload = process_obs_upload_body(+ raw,+ user_id=_request_user_id(request),+ )return _json(status, payload)@app.post(@@ -405,6 +421,7 @@ def register_file_compat_routes(app: FastAPI) -> None:file_bytes=raw,filename=name,session_id=session_id or "default",+ user_id=_request_user_id(request),)return _json(200, result)except ValueError:diff --git a/jiuwenswarm/gateway/routing/http_agent_client.py b/jiuwenswarm/gateway/routing/http_agent_client.pyindex 85d60bbf0f..a9c07788d0 100644--- a/jiuwenswarm/gateway/routing/http_agent_client.py+++ b/jiuwenswarm/gateway/routing/http_agent_client.py@@ -345,6 +345,9 @@ class HttpSseAgentServerClient(AgentServerClient):assembled.url,assembled.used_rpc_fallback,)+ # 信封身份:直调路径(如 session.delete)不走 open_gateway_request,+ # ContextVar 常为空;有值时显式写入,无值时仍回退审计上下文。+ uid = str(getattr(envelope, "user_id", None) or "").strip()try:response = await http.request(assembled.verb,@@ -367,6 +370,7 @@ class HttpSseAgentServerClient(AgentServerClient):request_id=rid,method=str(envelope.method or ""),DSTIP=peer_ip,+ **({"UID": uid} if uid else {}),)raiseemit_audit_ua(@@ -376,6 +380,7 @@ class HttpSseAgentServerClient(AgentServerClient):request_id=rid,method=str(envelope.method or ""),DSTIP=peer_ip,+ **({"UID": uid} if uid else {}),)return resultdiff --git a/tests/unit_tests/gateway/test_audit_emit.py b/tests/unit_tests/gateway/test_audit_emit.pyindex 7a580daf39..d923d12955 100644--- a/tests/unit_tests/gateway/test_audit_emit.py+++ b/tests/unit_tests/gateway/test_audit_emit.py@@ -67,6 +67,17 @@ def test_emit_audit_caller_is_business_site(_audit_memory: MemoryEmitter, monkeyassert "audit_claw_log" not in caller+def test_emit_audit_ua_passes_uid_without_context(+ _audit_memory: MemoryEmitter,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")+ emit_audit_ua(SUBMDL="api_client", PROC="http_agent_send", UA="ok", UID="user1")+ attrs = _audit_memory.records[0]["attributes"]+ assert attrs.get("UID") == "user1"+ assert attrs.get("user_id") == "user1"++def test_emit_audit_noop_when_config_disabled(_audit_memory: MemoryEmitter,monkeypatch: pytest.MonkeyPatch,diff --git a/tests/unit_tests/gateway/test_http_agent_client.py b/tests/unit_tests/gateway/test_http_agent_client.pyindex b37295cb88..1978785b06 100644--- a/tests/unit_tests/gateway/test_http_agent_client.py+++ b/tests/unit_tests/gateway/test_http_agent_client.py@@ -672,6 +672,57 @@ async def test_send_request_unary_success_and_non_json():await client.disconnect()+async def test_send_request_emits_uid_from_envelope(monkeypatch):+ monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")+ from jiuwenswarm.common.audit_gate import set_audit_config_enabled++ set_audit_config_enabled(True)+ captured: list[dict] = []++ def _cap_ua(**kwargs):+ captured.append(kwargs)++ monkeypatch.setattr(+ "jiuwenswarm.gateway.routing.http_agent_client.emit_audit_ua",+ _cap_ua,+ )++ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 200,+ json={+ "request_id": "t-uid",+ "ok": True,+ "data": {"result": {}},+ },+ )++ client = HttpSseAgentServerClient(+ http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler))+ )+ try:+ await client.send_request(+ e2a_from_agent_fields(+ request_id="t-uid",+ channel_id="web",+ session_id="s1",+ req_method=ReqMethod.SESSION_DELETE,+ params={"session_id": "s1"},+ user_id="user1",+ ),+ base_url="http://10.42.1.8:8080",+ )+ finally:+ await client.disconnect()+ set_audit_config_enabled(False)++ assert len(captured) == 1+ assert captured[0].get("PROC") == "http_agent_send"+ assert captured[0].get("UID") == "user1"+ assert captured[0].get("method") == "session.delete"++@pytest.mark.asyncioasync def test_send_request_stream_yields_chunks_and_skips_garbage():def handler(request: httpx.Request) -> httpx.Response:diff --git a/tests/unit_tests/test_web_http.py b/tests/unit_tests/test_web_http.pyindex a5fb36be44..42cf7d7350 100644--- a/tests/unit_tests/test_web_http.py+++ b/tests/unit_tests/test_web_http.py@@ -55,11 +55,21 @@ class _FakePeer:@pytest.fixturedef app_with_mock(monkeypatch: pytest.MonkeyPatch) -> tuple[FastAPI, AsyncMock]:- # Stub dispatch module before loading web_http_app+ # Stub dispatch module before loading web_http_app.+ # Use monkeypatch.setitem so xdist workers restore the real module after+ # this fixture (otherwise later file-api tests ImportError on+ # ``_trust_client_tenant_headers`` from a leftover bare ModuleType stub).dispatch_mod = ModuleType("jiuwenswarm.gateway.channel_manager.web.web_http_dispatch")dispatch_mock = AsyncMock()dispatch_mod.dispatch_http_request = dispatch_mock # type: ignore[attr-defined]- sys.modules["jiuwenswarm.gateway.channel_manager.web.web_http_dispatch"] = dispatch_mod+ dispatch_mod._trust_client_tenant_headers = ( # type: ignore[attr-defined]+ lambda client_host=None: True+ )+ monkeypatch.setitem(+ sys.modules,+ "jiuwenswarm.gateway.channel_manager.web.web_http_dispatch",+ dispatch_mod,+ )# Minimal package parents so relative imports in web_http_app resolve if anyfor pkg in (@@ -71,7 +81,7 @@ def app_with_mock(monkeypatch: pytest.MonkeyPatch) -> tuple[FastAPI, AsyncMock]:if pkg not in sys.modules:m = ModuleType(pkg)m.__path__ = [] # type: ignore[attr-defined]- sys.modules[pkg] = m+ monkeypatch.setitem(sys.modules, pkg, m)# Real route table (no Gateway imports) so create_web_http_app can register workspace routes._load_module(@@ -83,12 +93,20 @@ def app_with_mock(monkeypatch: pytest.MonkeyPatch) -> tuple[FastAPI, AsyncMock]:sessions_compat = ModuleType("jiuwenswarm.gateway.channel_manager.web.web_http_sessions_compat")sessions_compat.register_sessions_compat_routes = lambda app: None # type: ignore[attr-defined]sessions_compat.catalog_sessions_compat_entries = lambda: [] # type: ignore[attr-defined]- sys.modules["jiuwenswarm.gateway.channel_manager.web.web_http_sessions_compat"] = sessions_compat+ monkeypatch.setitem(+ sys.modules,+ "jiuwenswarm.gateway.channel_manager.web.web_http_sessions_compat",+ sessions_compat,+ )file_compat = ModuleType("jiuwenswarm.gateway.channel_manager.web.web_http_file_compat")file_compat.register_file_compat_routes = lambda app: None # type: ignore[attr-defined]file_compat.catalog_file_compat_entries = lambda: [] # type: ignore[attr-defined]- sys.modules["jiuwenswarm.gateway.channel_manager.web.web_http_file_compat"] = file_compat+ monkeypatch.setitem(+ sys.modules,+ "jiuwenswarm.gateway.channel_manager.web.web_http_file_compat",+ file_compat,+ )# web_http_app imports timeout helpers from web_http_server (stdlib-only)._load_module(