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

feat(a2a): add A2A outbound and access policy templates with CRUD operations

NickFuryXXX4d4ef10215d9
diff --git a/jiuwenswarm/gateway/config/enterprise/catalog.py b/jiuwenswarm/gateway/config/enterprise/catalog.py
index 54e221ff4b..ba118daa4c 100644
--- a/jiuwenswarm/gateway/config/enterprise/catalog.py
+++ b/jiuwenswarm/gateway/config/enterprise/catalog.py
@@ -32,6 +32,8 @@ ENTERPRISE_RECORD_SPECS: dict[str, EnterpriseRecordSpec] = {
"mcp_template": EnterpriseRecordSpec(key_fields=("template_id",)),
"permissions_template": EnterpriseRecordSpec(key_fields=("template_id",)),
"agent_template": EnterpriseRecordSpec(key_fields=("template_id",)),
+ "a2a_outbound_template": EnterpriseRecordSpec(key_fields=("template_id",)),
+ "a2a_access_policy_template": EnterpriseRecordSpec(key_fields=("policy_id",)),
"instance_agent_resource": EnterpriseRecordSpec(key_fields=("resource_id",)),
"log_masking_rule": EnterpriseRecordSpec(key_fields=("rule_id",)),
"cron_job": EnterpriseRecordSpec(key_fields=("job_id",)),
diff --git a/jiuwenswarm/gateway/config/enterprise/tables/table_init.py b/jiuwenswarm/gateway/config/enterprise/tables/table_init.py
index a7ba0f8015..96b6bc66d7 100644
--- a/jiuwenswarm/gateway/config/enterprise/tables/table_init.py
+++ b/jiuwenswarm/gateway/config/enterprise/tables/table_init.py
@@ -23,6 +23,8 @@ from .key_models import (
)
from .instance_resource_models import INSTANCE_AGENT_RESOURCE_TABLE_DEF
from .template_models import (
+ A2A_ACCESS_POLICY_TEMPLATE_TABLE_DEF,
+ A2A_OUTBOUND_TEMPLATE_TABLE_DEF,
AGENT_TEMPLATE_TABLE_DEF,
EMBEDDING_TEMPLATE_TABLE_DEF,
EXTENSION_CONFIG_TEMPLATE_TABLE_DEF,
@@ -43,6 +45,8 @@ ALL_TABLE_DEFINITIONS: tuple[TableDefinition, ...] = (
MCP_TEMPLATE_TABLE_DEF,
PERMISSIONS_TEMPLATE_TABLE_DEF,
AGENT_TEMPLATE_TABLE_DEF,
+ A2A_OUTBOUND_TEMPLATE_TABLE_DEF,
+ A2A_ACCESS_POLICY_TEMPLATE_TABLE_DEF,
INSTANCE_AGENT_RESOURCE_TABLE_DEF,
LOG_MASKING_RULE_TABLE_DEF,
LOGGING_CONFIG_TABLE_DEF,
diff --git a/jiuwenswarm/gateway/config/enterprise/tables/template_models.py b/jiuwenswarm/gateway/config/enterprise/tables/template_models.py
index 2f1739a27f..7b51227b6a 100644
--- a/jiuwenswarm/gateway/config/enterprise/tables/template_models.py
+++ b/jiuwenswarm/gateway/config/enterprise/tables/template_models.py
@@ -204,3 +204,58 @@ AGENT_TEMPLATE_TABLE_DEF = TableDefinition(
IndexDefinition(["template_id"], unique=True),
],
)
+
+A2A_OUTBOUND_TEMPLATE_TABLE_DEF = TableDefinition(
+ table_name="a2a_outbound_template",
+ columns=[
+ ColumnDefinition(
+ "id",
+ "integer",
+ primary_key=True,
+ autoincrement=True,
+ nullable=False,
+ ),
+ ColumnDefinition("template_id", "string", length=100, nullable=False),
+ ColumnDefinition("template_name", "string", length=128, nullable=False),
+ ColumnDefinition("description", "string", length=512, nullable=True),
+ ColumnDefinition("a2a_tags", "json", nullable=True),
+ ColumnDefinition("source_url", "string", length=2048, nullable=False),
+ ColumnDefinition("card_path", "string", length=512, nullable=False),
+ ColumnDefinition("agent_card", "json", nullable=False),
+ ColumnDefinition("card_fingerprint", "string", length=128, nullable=False),
+ ColumnDefinition("card_revision", "integer", nullable=False),
+ ColumnDefinition("selected_interface", "json", nullable=False),
+ ColumnDefinition("credential_ref", "string", length=512, nullable=True),
+ ColumnDefinition("connect_timeout_seconds", "float", nullable=False),
+ ColumnDefinition("sync_wait_seconds", "float", nullable=False),
+ ColumnDefinition("enabled", "boolean", nullable=False, default=True),
+ ColumnDefinition("data", "json", nullable=True),
+ ColumnDefinition("created_at", "datetime", nullable=False),
+ ColumnDefinition("updated_at", "datetime", nullable=False),
+ ],
+ indexes=[IndexDefinition(["template_id"], unique=True)],
+)
+
+A2A_ACCESS_POLICY_TEMPLATE_TABLE_DEF = TableDefinition(
+ table_name="a2a_access_policy_template",
+ columns=[
+ ColumnDefinition(
+ "id",
+ "integer",
+ primary_key=True,
+ autoincrement=True,
+ nullable=False,
+ ),
+ ColumnDefinition("policy_id", "string", length=100, nullable=False),
+ ColumnDefinition("policy_name", "string", length=128, nullable=False),
+ ColumnDefinition("description", "string", length=512, nullable=True),
+ ColumnDefinition("mode", "string", length=16, nullable=False),
+ ColumnDefinition("member_template_ids", "json", nullable=False),
+ ColumnDefinition("enabled", "boolean", nullable=False, default=True),
+ ColumnDefinition("revision", "integer", nullable=False),
+ ColumnDefinition("data", "json", nullable=True),
+ ColumnDefinition("created_at", "datetime", nullable=False),
+ ColumnDefinition("updated_at", "datetime", nullable=False),
+ ],
+ indexes=[IndexDefinition(["policy_id"], unique=True)],
+)
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_data_lifecycle.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_data_lifecycle.py
index 74d2b4cf41..d9dbca1f40 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_data_lifecycle.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_data_lifecycle.py
@@ -15,6 +15,7 @@ from ...infrastructure.repository_access import (
require_enterprise_repository,
require_logging_repository,
)
+from ..template.a2a_outbound_template import A2AOutboundTemplateService
logger = logging.getLogger(__name__)
@@ -27,6 +28,8 @@ INSTANCE_PURGE_TABLES: tuple[str, ...] = (
"skill_prebuilt_template",
"mcp_template",
"permissions_template",
+ "a2a_outbound_template",
+ "a2a_access_policy_template",
"agent_template",
"instance_agent_resource",
"log_masking_rule",
@@ -59,9 +62,24 @@ async def _purge_cron_job_table() -> int:
async def _purge_enterprise_table(table: str) -> int:
+ if table == "a2a_outbound_template":
+ return await _purge_a2a_outbound_templates()
return await _purge_enterprise_repository(require_enterprise_repository(table))
+async def _purge_a2a_outbound_templates() -> int:
+ repo = require_enterprise_repository("a2a_outbound_template")
+ service = A2AOutboundTemplateService()
+ deleted = 0
+ for row in await repo.list(limit=_LIST_ALL_CAP):
+ template_id = str(row.get("template_id") or "").strip()
+ if not template_id:
+ continue
+ await service.delete(template_id)
+ deleted += 1
+ return deleted
+
+
async def _purge_enterprise_repository(repo: EnterpriseRecordRepository) -> int:
key_fields = repo.key_fields
if not key_fields:
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_service.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_service.py
index 663f2d598b..26cff22b2e 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_service.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_service.py
@@ -16,13 +16,13 @@ logger = logging.getLogger(__name__)
def resolve_public_endpoint(cfg: Settings | None = None) -> str:
"""Manager 回调用的 Gateway Config Receiver Base URL(无尾斜杠)。
- 由 ``GATEWAY_CONFIG_PUBLIC_HOST`` + ``GATEWAY_CONFIG_HTTP_PORT`` 拼接;
- host 未配置时默认 ``127.0.0.1``。
+ 由 ``GATEWAY_CONFIG_PUBLIC_SCHEME``、``GATEWAY_CONFIG_PUBLIC_HOST`` 和
+ ``GATEWAY_CONFIG_HTTP_PORT`` 拼接;host 未配置时默认 ``127.0.0.1``。
"""
cfg = cfg or get_settings()
port = int(cfg.gateway_config_http_port or 8775)
host = (cfg.gateway_config_public_host or "").strip() or "127.0.0.1"
- return f"http://{host}:{port}"
+ return f"{cfg.gateway_config_public_scheme}://{host}:{port}"
def resolve_manager_http_base(cfg: Settings | None = None) -> str:
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/__init__.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/__init__.py
index c9fcf065bd..a5d4a2876b 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/__init__.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/__init__.py
@@ -1,3 +1,5 @@
+from .a2a_access_policy_template import A2AAccessPolicyTemplateService
+from .a2a_outbound_template import A2AOutboundTemplateService
from .embedding_template import EmbeddingTemplateService
from .extension_config_template import ExtensionConfigTemplateService
from .mcp_template import McpTemplateService
@@ -6,6 +8,8 @@ from .permissions_template import PermissionsTemplateService
from .skill_prebuilt_template import SkillPrebuiltTemplateService
__all__ = (
+ "A2AAccessPolicyTemplateService",
+ "A2AOutboundTemplateService",
"EmbeddingTemplateService",
"ModelTemplateService",
"ExtensionConfigTemplateService",
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/a2a_access_policy_template.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/a2a_access_policy_template.py
new file mode 100644
index 0000000000..2cedf54ca5
--- /dev/null
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/a2a_access_policy_template.py
@@ -0,0 +1,84 @@
+"""Manager-owned A2A access policy projection."""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from jiuwenswarm.gateway.config.enterprise.tables.template_models import (
+ A2A_ACCESS_POLICY_TEMPLATE_TABLE_DEF,
+)
+
+from ...infrastructure.repository_access import require_enterprise_repository
+from ...infrastructure.utils import parse_iso_datetime, utc_now
+from ...schemas.template_schemas import (
+ A2AAccessPolicyTemplateCreateRequest,
+ A2AAccessPolicyTemplateUpdateRequest,
+)
+
+_TABLE = A2A_ACCESS_POLICY_TEMPLATE_TABLE_DEF.table_name
+logger = logging.getLogger(__name__)
+
+
+def _policy_id(value: Any) -> str:
+ policy_id = str(value or "").strip()
+ if not policy_id:
+ raise ValueError("policy_id is required")
+ return policy_id
+
+
+class A2AAccessPolicyTemplateService:
+ async def _upsert(self, policy: dict[str, Any], *, full: bool) -> str:
+ policy_id = _policy_id(policy.get("policy_id"))
+ request = (
+ A2AAccessPolicyTemplateCreateRequest.model_validate(policy)
+ if full
+ else A2AAccessPolicyTemplateUpdateRequest.model_validate(
+ {key: value for key, value in policy.items() if key != "policy_id"}
+ )
+ )
+ repo = require_enterprise_repository(_TABLE)
+ existing = await repo.get(policy_id=policy_id)
+ values = request.model_dump(exclude_unset=True, exclude={"policy_id"})
+ now = utc_now()
+ values["updated_at"] = parse_iso_datetime(values.get("updated_at")) or now
+ if existing is None:
+ await repo.create({"policy_id": policy_id, **values, "created_at": now})
+ else:
+ updated = await repo.update({"policy_id": policy_id}, values)
+ if updated is None:
+ raise ValueError(
+ f"a2a access policy policy_id={policy_id!r} not found"
+ )
+ return policy_id
+
+ async def create(self, policy: dict[str, Any]) -> dict[str, str]:
+ if not isinstance(policy, dict):
+ raise ValueError("a2a_access_policies.create requires policy object")
+ policy_id = await self._upsert(policy, full=True)
+ logger.info(
+ "[ManagerConfigReceiver] a2a_access_policies upsert policy_id=%s",
+ policy_id,
+ )
+ return {"policy_id": policy_id}
+
+ async def update(self, policy_id: str, updates: dict[str, Any]) -> None:
+ pid = _policy_id(policy_id)
+ if not isinstance(updates, dict) or not updates:
+ raise ValueError("a2a_access_policies.update requires non-empty updates")
+ repo = require_enterprise_repository(_TABLE)
+ if await repo.get(policy_id=pid) is None:
+ raise ValueError(f"a2a access policy policy_id={pid!r} not found")
+ await self._upsert({"policy_id": pid, **updates}, full=False)
+ logger.info(
+ "[ManagerConfigReceiver] a2a_access_policies update policy_id=%s",
+ pid,
+ )
+
+ async def delete(self, policy_id: str) -> None:
+ pid = _policy_id(policy_id)
+ await require_enterprise_repository(_TABLE).delete(policy_id=pid)
+ logger.info(
+ "[ManagerConfigReceiver] a2a_access_policies delete policy_id=%s",
+ pid,
+ )
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/a2a_outbound_template.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/a2a_outbound_template.py
new file mode 100644
index 0000000000..9a261f5f19
--- /dev/null
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/a2a_outbound_template.py
@@ -0,0 +1,154 @@
+"""Manager-owned A2A outbound Agent projection."""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from jiuwenswarm.gateway.a2a_manager.outbound.credentials import (
+ A2AOutboundCredentialStore,
+)
+from jiuwenswarm.gateway.a2a_manager.outbound.models import sanitize_persisted_value
+from jiuwenswarm.gateway.config.enterprise.tables.template_models import (
+ A2A_OUTBOUND_TEMPLATE_TABLE_DEF,
+)
+
+from ...infrastructure.repository_access import require_enterprise_repository
+from ...infrastructure.utils import parse_iso_datetime, utc_now
+from ...schemas.template_schemas import (
+ A2AOutboundTemplateCreateRequest,
+ A2AOutboundTemplateUpdateRequest,
+)
+
+_TABLE = A2A_OUTBOUND_TEMPLATE_TABLE_DEF.table_name
+logger = logging.getLogger(__name__)
+
+
+def _template_id(value: Any) -> str:
+ template_id = str(value or "").strip()
+ if not template_id:
+ raise ValueError("template_id is required")
+ return template_id
+
+
+class A2AOutboundTemplateService:
+ def __init__(
+ self, credential_store: A2AOutboundCredentialStore | None = None
+ ) -> None:
+ self._credentials = credential_store or A2AOutboundCredentialStore()
+
+ def _restore_credential(
+ self,
+ template_id: str,
+ old_ref: str | None,
+ old_secret: str,
+ ) -> None:
+ current_ref = self._credentials.reference_for(template_id)
+ if old_ref and old_secret:
+ self._credentials.set_for_agent(template_id, old_secret)
+ else:
+ self._credentials.delete(current_ref)
+
+ async def _upsert(self, template: dict[str, Any], *, full: bool) -> str:
+ template_id = _template_id(template.get("template_id"))
+ request = (
+ A2AOutboundTemplateCreateRequest.model_validate(template)
+ if full
+ else A2AOutboundTemplateUpdateRequest.model_validate(
+ {key: value for key, value in template.items() if key != "template_id"}
+ )
+ )
+ repo = require_enterprise_repository(_TABLE)
+ existing = await repo.get(template_id=template_id)
+ old_ref = str(existing.get("credential_ref") or "") if existing else ""
+ old_secret = self._credentials.get(old_ref) if old_ref else ""
+
+ values = request.model_dump(
+ exclude_unset=True,
+ exclude={"credential", "template_id"},
+ )
+ for field in ("agent_card", "selected_interface", "data"):
+ if field in values:
+ values[field] = sanitize_persisted_value(values[field])
+ operation = request.credential.operation if request.credential else "keep"
+ if operation == "replace":
+ values["credential_ref"] = self._credentials.set_for_agent(
+ template_id, request.credential.value or ""
+ )
+ elif operation == "clear":
+ self._credentials.delete(
+ old_ref or self._credentials.reference_for(template_id)
+ )
+ values["credential_ref"] = None
+ elif existing is not None:
+ values["credential_ref"] = existing.get("credential_ref")
+
+ now = utc_now()
+ values["updated_at"] = parse_iso_datetime(values.get("updated_at")) or now
+ try:
+ if existing is None:
+ await repo.create(
+ {
+ "template_id": template_id,
+ **values,
+ "created_at": now,
+ }
+ )
+ else:
+ updated = await repo.update({"template_id": template_id}, values)
+ if updated is None:
+ raise ValueError(
+ f"a2a outbound template template_id={template_id!r} not found"
+ )
+ except Exception:
+ if operation in {"replace", "clear"}:
+ self._restore_credential(template_id, old_ref or None, old_secret)
+ raise
+ return template_id
+
+ async def create(self, template: dict[str, Any]) -> dict[str, str]:
+ if not isinstance(template, dict):
+ raise ValueError("a2a_outbound_templates.create requires template object")
+ template_id = await self._upsert(template, full=True)
+ logger.info(
+ "[ManagerConfigReceiver] a2a_outbound_templates upsert template_id=%s",
+ template_id,
+ )
+ return {"template_id": template_id}
+
+ async def update(self, template_id: str, updates: dict[str, Any]) -> None:
+ tid = _template_id(template_id)
+ if not isinstance(updates, dict) or not updates:
+ raise ValueError("a2a_outbound_templates.update requires non-empty updates")
+ repo = require_enterprise_repository(_TABLE)
+ existing = await repo.get(template_id=tid)
+ if existing is None:
+ raise ValueError(f"a2a outbound template template_id={tid!r} not found")
+ await self._upsert({"template_id": tid, **updates}, full=False)
+ logger.info(
+ "[ManagerConfigReceiver] a2a_outbound_templates update template_id=%s",
+ tid,
+ )
+
+ async def delete(self, template_id: str) -> None:
+ tid = _template_id(template_id)
+ repo = require_enterprise_repository(_TABLE)
+ existing = await repo.get(template_id=tid)
+ credential_ref = (
+ str(existing.get("credential_ref") or "")
+ if existing
+ else self._credentials.reference_for(tid)
+ )
+ old_secret = self._credentials.get(credential_ref)
+ self._credentials.delete(credential_ref)
+ try:
+ if existing is not None:
+ await repo.delete(template_id=tid)
+ except Exception:
+ if old_secret:
+ self._credentials.set_for_agent(tid, old_secret)
+ raise
+ logger.info(
+ "[ManagerConfigReceiver] a2a_outbound_templates delete template_id=%s",
+ tid,
+ )
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/http/sync_security.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/http/sync_security.py
index e76b147e19..e8c8436c5f 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/http/sync_security.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/http/sync_security.py
@@ -5,10 +5,11 @@ from __future__ import annotations
from typing import Any
-# 历史信封 / 兼容字段,不进入业务落库
-_LEGACY_KEYS = frozenset({"revision", "sig", "enc"})
+# 历史信封字段,不进入业务落库。``revision`` 也是 A2A 策略业务字段,
+# 由各显式 schema 决定是否接收,不能在这里全局剥离。
+_LEGACY_KEYS = frozenset({"sig", "enc"})
def split_business(body: dict[str, Any]) -> dict[str, Any]:
- """返回业务字段;忽略历史 ``revision`` / ``sig`` / ``enc``。"""
+ """返回业务字段;忽略历史 ``sig`` / ``enc``。"""
return {k: v for k, v in body.items() if k not in _LEGACY_KEYS}
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/config.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/config.py
index ba2a92d4f9..7cdb4038f4 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/config.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/config.py
@@ -5,7 +5,7 @@
from __future__ import annotations
from pathlib import Path
-from typing import Optional
+from typing import Literal, Optional
from pydantic import Field, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
@@ -67,11 +67,15 @@ class Settings(BaseSettings):
default=8775,
validation_alias="GATEWAY_CONFIG_HTTP_PORT",
)
- # 对外可被 Manager 访问的主机名(端口用 HTTP_PORT)
+ # 对外可被 Manager 访问的地址;HTTPS 通常由反向代理终止。
gateway_config_public_host: str = Field(
default="",
validation_alias="GATEWAY_CONFIG_PUBLIC_HOST",
)
+ gateway_config_public_scheme: Literal["http", "https"] = Field(
+ default="http",
+ validation_alias="GATEWAY_CONFIG_PUBLIC_SCHEME",
+ )
# Gateway 管理面 REST Base(可选;身份绑定后一般不再主动调用 Manager)
gateway_manager_http_url: str = Field(
default="",
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/public_endpoint.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/public_endpoint.py
index 4f47cd4b0f..411ff6f01d 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/public_endpoint.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/public_endpoint.py
@@ -9,10 +9,10 @@ from .config import Settings, get_settings
def resolve_public_endpoint(cfg: Settings | None = None) -> str:
"""Manager 回调用的 Gateway Config Receiver Base URL(无尾斜杠)。
- 由 ``GATEWAY_CONFIG_PUBLIC_HOST`` + ``GATEWAY_CONFIG_HTTP_PORT`` 拼接;
- host 未配置时默认 ``127.0.0.1``。
+ 由 ``GATEWAY_CONFIG_PUBLIC_SCHEME``、``GATEWAY_CONFIG_PUBLIC_HOST`` 和
+ ``GATEWAY_CONFIG_HTTP_PORT`` 拼接;host 未配置时默认 ``127.0.0.1``。
"""
cfg = cfg or get_settings()
port = int(cfg.gateway_config_http_port or 8775)
host = (cfg.gateway_config_public_host or "").strip() or "127.0.0.1"
- return f"http://{host}:{port}"
+ return f"{cfg.gateway_config_public_scheme}://{host}:{port}"
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/template_routers.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/template_routers.py
index 7254f3b93b..a3b45bcba5 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/template_routers.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/template_routers.py
@@ -8,6 +8,8 @@ from typing import Any
from fastapi import APIRouter, HTTPException, Request
+from ..core.template.a2a_access_policy_template import A2AAccessPolicyTemplateService
+from ..core.template.a2a_outbound_template import A2AOutboundTemplateService
from ..core.template.agent_template import AgentTemplateService
from ..core.template.embedding_template import EmbeddingTemplateService
from ..core.template.extension_config_template import ExtensionConfigTemplateService
@@ -18,16 +20,20 @@ from ..core.template.skill_prebuilt_template import SkillPrebuiltTemplateService
from ..schemas.common_schemas import ResponseModel
from ..schemas.sync_schemas import SyncEnvelopeOnlyBody, make_sync_body
from ..schemas.template_schemas import (
+ A2AAccessPolicyTemplateCreateRequest,
+ A2AAccessPolicyTemplateUpdateRequest,
+ A2AOutboundTemplateCreateRequest,
+ A2AOutboundTemplateUpdateRequest,
AgentTemplateCreateRequest,
AgentTemplateUpdateRequest,
EmbeddingTemplateCreateRequest,
EmbeddingTemplateUpdateRequest,
ExtensionConfigTemplateCreateRequest,
ExtensionConfigTemplateUpdateRequest,
- ModelTemplateCreateRequest,
- ModelTemplateUpdateRequest,
McpTemplateCreateRequest,
McpTemplateUpdateRequest,
+ ModelTemplateCreateRequest,
+ ModelTemplateUpdateRequest,
PermissionsTemplateCreateRequest,
PermissionsTemplateUpdateRequest,
SkillPrebuiltTemplateCreateRequest,
@@ -47,6 +53,24 @@ def _http_exc(exc: ValueError) -> HTTPException:
return HTTPException(status_code=status, detail=detail)
+def _require_secure_a2a_credential_transport(
+ request: Request,
+ tag: str,
+ business: dict[str, Any],
+) -> None:
+ credential = business.get("credential")
+ if (
+ tag == "a2a_outbound"
+ and isinstance(credential, dict)
+ and credential.get("operation") == "replace"
+ and request.url.scheme.lower() != "https"
+ ):
+ raise HTTPException(
+ status_code=400,
+ detail="A2A credentials may only be synchronized over HTTPS",
+ )
+
+
def _add_template_crud(
path: str,
svc_factory: _ServiceFactory,
@@ -62,6 +86,7 @@ def _add_template_crud(
body: Any,
):
sync = await build_sync_context(body, request.method)
+ _require_secure_a2a_credential_transport(request, tag, sync.business)
try:
result = await svc_factory().create(
sync.business
@@ -79,6 +104,7 @@ def _add_template_crud(
body: Any,
):
sync = await build_sync_context(body, request.method)
+ _require_secure_a2a_credential_transport(request, tag, sync.business)
try:
await svc_factory().update(
template_id, sync.business
@@ -128,6 +154,20 @@ def _add_template_crud(
)
+_add_template_crud(
+ "/a2a-outbound-templates",
+ A2AOutboundTemplateService,
+ "a2a_outbound",
+ A2AOutboundTemplateCreateRequest,
+ A2AOutboundTemplateUpdateRequest,
+)
+_add_template_crud(
+ "/a2a-access-policies",
+ A2AAccessPolicyTemplateService,
+ "a2a_access_policy",
+ A2AAccessPolicyTemplateCreateRequest,
+ A2AAccessPolicyTemplateUpdateRequest,
+)
_add_template_crud(
"/model-templates",
ModelTemplateService,
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/safe_text.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/safe_text.py
index 4b879b3321..b77e5f7ee5 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/safe_text.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/safe_text.py
@@ -29,6 +29,7 @@ _SQLI_RE = re.compile(
SAFE_TEXT_FIELD_NAMES: frozenset[str] = frozenset(
{
"template_name",
+ "policy_name",
"description",
"namespace",
"pod_name",
@@ -45,6 +46,7 @@ SAFE_TEXT_LIST_FIELD_NAMES: frozenset[str] = frozenset(
{
"model_tags",
"embed_tags",
+ "a2a_tags",
}
)
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/template_schemas.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/template_schemas.py
index 26a5736fd7..ca843ea492 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/template_schemas.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/template_schemas.py
@@ -1,8 +1,8 @@
from __future__ import annotations
-import re
-from typing import Annotated, Any
-from urllib.parse import urlparse
+from datetime import datetime
+from typing import Annotated, Any, Literal
+from urllib.parse import unquote, urlparse, urlsplit
from croniter import croniter
from pydantic import (
@@ -12,6 +12,7 @@ from pydantic import (
BeforeValidator,
ConfigDict,
Field,
+ field_validator,
model_validator,
)
@@ -78,6 +79,31 @@ OptionalSkillSourceUrl = Annotated[
]
+def _validate_a2a_card_path(value: str) -> str:
+ if not value.startswith("/") or value.startswith("//") or "\\" in value:
+ raise ValueError("must be an absolute same-origin path")
+ parsed = urlsplit(value)
+ decoded = unquote(parsed.path)
+ if parsed.scheme or parsed.netloc or parsed.query or parsed.fragment:
+ raise ValueError("must not contain a scheme, host, query, or fragment")
+ if decoded.startswith("//") or "\\" in decoded or ".." in decoded.split("/"):
+ raise ValueError("must remain a same-origin path")
+ return value
+
+
+A2ASourceUrl = Annotated[
+ str,
+ Field(min_length=1, max_length=2048),
+ AfterValidator(_validate_http_url),
+]
+A2ACardPath = Annotated[
+ str,
+ Field(min_length=1, max_length=512),
+ AfterValidator(_validate_a2a_card_path),
+]
+TemplateId = Annotated[str, Field(min_length=1, max_length=100)]
+
+
class HookConfig(BaseModel):
"""扩展模板 hook_config 结构(与设计文档一致)。"""
@@ -280,3 +306,112 @@ class AgentTemplateCreateRequest(AgentTemplateUpdateRequest):
template_id: str = Field(..., min_length=1, max_length=100)
template_name: str = Field(..., min_length=1, max_length=128)
template_ref: dict[str, list[str]] = Field(default_factory=dict)
+
+
+class A2ACredentialOperation(BaseModel):
+ model_config = ConfigDict(str_strip_whitespace=True, extra="forbid")
+
+ operation: Literal["keep", "replace", "clear"]
+ value: str | None = Field(default=None, max_length=4096)
+
+ @model_validator(mode="after")
+ def _validate_operation(self) -> A2ACredentialOperation:
+ if self.operation == "replace":
+ if not self.value:
+ raise ValueError("credential.value is required for replace")
+ if self.value.startswith("ENC:v1:"):
+ raise ValueError("encrypted credential envelopes are not supported")
+ elif self.value is not None:
+ raise ValueError("credential.value is only valid for replace")
+ return self
+
+
+class A2AOutboundTemplateUpdateRequest(SafeTextMixin):
+ model_config = ConfigDict(str_strip_whitespace=True, extra="ignore")
+
+ template_name: str | None = Field(default=None, min_length=1, max_length=128)
+ description: str | None = Field(default=None, max_length=512)
+ a2a_tags: list[str] | None = None
+ source_url: A2ASourceUrl | None = None
+ card_path: A2ACardPath | None = None
+ agent_card: dict[str, Any] | None = None
+ card_fingerprint: str | None = Field(default=None, min_length=1, max_length=128)
+ card_revision: int | None = Field(default=None, ge=1)
+ selected_interface: dict[str, Any] | None = None
+ connect_timeout_seconds: float | None = Field(default=None, gt=0)
+ sync_wait_seconds: float | None = Field(default=None, gt=0)
+ enabled: bool | None = None
+ credential: A2ACredentialOperation | None = None
+ data: dict[str, Any] | None = None
+ updated_at: datetime | None = None
+
+ @model_validator(mode="after")
+ def _validate_card_and_interface(self) -> A2AOutboundTemplateUpdateRequest:
+ if self.agent_card is not None and not str(self.agent_card.get("name") or "").strip():
+ raise ValueError("agent_card.name is required")
+ if self.selected_interface is not None:
+ protocol_binding = str(
+ self.selected_interface.get("protocol_binding") or ""
+ ).strip()
+ protocol_version = str(
+ self.selected_interface.get("protocol_version") or ""
+ ).strip()
+ if not protocol_binding:
+ raise ValueError("selected_interface.protocol_binding is required")
+ if not protocol_version:
+ raise ValueError("selected_interface.protocol_version is required")
+ interface_url = str(self.selected_interface.get("url") or "").strip()
+ if not interface_url:
+ raise ValueError("selected_interface.url is required")
+ _validate_http_url(interface_url)
+ return self
+
+
+class A2AOutboundTemplateCreateRequest(A2AOutboundTemplateUpdateRequest):
+ template_id: TemplateId
+ template_name: str = Field(..., min_length=1, max_length=128)
+ source_url: A2ASourceUrl
+ card_path: A2ACardPath
+ agent_card: dict[str, Any]
+ card_fingerprint: str = Field(..., min_length=1, max_length=128)
+ card_revision: int = Field(..., ge=1)
+ selected_interface: dict[str, Any]
+ connect_timeout_seconds: float = Field(..., gt=0)
+ sync_wait_seconds: float = Field(..., gt=0)
+ enabled: bool
+ credential: A2ACredentialOperation
+ updated_at: datetime
+
+ @model_validator(mode="after")
+ def _require_bootstrap_credential(self) -> A2AOutboundTemplateCreateRequest:
+ if self.credential.operation == "keep":
+ raise ValueError("credential keep is not valid for A2A Agent upsert")
+ return self
+
+
+class A2AAccessPolicyTemplateUpdateRequest(SafeTextMixin):
+ model_config = ConfigDict(str_strip_whitespace=True, extra="ignore")
+
+ policy_name: str | None = Field(default=None, min_length=1, max_length=128)
+ description: str | None = Field(default=None, max_length=512)
+ mode: Literal["allowlist", "denylist"] | None = None
+ member_template_ids: list[TemplateId] | None = None
+ enabled: bool | None = None
+ revision: int | None = Field(default=None, ge=1)
+ data: dict[str, Any] | None = None
+ updated_at: datetime | None = None
+
+ @field_validator("member_template_ids")
+ @classmethod
+ def _deduplicate_members(cls, value: list[str] | None) -> list[str] | None:
+ return None if value is None else list(dict.fromkeys(value))
+
+
+class A2AAccessPolicyTemplateCreateRequest(A2AAccessPolicyTemplateUpdateRequest):
+ policy_id: TemplateId
+ policy_name: str = Field(..., min_length=1, max_length=128)
+ mode: Literal["allowlist", "denylist"]
+ member_template_ids: list[TemplateId] = Field(default_factory=list)
+ enabled: bool
+ revision: int = Field(..., ge=1)
+ updated_at: datetime
diff --git a/tests/unit_tests/gateway/test_manager_config_receiver_a2a.py b/tests/unit_tests/gateway/test_manager_config_receiver_a2a.py
new file mode 100644
index 0000000000..53ff94ec77
--- /dev/null
+++ b/tests/unit_tests/gateway/test_manager_config_receiver_a2a.py
@@ -0,0 +1,383 @@
+"""Enterprise Manager Config Receiver A2A projection tests."""
+
+# ruff: noqa: E402 -- install optional openjiuwen-runtime DB stubs before imports
+
+from __future__ import annotations
+
+import logging
+import sys
+from collections.abc import Iterator
+from types import ModuleType
+from typing import Any
+
+import pytest
+from fastapi.testclient import TestClient
+
+
+def _install_runtime_db_stubs() -> None:
+ """Supply table-definition types when the lightweight test env lacks runtime DB."""
+ try:
+ __import__("openjiuwen_runtime.foundation.db.table_def")
+ return
+ except ModuleNotFoundError:
+ pass
+
+ class _Definition:
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ self.args = args
+ for key, value in kwargs.items():
+ setattr(self, key, value)
+
+ handler = ModuleType("openjiuwen_runtime.foundation.db.handler")
+ handler.DBHandler = object # type: ignore[attr-defined]
+ table_def = ModuleType("openjiuwen_runtime.foundation.db.table_def")
+ table_def.ColumnDefinition = _Definition # type: ignore[attr-defined]
+ table_def.IndexDefinition = _Definition # type: ignore[attr-defined]
+ table_def.TableDefinition = _Definition # type: ignore[attr-defined]
+ sys.modules[handler.__name__] = handler
+ sys.modules[table_def.__name__] = table_def
+ db_package = sys.modules["openjiuwen_runtime.foundation.db"]
+ for module_name, class_name in (
+ ("mysql_handler", "MySQLHandler"),
+ ("postgresql_handler", "PostgreSQLHandler"),
+ ("sqlite_handler", "SQLiteHandler"),
+ ):
+ module = ModuleType(f"openjiuwen_runtime.foundation.db.{module_name}")
+ setattr(module, class_name, type(class_name, (), {}))
+ sys.modules[module.__name__] = module
+ setattr(db_package, module_name, module)
+ runtime_log = ModuleType("openjiuwen_runtime.foundation.log")
+ runtime_log.get_logger = logging.getLogger # type: ignore[attr-defined]
+ sys.modules[runtime_log.__name__] = runtime_log
+
+
+_install_runtime_db_stubs()
+
+from jiuwenswarm.common.secrets import SecretStore
+from jiuwenswarm.gateway.config.enterprise import (
+ clear_enterprise_record_repositories,
+ set_enterprise_record_repositories,
+)
+from jiuwenswarm.gateway.config.enterprise.tables.table_init import (
+ ALL_TABLE_DEFINITIONS,
+)
+from jiuwenswarm.gateway.storage.backends.memory_persistent import (
+ InMemoryPersistentBackend,
+)
+from jiuwenswarm.gateway.storage_assembly.setup import (
+ create_enterprise_record_repositories,
+)
+from jiuwenswarm.infrastructure.module_importer import (
+ import_manager_config_receiver_module,
+)
+
+
+class _Secrets:
+ def __init__(self) -> None:
+ self.values: dict[str, str] = {}
+
+ def get(self, key: str) -> str:
+ return self.values.get(key, "")
+
+ def set(self, key: str, value: str, *, algorithm: str | None = None) -> None:
+ del algorithm
+ self.values[key] = value
+
+ def delete(self, key: str) -> None:
+ self.values.pop(key, None)
+
+
+def _outbound_payload(
+ *, operation: str = "replace", value: str | None = "secret"
+) -> dict[str, Any]:
+ credential: dict[str, Any] = {"operation": operation}
+ if value is not None:
+ credential["value"] = value
+ return {
+ "template_id": "a2a-weather",
+ "template_name": "Weather Agent",
+ "description": "weather",
+ "a2a_tags": ["weather"],
+ "source_url": "https://example.test/a2a",
+ "card_path": "/.well-known/agent-card.json",
+ "agent_card": {"name": "Weather Agent"},
+ "card_fingerprint": "sha256:card",
+ "card_revision": 1,
+ "selected_interface": {
+ "url": "https://example.test/a2a",
+ "protocol_binding": "JSONRPC",
+ "protocol_version": "1.0",
+ },
+ "connect_timeout_seconds": 10,
+ "sync_wait_seconds": 120,
+ "enabled": True,
+ "credential": credential,
+ "data": {},
+ "updated_at": "2026-09-05T00:00:00Z",
+ }
+
+
+def a2a_receiver() -> Iterator[tuple[TestClient, dict[str, Any], _Secrets]]:
+ store = InMemoryPersistentBackend()
+ repos = create_enterprise_record_repositories(store)
+ set_enterprise_record_repositories(repos)
+ secrets = _Secrets()
+ SecretStore.reset_for_tests(secrets) # type: ignore[arg-type]
+ app_module = import_manager_config_receiver_module("http.app")
+ try:
+ with TestClient(
+ app_module.create_app(), base_url="https://gateway.test"
+ ) as client:
+ yield client, repos, secrets
+ finally:
+ SecretStore.reset_for_tests()
+ clear_enterprise_record_repositories()
+
+
+def test_a2a_outbound_receiver_crud_and_secret_store(
+ a2a_receiver: tuple[TestClient, dict[str, Any], _Secrets],
+) -> None:
+ client, repos, secrets = a2a_receiver
+ path = "/api/v1/a2a-outbound-templates"
+ credential_ref = "a2a/outbound/a2a-weather.api_key"
+
+ response = client.post(path, json=_outbound_payload())
+ assert response.status_code == 200
+ stored = repos["a2a_outbound_template"]
+ projection = client.portal.call(lambda: stored.get(template_id="a2a-weather"))
+ assert projection["credential_ref"] == credential_ref
+ assert "credential" not in projection
+ assert secrets.values[credential_ref] == "secret"
+
+ sanitized = _outbound_payload()
+ sanitized["agent_card"]["authorization"] = "Bearer card-secret"
+ sanitized["selected_interface"]["api_key"] = "interface-secret"
+ sanitized["data"]["access_token"] = "metadata-secret"
+ assert client.post(path, json=sanitized).status_code == 200
+ projection = client.portal.call(lambda: stored.get(template_id="a2a-weather"))
+ assert projection["agent_card"]["authorization"] == "******"
+ assert projection["selected_interface"]["api_key"] == "******"
+ assert projection["data"]["access_token"] == "******"
+
+ replay = _outbound_payload()
+ replay["template_name"] = "Weather Agent v2"
+ assert client.post(path, json=replay).status_code == 200
+ projection = client.portal.call(lambda: stored.get(template_id="a2a-weather"))
+ assert projection["template_name"] == "Weather Agent v2"
+ assert secrets.values[credential_ref] == "secret"
+
+ assert (
+ client.patch(
+ f"{path}/a2a-weather",
+ json={"enabled": False, "credential": {"operation": "keep"}},
+ ).status_code
+ == 200
+ )
+ projection = client.portal.call(lambda: stored.get(template_id="a2a-weather"))
+ assert projection["enabled"] is False
+ assert secrets.values[credential_ref] == "secret"
+
+ assert (
+ client.patch(
+ f"{path}/a2a-weather",
+ json={"credential": {"operation": "clear"}},
+ ).status_code
+ == 200
+ )
+ projection = client.portal.call(lambda: stored.get(template_id="a2a-weather"))
+ assert projection["credential_ref"] is None
+ assert credential_ref not in secrets.values
+
+ assert client.request("DELETE", f"{path}/a2a-weather", json={}).status_code == 200
+ assert client.request("DELETE", f"{path}/a2a-weather", json={}).status_code == 200
+
+
+def test_a2a_access_policy_receiver_is_idempotent(
+ a2a_receiver: tuple[TestClient, dict[str, Any], _Secrets],
+) -> None:
+ client, repos, _ = a2a_receiver
+ path = "/api/v1/a2a-access-policies"
+ payload = {
+ "policy_id": "policy-1",
+ "policy_name": "Production",
+ "description": None,
+ "mode": "allowlist",
+ "member_template_ids": ["a2a-weather", "a2a-weather"],
+ "enabled": True,
+ "revision": 1,
+ "data": {"source": "manager"},
+ "updated_at": "2026-09-05T00:00:00Z",
+ "sig": "legacy-signature",
+ "enc": {"version": "legacy"},
+ }
+ assert client.post(path, json=payload).status_code == 200
+ payload.update({"mode": "denylist", "revision": 2})
+ assert client.post(path, json=payload).status_code == 200
+
+ repo = repos["a2a_access_policy_template"]
+ row = client.portal.call(lambda: repo.get(policy_id="policy-1"))
+ assert row["mode"] == "denylist"
+ assert row["member_template_ids"] == ["a2a-weather"]
+ assert row["data"] == {"source": "manager"}
+ assert "sig" not in row
+ assert "enc" not in row
+
+ assert (
+ client.patch(
+ f"{path}/policy-1", json={"enabled": False, "revision": 3}
+ ).status_code
+ == 200
+ )
+ assert client.portal.call(lambda: repo.get(policy_id="policy-1"))["revision"] == 3
+ assert client.request("DELETE", f"{path}/policy-1", json={}).status_code == 200
+ assert client.request("DELETE", f"{path}/policy-1", json={}).status_code == 200
+
+
+def test_a2a_receiver_rejects_undecryptable_envelope(
+ a2a_receiver: tuple[TestClient, dict[str, Any], _Secrets],
+) -> None:
+ client, _, secrets = a2a_receiver
+ payload = _outbound_payload(value="ENC:v1:dek:wrapped:ciphertext")
+ response = client.post("/api/v1/a2a-outbound-templates", json=payload)
+ assert response.status_code == 422
+ assert secrets.values == {}
+
+ payload = _outbound_payload(operation="keep", value=None)
+ response = client.post("/api/v1/a2a-outbound-templates", json=payload)
+ assert response.status_code == 422
+
+
+def test_a2a_receiver_requires_complete_selected_interface(
+ a2a_receiver: tuple[TestClient, dict[str, Any], _Secrets],
+) -> None:
+ client, _, _ = a2a_receiver
+ path = "/api/v1/a2a-outbound-templates"
+ for missing in ("protocol_binding", "protocol_version", "url"):
+ payload = _outbound_payload()
+ payload["selected_interface"].pop(missing)
+ assert client.post(path, json=payload).status_code == 422
+
+
+ "card_path",
+ ["../agent-card.json", "//evil.test/card", "/card?source=manager"],
+)
+def test_a2a_receiver_rejects_invalid_card_path(
+ a2a_receiver: tuple[TestClient, dict[str, Any], _Secrets],
+ card_path: str,
+) -> None:
+ client, _, _ = a2a_receiver
+ payload = _outbound_payload()
+ payload["card_path"] = card_path
+ assert client.post("/api/v1/a2a-outbound-templates", json=payload).status_code == 422
+
+
+def test_a2a_credential_replace_requires_https(
+ a2a_receiver: tuple[TestClient, dict[str, Any], _Secrets],
+) -> None:
+ _, _, secrets = a2a_receiver
+ app_module = import_manager_config_receiver_module("http.app")
+ with TestClient(app_module.create_app(), base_url="http://gateway.test") as client:
+ response = client.post(
+ "/api/v1/a2a-outbound-templates",
+ json=_outbound_payload(),
+ )
+ assert response.status_code == 400
+ assert secrets.values == {}
+
+
+def test_a2a_credential_is_restored_when_projection_update_fails(
+ a2a_receiver: tuple[TestClient, dict[str, Any], _Secrets],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ client, repos, secrets = a2a_receiver
+ path = "/api/v1/a2a-outbound-templates"
+ credential_ref = "a2a/outbound/a2a-weather.api_key"
+ assert client.post(path, json=_outbound_payload()).status_code == 200
+
+ repo = repos["a2a_outbound_template"]
+
+ async def _fail_update(*args: Any, **kwargs: Any) -> None:
+ del args, kwargs
+ raise RuntimeError("write failed")
+
+ monkeypatch.setattr(repo, "update", _fail_update)
+ with pytest.raises(RuntimeError, match="write failed"):
+ client.patch(
+ f"{path}/a2a-weather",
+ json={"credential": {"operation": "replace", "value": "new-secret"}},
+ )
+ assert secrets.values[credential_ref] == "secret"
+
+
+def test_a2a_credential_is_removed_when_projection_create_fails(
+ a2a_receiver: tuple[TestClient, dict[str, Any], _Secrets],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ client, repos, secrets = a2a_receiver
+ repo = repos["a2a_outbound_template"]
+
+ async def _fail_create(*args: Any, **kwargs: Any) -> None:
+ del args, kwargs
+ raise RuntimeError("write failed")
+
+ monkeypatch.setattr(repo, "create", _fail_create)
+ with pytest.raises(RuntimeError, match="write failed"):
+ client.post(
+ "/api/v1/a2a-outbound-templates",
+ json=_outbound_payload(),
+ )
+ assert secrets.values == {}
+
+
+def test_a2a_outbound_purge_removes_projection_and_secret(
+ a2a_receiver: tuple[TestClient, dict[str, Any], _Secrets],
+) -> None:
+ client, repos, secrets = a2a_receiver
+ path = "/api/v1/a2a-outbound-templates"
+ assert client.post(path, json=_outbound_payload()).status_code == 200
+
+ lifecycle = import_manager_config_receiver_module(
+ "core.instance.instance_data_lifecycle"
+ )
+ count = client.portal.call(
+ lambda: lifecycle._purge_enterprise_table("a2a_outbound_template")
+ )
+ assert count == 1
+ assert (
+ client.portal.call(
+ lambda: repos["a2a_outbound_template"].get(
+ template_id="a2a-weather"
+ )
+ )
+ is None
+ )
+ assert secrets.values == {}
+ assert "a2a_outbound_template" in lifecycle.INSTANCE_PURGE_TABLES
+ assert "a2a_access_policy_template" in lifecycle.INSTANCE_PURGE_TABLES
+
+
+def test_a2a_tables_are_in_enterprise_init_and_catalog() -> None:
+ table_names = {definition.table_name for definition in ALL_TABLE_DEFINITIONS}
+ assert "a2a_outbound_template" in table_names
+ assert "a2a_access_policy_template" in table_names
+
+ repos = create_enterprise_record_repositories(InMemoryPersistentBackend())
+ assert "a2a_outbound_template" in repos
+ assert "a2a_access_policy_template" in repos
+
+
+def test_manager_config_public_endpoint_can_advertise_https() -> None:
+ config = import_manager_config_receiver_module("infrastructure.config")
+ public_endpoint = import_manager_config_receiver_module(
+ "infrastructure.public_endpoint"
+ )
+ settings = config.Settings(
+ GATEWAY_CONFIG_PUBLIC_SCHEME="https",
+ GATEWAY_CONFIG_PUBLIC_HOST="gateway.test",
+ GATEWAY_CONFIG_HTTP_PORT=443,
+ )
+ assert public_endpoint.resolve_public_endpoint(settings) == (
+ "https://gateway.test:443"
+ )