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
a2a: add ingress authentication and viewable credentials
NickFuryXXXb7886a1c4727
diff --git a/docs/en/A2A.md b/docs/en/A2A.mdindex 9eadc857e2..8af6823c19 100644--- a/docs/en/A2A.md+++ b/docs/en/A2A.md@@ -32,7 +32,7 @@ This page explains the Gateway-side **A2A ingress service**: its management surf| Item | Web | ACP | A2A (current) ||------|-----|-----|-------------|| Bindings | `WEB_HOST` / `WEB_PORT` / `WEB_PATH` | `ACP_GATEWAY_*` | `A2A_SERVER_*` |-| Config source | Env + CLI (`--host`, etc.) | Env only | `.env` compatibility + Web management API |+| Config source | Env + CLI (`--host`, etc.) | Env only | `.env` configuration + Web management API || `.env` loading | `app_gateway` calls `load_dotenv(get_env_file())`, i.e. `~/.jiuwenswarm/config/.env` | same | same |---@@ -62,6 +62,10 @@ uv sync --extra a2a| `A2A_SERVER_APP_DESCRIPTION` | `A2A ingress for JiuwenSwarm Gateway` | Agent Card `description` || `A2A_SERVER_APP_VERSION` | `0.1.0` | Agent Card `version` || `A2A_SERVER_EXPOSE_REASONING` | `true` (enabled by default) | when enabled, reasoning (thinking) content is emitted as working-state `TaskStatusUpdateEvent` (see §6.2); set to `false`/`0`/`no`/`off` to drop it |+| `A2A_SERVER_AUTH_TYPE` | `none` | `none` / `bearer` / `api_key` |+| `A2A_SERVER_API_KEY_HEADER` | `X-API-Key` | Dedicated API key request header |+| `A2A_SERVER_CARD_AUTH_REQUIRED` | `false` | Require authentication for the public Agent Card |+| `A2A_SERVER_API_KEY` | empty | Security credential; uses the model API Key storage encryption mechanism |AgentServer connectivity still follows existing gateway config (for example `AGENT_SERVER_URL`) and is independent from the A2A listening endpoint.@@ -93,6 +97,18 @@ Gateway Web HTTP listens on `WEB_PORT + 2` by default (`19002`). Its ingress manSnapshots use `desired_*` for persisted targets and `effective_*` for the actual listener. Failures include stable error codes and display-safe summaries. Binding to `0.0.0.0` produces an exposure warning in the UI.+### 4.2 Security credentials++Under **Ingress → Security**, select Bearer Token or API Key and enter or generate a random credential. Credentials require 16–512 printable ASCII characters without spaces. Saved credentials are masked by default; use the eye icon to view or copy them, including after refreshing the page. Storage follows model API Key behavior: encrypted when a crypto provider is configured, otherwise stored as supplied. The editor retrieves credentials on demand through a dedicated WebSocket request; ordinary snapshots, HTTP GET responses, and error responses omit credentials; public Agent Cards contain neither credentials nor digests, and ingress authentication uses only a runtime digest.++- Bearer callers send `Authorization: Bearer <credential>`.+- API Key callers use the configured dedicated header, defaulting to `X-API-Key: <credential>`.+- With authentication enabled, all JSON-RPC operations (including streams, queries, and cancellation) and the extended Card require credentials. **Allow anonymous access to service information** is enabled by default; disabling it also requires authentication to view the public Agent Card. Cards advertise the authentication scheme without credentials.+- Blank input preserves the saved credential; a new value replaces it. To clear it, select **No authentication**, then check **Clear saved credential**. The default authentication method is none.+- **Save** persists and applies changes immediately, restarting a running ingress service with the new credential. **Cancel** discards unsaved edits and restores the saved configuration and credential.++This is a shared service credential, without caller identities, per-task access isolation, or OAuth login. Use an HTTPS reverse proxy to protect credentials in transit for remote deployments.+---## 5. Data Flow (Overview)diff --git a/docs/zh/A2A.md b/docs/zh/A2A.mdindex 218302e420..d355420e7a 100644--- a/docs/zh/A2A.md+++ b/docs/zh/A2A.md@@ -32,7 +32,7 @@| 项目 | Web | ACP | A2A(当前) ||------|-----|-----|-------------|| 绑定 | `WEB_HOST` / `WEB_PORT` / `WEB_PATH` | `ACP_GATEWAY_*` | `A2A_SERVER_*` |-| 配置来源 | 环境变量 + CLI(`--host` 等) | 仅环境变量 | `.env` 兼容配置 + Web 管理 API |+| 配置来源 | 环境变量 + CLI(`--host` 等) | 仅环境变量 | `.env` 配置 + Web 管理 API || `.env` | `app_gateway` 启动时 `load_dotenv(get_env_file())`,即 `~/.jiuwenswarm/config/.env` | 同上 | 同上 |---@@ -62,6 +62,10 @@ uv sync --extra a2a| `A2A_SERVER_APP_DESCRIPTION` | `A2A ingress for JiuwenSwarm Gateway` | Agent Card `description` || `A2A_SERVER_APP_VERSION` | `0.1.0` | Agent Card `version` || `A2A_SERVER_EXPOSE_REASONING` | `true`(默认开启) | 开启后思考(reasoning)内容以 working 状态的 `TaskStatusUpdateEvent` 输出(见 §6.2);设为 `false`/`0`/`no`/`off` 时直接丢弃 |+| `A2A_SERVER_AUTH_TYPE` | `none` | `none` / `bearer` / `api_key` |+| `A2A_SERVER_API_KEY_HEADER` | `X-API-Key` | API Key 使用的专用请求头名称 |+| `A2A_SERVER_CARD_AUTH_REQUIRED` | `false` | 公开 Agent Card 是否也要求认证 |+| `A2A_SERVER_API_KEY` | 空 | 安全凭据,沿用模型 API Key 的存储加解密机制 |AgentServer 连接仍由网关既有逻辑配置(例如 `AGENT_SERVER_URL` 等),与 A2A 监听端口独立。@@ -93,6 +97,18 @@ Gateway Web HTTP 默认监听 `WEB_PORT + 2`(默认 `19002`),管理端点返回快照以 `desired_*` 表示持久化目标,以 `effective_*` 表示当前真实监听;异常时提供稳定错误码和可展示摘要。绑定 `0.0.0.0` 时页面会展示对外暴露告警。+### 4.2 安全凭据++在“入站配置 → 安全配置”选择 Bearer Token 或 API Key,输入或生成随机凭据。凭据要求 16–512 个可打印 ASCII 字符且不含空格;建议使用生成器产生的随机值。已保存凭据默认隐藏,点击输入框内的眼睛可查看或复制明文,刷新页面后仍可查看。存储沿用模型 API Key 的机制:配置了加密提供方时加密保存,否则保存原值。编辑界面通过专用 WebSocket 请求按需读取凭据;常规状态快照、HTTP GET 和失败响应不返回凭据,公开 Agent Card 不包含凭据或摘要,入站认证仅使用运行时摘要进行校验。++- Bearer:调用方发送 `Authorization: Bearer <凭据>`。+- API Key:调用方通过配置的专用请求头发送凭据,默认 `X-API-Key: <凭据>`。+- 启用认证后,所有 JSON-RPC 操作(含流式、查询、取消)及扩展 Card 都需要认证。“允许匿名查看服务信息”默认开启,关闭后查看公开 Agent Card 也需要认证。Card 中会公布认证方案,不包含凭据。+- 留空保留已有凭据;输入新值替换。要清除凭据,先选择“无认证”,再勾选清除。默认认证方式为无认证。+- 页面“保存”统一执行保存并应用,正在运行的入站服务会重启并使用新凭据;“取消”放弃未保存的修改并恢复已保存配置及凭据。++这是一组共享服务凭据,不提供调用方身份、逐任务访问隔离或 OAuth 登录。远程部署应通过 HTTPS 反向代理保护凭据传输。+---## 5. 数据流(概要)diff --git a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AIngressSecurityFields.tsx b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AIngressSecurityFields.tsxnew file mode 100644index 0000000000..73ce557c64--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AIngressSecurityFields.tsx@@ -0,0 +1,151 @@+import { useId, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { ChevronDown, Eye, EyeOff } from 'lucide-react';+import { ConfigFieldHintLabel } from '../ConfigPanel/ConfigFieldHintLabel';+import { DEFAULT_API_KEY_HEADER, isValidA2AIngressApiKeyHeader, type A2AIngressDraft } from './a2aIngressPanelState';++export function A2AIngressSecurityFields({+ draft,+ disabled,+ onChange,+}: {+ draft: A2AIngressDraft;+ disabled: boolean;+ onChange: <K extends keyof A2AIngressDraft>(field: K, value: A2AIngressDraft[K]) => void;+}) {+ const { t } = useTranslation();+ const [visible, setVisible] = useState(false);+ const credentialInputId = useId();+ const inputClass = 'w-full rounded-md border border-border bg-bg px-3 py-2 text-sm text-text outline-none focus:border-accent';+ const generate = () => {+ const bytes = crypto.getRandomValues(new Uint8Array(32));+ onChange('credential', Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join(''));+ onChange('clear_credential', false);+ };+ return (+ <fieldset className="mt-5 rounded-lg border border-border p-4" disabled={disabled}>+ <legend className="px-2 text-sm font-semibold text-text">+ <ConfigFieldHintLabel label={t('a2aIngress.security.title')} help={t('a2aIngress.security.description')} />+ </legend>+ <div className="grid gap-4 md:grid-cols-2">+ <label>+ <span className="text-xs font-medium text-text-muted">{t('a2aIngress.fields.auth_type')}</span>+ <span className="relative mt-2 block">+ <select+ className={`${inputClass} appearance-none pr-10 transition-colors hover:border-border-strong disabled:cursor-not-allowed disabled:opacity-50`}+ value={draft.auth_type}+ onChange={event => {+ const nextType = event.target.value as A2AIngressDraft['auth_type'];+ onChange('auth_type', nextType);+ if (nextType === 'none') onChange('card_auth_required', false);+ else onChange('clear_credential', false);+ if (nextType !== 'api_key' && !isValidA2AIngressApiKeyHeader(draft.api_key_header)) {+ onChange('api_key_header', DEFAULT_API_KEY_HEADER);+ }+ }}+ >+ {(['none', 'bearer', 'api_key'] as const).map(type => (+ <option key={type} value={type}>+ {t(`a2aIngress.security.types.${type}`)}+ </option>+ ))}+ </select>+ <ChevronDown size={16} className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-text-muted" aria-hidden="true" />+ </span>+ </label>+ {draft.auth_type === 'api_key' && (+ <label>+ <span className="text-xs font-medium text-text-muted">{t('a2aIngress.fields.api_key_header')}</span>+ <input+ className={`mt-2 ${inputClass}`}+ value={draft.api_key_header}+ onChange={event => onChange('api_key_header', event.target.value)}+ spellCheck={false}+ />+ </label>+ )}+ <div className="md:col-span-2">+ <div className="flex items-center gap-2">+ <ConfigFieldHintLabel+ label={<label htmlFor={credentialInputId}>{t('a2aIngress.fields.credential')}</label>}+ help={t('a2aIngress.security.credentialHint')}+ className="text-xs font-medium text-text-muted"+ />+ <span className="text-xs text-text-muted">+ {t(draft.credential_configured ? 'a2aIngress.security.configured' : 'a2aIngress.security.notConfigured')}+ </span>+ </div>+ <div className="mt-2 flex items-stretch gap-2">+ <div className="relative min-w-0 flex-1">+ <input+ id={credentialInputId}+ className={`${inputClass} block h-full pr-10`}+ type={visible ? 'text' : 'password'}+ value={draft.credential}+ onChange={event => onChange('credential', event.target.value)}+ autoComplete="new-password"+ spellCheck={false}+ maxLength={512}+ disabled={disabled || draft.clear_credential}+ placeholder={t('a2aIngress.security.credentialPlaceholder')}+ />+ <button+ type="button"+ className="absolute inset-y-0 right-0 flex w-9 items-center justify-center rounded-r-md text-text-muted transition-colors hover:text-text focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent disabled:cursor-not-allowed disabled:opacity-50"+ aria-label={t(visible ? 'a2aIngress.security.hide' : 'a2aIngress.security.show')}+ title={t(visible ? 'a2aIngress.security.hide' : 'a2aIngress.security.show')}+ aria-pressed={visible}+ disabled={disabled || draft.clear_credential}+ onClick={() => setVisible(value => !value)}+ >+ {visible ? <EyeOff size={16} strokeWidth={1.8} aria-hidden="true" /> : <Eye size={16} strokeWidth={1.8} aria-hidden="true" />}+ </button>+ </div>+ <button type="button" className="btn secondary shrink-0 whitespace-nowrap" onClick={generate}>+ {t('a2aIngress.security.generate')}+ </button>+ </div>+ </div>+ <label className="flex items-center gap-3 md:col-span-2">+ <input+ type="checkbox"+ className="h-4 w-4 accent-[var(--color-accent)]"+ checked={draft.clear_credential}+ disabled={disabled || draft.auth_type !== 'none' || !draft.credential_configured}+ onChange={event => {+ onChange('clear_credential', event.target.checked);+ if (event.target.checked) onChange('credential', '');+ }}+ />+ <span className="text-sm text-text">{t('a2aIngress.security.clear')}</span>+ </label>+ <div className="md:col-span-2">+ <ConfigFieldHintLabel+ label={+ <label className="flex items-center gap-3">+ <input+ type="checkbox"+ className="h-4 w-4 accent-[var(--color-accent)]"+ checked={!draft.card_auth_required}+ disabled={disabled || draft.auth_type === 'none'}+ onChange={event => onChange('card_auth_required', !event.target.checked)}+ />+ <span className="text-sm text-text">{t('a2aIngress.fields.card_auth_required')}</span>+ </label>+ }+ help={t('a2aIngress.security.cardHint')}+ />+ </div>+ <label className="flex items-center gap-3 md:col-span-2">+ <input+ type="checkbox"+ className="h-4 w-4 accent-[var(--color-accent)]"+ checked={draft.expose_reasoning}+ onChange={event => onChange('expose_reasoning', event.target.checked)}+ />+ <span className="text-sm text-text">{t('a2aIngress.fields.expose_reasoning')}</span>+ </label>+ </div>+ </fieldset>+ );+}diff --git a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundCredentialInput.tsx b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundCredentialInput.tsxnew file mode 100644index 0000000000..0828188516--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundCredentialInput.tsx@@ -0,0 +1,57 @@+import { useId, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { Eye, EyeOff } from 'lucide-react';+import { ConfigFieldHintLabel } from '../ConfigPanel/ConfigFieldHintLabel';++import { describeA2AOutboundAuthentication } from './a2aOutboundPanelState';++export function A2AOutboundCredentialInput({+ card,+ value,+ onChange,+ disabled,+}: {+ card: Record<string, unknown>;+ value: string;+ onChange: (value: string) => void;+ disabled: boolean;+}) {+ const { t } = useTranslation();+ const id = useId();+ const [visible, setVisible] = useState(false);+ const method = describeA2AOutboundAuthentication(card, t);+ const help = `${t('a2aIngress.outbound.credentialHelp.method', { method })}\n${t('a2aIngress.outbound.credentialHelp.value')}`;+ return (+ <div>+ <ConfigFieldHintLabel+ label={<label htmlFor={id}>{t('a2aIngress.outbound.fields.credential')}</label>}+ help={help}+ className="text-xs font-medium text-text-muted"+ />+ <div className="relative mt-2">+ <input+ id={id}+ type={visible ? 'text' : 'password'}+ className="w-full rounded-md border border-border bg-bg px-3 py-2 pr-10 text-sm text-text outline-none focus:border-accent disabled:opacity-50"+ value={value}+ onChange={event => onChange(event.target.value)}+ autoComplete="new-password"+ spellCheck={false}+ disabled={disabled}+ placeholder={t('a2aIngress.security.credentialPlaceholder')}+ />+ <button+ type="button"+ className="absolute inset-y-0 right-0 flex w-9 items-center justify-center rounded-r-md text-text-muted transition-colors hover:text-text focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent disabled:cursor-not-allowed disabled:opacity-50"+ aria-label={t(visible ? 'a2aIngress.security.hide' : 'a2aIngress.security.show')}+ title={t(visible ? 'a2aIngress.security.hide' : 'a2aIngress.security.show')}+ aria-pressed={visible}+ disabled={disabled}+ onClick={() => setVisible(current => !current)}+ >+ {visible ? <EyeOff size={16} strokeWidth={1.8} aria-hidden="true" /> : <Eye size={16} strokeWidth={1.8} aria-hidden="true" />}+ </button>+ </div>+ </div>+ );+}diff --git a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundPanel.tsx b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundPanel.tsxindex 4c14f8de41..8a8eac88dc 100644--- a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundPanel.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundPanel.tsx@@ -4,12 +4,13 @@ import { useTranslation } from 'react-i18next';import { ChevronDown, Plus, Power, RefreshCw, Search, Server, Trash2, X } from 'lucide-react';import type { WebError } from '../../types/websocket';import { Switch } from '../Switch';+import { A2AOutboundCredentialInput } from './A2AOutboundCredentialInput';import {normalizeA2AOutboundAgent,normalizeA2AOutboundDiscovery,normalizeA2AOutboundList,normalizeA2AOutboundSettings,- shouldAcceptA2AOutboundResponse,+ createA2AOutboundRequestScope,type A2AOutboundAgent,type A2AOutboundAvailability,type A2AOutboundDiscovery,@@ -52,14 +53,23 @@ export function A2AOutboundPanel({ isConnected, request, headerActionsContainercredential: string;clearCredential: boolean;} | null>(null);- const generationRef = useRef(0);+ const generationRef = useRef(createA2AOutboundRequestScope());+ const editGenerationRef = useRef(createA2AOutboundRequestScope());++ useEffect(() => {+ editGenerationRef.current.next();+ if (!isConnected) setEditing(null);+ return () => {+ editGenerationRef.current.next();+ };+ }, [isConnected]);const refresh = useCallback(async () => {if (!isConnected) return;- const generation = ++generationRef.current;+ const generation = generationRef.current.next();try {const [payload, rawSettings] = await Promise.all([request('a2a.outbound.list'), request('a2a.outbound.settings.get')]);- if (!shouldAcceptA2AOutboundResponse(generation, generationRef.current)) return;+ if (!generationRef.current.accepts(generation)) return;const next = normalizeA2AOutboundList(payload);const settings = normalizeA2AOutboundSettings(rawSettings);if (!next || !settings) throw new Error(t('a2aIngress.outbound.errors.invalidResponse'));@@ -68,7 +78,7 @@ export function A2AOutboundPanel({ isConnected, request, headerActionsContainersetSavedAllowLoopbackHttp(settings.allow_loopback_http);setError(null);} catch (nextError) {- if (shouldAcceptA2AOutboundResponse(generation, generationRef.current)) setError(errorMessage(nextError));+ if (generationRef.current.accepts(generation)) setError(errorMessage(nextError));}}, [isConnected, request, t]);@@ -119,7 +129,7 @@ export function A2AOutboundPanel({ isConnected, request, headerActionsContainerconst updateAllowLoopbackHttp = async (nextEnabled: boolean) => {if (busy || !isConnected) return;- const generation = ++generationRef.current;+ const generation = generationRef.current.next();const previous = savedAllowLoopbackHttp;setAllowLoopbackHttp(nextEnabled);setBusy('settings');@@ -132,12 +142,12 @@ export function A2AOutboundPanel({ isConnected, request, headerActionsContainer}),);if (!settings) throw new Error(t('a2aIngress.outbound.errors.invalidResponse'));- if (!shouldAcceptA2AOutboundResponse(generation, generationRef.current)) return;+ if (!generationRef.current.accepts(generation)) return;setAllowLoopbackHttp(settings.allow_loopback_http);setSavedAllowLoopbackHttp(settings.allow_loopback_http);setNotice(t('a2aIngress.outbound.localDebug.saved'));} catch (nextError) {- if (!shouldAcceptA2AOutboundResponse(generation, generationRef.current)) return;+ if (!generationRef.current.accepts(generation)) return;setAllowLoopbackHttp(previous);setError(errorMessage(nextError));} finally {@@ -158,7 +168,7 @@ export function A2AOutboundPanel({ isConnected, request, headerActionsContainer});const created = normalizeA2AOutboundAgent(payload);if (!created) throw new Error(t('a2aIngress.outbound.errors.invalidResponse'));- generationRef.current += 1;+ generationRef.current.next();setAgents(current => [created, ...current]);setDiscovery(null);setCredential('');@@ -179,7 +189,7 @@ export function A2AOutboundPanel({ isConnected, request, headerActionsContainersetBusy(`${operation}:${agent.agent_id}`);setError(null);setNotice(null);- generationRef.current += 1;+ generationRef.current.next();try {let payload: unknown;if (operation === 'toggle') payload = await request('a2a.outbound.update', { agent_id: agent.agent_id, enabled: !agent.enabled });@@ -211,7 +221,7 @@ export function A2AOutboundPanel({ isConnected, request, headerActionsContainer}setBusy(`save:${agent.agent_id}`);setError(null);- generationRef.current += 1;+ generationRef.current.next();try {const payload = await request('a2a.outbound.update', {agent_id: agent.agent_id,@@ -234,19 +244,34 @@ export function A2AOutboundPanel({ isConnected, request, headerActionsContainer}};- const toggleSettings = (agent: A2AOutboundAgent) => {- setEditing(current =>- current?.agentId === agent.agent_id- ? null- : {- agentId: agent.agent_id,- displayName: agent.display_name,- connectTimeout: String(agent.connect_timeout_seconds),- syncWait: String(agent.sync_wait_seconds),- credential: '',- clearCredential: false,- },- );+ const toggleSettings = async (agent: A2AOutboundAgent) => {+ if (busy || !isConnected) return;+ if (editing?.agentId === agent.agent_id) {+ setEditing(null);+ return;+ }+ setBusy(`edit:${agent.agent_id}`);+ setEditing(null);+ setError(null);+ const generation = editGenerationRef.current.next();+ try {+ const payload = await request<Record<string, unknown>>('a2a.outbound.edit', { agent_id: agent.agent_id });+ if (!editGenerationRef.current.accepts(generation)) return;+ const detail = normalizeA2AOutboundAgent(payload);+ if (!detail || typeof payload.credential !== 'string') throw new Error(t('a2aIngress.outbound.errors.invalidResponse'));+ setEditing({+ agentId: detail.agent_id,+ displayName: detail.display_name,+ connectTimeout: String(detail.connect_timeout_seconds),+ syncWait: String(detail.sync_wait_seconds),+ credential: payload.credential,+ clearCredential: false,+ });+ } catch (nextError) {+ if (editGenerationRef.current.accepts(generation)) setError(errorMessage(nextError));+ } finally {+ setBusy(null);+ }};return (@@ -410,7 +435,7 @@ export function A2AOutboundPanel({ isConnected, request, headerActionsContainer<p className="mt-1 text-xs text-text-muted">{t('a2aIngress.outbound.discovery.registrationDescription')}</p><div className="mt-4 grid gap-3 sm:grid-cols-2"><Input label={t('a2aIngress.outbound.fields.displayName')} value={displayName} onChange={setDisplayName} />- <Input label={t('a2aIngress.outbound.fields.credential')} value={credential} onChange={setCredential} type="password" />+ <A2AOutboundCredentialInput card={discovery.agent_card} value={credential} onChange={setCredential} disabled={!!busy} /></div><div className="mt-4 flex justify-end gap-2 border-t border-border pt-4"><button type="button" className="btn secondary" onClick={() => setDiscovery(null)} disabled={!!busy}>@@ -519,11 +544,11 @@ export function A2AOutboundPanel({ isConnected, request, headerActionsContainervalue={editing.syncWait}onChange={value => setEditing(current => (current ? { ...current, syncWait: value } : current))}/>- <Input- label={t('a2aIngress.outbound.fields.replaceCredential')}+ <A2AOutboundCredentialInput+ card={agent.agent_card}value={editing.credential}onChange={value => setEditing(current => (current ? { ...current, credential: value, clearCredential: false } : current))}- type="password"+ disabled={!!busy || editing.clearCredential}/></div><label className="mt-3 flex items-center gap-2 text-sm text-text">@@ -611,7 +636,10 @@ function Notice({}) {const style = tone === 'danger' ? 'border-danger/30 bg-danger/10' : tone === 'warn' ? 'border-warn/30 bg-warn/10' : 'border-ok/30 bg-ok/10';return (- <div className={`flex items-center justify-between gap-3 rounded-xl border px-4 py-3 text-sm text-text ${style}`} role={tone === 'danger' ? 'alert' : 'status'}>+ <div+ className={`flex items-center justify-between gap-3 rounded-xl border px-4 py-3 text-sm text-text ${style}`}+ role={tone === 'danger' ? 'alert' : 'status'}+ ><div className="min-w-0 flex-1 leading-5">{children}</div>{onClose && (<buttondiff --git a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/a2aIngressPanelState.ts b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/a2aIngressPanelState.tsindex 6ffe1ee3f7..4b36d0b99f 100644--- a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/a2aIngressPanelState.ts+++ b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/a2aIngressPanelState.ts@@ -28,6 +28,13 @@ export interface A2AIngressSnapshot {started_at: number | null;last_error: string | null;config_revision: number;+ desired_auth_type: 'none' | 'bearer' | 'api_key';+ desired_api_key_header: string;+ desired_card_auth_required: boolean;+ credential_configured: boolean;+ effective_auth_type: string | null;+ effective_card_auth_required: boolean | null;+ security_pending_apply: boolean;}export interface A2AIngressDraft {@@ -41,6 +48,12 @@ export interface A2AIngressDraft {app_description: string;app_version: string;expose_reasoning: boolean;+ auth_type: 'none' | 'bearer' | 'api_key';+ api_key_header: string;+ card_auth_required: boolean;+ credential: string;+ credential_configured: boolean;+ clear_credential: boolean;}export type A2AIngressRequestStatus = 'processing' | 'completed' | 'failed' | 'canceled';@@ -96,6 +109,25 @@ export interface A2AOutboundDispatchHistory {total: number;}+export const DEFAULT_API_KEY_HEADER = 'X-API-Key';+const RESERVED_API_KEY_HEADERS = [+ 'authorization',+ 'host',+ 'content-length',+ 'content-type',+ 'connection',+ 'transfer-encoding',+ 'cookie',+ 'set-cookie',+ 'accept',+ 'origin',+];++export function isValidA2AIngressApiKeyHeader(value: string): boolean {+ const header = value.trim();+ return /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(header) && !RESERVED_API_KEY_HEADERS.includes(header.toLowerCase());+}+const DEFAULT_DRAFT: A2AIngressDraft = {host: '127.0.0.1',port: '19100',@@ -107,6 +139,12 @@ const DEFAULT_DRAFT: A2AIngressDraft = {app_description: 'A2A ingress for JiuwenSwarm Gateway',app_version: '0.1.0',expose_reasoning: true,+ auth_type: 'none',+ api_key_header: DEFAULT_API_KEY_HEADER,+ card_auth_required: false,+ credential: '',+ credential_configured: false,+ clear_credential: false,};function asString(value: unknown, fallback = ''): string {@@ -151,6 +189,13 @@ export function normalizeA2AIngressSnapshot(value: unknown): A2AIngressSnapshotstarted_at: typeof payload.started_at === 'number' ? payload.started_at : null,last_error: typeof payload.last_error === 'string' ? payload.last_error : null,config_revision: asNumber(payload.config_revision),+ desired_auth_type: payload.desired_auth_type === 'bearer' || payload.desired_auth_type === 'api_key' ? payload.desired_auth_type : 'none',+ desired_api_key_header: asString(payload.desired_api_key_header, 'X-API-Key'),+ desired_card_auth_required: payload.desired_card_auth_required === true,+ credential_configured: payload.credential_configured === true,+ effective_auth_type: typeof payload.effective_auth_type === 'string' ? payload.effective_auth_type : null,+ effective_card_auth_required: typeof payload.effective_card_auth_required === 'boolean' ? payload.effective_card_auth_required : null,+ security_pending_apply: payload.security_pending_apply === true,};}@@ -229,7 +274,7 @@ export function normalizeA2AOutboundDispatchHistory(value: unknown): A2AOutboundreturn { items, total: asNumber(payload.total, items.length) };}-export function draftFromA2AIngressSnapshot(snapshot: A2AIngressSnapshot): A2AIngressDraft {+export function draftFromA2AIngressSnapshot(snapshot: A2AIngressSnapshot, credential = ''): A2AIngressDraft {return {host: snapshot.desired_host,port: String(snapshot.desired_port),@@ -241,10 +286,21 @@ export function draftFromA2AIngressSnapshot(snapshot: A2AIngressSnapshot): A2AInapp_description: snapshot.desired_app_description,app_version: snapshot.desired_app_version,expose_reasoning: snapshot.desired_expose_reasoning,+ auth_type: snapshot.desired_auth_type,+ api_key_header: snapshot.desired_api_key_header,+ card_auth_required: snapshot.desired_card_auth_required,+ credential,+ credential_configured: snapshot.credential_configured,+ clear_credential: false,};}export function validateA2AIngressDraft(draft: A2AIngressDraft): string | null {+ if (!['none', 'bearer', 'api_key'].includes(draft.auth_type)) return 'auth_type';+ if (draft.credential && (!/^[!-~]{16,512}$/.test(draft.credential) || draft.clear_credential)) return 'credential';+ if (draft.auth_type !== 'none' && !draft.credential && (!draft.credential_configured || draft.clear_credential)) return 'credential';+ if (draft.card_auth_required && draft.auth_type === 'none') return 'card_auth_required';+ if (draft.auth_type === 'api_key' && !isValidA2AIngressApiKeyHeader(draft.api_key_header)) return 'api_key_header';if (!draft.host.trim()) return 'host';const port = Number(draft.port);if (!Number.isInteger(port) || port < 1 || port > 65535) return 'port';@@ -265,6 +321,14 @@ export function toA2AIngressPatch(draft: A2AIngressDraft): Record<string, stringapp_description: draft.app_description.trim(),app_version: draft.app_version.trim(),expose_reasoning: draft.expose_reasoning,+ auth_type: draft.auth_type,+ api_key_header:+ draft.auth_type === 'api_key' || isValidA2AIngressApiKeyHeader(draft.api_key_header)+ ? draft.api_key_header.trim()+ : DEFAULT_API_KEY_HEADER,+ card_auth_required: draft.card_auth_required,+ ...(draft.credential ? { credential: draft.credential } : {}),+ ...(draft.clear_credential ? { clear_credential: true } : {}),};}diff --git a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/a2aOutboundPanelState.ts b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/a2aOutboundPanelState.tsindex c549441ce8..4b8ea53cda 100644--- a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/a2aOutboundPanelState.ts+++ b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/a2aOutboundPanelState.ts@@ -7,6 +7,7 @@ export interface A2AOutboundInterface {}export interface A2AOutboundDiscovery {+ agent_card: Record<string, unknown>;discovery_id: string;expires_at: string;source_url: string;@@ -43,8 +44,8 @@ export interface A2AOutboundSettings {allow_loopback_http: boolean;}-const asString = (value: unknown): string => typeof value === 'string' ? value : '';-const asNumber = (value: unknown): number => typeof value === 'number' && Number.isFinite(value) ? value : 0;+const asString = (value: unknown): string => (typeof value === 'string' ? value : '');+const asNumber = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) ? value : 0);function normalizeInterface(value: unknown): A2AOutboundInterface | null {if (!value || typeof value !== 'object') return null;@@ -68,16 +69,19 @@ export function normalizeA2AOutboundDiscovery(value: unknown): A2AOutboundDiscovif (!discoveryId || !asString(agent.name) || interfaces.length === 0) return null;return {discovery_id: discoveryId,+ agent_card: payload.agent_card && typeof payload.agent_card === 'object' ? (payload.agent_card as Record<string, unknown>) : {},expires_at: asString(payload.expires_at),source_url: asString(payload.source_url),card_path: asString(payload.card_path),card_fingerprint: asString(payload.card_fingerprint),agent: {- name: asString(agent.name), description: asString(agent.description), version: asString(agent.version),- skills: Array.isArray(agent.skills) ? agent.skills.filter(item => !!item && typeof item === 'object') as Array<Record<string, unknown>> : [],+ name: asString(agent.name),+ description: asString(agent.description),+ version: asString(agent.version),+ skills: Array.isArray(agent.skills) ? (agent.skills.filter(item => !!item && typeof item === 'object') as Array<Record<string, unknown>>) : [],compatible_interfaces: interfaces,},- security_requirements: Array.isArray(payload.security_requirements) ? payload.security_requirements as Array<Record<string, unknown>> : [],+ security_requirements: Array.isArray(payload.security_requirements) ? (payload.security_requirements as Array<Record<string, unknown>>) : [],warnings: Array.isArray(payload.warnings) ? payload.warnings.map(asString).filter(Boolean) : [],};}@@ -89,13 +93,19 @@ export function normalizeA2AOutboundAgent(value: unknown): A2AOutboundAgent | nuconst selectedInterface = normalizeInterface(item.selected_interface);if (!asString(item.agent_id) || !selectedInterface || !['available', 'unreachable', 'incompatible', 'review_required'].includes(availability)) return null;return {- agent_id: asString(item.agent_id), display_name: asString(item.display_name), card_revision: asNumber(item.card_revision),- agent_card: item.agent_card && typeof item.agent_card === 'object' ? item.agent_card as Record<string, unknown> : {},- selected_interface: selectedInterface, enabled: item.enabled === true, availability,- has_credential: item.has_credential === true, connect_timeout_seconds: asNumber(item.connect_timeout_seconds),- sync_wait_seconds: asNumber(item.sync_wait_seconds), last_checked_at: typeof item.last_checked_at === 'string' ? item.last_checked_at : null,+ agent_id: asString(item.agent_id),+ display_name: asString(item.display_name),+ card_revision: asNumber(item.card_revision),+ agent_card: item.agent_card && typeof item.agent_card === 'object' ? (item.agent_card as Record<string, unknown>) : {},+ selected_interface: selectedInterface,+ enabled: item.enabled === true,+ availability,+ has_credential: item.has_credential === true,+ connect_timeout_seconds: asNumber(item.connect_timeout_seconds),+ sync_wait_seconds: asNumber(item.sync_wait_seconds),+ last_checked_at: typeof item.last_checked_at === 'string' ? item.last_checked_at : null,last_error_summary: typeof item.last_error_summary === 'string' ? item.last_error_summary : null,- pending_revision: item.pending_revision && typeof item.pending_revision === 'object' ? item.pending_revision as Record<string, unknown> : null,+ pending_revision: item.pending_revision && typeof item.pending_revision === 'object' ? (item.pending_revision as Record<string, unknown>) : null,};}@@ -117,3 +127,45 @@ export function normalizeA2AOutboundSettings(value: unknown): A2AOutboundSetting}export const shouldAcceptA2AOutboundResponse = (generation: number, current: number): boolean => generation === current;++export function createA2AOutboundRequestScope() {+ let generation = 0;+ return {+ next: () => ++generation,+ accepts: (responseGeneration: number) => responseGeneration === generation,+ };+}++const asRecord = (value: unknown): Record<string, unknown> =>+ value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : {};++export function describeA2AOutboundAuthentication(card: Record<string, unknown>, t: (key: string) => string): string {+ const requirements = Array.isArray(card.securityRequirements) ? card.securityRequirements : [];+ const schemes = asRecord(card.securitySchemes);+ const alternatives = requirements.map(requirement => {+ const raw = asRecord(requirement);+ if (!('schemes' in raw) && Object.keys(raw).length) return t('a2aIngress.outbound.credentialHelp.unknown');+ const names = Object.keys(asRecord(raw.schemes));+ if (!names.length) return t('a2aIngress.security.types.none');+ return names+ .map(name => {+ const scheme = asRecord(schemes[name]);+ const apiKey = asRecord(scheme.apiKeySecurityScheme);+ const httpAuth = asRecord(scheme.httpAuthSecurityScheme);+ if (typeof apiKey.name === 'string') {+ const location = typeof apiKey.location === 'string' ? apiKey.location : '';+ const label = ['header', 'query', 'cookie'].includes(location)+ ? t(`a2aIngress.outbound.credentialHelp.${location}`)+ : t('a2aIngress.outbound.credentialHelp.unknown');+ return `API Key (${label}: ${apiKey.name})`;+ }+ if (httpAuth.scheme === 'bearer') return 'Bearer Token';+ if (typeof httpAuth.scheme === 'string') return `HTTP ${httpAuth.scheme}`;+ if (scheme.oauth2SecurityScheme) return 'OAuth 2.0 (Bearer Token)';+ if (scheme.openIdConnectSecurityScheme) return 'OpenID Connect (Bearer Token)';+ return t('a2aIngress.outbound.credentialHelp.unknown');+ })+ .join(' + ');+ });+ return alternatives.length ? alternatives.join(t('a2aIngress.outbound.credentialHelp.or')) : t('a2aIngress.outbound.credentialHelp.undeclared');+}diff --git a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/index.tsxindex 7ce3a7bdad..f94a0c28ad 100644--- a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/index.tsx@@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next';import { Check, Copy, Power, RefreshCw, RotateCw, X } from 'lucide-react';import type { WebError } from '../../types/websocket';import { A2AOutboundPanel } from './A2AOutboundPanel';+import { A2AIngressSecurityFields } from './A2AIngressSecurityFields';import {canOperateA2AIngress,draftFromA2AIngressSnapshot,@@ -49,7 +50,7 @@ export function A2AIngressPanel({ isConnected, request }: A2AIngressPanelProps)const [snapshot, setSnapshot] = useState<A2AIngressSnapshot | null>(null);const [draft, setDraft] = useState<A2AIngressDraft | null>(null);const [loading, setLoading] = useState(false);- const [operation, setOperation] = useState<'save' | 'apply' | 'enable' | 'disable' | 'reload' | null>(null);+ const [operation, setOperation] = useState<'save' | 'enable' | 'disable' | 'reload' | null>(null);const [error, setError] = useState<string | null>(null);const [notice, setNotice] = useState<string | null>(null);const [isDirty, setIsDirty] = useState(false);@@ -64,16 +65,19 @@ export function A2AIngressPanel({ isConnected, request }: A2AIngressPanelProps)const [copyError, setCopyError] = useState<string | null>(null);const [outboundHeaderActionsContainer, setOutboundHeaderActionsContainer] = useState<HTMLDivElement | null>(null);const responseGenerationRef = useRef(0);+ const savedCredentialRef = useRef('');const historyResponseGenerationRef = useRef(0);const outboundHistoryResponseGenerationRef = useRef(0);const copyFeedbackTimerRef = useRef<number | null>(null);const acceptSnapshot = useCallback(- (payload: unknown) => {+ (payload: unknown, credential?: string) => {const next = normalizeA2AIngressSnapshot(payload);if (!next) throw new Error(t('a2aIngress.errors.invalidResponse'));+ if (credential !== undefined) savedCredentialRef.current = credential;+ else if (!next.credential_configured) savedCredentialRef.current = '';setSnapshot(next);- setDraft(draftFromA2AIngressSnapshot(next));+ setDraft(draftFromA2AIngressSnapshot(next, savedCredentialRef.current));setIsDirty(false);return next;},@@ -86,9 +90,10 @@ export function A2AIngressPanel({ isConnected, request }: A2AIngressPanelProps)const responseGeneration = ++responseGenerationRef.current;if (showLoading) setLoading(true);try {- const payload = await request('a2a.ingress.get');+ const payload = await request<Record<string, unknown>>(showLoading ? 'a2a.ingress.edit' : 'a2a.ingress.get');if (!shouldAcceptA2AIngressResponse(responseGeneration, responseGenerationRef.current)) return;- acceptSnapshot(payload);+ if (showLoading && typeof payload.credential !== 'string') throw new Error(t('a2aIngress.errors.invalidResponse'));+ acceptSnapshot(payload, showLoading ? (payload.credential as string) : undefined);setError(null);} catch (refreshError) {if (!shouldAcceptA2AIngressResponse(responseGeneration, responseGenerationRef.current)) return;@@ -104,10 +109,10 @@ export function A2AIngressPanel({ isConnected, request }: A2AIngressPanelProps)void refresh();}, [refresh]);useEffect(() => {- if (!isA2AIngressTransitioning(snapshot?.state)) return;+ if (loading || operation || isDirty || !isA2AIngressTransitioning(snapshot?.state)) return;const timer = window.setInterval(() => void refresh(false), 1200);return () => window.clearInterval(timer);- }, [refresh, snapshot?.state]);+ }, [refresh, snapshot?.state, loading, operation, isDirty]);const refreshHistory = useCallback(async (showLoading = true) => {@@ -189,20 +194,29 @@ export function A2AIngressPanel({ isConnected, request }: A2AIngressPanelProps)setNotice(null);};- const save = async (apply: boolean) => {+ const cancelEdit = () => {+ if (!snapshot) return;+ setDraft(draftFromA2AIngressSnapshot(snapshot, savedCredentialRef.current));+ setIsDirty(false);+ setError(null);+ setNotice(null);+ };++ const save = async () => {if (!draft || operation || !isConnected) return;const invalidField = validateA2AIngressDraft(draft);if (invalidField) {setError(t('a2aIngress.errors.invalidField', { field: t(`a2aIngress.fields.${invalidField}`) }));return;}- setOperation(apply ? 'apply' : 'save');+ setOperation('save');responseGenerationRef.current += 1;setLoading(false);setError(null);try {- acceptSnapshot(await request('a2a.ingress.update', { config: toA2AIngressPatch(draft), apply }));- setNotice(t(apply ? 'a2aIngress.savedAndApplied' : 'a2aIngress.saved'));+ const savedCredential = draft.clear_credential ? '' : draft.credential || savedCredentialRef.current;+ acceptSnapshot(await request('a2a.ingress.update', { config: toA2AIngressPatch(draft), apply: true }), savedCredential);+ setNotice(t('a2aIngress.saved'));} catch (saveError) {const failedSnapshot = normalizeA2AIngressSnapshot((saveError as WebError).payload);if (failedSnapshot) acceptSnapshot(failedSnapshot);@@ -353,6 +367,18 @@ export function A2AIngressPanel({ isConnected, request }: A2AIngressPanelProps){snapshot.last_error}</Alert>)}+ {snapshot && (+ <p className="mt-4 text-xs text-text-muted">+ {t('a2aIngress.security.effective', {+ method: snapshot.effective_auth_type ? t(`a2aIngress.security.types.${snapshot.effective_auth_type}`) : t('a2aIngress.status.notListening'),+ })}+ </p>+ )}+ {snapshot?.security_pending_apply && (+ <Alert tone="warn" className="mt-3">+ {t('a2aIngress.security.pendingApply')}+ </Alert>+ )}{snapshot?.exposure_warning && (<Alert tone="warn" className="mt-4">{snapshot.exposure_warning}@@ -367,11 +393,11 @@ export function A2AIngressPanel({ isConnected, request }: A2AIngressPanelProps)<p className="mt-1 text-xs text-text-muted">{t('a2aIngress.config.description')}</p></div><div className="flex gap-2">- <button type="button" className="btn secondary" onClick={() => void save(false)} disabled={!isConnected || busy}>- {operation === 'save' ? t('common.saving') : t('a2aIngress.save')}+ <button type="button" className="btn secondary" onClick={cancelEdit} disabled={!isDirty || busy}>+ {t('common.cancel')}</button>- <button type="button" className="btn primary" onClick={() => void save(true)} disabled={!isConnected || busy}>- {operation === 'apply' ? t('a2aIngress.applying') : t('a2aIngress.saveAndApply')}+ <button type="button" className="btn primary" onClick={() => void save()} disabled={!isConnected || busy}>+ {operation === 'save' ? t('common.saving') : t('a2aIngress.save')}</button></div></div>@@ -431,17 +457,8 @@ export function A2AIngressPanel({ isConnected, request }: A2AIngressPanelProps)disabled={busy}/></label>- <label className="flex items-center gap-3 rounded-lg border border-border bg-bg px-3 py-3 md:col-span-2">- <input- type="checkbox"- checked={draft.expose_reasoning}- onChange={event => updateDraft('expose_reasoning', event.target.checked)}- disabled={busy}- className="h-4 w-4 accent-[var(--color-accent)]"- />- <span className="text-sm text-text">{t('a2aIngress.fields.expose_reasoning')}</span>- </label></div>+ <A2AIngressSecurityFields draft={draft} disabled={busy} onChange={updateDraft} /></section>)}</div>diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex b285be019b..dd1d38de91 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -544,6 +544,26 @@"moreSettings": "More Settings"},"a2aIngress": {+ "security": {+ "title": "Security",+ "description": "Configure caller authentication and response visibility. Use an HTTPS reverse proxy for remote access.",+ "types": {+ "none": "No authentication",+ "bearer": "Bearer Token",+ "api_key": "API Key (header)"+ },+ "configured": "Credential saved",+ "notConfigured": "No credential saved",+ "credentialPlaceholder": "Enter security credential",+ "credentialHint": "16–512 printable ASCII characters without spaces. You can generate a random credential. After saving, use the eye icon to view or copy it. Blank input keeps the saved credential; select Clear to remove it.",+ "generate": "Generate credential",+ "show": "Show credential",+ "hide": "Hide credential",+ "clear": "Clear saved credential (select no authentication first)",+ "cardHint": "When enabled, anyone can view the service name, capabilities, and endpoint addresses (Agent Card) without credentials. When disabled, viewing this information also requires authentication. Once authentication is configured, all actual calls always require credentials.",+ "effective": "Active authentication: {{method}}",+ "pendingApply": "Stored security settings differ from the running configuration. Save applies them immediately and restarts the running ingress service."+ },"title": "A2A Control Center","subtitle": "Manage the A2A service exposed by JiuwenSwarm.","tabs": {@@ -561,13 +581,10 @@"restartHint": "Stop and restart the ingress service. Existing connections may be briefly interrupted.","refreshStatus": "Refresh status","refreshHint": "Fetch the latest status and configuration without restarting the service.",- "save": "Save configuration",- "saveAndApply": "Save and apply",- "applying": "Applying...",- "saved": "Configuration saved; it has not been applied to the running service.",- "savedAndApplied": "Configuration saved and applied.",+ "save": "Save",+ "saved": "Configuration saved and applied.","disconnected": "Gateway is disconnected, so the A2A service cannot be read or changed.",- "saveBeforeLifecycleAction": "Configuration has unsaved changes. Save it before enabling, disabling, or restarting the service.",+ "saveBeforeLifecycleAction": "Configuration has unsaved changes. Save or cancel them before enabling, disabling, or restarting the service.","states": { "disabled": "Disabled", "starting": "Starting", "running": "Running", "stopping": "Stopping", "error": "Error" },"status": {"title": "Service status",@@ -576,8 +593,21 @@"effectiveCardUrl": "Effective Agent Card URL","notListening": "Not listening"},- "config": { "title": "Ingress configuration", "description": "Save updates the desired configuration only; Save and apply reloads the running service." },+ "config": {+ "title": "Ingress configuration",+ "description": "Save applies changes immediately and restarts the service if running. Cancel discards your edits."+ },"outbound": {+ "credentialHelp": {+ "method": "Authentication declared by the Agent Card: {{method}}.",+ "value": "Enter the credential supplied by the remote service. It is sent using the declared authentication method. Use the eye icon to view the saved value. Blank input keeps it; select Clear to remove it.",+ "header": "header",+ "query": "query parameter",+ "cookie": "cookie",+ "unknown": "Unrecognized authentication method",+ "undeclared": "No authentication method declared; dispatch fails if a credential is configured",+ "or": " or "+ },"localDebug": {"title": "Local Agent debugging","description": "Controls whether plaintext HTTP Agents on loopback addresses may be discovered and called. Changes apply immediately after saving.",@@ -611,7 +641,7 @@"protocol": "Protocol","expiresAt": "Candidate expires","displayName": "Display name",- "credential": "API Key / Bearer (optional, never displayed)",+ "credential": "Security credential","revision": "Card revision","credentialState": "Credential","lastChecked": "Last checked",@@ -694,11 +724,15 @@}},"fields": {+ "auth_type": "Authentication method",+ "api_key_header": "API Key header name",+ "credential": "Security credential",+ "card_auth_required": "Allow anonymous access to service information","host": "Bind host","port": "Bind port","rpc_path": "RPC path","card_path": "Agent Card path",- "extended_card_path": "Public Agent Card alias path (no authentication)",+ "extended_card_path": "Extended Agent Card path","protocol_version": "Protocol version","app_name": "Agent name","app_description": "Agent description",diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex 379ca5a81d..795f6d3cc7 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -545,6 +545,26 @@"moreSettings": "更多设置"},"a2aIngress": {+ "security": {+ "title": "安全配置",+ "description": "配置调用方认证与响应信息的开放范围。远程访问请通过 HTTPS 反向代理保护传输。",+ "types": {+ "none": "无认证",+ "bearer": "Bearer Token",+ "api_key": "API Key(请求头)"+ },+ "configured": "已保存凭据",+ "notConfigured": "尚未配置凭据",+ "credentialPlaceholder": "输入安全凭据",+ "credentialHint": "16–512 个可打印 ASCII 字符,不含空格。可生成随机凭据;保存后点击眼睛可查看或复制原文。留空保留已保存的凭据,删除请勾选清除。",+ "generate": "生成随机凭据",+ "show": "显示凭据",+ "hide": "隐藏凭据",+ "clear": "清除已保存凭据(需先选择无认证)",+ "cardHint": "开启后,无需凭据即可查看服务名称、能力和接口地址(Agent Card);关闭后,查看这些信息也需要认证。配置认证后,所有实际调用始终需要凭据。",+ "effective": "当前生效的认证方式:{{method}}",+ "pendingApply": "已存储的安全配置与当前运行配置不同。点击“保存”会立即应用并重启正在运行的入站服务。"+ },"title": "A2A 调度中心","subtitle": "管理 JiuwenSwarm 对外提供的 A2A 服务。","tabs": { "ariaLabel": "A2A 调度中心页面", "config": "入站配置", "outbound": "出站配置", "history": "处理历史" },@@ -557,13 +577,10 @@"restartHint": "停止并重新启动入站服务,现有连接可能短暂中断。","refreshStatus": "刷新状态","refreshHint": "重新读取当前状态和配置,不会重启服务。",- "save": "保存配置",- "saveAndApply": "保存并应用",- "applying": "应用中...",- "saved": "配置已保存,尚未应用到正在运行的服务。",- "savedAndApplied": "配置已保存并应用。",+ "save": "保存",+ "saved": "配置已保存并应用。","disconnected": "当前未连接到 Gateway,无法读取或修改 A2A 服务。",- "saveBeforeLifecycleAction": "配置有未保存的修改,请先保存后再启用、停用或重启服务。",+ "saveBeforeLifecycleAction": "配置有未保存的修改,请先保存或取消,再启用、停用或重启服务。","states": { "disabled": "已关闭", "starting": "启动中", "running": "运行中", "stopping": "停止中", "error": "异常" },"status": {"title": "服务状态",@@ -572,8 +589,18 @@"effectiveCardUrl": "实际 Agent Card 地址","notListening": "当前未监听"},- "config": { "title": "入站服务配置", "description": "保存只更新目标配置;“保存并应用”会重载正在运行的服务。" },+ "config": { "title": "入站服务配置", "description": "保存后立即应用,正在运行的服务将重启;取消可放弃本次修改。" },"outbound": {+ "credentialHelp": {+ "method": "Agent Card 声明的认证方式:{{method}}。",+ "value": "填写对方提供的凭据原文,调用时按认证方式自动携带。已保存凭据可点击眼睛查看;留空保留原值,删除请勾选清除。",+ "header": "请求头",+ "query": "查询参数",+ "cookie": "Cookie",+ "unknown": "未识别的认证方式",+ "undeclared": "未声明认证方式;若配置凭据,派发会报错",+ "or": " 或 "+ },"localDebug": {"title": "本地 Agent 调试","description": "控制是否允许发现和调用本机 loopback 地址上的明文 HTTP Agent。设置保存后立即生效。",@@ -607,7 +634,7 @@"protocol": "协议","expiresAt": "候选过期时间","displayName": "显示名称",- "credential": "API Key / Bearer(可选,不会回显)",+ "credential": "安全凭据","revision": "Card 版本","credentialState": "凭据","lastChecked": "最近检查",@@ -687,11 +714,15 @@}},"fields": {+ "auth_type": "认证方式",+ "api_key_header": "API Key 请求头名称",+ "credential": "安全凭据",+ "card_auth_required": "允许匿名查看服务信息","host": "监听地址","port": "监听端口","rpc_path": "RPC 路径","card_path": "Agent Card 路径",- "extended_card_path": "公开 Agent Card 别名路径(无认证)",+ "extended_card_path": "扩展 Agent Card 路径","protocol_version": "协议版本","app_name": "Agent 名称","app_description": "Agent 描述",diff --git a/jiuwenswarm/channels/web/frontend/tests/a2aIngressPanelState.test.mjs b/jiuwenswarm/channels/web/frontend/tests/a2aIngressPanelState.test.mjsindex 9cf502c19c..cdf7901652 100644--- a/jiuwenswarm/channels/web/frontend/tests/a2aIngressPanelState.test.mjs+++ b/jiuwenswarm/channels/web/frontend/tests/a2aIngressPanelState.test.mjs@@ -53,6 +53,12 @@ test('A2A ingress snapshot preserves desired configuration for the form', () =>app_description: 'Test description',app_version: '1.2.3',expose_reasoning: false,+ auth_type: 'none',+ api_key_header: 'X-API-Key',+ card_auth_required: false,+ credential: '',+ credential_configured: false,+ clear_credential: false,});});@@ -71,6 +77,9 @@ test('A2A ingress form validates locally and sends typed patch values', () => {app_description: 'Test description',app_version: '1.2.3',expose_reasoning: false,+ auth_type: 'none',+ api_key_header: 'X-API-Key',+ card_auth_required: false,});});@@ -217,3 +226,37 @@ test('A2A outbound history skips malformed rows without discarding valid recordsassert.equal(history?.items[0].updated_at, '2026-08-27T01:00:10Z');assert.equal(history?.total, 2);});++test('A2A security reloads saved credentials for visibility, replacement and cancellation', () => {+ const savedCredential = 'test-saved-credential-long';+ const normalized = normalizeA2AIngressSnapshot({+ ...snapshot,+ desired_auth_type: 'bearer',+ credential_configured: true,+ credential: savedCredential,+ });+ assert.equal(JSON.stringify(normalized).includes(savedCredential), false);+ const draft = draftFromA2AIngressSnapshot(normalized, savedCredential);+ assert.equal(draft.credential, savedCredential);+ assert.equal(validateA2AIngressDraft(draft), null);+ assert.equal(toA2AIngressPatch(draft).credential, savedCredential);+ assert.equal(Object.hasOwn(toA2AIngressPatch({ ...draft, credential: '' }), 'credential'), false);+ assert.equal(Object.hasOwn(toA2AIngressPatch(draft), 'credential_configured'), false);+ assert.equal(validateA2AIngressDraft({ ...draft, credential: '', credential_configured: false }), 'credential');+ assert.equal(validateA2AIngressDraft({ ...draft, credential: 'short' }), 'credential');+ assert.equal(validateA2AIngressDraft({ ...draft, clear_credential: true }), 'credential');+ assert.equal(validateA2AIngressDraft({ ...draft, auth_type: 'api_key', api_key_header: 'Authorization' }), 'api_key_header');+ assert.equal(validateA2AIngressDraft({ ...draft, auth_type: 'none', api_key_header: 'Authorization' }), null);+ assert.equal(validateA2AIngressDraft({ ...draft, api_key_header: '' }), null);+ assert.equal(toA2AIngressPatch({ ...draft, auth_type: 'none', api_key_header: 'Authorization' }).api_key_header, 'X-API-Key');+ assert.equal(toA2AIngressPatch({ ...draft, api_key_header: 'X-Custom-Key' }).api_key_header, 'X-Custom-Key');+ const replacement = { ...draft, credential: 'test-replacement-credential' };+ assert.equal(validateA2AIngressDraft(replacement), null);+ assert.equal(toA2AIngressPatch(replacement).credential, replacement.credential);+ const cleared = { ...draft, auth_type: 'none', credential: '', clear_credential: true };+ assert.equal(validateA2AIngressDraft(cleared), null);+ assert.equal(toA2AIngressPatch(cleared).clear_credential, true);+ assert.equal(draftFromA2AIngressSnapshot(normalized, savedCredential).credential, savedCredential);+ assert.equal(draftFromA2AIngressSnapshot(normalized).credential, '');+ assert.equal(draftFromA2AIngressSnapshot(normalizeA2AIngressSnapshot(snapshot)).credential, '');+});diff --git a/jiuwenswarm/channels/web/frontend/tests/a2aOutboundPanelState.test.mjs b/jiuwenswarm/channels/web/frontend/tests/a2aOutboundPanelState.test.mjsindex cff5c8da0b..d568276baa 100644--- a/jiuwenswarm/channels/web/frontend/tests/a2aOutboundPanelState.test.mjs+++ b/jiuwenswarm/channels/web/frontend/tests/a2aOutboundPanelState.test.mjs@@ -6,6 +6,8 @@ import {normalizeA2AOutboundList,normalizeA2AOutboundSettings,shouldAcceptA2AOutboundResponse,+ createA2AOutboundRequestScope,+ describeA2AOutboundAuthentication,} from '../node_modules/.cache/a2a-outbound-panel-state/components/A2AIngressPanel/a2aOutboundPanelState.js';const selectedInterface = {@@ -37,6 +39,7 @@ test('A2A outbound discovery requires an id, name, and compatible interface', ()source_url: 'https://agent.example.com',card_path: '/.well-known/agent-card.json',card_fingerprint: 'sha256:card',+ agent_card: { securitySchemes: { auth: { apiKeySecurityScheme: { location: 'header', name: 'X-API-Key' } } } },agent: {name: 'Research Agent',description: 'Researches',@@ -49,6 +52,7 @@ test('A2A outbound discovery requires an id, name, and compatible interface', ()});assert.ok(discovery);+ assert.equal(discovery.agent_card.securitySchemes.auth.apiKeySecurityScheme.name, 'X-API-Key');assert.equal(discovery.agent.compatible_interfaces[0].url, selectedInterface.url);assert.equal(normalizeA2AOutboundDiscovery({ discovery_id: 'disc-1', agent: { name: 'Agent' } }), null);});@@ -75,3 +79,52 @@ test('A2A outbound ignores obsolete responses', () => {assert.equal(shouldAcceptA2AOutboundResponse(7, 7), true);assert.equal(shouldAcceptA2AOutboundResponse(6, 7), false);});++test('outbound editing and list refresh accept either completion order independently', async () => {+ for (const editFirst of [true, false]) {+ const list = createA2AOutboundRequestScope();+ const edit = createA2AOutboundRequestScope();+ const oldList = list.next();+ const editRequest = edit.next();+ const listRequest = list.next();+ let resolveEdit, resolveList;+ const accepted = [];+ const editWork = new Promise(resolve => {+ resolveEdit = resolve;+ }).then(() => {+ if (edit.accepts(editRequest)) accepted.push('edit');+ });+ const listWork = new Promise(resolve => {+ resolveList = resolve;+ }).then(() => {+ if (list.accepts(listRequest)) accepted.push('list');+ });+ if (editFirst) {+ resolveEdit();+ await editWork;+ resolveList();+ } else {+ resolveList();+ await listWork;+ resolveEdit();+ }+ await Promise.all([editWork, listWork]);+ assert.deepEqual(accepted, editFirst ? ['edit', 'list'] : ['list', 'edit']);+ assert.equal(list.accepts(oldList), false);+ edit.next();+ assert.equal(edit.accepts(editRequest), false);+ }+});++test('Card credential help reads current scheme declarations without guessing', () => {+ const t = key => key.split('.').at(-1);+ const card = scheme => ({ securityRequirements: [{ schemes: { auth: {} } }], securitySchemes: { auth: scheme } });+ assert.equal(describeA2AOutboundAuthentication(card({ httpAuthSecurityScheme: { scheme: 'bearer' } }), t), 'Bearer Token');+ assert.equal(+ describeA2AOutboundAuthentication(card({ apiKeySecurityScheme: { location: 'header', name: 'X-Custom-Key' } }), t),+ 'API Key (header: X-Custom-Key)',+ );+ assert.equal(describeA2AOutboundAuthentication({}, t), 'undeclared');+ assert.equal(describeA2AOutboundAuthentication({ securityRequirements: [{}] }, t), 'none');+ assert.equal(describeA2AOutboundAuthentication({ securityRequirements: [{ schemes: { bearer: {} } }] }, t), 'unknown');+});diff --git a/jiuwenswarm/gateway/a2a_manager/config.py b/jiuwenswarm/gateway/a2a_manager/config.pyindex 1cf4ecf4b4..9350d4b76f 100644--- a/jiuwenswarm/gateway/a2a_manager/config.py+++ b/jiuwenswarm/gateway/a2a_manager/config.py@@ -1,4 +1,4 @@-"""Compatibility loader for the existing A2A ingress environment variables."""+"""Load and persist A2A ingress environment configuration."""from __future__ import annotations@@ -11,6 +11,8 @@ from pathlib import Pathimport portalocker+from jiuwenswarm.common.local_env_config import decrypt, encrypt+from .models import A2AIngressConfig, A2AIngressError_TRUE_VALUES = {"1", "true", "yes", "on"}@@ -28,6 +30,10 @@ A2A_INGRESS_ENV_MAP = {"app_description": "A2A_SERVER_APP_DESCRIPTION","app_version": "A2A_SERVER_APP_VERSION","expose_reasoning": "A2A_SERVER_EXPOSE_REASONING",+ "auth_type": "A2A_SERVER_AUTH_TYPE",+ "api_key_header": "A2A_SERVER_API_KEY_HEADER",+ "card_auth_required": "A2A_SERVER_CARD_AUTH_REQUIRED",+ "credential": "A2A_SERVER_API_KEY",}A2A_OUTBOUND_ALLOW_LOOPBACK_HTTP_ENV = "A2A_OUTBOUND_ALLOW_LOOPBACK_HTTP"_ENV_ASSIGNMENT_RE = re.compile(@@ -53,9 +59,7 @@ def _persist_dotenv_updates(env_path: Path, updates: Mapping[str, str]) -> None:lock_path = env_path.with_name(f"{env_path.name}.lock")try:with _DOTENV_WRITE_LOCK:- with portalocker.Lock(- str(lock_path), timeout=_DOTENV_LOCK_TIMEOUT_SECONDS- ):+ with portalocker.Lock(str(lock_path), timeout=_DOTENV_LOCK_TIMEOUT_SECONDS):lines = (env_path.read_text(encoding="utf-8").splitlines(keepends=True)if env_path.is_file()@@ -66,13 +70,17 @@ def _persist_dotenv_updates(env_path: Path, updates: Mapping[str, str]) -> None:for line in lines:match = _ENV_ASSIGNMENT_RE.match(line)key = match.group("key") if match else ""- if key not in pending:+ if key not in updates:output.append(line)continue+ if key not in pending:+ continueoutput.append(f"{match.group('indent')}{match.group('export') or ''}{key}="f'"{_quote_dotenv_value(pending.pop(key))}"\n')+ if output and not output[-1].endswith("\n"):+ output[-1] += "\n"output.extend(f'{key}="{_quote_dotenv_value(value)}"\n'for key, value in pending.items()@@ -108,8 +116,15 @@ def _bool(env: Mapping[str, str], name: str, default: bool) -> bool:def load_a2a_ingress_config(env: Mapping[str, str] | None = None) -> A2AIngressConfig:- """Load ``A2A_SERVER_*`` without changing current deployment defaults."""+ """Load and validate ``A2A_SERVER_*`` configuration."""source = os.environ if env is None else env+ card_auth_text = (+ str(source.get("A2A_SERVER_CARD_AUTH_REQUIRED", "false")).strip().lower()+ )+ if card_auth_text not in _TRUE_VALUES | _FALSE_VALUES:+ raise A2AIngressError(+ "A2A_CONFIG_INVALID", "A2A_SERVER_CARD_AUTH_REQUIRED must be a boolean"+ )port_text = _value(source, "A2A_SERVER_PORT", "19100")try:port = int(port_text)@@ -122,6 +137,10 @@ def load_a2a_ingress_config(env: Mapping[str, str] | None = None) -> A2AIngressC"A2A_CONFIG_INVALID", "A2A_SERVER_PORT must be between 1 and 65535")+ stored_credential = _value(source, "A2A_SERVER_API_KEY", "")+ credential = (+ decrypt("A2A_SERVER_API_KEY", stored_credential) if stored_credential else ""+ )return A2AIngressConfig(enabled=_bool(source, "A2A_SERVER_ENABLED", False),host=_value(source, "A2A_SERVER_HOST", "127.0.0.1"),@@ -142,6 +161,10 @@ def load_a2a_ingress_config(env: Mapping[str, str] | None = None) -> A2AIngressC),app_version=_value(source, "A2A_SERVER_APP_VERSION", "0.1.0"),expose_reasoning=_bool(source, "A2A_SERVER_EXPOSE_REASONING", True),+ auth_type=_value(source, "A2A_SERVER_AUTH_TYPE", "none"),+ api_key_header=_value(source, "A2A_SERVER_API_KEY_HEADER", "X-API-Key"),+ card_auth_required=card_auth_text in _TRUE_VALUES,+ credential=credential,).validate()@@ -193,6 +216,12 @@ class A2AIngressConfigRepository:"app_description": config.app_description,"app_version": config.app_version,"expose_reasoning": "true" if config.expose_reasoning else "false",+ "auth_type": config.auth_type,+ "api_key_header": config.api_key_header,+ "card_auth_required": "true" if config.card_auth_required else "false",+ "credential": encrypt("A2A_SERVER_API_KEY", config.credential)+ if config.credential+ else "",}return {A2A_INGRESS_ENV_MAP[name]: value for name, value in values.items()}diff --git a/jiuwenswarm/gateway/a2a_manager/manager.py b/jiuwenswarm/gateway/a2a_manager/manager.pyindex c2178550cf..34a159832f 100644--- a/jiuwenswarm/gateway/a2a_manager/manager.py+++ b/jiuwenswarm/gateway/a2a_manager/manager.py@@ -167,6 +167,13 @@ class A2AManager:async def outbound_get(self, agent_id: str) -> dict[str, Any]:return await self._require_outbound().get_agent(agent_id)+ async def outbound_edit(self, agent_id: str) -> dict[str, Any]:+ return await self._require_outbound().edit_agent(agent_id)++ async def edit_config(self) -> dict[str, Any]:+ async with self._lock:+ return {**self.snapshot().to_dict(), "credential": self._config.credential}+async def outbound_update(self, agent_id: str, params: dict[str, Any]) -> dict[str, Any]:@@ -234,6 +241,18 @@ class A2AManager:effective_base_url = (f"http://{effective.host}:{effective.port}" if effective else None)+ security_fields = (+ "auth_type",+ "api_key_header",+ "card_auth_required",+ "credential_hash",+ )+ security_pending_apply = False+ if effective is not None:+ for name in security_fields:+ if getattr(config, name) != getattr(effective, name):+ security_pending_apply = True+ breakreturn A2AIngressSnapshot(enabled=config.enabled,state=self._state,@@ -278,6 +297,15 @@ class A2AManager:started_at=self._started_at,last_error=self._last_error,config_revision=self._config_revision,+ desired_auth_type=config.auth_type,+ desired_api_key_header=config.api_key_header,+ desired_card_auth_required=config.card_auth_required,+ credential_configured=bool(config.credential_hash),+ effective_auth_type=effective.auth_type if effective else None,+ effective_card_auth_required=effective.card_auth_required+ if effective+ else None,+ security_pending_apply=security_pending_apply,)def history(self, limit: int = 100) -> dict[str, Any]:diff --git a/jiuwenswarm/gateway/a2a_manager/models.py b/jiuwenswarm/gateway/a2a_manager/models.pyindex e10c99b155..f6c09d2b56 100644--- a/jiuwenswarm/gateway/a2a_manager/models.py+++ b/jiuwenswarm/gateway/a2a_manager/models.py@@ -2,10 +2,15 @@from __future__ import annotations-from dataclasses import asdict, dataclass, replace+from dataclasses import asdict, dataclass, field, replacefrom enum import Enumfrom typing import Any+from jiuwenswarm.gateway.channel_manager.protocol.a2a.security import (+ hash_credential,+ validate_security,+)+class A2AIngressState(str, Enum):DISABLED = "disabled"@@ -25,7 +30,7 @@ class A2AIngressError(RuntimeError):@dataclass(frozen=True)class A2AIngressConfig:- """Configuration retained from the existing ``A2A_SERVER_*`` contract."""+ """Configuration for the ``A2A_SERVER_*`` settings."""enabled: bool = Falsehost: str = "127.0.0.1"@@ -38,8 +43,20 @@ class A2AIngressConfig:app_description: str = "A2A ingress for JiuwenSwarm Gateway"app_version: str = "0.1.0"expose_reasoning: bool = True+ auth_type: str = "none"+ api_key_header: str = "X-API-Key"+ card_auth_required: bool = False+ credential: str = field(default="", repr=False)++ @property+ def credential_hash(self) -> str:+ return hash_credential(self.credential) if self.credential else ""def validate(self) -> "A2AIngressConfig":+ try:+ validate_security(self)+ except ValueError as exc:+ raise A2AIngressError("A2A_CONFIG_INVALID", str(exc)) from excif not self.host.strip():raise A2AIngressError("A2A_CONFIG_INVALID", "A2A_SERVER_HOST cannot be empty"@@ -63,7 +80,7 @@ class A2AIngressConfig:return selfdef with_patch(self, patch: dict[str, Any]) -> "A2AIngressConfig":- allowed = set(asdict(self))+ allowed = set(asdict(self)) | {"clear_credential"}unknown = set(patch) - allowedif unknown:raise A2AIngressError(@@ -71,7 +88,25 @@ class A2AIngressConfig:f"Unsupported fields: {', '.join(sorted(unknown))}",)values = asdict(self)+ clear = patch.get("clear_credential", False)+ if not isinstance(clear, bool):+ raise A2AIngressError(+ "A2A_CONFIG_INVALID", "clear_credential must be a boolean"+ )+ credential = patch.get("credential", "")+ if not isinstance(credential, str):+ raise A2AIngressError("A2A_CONFIG_INVALID", "credential must be a string")+ if clear and credential:+ raise A2AIngressError(+ "A2A_CONFIG_INVALID", "Cannot replace and clear a credential together"+ )+ if clear:+ values["credential"] = ""+ elif credential:+ values["credential"] = credentialfor name, value in patch.items():+ if name in {"credential", "clear_credential"}:+ continueif name == "port":try:values[name] = int(value)@@ -79,7 +114,7 @@ class A2AIngressConfig:raise A2AIngressError("A2A_CONFIG_INVALID", "port must be an integer") from exc- elif name in {"enabled", "expose_reasoning"}:+ elif name in {"enabled", "expose_reasoning", "card_auth_required"}:if not isinstance(value, bool):raise A2AIngressError("A2A_CONFIG_INVALID", f"{name} must be a boolean"@@ -92,7 +127,7 @@ class A2AIngressConfig:return replace(self, **values).validate()def to_channel_config(self):- """Create the unchanged protocol-adapter configuration."""+ """Create the protocol-adapter configuration."""from jiuwenswarm.gateway.channel_manager.protocol.a2a.a2a_connect import (A2AChannelConfig,)@@ -109,6 +144,10 @@ class A2AIngressConfig:app_description=self.app_description,app_version=self.app_version,expose_reasoning=self.expose_reasoning,+ auth_type=self.auth_type,+ api_key_header=self.api_key_header,+ card_auth_required=self.card_auth_required,+ credential_hash=self.credential_hash,)@@ -141,6 +180,13 @@ class A2AIngressSnapshot:started_at: float | Nonelast_error: str | Noneconfig_revision: int+ desired_auth_type: str = "none"+ desired_api_key_header: str = "X-API-Key"+ desired_card_auth_required: bool = False+ credential_configured: bool = False+ effective_auth_type: str | None = None+ effective_card_auth_required: bool | None = None+ security_pending_apply: bool = Falsedef to_dict(self) -> dict[str, Any]:result = asdict(self)diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py b/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.pyindex 0ab748e77b..0511971c30 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py@@ -241,7 +241,9 @@ class A2AOutboundDispatcher:):terms.add(token)if all("\u3400" <= char <= "\u9fff" for char in token) and len(token) > 2:- terms.update(token[index:index + 2] for index in range(len(token) - 1))+ terms.update(+ token[index:index + 2] for index in range(len(token) - 1)+ )return termsasync def dispatch(@@ -595,15 +597,14 @@ class A2AOutboundDispatcher:credential = self._credentials.get(agent.credential_ref)if self._credential_required(agent.agent_card) and not credential:raise A2AOutboundError(A2AOutboundErrorCode.AUTH_REQUIRED)+ headers, params, cookies = self._credential_transport_options(+ agent.agent_card, credential+ )if self._client_builder is not None:return await self._client_builder(agent, credential)target = await self._discovery.validate_network_target(agent.selected_interface.url)- headers, params, cookies = self._credential_transport_options(- agent.agent_card,- credential,- )http_client = httpx.AsyncClient(transport=create_pinned_transport({target.host: target.pinned_address}),headers=headers,@@ -675,7 +676,8 @@ class A2AOutboundDispatcher:def _credential_required(card: dict[str, Any]) -> bool:requirements = card.get("securityRequirements") or []return bool(requirements) and not any(- isinstance(requirement, dict) and not requirement+ isinstance(requirement, dict)+ and (not requirement or requirement == {"schemes": {}})for requirement in requirements)@@ -688,39 +690,27 @@ class A2AOutboundDispatcher:return {}, {}, {}requirements = card.get("securityRequirements") or []if not requirements:- # Card doesn't declare a security contract (common for agents registered- # before A2A security schemes were adopted). Fall back to the previous- # unconditional bearer-header behavior instead of silently dropping a- # configured credential, which would turn into a remote 401.- return (- {- "Authorization": (- credential- if credential.lower().startswith("bearer ")- else f"Bearer {credential}"- )- },- {},- {},- )+ raise A2AOutboundError(A2AOutboundErrorCode.AUTH_SCHEME_MISSING)schemes = card.get("securitySchemes") or {}for requirement in requirements:if not isinstance(requirement, dict):continueif not requirement:return {}, {}, {}+ required_schemes = requirement.get("schemes")+ if not isinstance(required_schemes, dict):+ continue+ if not required_schemes:+ return {}, {}, {}headers: dict[str, str] = {}params: dict[str, str] = {}cookies: dict[str, str] = {}supported = True- for scheme_name in requirement:+ for scheme_name in required_schemes:scheme = schemes.get(scheme_name)if not isinstance(scheme, dict):- if str(scheme_name).lower() == "bearer":- scheme = {"httpAuthSecurityScheme": {"scheme": "bearer"}}- else:- supported = False- break+ supported = False+ breakapi_key = scheme.get("apiKeySecurityScheme")http_auth = scheme.get("httpAuthSecurityScheme")if isinstance(api_key, dict):diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/errors.py b/jiuwenswarm/gateway/a2a_manager/outbound/errors.pyindex da6851f15e..91e43fb3a4 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/errors.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/errors.py@@ -18,6 +18,7 @@ class A2AOutboundErrorCode(str, Enum):AGENT_UNAVAILABLE = "A2A_AGENT_UNAVAILABLE"AGENT_REVIEW_REQUIRED = "A2A_AGENT_REVIEW_REQUIRED"AUTH_REQUIRED = "A2A_AUTH_REQUIRED"+ AUTH_SCHEME_MISSING = "A2A_AUTH_SCHEME_MISSING"DISPATCH_NOT_FOUND = "A2A_DISPATCH_NOT_FOUND"DISPATCH_REJECTED = "A2A_DISPATCH_REJECTED"DISPATCH_TIMEOUT = "A2A_DISPATCH_TIMEOUT"@@ -43,6 +44,7 @@ _SAFE_SUMMARIES: dict[A2AOutboundErrorCode, str] = {A2AOutboundErrorCode.AGENT_UNAVAILABLE: "指定的第三方 Agent 当前不可用。",A2AOutboundErrorCode.AGENT_REVIEW_REQUIRED: "第三方 Agent 配置变化需要确认。",A2AOutboundErrorCode.AUTH_REQUIRED: "第三方 Agent 需要有效凭据。",+ A2AOutboundErrorCode.AUTH_SCHEME_MISSING: "已配置凭据,但 Agent Card 未声明认证方式。请让对方补充认证声明后刷新 Card,或清除不需要的凭据。",A2AOutboundErrorCode.DISPATCH_NOT_FOUND: "未找到指定的出站请求。",A2AOutboundErrorCode.DISPATCH_REJECTED: "第三方 Agent 拒绝了本次请求。",A2AOutboundErrorCode.DISPATCH_TIMEOUT: "等待第三方 Agent 回复超时。",diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/registry.py b/jiuwenswarm/gateway/a2a_manager/outbound/registry.pyindex 74f8674d03..dd32cc2664 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/registry.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/registry.py@@ -205,6 +205,14 @@ class A2AOutboundRegistry:async def get_agent(self, agent_id: str) -> dict[str, Any]:return (await self._require_agent(agent_id)).public_dict()+ async def edit_agent(self, agent_id: str) -> dict[str, Any]:+ """Read the credential only for an explicit management editing request."""+ async with self._agent_operation_locks.hold(agent_id):+ agent = await self._require_agent(agent_id)+ result = agent.public_dict()+ result["credential"] = self._credentials.get(agent.credential_ref)+ return result+async def update_agent(self, agent_id: str, params: Mapping[str, Any]) -> dict[str, Any]:diff --git a/jiuwenswarm/gateway/channel_manager/protocol/a2a/a2a_connect.py b/jiuwenswarm/gateway/channel_manager/protocol/a2a/a2a_connect.pyindex 8a2cad3e9d..f6025561a0 100644--- a/jiuwenswarm/gateway/channel_manager/protocol/a2a/a2a_connect.py+++ b/jiuwenswarm/gateway/channel_manager/protocol/a2a/a2a_connect.py@@ -7,13 +7,18 @@ import osimport socketimport timeimport uuid-from dataclasses import dataclass+from dataclasses import dataclass, fieldfrom typing import Anyfrom jiuwenswarm.gateway.channel_manager.base import BaseChannelfrom jiuwenswarm.common.e2a.acp.acp_tool_updates import is_reasoning_eventfrom jiuwenswarm.common.schema.message import EventType, Message, ReqMethodfrom jiuwenswarm.gateway.routing.session_sharing import RoutingTarget+from .security import (+ A2AAuthenticationMiddleware,+ agent_card_security,+ validate_security,+)logger = logging.getLogger(__name__)@@ -79,6 +84,10 @@ class A2AChannelConfig:# dropped. Reasoning is never written into the final `response` artifact# either way.expose_reasoning: bool = True+ auth_type: str = "none"+ api_key_header: str = "X-API-Key"+ card_auth_required: bool = False+ credential_hash: str = field(default="", repr=False)@dataclass@@ -423,7 +432,9 @@ class A2AChannel(BaseChannel):_raise_missing_a2a_sdk(exc)import uvicorn+ validate_security(self.config)agent_card = AgentCard(+ **agent_card_security(self.config),name=self.config.app_name,description=self.config.app_description,version=self.config.app_version,@@ -469,7 +480,10 @@ class A2AChannel(BaseChannel):card_url=self.config.extended_card_path,))- fastapi_app = FastAPI(routes=routes)+ fastapi_app = FastAPI(+ routes=routes, docs_url=None, redoc_url=None, openapi_url=None+ )+ fastapi_app.add_middleware(A2AAuthenticationMiddleware, config=self.config)uv_cfg = uvicorn.Config(app=fastapi_app,diff --git a/jiuwenswarm/gateway/channel_manager/protocol/a2a/security.py b/jiuwenswarm/gateway/channel_manager/protocol/a2a/security.pynew file mode 100644index 0000000000..7d7acd716d--- /dev/null+++ b/jiuwenswarm/gateway/channel_manager/protocol/a2a/security.py@@ -0,0 +1,124 @@+"""Shared ingress authentication validation and ASGI enforcement."""++from __future__ import annotations++import hashlib+import hmac+import re+from typing import Any+++def hash_credential(value: str) -> str:+ if not isinstance(value, str) or not re.fullmatch(r"[!-~]{16,512}", value):+ raise ValueError(+ "credential must contain 16 to 512 printable ASCII characters without spaces"+ )+ return hashlib.sha256(value.encode("ascii")).hexdigest()+++def validate_security(config: Any) -> None:+ if config.auth_type not in {"none", "bearer", "api_key"}:+ raise ValueError("auth_type must be none, bearer, or api_key")+ if not re.fullmatch(r"[!#$%&'*+.^_`|~0-9A-Za-z-]+", config.api_key_header):+ raise ValueError("api_key_header must be a valid HTTP header name")+ if config.api_key_header.lower() in {+ "authorization",+ "host",+ "content-length",+ "content-type",+ "connection",+ "transfer-encoding",+ "cookie",+ "set-cookie",+ "accept",+ "origin",+ }:+ raise ValueError("api_key_header must be a dedicated credential header")+ if not isinstance(config.card_auth_required, bool):+ raise ValueError("card_auth_required must be a boolean")+ if config.credential_hash and not re.fullmatch(+ r"[0-9a-f]{64}", config.credential_hash+ ):+ raise ValueError("Invalid stored ingress credential digest")+ if config.auth_type != "none" and not config.credential_hash:+ raise ValueError("A credential is required when authentication is enabled")+ if config.card_auth_required and config.auth_type == "none":+ raise ValueError("Card authentication requires an authentication method")+++def agent_card_security(config: Any) -> dict[str, Any]:+ if config.auth_type == "none":+ return {}+ from a2a.types import SecurityScheme++ scheme = (+ SecurityScheme(http_auth_security_scheme={"scheme": "bearer"})+ if config.auth_type == "bearer"+ else SecurityScheme(+ api_key_security_scheme={+ "location": "header",+ "name": config.api_key_header,+ }+ )+ )+ return {+ "security_schemes": {"ingress": scheme},+ "security_requirements": [{"schemes": {"ingress": {"list": []}}}],+ }+++class A2AAuthenticationMiddleware:+ """Check headers before routing or reading request bodies, including streams."""++ def __init__(self, app: Any, *, config: Any) -> None:+ validate_security(config)+ self.app = app+ self.config = config++ async def __call__(self, scope, receive, send) -> None:+ config = self.config+ public_card = (+ not config.card_auth_required+ and scope.get("path") == config.card_path+ and scope.get("method") in {"GET", "HEAD"}+ )+ if scope["type"] != "http" or config.auth_type == "none" or public_card:+ await self.app(scope, receive, send)+ return+ header = (+ "authorization"+ if config.auth_type == "bearer"+ else config.api_key_header.lower()+ )+ values = [+ value+ for key, value in scope.get("headers", [])+ if key.lower() == header.encode("ascii")+ ]+ credential = b""+ if len(values) == 1:+ credential = values[0]+ if config.auth_type == "bearer":+ scheme, separator, credential = credential.partition(b" ")+ if not separator or scheme.lower() != b"bearer":+ credential = b""+ try:+ digest = hash_credential(credential.decode("ascii"))+ except ValueError:+ digest = ""+ if credential and hmac.compare_digest(digest, config.credential_hash):+ await self.app(scope, receive, send)+ return+ from starlette.responses import JSONResponse++ response = JSONResponse(+ {"error": "Unauthorized"},+ status_code=401,+ headers={+ "WWW-Authenticate": "Bearer"+ if config.auth_type == "bearer"+ else 'ApiKey realm="a2a"',+ "Cache-Control": "no-store",+ },+ )+ await response(scope, receive, send)diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex 1f95fed45c..730284fbd4 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -1705,6 +1705,25 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:async def _a2a_ingress_get(ws, req_id, params, session_id):await _send_a2a_snapshot(ws, req_id, lambda: _a2a_snapshot_async(a2a_manager))+ async def _a2a_ingress_edit(ws, req_id, params, session_id):+ if a2a_manager is None:+ await channel.send_response(+ ws, req_id, ok=False, error="A2A ingress manager is unavailable", code="A2A_BIND_FAILED"+ )+ return+ try:+ payload = await a2a_manager.edit_config()+ except Exception:+ await channel.send_response(+ ws,+ req_id,+ ok=False,+ error="Unable to read A2A ingress configuration",+ code="A2A_CONFIG_INVALID",+ )+ return+ await channel.send_response(ws, req_id, ok=True, payload=payload)+async def _a2a_ingress_history(ws, req_id, params, session_id):if a2a_manager is None:await channel.send_response(@@ -1747,6 +1766,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:await _send_a2a_snapshot(ws, req_id, lambda: a2a_manager.reload())channel.register_method("a2a.ingress.get", _a2a_ingress_get)+ channel.register_method("a2a.ingress.edit", _a2a_ingress_edit)channel.register_method("a2a.ingress.history", _a2a_ingress_history)channel.register_method("a2a.ingress.update", _a2a_ingress_update)channel.register_method("a2a.ingress.enable", _a2a_ingress_enable)@@ -1829,6 +1849,11 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:ws, req_id, lambda: a2a_manager.outbound_get(str(params.get("agent_id") or "")))+ async def _a2a_outbound_edit(ws, req_id, params, session_id):+ await _send_a2a_outbound(+ ws, req_id, lambda: a2a_manager.outbound_edit(str(params.get("agent_id") or ""))+ )+async def _a2a_outbound_update(ws, req_id, params, session_id):payload = dict(params)agent_id = str(payload.pop("agent_id", ""))@@ -1904,6 +1929,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:channel.register_method("a2a.outbound.register", _a2a_outbound_register)channel.register_method("a2a.outbound.list", _a2a_outbound_list)channel.register_method("a2a.outbound.get", _a2a_outbound_get)+ channel.register_method("a2a.outbound.edit", _a2a_outbound_edit)channel.register_method("a2a.outbound.update", _a2a_outbound_update)channel.register_method("a2a.outbound.refresh", _a2a_outbound_refresh)channel.register_method(diff --git a/tests/unit_tests/channel/test_a2a_security.py b/tests/unit_tests/channel/test_a2a_security.pynew file mode 100644index 0000000000..683552a3f0--- /dev/null+++ b/tests/unit_tests/channel/test_a2a_security.py@@ -0,0 +1,146 @@+"""Exercise ingress authentication over a real HTTP listener and SDK routes."""++import httpx+import pytest+import time++from jiuwenswarm.common.schema.message import EventType, Message++from jiuwenswarm.gateway.channel_manager.protocol.a2a.a2a_connect import (+ A2AChannel,+ A2AChannelConfig,+)+from jiuwenswarm.gateway.channel_manager.protocol.a2a.security import hash_credential++[email protected]("auth_type", ["bearer", "api_key"])[email protected]("protect_card", [False, True])+async def test_authentication_protects_rpc_and_card_routes(auth_type, protect_card):+ secret = "test-credential-with-32-characters"+ channel = A2AChannel(+ A2AChannelConfig(+ enabled=True,+ port=0,+ auth_type=auth_type,+ api_key_header="X-Custom-Key",+ card_auth_required=protect_card,+ credential_hash=hash_credential(secret),+ ),+ object(),+ )+ dispatched = []++ async def reply(message):+ dispatched.append(message)+ await channel.send(+ Message(+ id=message.id,+ type="event",+ channel_id="a2a",+ session_id=message.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "authenticated reply", "is_complete": True},+ event_type=EventType.CHAT_FINAL,+ )+ )++ channel.on_message(reply)+ await channel.start()+ try:+ port = channel._listen_socket.getsockname()[1]+ async with httpx.AsyncClient(+ base_url=f"http://127.0.0.1:{port}", headers={"A2A-Version": "1.0"}+ ) as client:+ header = "Authorization" if auth_type == "bearer" else "X-Custom-Key"+ value = f"bEaReR {secret}" if auth_type == "bearer" else secret+ for method in [+ "SendMessage",+ "SendStreamingMessage",+ "GetTask",+ "CancelTask",+ "SubscribeToTask",+ ]:+ response = await client.post(+ "/a2a",+ json={"jsonrpc": "2.0", "id": "1", "method": method, "params": {}},+ )+ assert response.status_code == 401+ assert "www-authenticate" in response.headers+ assert secret not in response.text+ for headers in [+ {header: "wrong"},+ [(header, value), (header, value)],+ [+ (+ header.encode(),+ b"Bearer \xff" if auth_type == "bearer" else b"\xff",+ )+ ],+ ]:+ assert (+ await client.post("/a2a", headers=headers, content=b"not json")+ ).status_code == 401+ assert (+ await client.get(channel.config.extended_card_path)+ ).status_code == 401+ assert (await client.get(channel.config.card_path)).status_code == (+ 401 if protect_card else 200+ )+ response = await client.get(+ channel.config.card_path, headers={header: value}+ )+ assert response.status_code == 200+ card = response.json()+ assert secret not in response.text+ assert channel.config.credential_hash not in response.text+ assert card["securityRequirements"]+ scheme = card["securitySchemes"]["ingress"]+ if auth_type == "bearer":+ assert scheme["httpAuthSecurityScheme"]["scheme"] == "bearer"+ else:+ assert scheme["apiKeySecurityScheme"]["name"] == "X-Custom-Key"+ assert (+ await client.get(+ channel.config.extended_card_path, headers={header: value}+ )+ ).status_code == 200+ # Correct credentials reach the SDK, even for a nonexistent task.+ response = await client.post(+ "/a2a",+ headers={header: value},+ json={+ "jsonrpc": "2.0",+ "id": "1",+ "method": "GetTask",+ "params": {"id": "missing"},+ },+ )+ assert response.status_code != 401+ assert response.json()["id"] == "1"+ assert response.json()["error"]["code"] != -32601+ assert not dispatched+ response = await client.post(+ "/a2a",+ headers={header: value},+ json={+ "jsonrpc": "2.0",+ "id": "stream",+ "method": "SendStreamingMessage",+ "params": {+ "message": {+ "messageId": "auth-test",+ "role": "ROLE_USER",+ "parts": [{"text": "hello"}],+ }+ },+ },+ )+ assert response.status_code == 200+ assert "text/event-stream" in response.headers["content-type"]+ assert "authenticated reply" in response.text+ assert len(dispatched) == 1+ finally:+ await channel.stop()diff --git a/tests/unit_tests/gateway/test_a2a_manager.py b/tests/unit_tests/gateway/test_a2a_manager.pyindex 524e5b20bd..73b5cb43a8 100644--- a/tests/unit_tests/gateway/test_a2a_manager.py+++ b/tests/unit_tests/gateway/test_a2a_manager.py@@ -747,3 +747,166 @@ async def test_enable_surfaces_stable_startup_error_codes(start_error, code):assert exc_info.value.code == codeassert manager.snapshot().state.value == "error"+++ "patch",+ [+ {"auth_type": "unknown"},+ {"auth_type": "bearer"},+ {"credential": "short"},+ {"credential": "bad\r\ncredential-value"},+ {"credential": 123},+ {"credential_hash": "a" * 64},+ {"api_key_header": "Authorization"},+ {"api_key_header": "bad header"},+ {"card_auth_required": True},+ {"clear_credential": "true"},+ {"clear_credential": True, "credential": "test-secret-with-enough-length"},+ ],+)+def test_ingress_rejects_invalid_security_without_echoing_credentials(patch):+ with pytest.raises(A2AIngressError) as error:+ A2AIngressConfig().with_patch(patch)+ if isinstance(patch.get("credential"), str):+ assert patch["credential"] not in str(error.value)++[email protected]("encrypted", [False, True])+def test_ingress_credentials_use_model_key_storage_and_reload(+ tmp_path, monkeypatch, encrypted+):+ from cryptography.fernet import Fernet+ from types import SimpleNamespace+ from dotenv import dotenv_values+ from jiuwenswarm.extensions.registry import ExtensionRegistry++ cipher = Fernet(Fernet.generate_key())+ provider = (+ SimpleNamespace(+ encrypt=lambda value: cipher.encrypt(value.encode()).decode(),+ decrypt=lambda value: cipher.decrypt(value.encode()).decode(),+ )+ if encrypted+ else None+ )+ monkeypatch.setattr(+ ExtensionRegistry,+ "get_instance",+ lambda: SimpleNamespace(get_crypto_provider=lambda: provider),+ )+ monkeypatch.setattr(a2a_config_module.os, "environ", {})+ secret = "test-secret-with-enough-length"+ config = A2AIngressConfig().with_patch(+ {"auth_type": "bearer", "credential": secret}+ )+ repo = A2AIngressConfigRepository(tmp_path / ".env")+ repo.save(config)+ values = dotenv_values(tmp_path / ".env")+ assert (values["A2A_SERVER_API_KEY"] != secret) == encrypted+ assert config.credential_hash not in (tmp_path / ".env").read_text(encoding="utf-8")+ assert load_a2a_ingress_config(values) == config+ assert config.credential == secret+ assert not hasattr(config.to_channel_config(), "credential")+ assert secret not in repr(config)+ assert config.credential_hash not in repr(config)+ assert load_a2a_ingress_config(a2a_config_module.os.environ) == config+ assert (+ config.with_patch({"credential": "", "app_name": "Renamed"}).credential_hash+ == config.credential_hash+ )+ with pytest.raises(A2AIngressError):+ config.with_patch({"clear_credential": True})+ cleared = config.with_patch({"auth_type": "none", "clear_credential": True})+ repo.save(cleared)+ assert not load_a2a_ingress_config(a2a_config_module.os.environ).credential_hash+ assert not load_a2a_ingress_config(dotenv_values(tmp_path / ".env")).credential+++async def test_ingress_rotation_only_takes_effect_after_apply():+ manager = A2AManager(+ _ChannelManagerProbe(),+ object(),+ A2AIngressConfig(),+ repository=_ConfigRepositoryProbe(),+ channel_factory=_ChannelProbe,+ )+ first = "test-first-secret-with-enough-length"+ second = "test-second-secret-with-enough-length"+ await manager.update({"auth_type": "bearer", "credential": first})+ await manager.enable()+ old_channel = manager._channel+ snapshot = await manager.update({"credential": second})+ assert snapshot.security_pending_apply+ assert snapshot.credential_configured+ assert first not in str(snapshot.to_dict())+ assert second not in str(snapshot.to_dict())+ assert (await manager.edit_config())["credential"] == second+ assert second not in repr(snapshot)+ assert manager._config.credential_hash not in str(snapshot.to_dict())+ assert old_channel.config.credential_hash != manager._config.credential_hash+ snapshot = await manager.update({}, apply=True)+ assert not snapshot.security_pending_apply+ assert snapshot.effective_auth_type == "bearer"+ assert old_channel.stop_calls == 1+ assert manager._channel.config.credential_hash == manager._config.credential_hash+ await manager.disable()+++def test_ingress_rotation_removes_duplicate_env_values(tmp_path, monkeypatch):+ from dotenv import dotenv_values++ monkeypatch.setattr(a2a_config_module.os, "environ", {})+ env_path = tmp_path / ".env"+ env_path.write_text(+ "A2A_SERVER_AUTH_TYPE=none\nA2A_SERVER_AUTH_TYPE=none\nMODEL_NAME=keep",+ encoding="utf-8",+ )+ config = A2AIngressConfig().with_patch(+ {"auth_type": "bearer", "credential": "test-rotation-secret-long"}+ )+ A2AIngressConfigRepository(env_path).save(config)+ values = dotenv_values(env_path)+ assert values["MODEL_NAME"] == "keep"+ assert load_a2a_ingress_config(values) == config+ assert env_path.read_text(encoding="utf-8").count("A2A_SERVER_AUTH_TYPE=") == 1+++ "env",+ [+ {"A2A_SERVER_AUTH_TYPE": "bearer"},+ {"A2A_SERVER_AUTH_TYPE": "invalid"},+ {"A2A_SERVER_CARD_AUTH_REQUIRED": "invalid"},+ {"A2A_SERVER_API_KEY": "short"},+ ],+)+def test_invalid_security_configuration_never_starts_anonymous_ingress(env):+ config, error = load_a2a_ingress_config_safely(+ {"A2A_SERVER_ENABLED": "true", **env}+ )+ assert error is not None+ assert not config.enabled+++async def test_failed_credential_persistence_keeps_saved_and_effective_values():+ class FailingRepository:+ def save(self, config):+ raise A2AIngressError("A2A_CONFIG_INVALID", "Storage unavailable")++ original = A2AIngressConfig().with_patch(+ {"auth_type": "bearer", "credential": "test-original-credential"}+ )+ manager = A2AManager(+ _ChannelManagerProbe(),+ object(),+ original,+ repository=FailingRepository(),+ channel_factory=_ChannelProbe,+ )+ with pytest.raises(A2AIngressError):+ await manager.update({"credential": "test-replacement-credential"}, apply=True)+ assert manager._config == original+ assert manager.snapshot().config_revision == 0diff --git a/tests/unit_tests/gateway/test_a2a_manager_web_handlers.py b/tests/unit_tests/gateway/test_a2a_manager_web_handlers.pyindex e011675300..6fb3cffa26 100644--- a/tests/unit_tests/gateway/test_a2a_manager_web_handlers.py+++ b/tests/unit_tests/gateway/test_a2a_manager_web_handlers.py@@ -120,6 +120,45 @@ async def test_a2a_ingress_web_handlers_return_snapshots():assert channel.responses[3]["payload"]["state"] == "running"+async def test_saved_ingress_credential_is_returned_to_configuration_ui():+ channel = _WebChannelProbe()+ manager = A2AManager(+ _ChannelManagerProbe(),+ object(),+ A2AIngressConfig(),+ repository=_RepositoryProbe(),+ channel_factory=lambda config, router: _ChannelProbe(),+ )+ _register_web_handlers(WebHandlersBindParams(channel=channel, a2a_manager=manager))+ credential = "test-viewable-ingress-credential"+ await channel.methods["a2a.ingress.update"](+ object(),+ "save",+ {"config": {"auth_type": "bearer", "credential": credential}, "apply": True},+ "session",+ )+ await channel.methods["a2a.ingress.get"](object(), "refresh", {}, "session")+ await channel.methods["a2a.ingress.get"](object(), "poll", {}, "session")+ for response in channel.responses:+ assert response["ok"] is True+ assert credential not in str(response)+ assert "credential" not in response["payload"]+ assert "desired_credential" not in response["payload"]+ assert "credential_hash" not in response["payload"]+ await channel.methods["a2a.ingress.update"](+ object(), "failed-save", {"config": {"rpc_path": "invalid"}}, "session"+ )+ assert channel.responses[-1]["ok"] is False+ assert credential not in str(channel.responses[-1])+ await channel.methods["a2a.ingress.edit"](object(), "edit", {}, "session")+ assert channel.responses[-1]["payload"]["credential"] == credential+ assert not any(+ route.rpc_method in {"a2a.ingress.edit", "a2a.outbound.edit"}+ for route in MAPPED_ROUTES+ )++@pytest.mark.asyncioasync def test_a2a_ingress_update_apply_disables_the_running_service():channel = _WebChannelProbe()@@ -379,7 +418,9 @@ async def test_a2a_outbound_handlers_tolerate_missing_manager():)assert [item["ok"] for item in channel.responses] == [False] * 8- assert {item["code"] for item in channel.responses} == {"A2A_OUTBOUND_STORE_INVALID"}+ assert {item["code"] for item in channel.responses} == {+ "A2A_OUTBOUND_STORE_INVALID"+ }def test_a2a_outbound_http_routes_map_to_rpc_methods():@@ -392,10 +433,7 @@ def test_a2a_outbound_http_routes_map_to_rpc_methods():assert routes[("POST", "/a2a/outbound/discover")] == "a2a.outbound.discover"assert routes[("POST", "/a2a/outbound/agents")] == "a2a.outbound.register"assert routes[("GET", "/a2a/outbound/agents")] == "a2a.outbound.list"- assert (- routes[("GET", "/a2a/outbound/dispatches")]- == "a2a.outbound.dispatch.list"- )+ assert routes[("GET", "/a2a/outbound/dispatches")] == "a2a.outbound.dispatch.list"assert routes[("PATCH", "/a2a/outbound/agents/{agent_id}")] == "a2a.outbound.update"assert (routes[("POST", "/a2a/outbound/agents/{agent_id}:refresh")]diff --git a/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.py b/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.pyindex 0ddbff42e5..202fa00e71 100644--- a/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.py+++ b/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.py@@ -9,6 +9,7 @@ from types import SimpleNamespaceimport pytestfrom a2a.types import (+ AgentCard,Artifact,Message,Part,@@ -20,6 +21,7 @@ from a2a.types import (TaskStatus,TaskStatusUpdateEvent,)+from google.protobuf.json_format import MessageToDict, ParseDictfrom jiuwenswarm.agents.harness.common.rails.a2a_outbound_toolkit_rail import (A2AOutboundToolkitRail,@@ -656,7 +658,13 @@ async def test_required_remote_auth_without_credential_is_not_left_submitting()"agent-1",lambda current: replace(current,- agent_card={**current.agent_card, "securityRequirements": [{"bearer": []}]},+ agent_card={+ **current.agent_card,+ "securityRequirements": [{"schemes": {"bearer": {}}}],+ "securitySchemes": {+ "bearer": {"httpAuthSecurityScheme": {"scheme": "bearer"}}+ },+ },),)@@ -700,10 +708,15 @@ def test_client_credentials_follow_agent_card_security_scheme(scheme, expected):if scheme.get("httpAuthSecurityScheme", {}).get("scheme") == "basic"else "secret")- card = {- "securityRequirements": [{"auth": []}],- "securitySchemes": {"auth": scheme},- }+ card = MessageToDict(+ ParseDict(+ {+ "securityRequirements": [{"schemes": {"auth": {}}}],+ "securitySchemes": {"auth": scheme},+ },+ AgentCard(),+ )+ )assert (A2AOutboundDispatcher._credential_transport_options(card, credential)@@ -713,7 +726,7 @@ def test_client_credentials_follow_agent_card_security_scheme(scheme, expected):def test_client_rejects_unsupported_mtls_credential_contract():card = {- "securityRequirements": [{"mtls": []}],+ "securityRequirements": [{"schemes": {"mtls": {}}}],"securitySchemes": {"mtls": {"mtlsSecurityScheme": {}}},}@@ -725,7 +738,7 @@ def test_client_rejects_unsupported_mtls_credential_contract():def test_empty_security_requirement_allows_anonymous_access():card = {- "securityRequirements": [{"bearer": []}, {}],+ "securityRequirements": [{"schemes": {"bearer": {}}}, {}],"securitySchemes": {"bearer": {"httpAuthSecurityScheme": {"scheme": "bearer"}}},}@@ -733,17 +746,21 @@ def test_empty_security_requirement_allows_anonymous_access():assert A2AOutboundDispatcher._credential_transport_options(card, "") == ({}, {}, {})-def test_card_without_security_contract_still_sends_configured_credential():- """Regression: a card without securityRequirements must not silently drop a- configured credential_ref (previously fell back to a bearer header)."""+def test_card_without_security_contract_rejects_configured_credentials():card = {"securitySchemes": {}}assert A2AOutboundDispatcher._credential_required(card) is False- assert A2AOutboundDispatcher._credential_transport_options(card, "secret") == (- {"Authorization": "Bearer secret"},- {},- {},- )+ assert A2AOutboundDispatcher._credential_transport_options(card, "") == ({}, {}, {})+ with pytest.raises(A2AOutboundError) as error:+ A2AOutboundDispatcher._credential_transport_options(card, "secret")+ assert error.value.code is A2AOutboundErrorCode.AUTH_SCHEME_MISSING+++def test_scheme_name_alone_does_not_infer_bearer_authentication():+ card = {"securityRequirements": [{"schemes": {"bearer": {}}}]}+ with pytest.raises(A2AOutboundError) as error:+ A2AOutboundDispatcher._credential_transport_options(card, "secret")+ assert error.value.code is A2AOutboundErrorCode.AUTH_REQUIRED@pytest.mark.asyncio@@ -1324,10 +1341,7 @@ async def test_reverse_rpc_emits_cancel_notification_when_tool_is_canceled(A2A_TOOL_DISPATCH_TASK,A2A_TOOL_CANCEL_CALL,]- assert (- pushes[1]["body"]["params"]["jsonrpc_id"]- == pushes[0]["body"]["id"]- )+ assert pushes[1]["body"]["params"]["jsonrpc_id"] == pushes[0]["body"]["id"]finally:if not pending.done():pending.cancel()diff --git a/tests/unit_tests/gateway/test_a2a_outbound_management.py b/tests/unit_tests/gateway/test_a2a_outbound_management.pyindex 003f4d1c15..6d4f46bdaa 100644--- a/tests/unit_tests/gateway/test_a2a_outbound_management.py+++ b/tests/unit_tests/gateway/test_a2a_outbound_management.py@@ -146,6 +146,9 @@ def _card(class _DiscoverySequence:+ def set_allow_loopback_http(self, enabled: bool) -> None:+ self.allow_loopback_http = enabled+def __init__(self, *cards: DiscoveredCard) -> None:self.cards = list(cards)@@ -362,12 +365,68 @@ async def test_credential_update_and_clear_are_persisted_together() -> None:assert persisted is not Noneassert updated["has_credential"] is Trueassert secrets.values[persisted.credential_ref] == "new-secret"+ assert "credential" not in await registry.get_agent(created["agent_id"])+ assert (await registry.edit_agent(created["agent_id"]))[+ "credential"+ ] == "new-secret"+ assert "credential" not in (await registry.list_agents())["items"][0]cleared = await registry.update_agent(created["agent_id"], {"clear_credential": True})assert cleared["has_credential"] is Falseassert secrets.values == {}+ assert (await registry.edit_agent(created["agent_id"]))["credential"] == ""+++async def test_http_get_and_error_snapshots_never_include_saved_credentials():+ from jiuwenswarm.gateway.a2a_manager import A2AIngressConfig, A2AManager+ from jiuwenswarm.gateway.channel_manager.base import RobotMessageRouter+ from jiuwenswarm.gateway.channel_manager.web.app_web_handlers import (+ WebHandlersBindParams,+ _register_web_handlers,+ )+ from jiuwenswarm.gateway.channel_manager.web.web_connect import (+ WebChannel,+ WebChannelConfig,+ )+ from jiuwenswarm.gateway.channel_manager.web.web_http_app import create_web_http_app++ secret = "test-http-secret-must-stay-private"+ registry, _, _ = _registry(_card())+ preview = await registry.discover("https://agent.example.com")+ agent = await registry.register(+ {"discovery_id": preview["discovery_id"], "credential": secret}+ )+ manager = A2AManager(+ object(),+ object(),+ A2AIngressConfig().with_patch({"auth_type": "bearer", "credential": secret}),+ outbound_registry=registry,+ )+ channel = WebChannel(+ WebChannelConfig(host="127.0.0.1", port=0), RobotMessageRouter()+ )+ _register_web_handlers(WebHandlersBindParams(channel=channel, a2a_manager=manager))+ transport = httpx.ASGITransport(app=create_web_http_app(channel))+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as http:+ for path in [+ "/a2a/ingress",+ "/a2a/outbound/agents",+ f"/a2a/outbound/agents/{agent['agent_id']}",+ ]:+ response = await http.get(f"/api/v1{path}")+ assert response.status_code == 200+ assert secret not in response.text+ assert '"credential"' not in response.text+ assert '"desired_credential"' not in response.text+ failed = await http.patch(+ "/api/v1/a2a/ingress", json={"config": {"rpc_path": "invalid"}}+ )+ assert failed.json()["ok"] is False+ assert secret not in failed.text+ assert '"credential"' not in failed.text@pytest.mark.asyncio