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): enforce Agent authorization before chat routing
NickFuryXXXf677bdbc4990
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/enterprise_config/expressions.py b/jiuwenswarm/gateway/config/enterprise/expressions.pysimilarity index 57%rename from packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/enterprise_config/expressions.pyrename to jiuwenswarm/gateway/config/enterprise/expressions.pyindex 22eaf3aab2..979b39c875 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/enterprise_config/expressions.py+++ b/jiuwenswarm/gateway/config/enterprise/expressions.py@@ -1,6 +1,6 @@# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved-"""``match_expr`` 写入校验(求值见 OSS ``server/runtime/enterprise_config/expressions``)。"""+"""实例 Agent 授权表达式:配置写入和请求准入共用解析、校验与求值。"""from __future__ import annotations@@ -10,13 +10,13 @@ import refrom typing import Any_ALLOWED_MATCH_NAMES = frozenset({"user_id", "group_id", "bot_id"})-# 不含 == / != 时仍视为全匹配,但若出现下列记号则视为误写,写入时拒绝。+# 对常见误写保留明确的错误提示;其余非空表达式统一通过 AST 校验。_ALWAYS_MATCH_FORBIDDEN_CHECKS: tuple[tuple[re.Pattern[str], str], ...] = ((re.compile(r"\$\{"), "template_ref placeholders like ${...} are not allowed"),(re.compile(r"===|!=="), "=== / !== are not allowed; use == / !="),(re.compile(r">=|<=|(?<![!=])>(?!=)|(?<!<|>)<(?!=)"),- "ordering operators (>, <, >=, <=) are not allowed; only == / != are supported",+ "ordering operators (>, <, >=, <=) are not allowed; only == / != / in / not in are supported",),(re.compile(r"\bservice_id\b|\bagent_id\b", re.IGNORECASE),@@ -38,28 +38,38 @@ def _always_match_forbidden_reason(text: str) -> str | None:def validate_match_expr(expr: Any) -> None:- """校验 ``match_expr`` 是否符合支持的语法;不合规时抛出 ``ValueError``。+ """校验表达式;空值全匹配,表达式列表为 OR,不合法时抛出 ValueError。"""+ _parse_match_expr(expr)- 空值/空列表为全匹配;列表或 JSON 数组为 OR;含 ``==`` / ``!=`` 时仅允许- ``user_id`` / ``group_id`` / ``bot_id`` 与字面量,以及 ``and`` / ``or`` 组合。- 写入策略时应调用本函数,避免非法表达式入库后静默不命中。- """++def _parse_match_expr(expr: Any) -> ast.AST | list | None:+ """返回已校验的 AST;写入和求值不各自解释表达式。"""if expr is None:- return+ return Noneif isinstance(expr, list):+ if not expr:+ return None+ nodes = []for index, item in enumerate(expr):try:- validate_match_expr(item)+ if not isinstance(item, str) or not item.strip():+ raise _match_expr_error("OR clauses must be non-empty expression strings")+ node = _parse_match_expr(item)+ if node is None or isinstance(node, list):+ raise _match_expr_error("OR clauses must be non-empty expressions")+ nodes.append(node)except ValueError as exc:detail = str(exc)if detail.startswith(_MATCH_EXPR_PREFIX):detail = detail[len(_MATCH_EXPR_PREFIX):].lstrip(": ").lstrip(":")raise _match_expr_error(f"item[{index}]: {detail}") from exc- return+ return nodes- text = str(expr).strip()+ if not isinstance(expr, str):+ raise _match_expr_error("expected string, string array or null")+ text = expr.strip()if not text:- return+ return Noneif text.startswith("["):try:@@ -70,14 +80,12 @@ def validate_match_expr(expr: Any) -> None:) from excif not isinstance(parsed, list):raise _match_expr_error("JSON value must be an array")- validate_match_expr(parsed)- return+ return _parse_match_expr(parsed)- if "==" not in text and "!=" not in text:+ if "==" not in text and "!=" not in text and not re.search(r"\bin\b", text):reason = _always_match_forbidden_reason(text)if reason:raise _match_expr_error(reason)- return# === / !== contain == / != as substrings; reject before ast.parse.if "===" in text or "!==" in text:@@ -92,6 +100,7 @@ def validate_match_expr(expr: Any) -> None:_validate_match_ast(tree.body)except ValueError as exc:raise _match_expr_error(str(exc)) from exc+ return tree.bodydef _validate_match_ast(node: ast.AST) -> None:@@ -99,9 +108,9 @@ def _validate_match_ast(node: ast.AST) -> None:if isinstance(node, ast.Compare):_validate_match_value(node.left)for op, comparator in zip(node.ops, node.comparators):- if not isinstance(op, (ast.Eq, ast.NotEq)):+ if not isinstance(op, (ast.Eq, ast.NotEq, ast.In, ast.NotIn)):raise ValueError(- "only == and != are supported; "+ "only ==, !=, in and not in are supported; ""ordering operators (>, <, >=, <=) are not allowed")_validate_match_value(comparator)@@ -125,6 +134,10 @@ def _validate_match_ast(node: ast.AST) -> None:def _validate_match_value(node: ast.AST) -> None:"""校验比较左右操作数:字面量或允许的字段名。"""+ if isinstance(node, (ast.List, ast.Tuple)):+ if not all(isinstance(item, ast.Constant) for item in node.elts):+ raise ValueError("membership values must be literals")+ returnif isinstance(node, ast.Constant):returnif isinstance(node, ast.Name):@@ -142,4 +155,42 @@ def _validate_match_value(node: ast.AST) -> None:raise ValueError("operands must be field names or literals")-__all__ = ("validate_match_expr",)+def matches(expr: Any, identity: dict[str, str]) -> bool:+ """仅对已校验的语法求值;非法规则抛错,由准入层拒绝请求。"""+ return _evaluate_match_ast(_parse_match_expr(expr), identity)+++def _match_value(node: ast.AST, identity: dict[str, str]) -> Any:+ if isinstance(node, ast.Name):+ return identity[node.id]+ if isinstance(node, (ast.List, ast.Tuple)):+ return [item.value for item in node.elts]+ return node.value+++def _evaluate_match_ast(node: ast.AST | list | None, identity: dict[str, str]) -> bool:+ if node is None:+ return True+ if isinstance(node, list):+ return any(_evaluate_match_ast(item, identity) for item in node)+ if isinstance(node, ast.BoolOp):+ results = (_evaluate_match_ast(item, identity) for item in node.values)+ return all(results) if isinstance(node.op, ast.And) else any(results)+ if isinstance(node, ast.Constant):+ return node.value+ left = _match_value(node.left, identity)+ for op, comparator in zip(node.ops, node.comparators):+ right = _match_value(comparator, identity)+ if isinstance(op, (ast.In, ast.NotIn)):+ # 与 Manager 一致:单值 RHS 按单元素集合处理,不能做子串匹配。+ members = right if isinstance(right, list) else [right]+ matched = (left in members) == isinstance(op, ast.In)+ else:+ matched = (left == right) == isinstance(op, ast.Eq)+ if not matched:+ return False+ left = right+ return True+++__all__ = ("validate_match_expr", "matches")diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/instance_resource_schemas.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/instance_resource_schemas.pyindex db3787c0b1..4bdad884e6 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/instance_resource_schemas.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/instance_resource_schemas.py@@ -5,7 +5,7 @@ from typing import Annotated, Anyfrom pydantic import BaseModel, BeforeValidator, ConfigDict, Field-from ..core.enterprise_config.expressions import validate_match_expr+from jiuwenswarm.gateway.config.enterprise.expressions import validate_match_exprdef _validate_match_expr(value: Any) -> Any:diff --git a/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/agent_authorization.py b/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/agent_authorization.pynew file mode 100644index 0000000000..a175149528--- /dev/null+++ b/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/agent_authorization.py@@ -0,0 +1,48 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""Per-request Agent resource admission, independent of Runtime pool routing."""+from datetime import datetime, timezone++from jiuwenswarm.common.e2a.models import E2AEnvelope++from jiuwenswarm.gateway.config.enterprise.access import get_enterprise_record_repository+from jiuwenswarm.gateway.config.enterprise.expressions import matches++from .invoke_ids import routing_triple_from_envelope+from .session_route_client import FatalRouteError++# 本单约束发起/继续 Agent 执行的对话入口。会话管理、历史查询与中断+# 沿用各自接口契约,不在这里按前缀扩大授权范围。+CHAT_METHODS = frozenset({+ "chat.send", "chat.resume", "chat.user_answer", "chat.swarmflow_reply",+})+++async def authorize_agent(envelope: E2AEnvelope) -> tuple[str, str, str] | None:+ if envelope.method not in CHAT_METHODS:+ return None+ group_id, bot_id, user_id = routing_triple_from_envelope(envelope)+ identity = {"group_id": group_id, "bot_id": bot_id, "user_id": user_id}+ if not all(identity.values()):+ raise FatalRouteError("Agent routing identity is required", code="FORBIDDEN")+ repo = get_enterprise_record_repository("instance_agent_resource")+ if repo is None:+ raise RuntimeError("instance_agent_resource repository is unavailable")+ # Do not cache admission: revocation and expiry apply to the next request.+ row = await repo.get(resource_id=bot_id)+ allowed = False+ # PostgreSQL 读回 bool,MySQL 的布尔编解码器读回 1/0。+ if row is not None and row.get("enabled") == 1:+ try:+ expiry = row.get("expires_at")+ if isinstance(expiry, str):+ expiry = datetime.fromisoformat(expiry.replace("Z", "+00:00"))+ if expiry is not None and expiry.tzinfo is None:+ expiry = expiry.replace(tzinfo=timezone.utc)+ allowed = (expiry is None or expiry > datetime.now(timezone.utc)) and matches(+ row.get("match_expr"), identity+ )+ except (ValueError, TypeError, AttributeError):+ allowed = False+ if not allowed:+ raise FatalRouteError("Agent access denied", code="FORBIDDEN")+ return group_id, bot_id, user_iddiff --git a/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/runtime_routed_client.py b/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/runtime_routed_client.pyindex 15c27d4e0b..73d8d78d60 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/runtime_routed_client.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/runtime_routed_client.py@@ -20,6 +20,7 @@ from jiuwenswarm.common.schema.agent import AgentResponse, AgentResponseChunkfrom jiuwenswarm.gateway.routing.agent_client import AgentServerClientfrom jiuwenswarm.gateway.routing.http_agent_client import HttpSseAgentServerClient+from .agent_authorization import authorize_agentfrom .invoke_ids import apply_invoke_ids_to_envelopefrom .session_route_client import (FatalRouteError,@@ -119,7 +120,11 @@ def _default_http_base() -> str:return f"http://{host}:{port}"-def identity_from_envelope(envelope: E2AEnvelope) -> tuple[str, str, str, str, str | None]:+def identity_from_envelope(+ envelope: E2AEnvelope,+ *,+ authorized_identity: tuple[str, str, str] | None = None,+) -> tuple[str, str, str, str, str | None]:"""返回 ``session_id, group_id, bot_id, request_id, user_id``。"""params = envelope.params if isinstance(envelope.params, dict) else {}ctx = envelope.channel_context if isinstance(envelope.channel_context, dict) else {}@@ -148,6 +153,9 @@ def identity_from_envelope(envelope: E2AEnvelope) -> tuple[str, str, str, str, sgroup_id = "default"if not bot_id:bot_id = "default"+ # 授权身份必须在合成 session key 前生效,不能仅覆盖最终路由参数。+ if authorized_identity is not None:+ group_id, bot_id, user_id = authorized_identitysession_id = _first_text(envelope.session_id, params.get("session_id"))if not session_id and group_id and bot_id:session_id = f"{group_id}:{bot_id}:{user_id or '_'}"@@ -340,6 +348,7 @@ class RuntimeRoutedAgentClient(AgentServerClient):async def send_request(self, envelope: E2AEnvelope) -> AgentResponse:self._ensure_connected()+ authorized_identity = await authorize_agent(envelope)if envelope.method == "acp.tool_response":params = envelope.params or {}key = (@@ -357,7 +366,9 @@ class RuntimeRoutedAgentClient(AgentServerClient):if _is_routeless_envelope(envelope):result = await self._http.send_request(envelope, base_url=_default_http_base())return result- session_id, group_id, bot_id, request_id, user_id = identity_from_envelope(envelope)+ session_id, group_id, bot_id, request_id, user_id = identity_from_envelope(+ envelope, authorized_identity=authorized_identity,+ )base_url, route_id = await self._route_with_retry(session_id=session_id,group_id=group_id,@@ -392,6 +403,7 @@ class RuntimeRoutedAgentClient(AgentServerClient):self, envelope: E2AEnvelope) -> AsyncIterator[AgentResponseChunk]:self._ensure_connected()+ authorized_identity = await authorize_agent(envelope)if _is_heartbeat_envelope(envelope):yield AgentResponseChunk(request_id=str(envelope.request_id or ""),@@ -408,7 +420,9 @@ class RuntimeRoutedAgentClient(AgentServerClient):):yield chunkreturn- session_id, group_id, bot_id, request_id, user_id = identity_from_envelope(envelope)+ session_id, group_id, bot_id, request_id, user_id = identity_from_envelope(+ envelope, authorized_identity=authorized_identity,+ )base_url, route_id = await self._route_with_retry(session_id=session_id,group_id=group_id,diff --git a/tests/unit_tests/gateway/test_agent_match_expressions.py b/tests/unit_tests/gateway/test_agent_match_expressions.pynew file mode 100644index 0000000000..35ee95ae16--- /dev/null+++ b/tests/unit_tests/gateway/test_agent_match_expressions.py@@ -0,0 +1,102 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+import pytest+from jiuwenswarm.gateway.config.enterprise.expressions import matches, validate_match_expr++IDENTITY = {"user_id": "u2", "group_id": "g1", "bot_id": "A"}+[email protected]("expr, expected", [+ (None, True), ("", True), ([], True), ("[]", True),+ ("user_id == 'u1'", False), ("user_id != 'u1'", True),+ ("(user_id == 'u1' or user_id == 'u2') and group_id == 'g1'", True),+ ("user_id == 'u2' and group_id == 'g2'", False),+ (["user_id == 'u1'", "group_id == 'g1'"], True),+ ('["user_id == \'u1\'", "bot_id == \'B\'"]', False),+ ("user_id in ('u1', 'u2')", True),+ ("user_id in ['u1', 'u3']", False),+ ("group_id not in ['g2', 'g3']", True),+ ("user_id in ('u2')", True),+ ("user_id in ('u22')", False),+ ("user_id in 'u2xx'", False),+ ("user_id not in 'u2xx'", True),+ ("False", False), ("True", True),+ ("user_id == group_id == 'g1'", False),+])+def test_match_contract(expr, expected, resource_schema):+ resource_schema.model_validate({+ "resource_id": "A", "resource_name": "Agent A", "ref_template_id": "shared",+ "match_expr": expr,+ })+ assert matches(expr, IDENTITY) is expected+[email protected]("expr", [+ "garbage", "user_id === 'u1'", "user_id > 'u1'",+ "service_id == 'x'", "user_id.lower() == 'u2'", "__import__('os')",+ {"user_id": "u1"}, 42, "[broken", ["True", "unknown"],+ ["user_id == 'nobody'", ""], [" "], [None], [[]], ["[]"],+])+def test_invalid_rules_are_rejected_on_write_and_read(expr):+ with pytest.raises(ValueError, match="invalid match_expr"):+ validate_match_expr(expr)+ with pytest.raises(ValueError, match="invalid match_expr"):+ matches(expr, IDENTITY)++[email protected](scope="module")+def resource_schema():+ import importlib+ import sys+ import types+ from pathlib import Path+ name = "_agent_authorization_receiver"+ package = types.ModuleType(name)+ package.__path__ = [str(Path(__file__).resolve().parents[3] /+ "packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver")]+ sys.modules[name] = package+ module = importlib.import_module(name + ".schemas.instance_resource_schemas")+ yield module.InstanceAgentResourceUpsertRequest+ for key in list(sys.modules):+ if key == name or key.startswith(name + "."):+ del sys.modules[key]++[email protected]("expr", [None, [], "user_id in ('alice')", ["group_id == 'g1'", "user_id != 'bob'"]])+def test_upsert_schema_keeps_designed_payload(resource_schema, expr):+ payload = {"resource_id": "A", "resource_name": "Agent A", "ref_template_id": "shared", "match_expr": expr}+ parsed = resource_schema.model_validate(payload)+ assert parsed.model_dump()["match_expr"] == expr+++def test_upsert_rejects_invalid_expression(resource_schema):+ from pydantic import ValidationError+ with pytest.raises(ValidationError, match="invalid match_expr"):+ resource_schema.model_validate({+ "resource_id": "A", "resource_name": "Agent A", "ref_template_id": "shared",+ "match_expr": "user_id === 'alice'",+ })++[email protected]("expr, message", [+ ("user_id === 'alice'", "=== / !== are not allowed; use == / !="),+ ("unknown == 'alice'", "unknown name 'unknown'; only user_id / group_id / bot_id are allowed"),+ ("user_id.lower() == 'alice'", "function calls are not supported"),+ (["user_id == 'alice'", "user_id === 'bob'"], "item[1]: === / !== are not allowed; use == / !="),+ ("user_id in [other]", "membership values must be literals"),+])+def test_upsert_preserves_validation_errors(resource_schema, expr, message):+ from pydantic import ValidationError+ with pytest.raises(ValidationError) as exc:+ resource_schema.model_validate({+ "resource_id": "A", "resource_name": "Agent A", "ref_template_id": "shared",+ "match_expr": expr,+ })+ assert message in str(exc.value)++[email protected]("expr", ["unknown", "__import__('os')", ["True", "unknown"]])+def test_upsert_rejects_unknown_rules(resource_schema, expr):+ from pydantic import ValidationError+ with pytest.raises(ValidationError, match="invalid match_expr"):+ resource_schema.model_validate({+ "resource_id": "A", "resource_name": "Agent A", "ref_template_id": "shared",+ "match_expr": expr,+ })diff --git a/tests/unit_tests/gateway/test_runtime_routed_client.py b/tests/unit_tests/gateway/test_runtime_routed_client.pyindex 07f385b9bc..de1d3ff406 100644--- a/tests/unit_tests/gateway/test_runtime_routed_client.py+++ b/tests/unit_tests/gateway/test_runtime_routed_client.py@@ -59,6 +59,15 @@ http_base_from_pod_sse_url = _routed_mod.http_base_from_pod_sse_urlidentity_from_envelope = _routed_mod.identity_from_envelope[email protected](autouse=True)+def agent_resources(monkeypatch):+ from unittest.mock import AsyncMock+ auth = _load("agent_authorization")+ repo = types.SimpleNamespace(get=AsyncMock(return_value={"enabled": True, "match_expr": []}))+ monkeypatch.setattr(auth, "get_enterprise_record_repository", lambda _: repo)+ return repo++def _chat_env():from jiuwenswarm.common.request_identity import apply_routing_metadata@@ -741,3 +750,218 @@ async def test_unary_value_error_not_rerouted() -> None:await client.send_request(env)assert len(route.routes) == 1await client.disconnect()++[email protected]("stream", [False, True])[email protected]("method", ["chat.send", "chat.resume", "chat.user_answer", "chat.swarmflow_reply"])[email protected]("row", [+ None,+ {"enabled": False, "match_expr": []},+ {"enabled": True, "match_expr": "user_id == 'other'"},+ {"enabled": True, "match_expr": "user_id in ('other')"},+ {"enabled": True, "expires_at": "2000-01-01T00:00:00Z"},+ {"enabled": True, "expires_at": "invalid"},+])+async def test_agent_denial_never_routes_or_sends(agent_resources, stream, method, row):+ agent_resources.get.return_value = row+ route, http = _FakeRoute(), _FakeHttp()+ client = RuntimeRoutedAgentClient(route_client=route, http_client=http)+ await client.connect("")+ env = _chat_env()+ env.method = method+ with pytest.raises(FatalRouteError) as exc:+ if stream:+ _ = [chunk async for chunk in client.send_request_stream(env)]+ else:+ await client.send_request(env)+ assert exc.value.code == "FORBIDDEN"+ assert not route.routes and not http.calls and not route.touches+ await client.disconnect()++[email protected]("missing_session", [False, True])+async def test_authorization_and_route_use_trusted_identity(agent_resources, missing_session):+ agent_resources.get.return_value = {"enabled": True, "match_expr": "user_id == 'user-1'"}+ route, http = _FakeRoute(), _FakeHttp()+ client = RuntimeRoutedAgentClient(route_client=route, http_client=http)+ await client.connect("")+ env = _chat_env()+ env.params.update(user_id="forged", group_id="forged", bot_id="forged")+ if missing_session:+ env.session_id = None+ env.params.pop("session_id", None)+ assert (await client.send_request(env)).ok+ agent_resources.get.assert_awaited_once_with(resource_id="bot-1")+ assert route.routes[0]["session_id"] == ("grp-1:bot-1:user-1" if missing_session else "sess-1")+ assert (route.routes[0]["group_id"], route.routes[0]["bot_id"], route.routes[0]["user_id"]) == (+ "grp-1", "bot-1", "user-1",+ )+ await client.disconnect()+++async def test_missing_trusted_identity_cannot_use_params(agent_resources):+ route, http = _FakeRoute(), _FakeHttp()+ client = RuntimeRoutedAgentClient(route_client=route, http_client=http)+ await client.connect("")+ env = _chat_env()+ env.channel_context = {}+ with pytest.raises(FatalRouteError):+ await client.send_request(env)+ agent_resources.get.assert_not_awaited()+ assert not route.routes and not http.calls+ await client.disconnect()++[email protected]("change", ["revoke", "expire"])+async def test_existing_session_rechecks_grant(agent_resources, monkeypatch, change):+ from datetime import datetime, timezone+ auth = _load("agent_authorization")+ class Clock(datetime):+ current = datetime(2026, 9, 18, tzinfo=timezone.utc)+ @classmethod+ def now(cls, tz=None):+ return cls.current+ monkeypatch.setattr(auth, "datetime", Clock)+ agent_resources.get.return_value = {+ "enabled": True, "match_expr": [], "expires_at": "2026-09-19T00:00:00Z",+ }+ route, http = _FakeRoute(), _FakeHttp()+ client = RuntimeRoutedAgentClient(route_client=route, http_client=http)+ await client.connect("")+ assert (await client.send_request(_chat_env())).ok+ if change == "revoke":+ agent_resources.get.return_value = {"enabled": True, "match_expr": "user_id == 'other'"}+ else:+ Clock.current = datetime(2026, 9, 19, tzinfo=timezone.utc)+ with pytest.raises(FatalRouteError):+ await client.send_request(_chat_env())+ assert len(route.routes) == len(http.calls) == 1+ assert agent_resources.get.await_count == 2+ await client.disconnect()+++async def test_repository_failure_does_not_forward(agent_resources):+ agent_resources.get.side_effect = RuntimeError("database unavailable")+ route, http = _FakeRoute(), _FakeHttp()+ client = RuntimeRoutedAgentClient(route_client=route, http_client=http)+ await client.connect("")+ with pytest.raises(RuntimeError, match="database unavailable"):+ await client.send_request(_chat_env())+ assert not route.routes and not http.calls+ await client.disconnect()+++async def test_distinct_resource_grants_with_same_template(agent_resources):+ from jiuwenswarm.common.request_identity import apply_routing_metadata+ grants = {+ "bot-1": {"enabled": True, "ref_template_id": "shared", "match_expr": "user_id in ('user-1')"},+ "bot-2": {"enabled": True, "ref_template_id": "shared", "match_expr": "user_id in ('other')"},+ }+ agent_resources.get.side_effect = lambda *, resource_id: grants[resource_id]+ route, http = _FakeRoute(), _FakeHttp()+ client = RuntimeRoutedAgentClient(route_client=route, http_client=http)+ await client.connect("")+ assert (await client.send_request(_chat_env())).ok+ env = _chat_env()+ env.channel_context = apply_routing_metadata(+ {}, {"user_id": "user-1", "group_id": "grp-1", "bot_id": "bot-2"},+ )+ with pytest.raises(FatalRouteError):+ await client.send_request(env)+ assert len(route.routes) == len(http.calls) == 1+ await client.disconnect()+++def test_authorization_error_uses_existing_http_contract():+ from jiuwenswarm.gateway.channel_manager.web.web_http_app import _envelope_from_res+ body, status = _envelope_from_res(+ { "ok": False, "error": "Agent access denied", "code": "FORBIDDEN", "payload": {}},+ "request-1", rpc_method="chat.send",+ )+ assert status == 403+ assert body["error"]["code"] == "FORBIDDEN"++[email protected]("method", ["session.create", "history.get", "chat.interrupt"])+async def test_non_chat_requests_keep_existing_behavior(agent_resources, method):+ agent_resources.get.side_effect = AssertionError("must not query chat admission")+ route, http = _FakeRoute(), _FakeHttp()+ client = RuntimeRoutedAgentClient(route_client=route, http_client=http)+ await client.connect("")+ env = _chat_env()+ env.method = method+ assert (await client.send_request(env)).ok+ agent_resources.get.assert_not_awaited()+ await client.disconnect()++[email protected]("stream", [False, True])[email protected]("change", ["revoke", "disable", "delete", "expire", "invalid"])+async def test_persisted_grant_changes_block_next_chat(monkeypatch, stream, change):+ from jiuwenswarm.gateway.config.enterprise.repository import EnterpriseRecordRepository+ from jiuwenswarm.gateway.storage.backends.memory_persistent import InMemoryPersistentBackend++ repo = EnterpriseRecordRepository(InMemoryPersistentBackend(), "instance_agent_resource")+ await repo.create({+ "resource_id": "bot-1", "enabled": True, "match_expr": "user_id == 'user-1'",+ })+ auth = _load("agent_authorization")+ monkeypatch.setattr(auth, "get_enterprise_record_repository", lambda _: repo)+ route, http = _FakeRoute(), _FakeHttp()+ client = RuntimeRoutedAgentClient(route_client=route, http_client=http)+ await client.connect("")++ async def chat():+ if stream:+ return [chunk async for chunk in client.send_request_stream(_chat_env())]+ return await client.send_request(_chat_env())++ await chat()+ if change == "delete":+ await repo.delete(resource_id="bot-1")+ else:+ updates = {+ "revoke": {"match_expr": "user_id == 'other'"},+ "disable": {"enabled": False},+ "expire": {"expires_at": "2000-01-01T00:00:00Z"},+ "invalid": {"match_expr": "unknown"},+ }+ await repo.update({"resource_id": "bot-1"}, updates[change])+ with pytest.raises(FatalRouteError) as exc:+ await chat()+ assert exc.value.code == "FORBIDDEN"+ assert len(route.routes) == len(http.calls) == 1+ await client.disconnect()++[email protected]("stream", [False, True])[email protected]("enabled", [True, False, 1, 0, None, "0", "false"])+async def test_database_enabled_values(agent_resources, stream, enabled):+ from jiuwenswarm.gateway.storage.backends.db.bool_codec import mysql_boolean_for_read+ # 包括实际 MySQL 读值转换,避免仅用 bool 字面量模拟数据库。+ value = mysql_boolean_for_read(enabled) if isinstance(enabled, (bool, int)) else enabled+ agent_resources.get.return_value = {"enabled": value, "match_expr": []}+ route, http = _FakeRoute(), _FakeHttp()+ client = RuntimeRoutedAgentClient(route_client=route, http_client=http)+ await client.connect("")+ async def chat():+ if stream:+ return [chunk async for chunk in client.send_request_stream(_chat_env())]+ return await client.send_request(_chat_env())+ if enabled is True or enabled == 1:+ await chat()+ assert len(route.routes) == len(http.calls) == 1+ else:+ with pytest.raises(FatalRouteError):+ await chat()+ assert not route.routes and not http.calls+ await client.disconnect()