JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat(ssh): issue ephemeral keys on 3rdagent.switch for TUI auth
yechenzhen88edd70deae3
diff --git a/deploy/yuanrong/.env.example b/deploy/yuanrong/.env.exampleindex 8a2aaf8f30..3850b68f29 100644--- a/deploy/yuanrong/.env.example+++ b/deploy/yuanrong/.env.example@@ -95,8 +95,9 @@ WEB_PORT=""# 默认 600;<=0 禁用回收。未设置时使用 yaml 配置。SANDBOX_IDLE_TIMEOUT_SECONDS=""-# AgentOS IAM 鉴权(gateway.agentos.auth_enabled=true 时生效)-AGENTOS_AUTH_SERVICE_URL="http://iam-agentos:8080"+# AgentOS IAM 鉴权(写入 gateway-config.yaml 的 <<AGENTOS_AUTH_*>>)+# gateway.agentos.auth_enabled=true 时生效;勿留空,否则 yaml 里 URL/timeout 会变成空值+AGENTOS_AUTH_SERVICE_URL="http://iam-agentos:8090"AGENTOS_AUTH_TIMEOUT="10"# 函数ID(单独部署 gateway 时需要指定,由 openYuanrong 注册函数后返回)diff --git a/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml b/deploy/yuanrong/conf/gateway-config-yuanrong.template.yamlindex 3fded6e7d9..24cc05f7c0 100644--- a/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml+++ b/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml@@ -498,8 +498,9 @@ gateway:port: 2222user_template: "yr:instance:{instance}"connect_timeout_s: 30- auth_service_url: ${AGENTOS_AUTH_SERVICE_URL:-http://iam-agentos:8080}- timeout: ${AGENTOS_AUTH_TIMEOUT:-10}+ # agentos_router.load_router_config 不会解析 ${VAR},部署时用 <<>> 替换进 yaml。+ auth_service_url: <<AGENTOS_AUTH_SERVICE_URL>>+ timeout: <<AGENTOS_AUTH_TIMEOUT>># Web/TUI token 鉴权总开关;默认关闭。true 时创建 AgentOSAuthenticator 校验连接。auth_enabled: false@@ -673,6 +674,15 @@ channels:listen_port: <<SSH_PORT>>host_key_path: ~/.jiuwenswarm/config/ssh_host_keyrelay_timeout_sec: 3600+ auth:+ # 公钥认证开关。false 时保持宽松认证(向后兼容)。+ enabled: false+ # TUI 场景: 临时密钥有效期(秒)+ ephemeral_key_ttl_sec: 300+ # 临时密钥类型+ ephemeral_key_type: "ssh-ed25519"+ # 过期清理间隔(秒)+ cleanup_interval_sec: 60# ========== 细粒度权限管控(tiered_policy)==========#diff --git a/deploy/yuanrong/global_vars.sh b/deploy/yuanrong/global_vars.shindex a71881484d..04f448beef 100755--- a/deploy/yuanrong/global_vars.sh+++ b/deploy/yuanrong/global_vars.sh@@ -58,4 +58,6 @@ declare -A DEPLOY_VARS=(["SANDBOX_IDLE_TIMEOUT_SECONDS"]=""["OS_TYPE"]=""["EXTENSION_DIRS"]=""+ ["AGENTOS_AUTH_SERVICE_URL"]=""+ ["AGENTOS_AUTH_TIMEOUT"]="")diff --git a/jiuwenswarm/extensions/agentos/agentos_router/__init__.py b/jiuwenswarm/extensions/agentos/agentos_router/__init__.pyindex 5ee9930287..a35ebfe887 100644--- a/jiuwenswarm/extensions/agentos/agentos_router/__init__.py+++ b/jiuwenswarm/extensions/agentos/agentos_router/__init__.py@@ -10,7 +10,7 @@ from jiuwenswarm.extensions.agentos.agentos_router.agent_manager import (is_third_party_agent_type,normalize_agent_key_fields,)-from jiuwenswarm.extensions.agentos.agentos_router.extension import AgentOSRouter+from jiuwenswarm.extensions.agentos.agentos_router.extension import AgentOSRouter, register_extensionsfrom jiuwenswarm.extensions.agentos.agentos_router.models import (AgentInfo,AgentStatus,@@ -63,4 +63,5 @@ __all__ = ["is_third_party_agent_type","normalize_agent_key_fields","resolve_instance_kind",+ "register_extensions"]diff --git a/jiuwenswarm/extensions/agentos/agentos_router/agentos_authenticator.py b/jiuwenswarm/extensions/agentos/agentos_router/agentos_authenticator.pyindex 63d46c5a3c..f0c3db6ccc 100644--- a/jiuwenswarm/extensions/agentos/agentos_router/agentos_authenticator.py+++ b/jiuwenswarm/extensions/agentos/agentos_router/agentos_authenticator.py@@ -52,8 +52,8 @@ class AgentOSAuthenticator(CredentialAuthenticator):"Content-Type": "application/json","Authorization": f"Bearer {token}",}- if extra_headers:- headers.update(extra_headers)+ # 不要把 WS 握手头(Host/Upgrade/authorization 等)原样并入 IAM 请求,+ # 否则可能产生重复 Authorization 或错误 Host,导致 verify 失败。try:resp = await self._auth_client.post(f"{self._auth_service_url}/api/v1/auth/verify",diff --git a/jiuwenswarm/extensions/agentos/agentos_router/extension.py b/jiuwenswarm/extensions/agentos/agentos_router/extension.pyindex 12ac4be589..afecbee8bf 100644--- a/jiuwenswarm/extensions/agentos/agentos_router/extension.py+++ b/jiuwenswarm/extensions/agentos/agentos_router/extension.py@@ -72,6 +72,18 @@ class AgentOSRouter(AgentServerClientExtension, ThirdAgentExtension):def get_third_agent(self) -> ThirdAgent:return self._third_agent+ def set_key_issuer(+ self,+ key_issuer,+ *,+ ephemeral_key_ttl_sec: float = 300.0,+ ) -> None:+ """Inject AgentOS SSH key issuer (or clear)."""+ self._router_client.set_key_issuer(+ key_issuer,+ ephemeral_key_ttl_sec=ephemeral_key_ttl_sec,+ )+async def shutdown(self) -> None:if self._closed:returndiff --git a/jiuwenswarm/extensions/agentos/agentos_router/router_client.py b/jiuwenswarm/extensions/agentos/agentos_router/router_client.pyindex 55b51b49c3..45fe5f29c5 100644--- a/jiuwenswarm/extensions/agentos/agentos_router/router_client.py+++ b/jiuwenswarm/extensions/agentos/agentos_router/router_client.py@@ -48,6 +48,7 @@ from jiuwenswarm.extensions.yuanrong_frontend_client import (AgentRuntimeSpec,YuanrongFrontendAgentClient,)+from jiuwenswarm.extensions.agentos.auth.ssh_key_issuer import SshKeyIssuerfrom jiuwenswarm.gateway import ChannelManagerfrom jiuwenswarm.gateway.channel_manager.base import ChannelTypefrom jiuwenswarm.gateway.routing.agent_client import (@@ -92,6 +93,10 @@ class UnsupportedAgentType(ValueError):pass+class EphemeralKeyIssueError(RuntimeError):+ """A configured issuer could not mint an ephemeral SSH key."""++def build_inline_runtime_spec(image_info: ImageInfo) -> AgentRuntimeSpec:"""Take registry ``metadata.runtime_spec`` (YuanRong ``RuntimeSpec`` shape)."""meta = image_info.metadata if isinstance(image_info.metadata, dict) else {}@@ -153,6 +158,8 @@ class AgentOSRouterClient(AgentServerClient):agent_manager: AgentManager,ssh_relay: YuanrongSshRelay | None = None,ssh_channel_endpoint: SshChannelEndpoint | None = None,+ key_issuer: SshKeyIssuer | None = None,+ ephemeral_key_ttl_sec: float = 300.0,workspace_root: str = DEFAULT_AGENT_WORKSPACE_ROOT,sandbox_idle_timeout_seconds: float = 600.0,sandbox_idle_check_interval_seconds: float = 30.0,@@ -164,6 +171,8 @@ class AgentOSRouterClient(AgentServerClient):self._agent_manager = agent_managerself._ssh_relay = ssh_relayself._ssh_channel_endpoint = ssh_channel_endpoint+ self._key_issuer = key_issuer+ self._ephemeral_key_ttl_sec = float(ephemeral_key_ttl_sec)self._workspace_root = (str(workspace_root or "").strip() or DEFAULT_AGENT_WORKSPACE_ROOT)@@ -234,6 +243,16 @@ class AgentOSRouterClient(AgentServerClient):await retreturn result+ def set_key_issuer(+ self,+ key_issuer: SshKeyIssuer | None,+ *,+ ephemeral_key_ttl_sec: float = 300.0,+ ) -> None:+ """Inject or clear the northbound SSH ephemeral key issuer."""+ self._key_issuer = key_issuer+ self._ephemeral_key_ttl_sec = float(ephemeral_key_ttl_sec)+async def _on_channel_event(self, event: Any) -> None:"""处理 Channel 连接事件,维护用户连接计数并触发延迟清理。"""user_id = str(getattr(event, "user_id", "") or "").strip()@@ -658,19 +677,31 @@ class AgentOSRouterClient(AgentServerClient):ssh_fields = self._ssh_endpoint_fields()if ssh_fields is None:return self._missing_ssh_endpoint_error()+ # Fail fast before create: without the key the client cannot pass+ # SSH public-key auth, so a "successful" switch would be unusable.+ try:+ key_fields = self._ephemeral_ssh_key_fields(+ user_id=uid,+ session_id=session_id,+ )+ except EphemeralKeyIssueError as exc:+ return {+ "ok": False,+ "error": str(exc),+ "code": "SSH_KEY_ISSUE_FAILED",+ }# Builtin swarm: no registry / create_sandbox; mark current type only.if self._uses_direct_yuanrong(normalized):self._current_agent_types[uid] = normalized- return {- "ok": True,- "payload": {- "agent_id": "",- "agent_type": normalized,- "sandbox_id": "",- "status": AgentStatus.READY.value,- **ssh_fields,- },+ payload = {+ "agent_id": "",+ "agent_type": normalized,+ "sandbox_id": "",+ "status": AgentStatus.READY.value,+ **ssh_fields,+ **key_fields,}+ return {"ok": True, "payload": payload}try:runtime = await self._agent_manager.get_or_create_agent(uid,@@ -689,19 +720,63 @@ class AgentOSRouterClient(AgentServerClient):status = info.status.value if hasattr(info.status, "value") else str(info.status)# 记录用户当前 agent_type,后续 SSH 接入默认跟随self._current_agent_types[uid] = normalized- return {- "ok": True,- "payload": {- "agent_id": info.agent_id,- "agent_type": info.agent_type,- "sandbox_id": info.sandbox_id,- "status": status,- **ssh_fields,- },+ payload = {+ "agent_id": info.agent_id,+ "agent_type": info.agent_type,+ "sandbox_id": info.sandbox_id,+ "status": status,+ **ssh_fields,+ **key_fields,}+ return {"ok": True, "payload": payload}++ def _ephemeral_ssh_key_fields(+ self,+ *,+ user_id: str,+ session_id: str,+ ) -> dict[str, Any]:+ """Mint ``ssh_private_key`` when an issuer is configured.++ Returns an empty mapping when no issuer is injected (auth disabled).+ Raises :class:`EphemeralKeyIssueError` when issuance is expected but+ does not yield a usable key.+ """+ issuer = self._key_issuer+ if issuer is None:+ return {}+ try:+ private_key = issuer.issue_ephemeral_key(+ user_id=user_id,+ username=user_id,+ session_id=str(session_id or ""),+ ttl_sec=self._ephemeral_key_ttl_sec,+ )+ except Exception as exc:+ logger.error(+ "[AgentOSRouter] failed to issue ephemeral SSH key: user=%s error=%s",+ user_id,+ exc,+ )+ raise EphemeralKeyIssueError(+ f"failed to issue ephemeral SSH key: {exc}"+ ) from exc+ if not private_key:+ logger.error(+ "[AgentOSRouter] ephemeral SSH key issuer returned an empty key: user=%s",+ user_id,+ )+ raise EphemeralKeyIssueError("ephemeral SSH key issuer returned an empty key")+ return {"ssh_private_key": private_key}async def shutdown(self) -> None:- await self.disconnect()+ try:+ await self.disconnect()+ finally:+ auth_client = self._auth_client+ close = getattr(auth_client, "aclose", None)+ if callable(close):+ await close()# ---------- SSH relay (northbound SshChannel -> YuanRong instance) ----------diff --git a/jiuwenswarm/extensions/agentos/auth/__init__.py b/jiuwenswarm/extensions/agentos/auth/__init__.pyindex 2381bfdc05..34e172ba17 100644--- a/jiuwenswarm/extensions/agentos/auth/__init__.py+++ b/jiuwenswarm/extensions/agentos/auth/__init__.py@@ -7,9 +7,23 @@ from jiuwenswarm.extensions.agentos.auth.credential_authenticator import (AuthResult,CredentialAuthenticator,)+from jiuwenswarm.extensions.agentos.auth.ssh_authenticator import SshPublicKeyAuthenticator+from jiuwenswarm.extensions.agentos.auth.ssh_key_issuer import (+ AgentOSSshKeyIssuer,+ SshKeyIssuer,+)+from jiuwenswarm.extensions.agentos.auth.ssh_key_registry import (+ KeyRegistry,+ KeyRegistryEntry,+)__all__ = ["AuthContext","AuthResult","CredentialAuthenticator",+ "KeyRegistry",+ "KeyRegistryEntry",+ "SshKeyIssuer",+ "AgentOSSshKeyIssuer",+ "SshPublicKeyAuthenticator",]diff --git a/jiuwenswarm/extensions/agentos/auth/ssh_authenticator.py b/jiuwenswarm/extensions/agentos/auth/ssh_authenticator.pynew file mode 100644index 0000000000..aa14ced9f2--- /dev/null+++ b/jiuwenswarm/extensions/agentos/auth/ssh_authenticator.py@@ -0,0 +1,71 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Verify SSH public-key fingerprints via KeyRegistry."""++from __future__ import annotations++from jiuwenswarm.extensions.agentos.auth.credential_authenticator import (+ AuthContext,+ AuthResult,+ CredentialAuthenticator,+)+from jiuwenswarm.extensions.agentos.auth.ssh_key_registry import KeyRegistry, KeyRegistryEntry+++class SshPublicKeyAuthenticator(CredentialAuthenticator):+ """Look up an SSH fingerprint (+ username) and return AuthResult."""++ def __init__(self, registry: KeyRegistry) -> None:+ self._registry = registry++ @property+ def registry(self) -> KeyRegistry:+ return self._registry++ def lookup_entry(self, fingerprint: str) -> KeyRegistryEntry | None:+ return self._registry.lookup(fingerprint)++ def verify(self, *, fingerprint: str, username: str = "") -> AuthResult:+ """Sync verify for SSHServer callbacks that cannot await."""+ fingerprint = str(fingerprint or "").strip()+ username = str(username or "").strip()+ if not fingerprint:+ return AuthResult(+ success=False,+ error="缺少 SSH fingerprint",+ extensions={"error_code": "MISSING_FINGERPRINT"},+ )+ entry = self._registry.lookup(fingerprint)+ if entry is None:+ return AuthResult(+ success=False,+ error="未登记的 SSH 公钥",+ extensions={"error_code": "UNKNOWN_FINGERPRINT"},+ )+ if username and username != entry.username:+ return AuthResult(+ success=False,+ error="SSH username 与登记身份不一致",+ extensions={+ "error_code": "USERNAME_MISMATCH",+ "expected_username": entry.username,+ },+ )+ return AuthResult(+ success=True,+ user_id=entry.user_id,+ extensions={+ "username": entry.username,+ "auth_method": "ssh_public_key",+ "source": entry.source,+ "session_id": entry.session_id,+ "fingerprint": entry.fingerprint,+ },+ )++ async def authenticate(self, context: AuthContext) -> AuthResult:+ credentials = context.credentials or {}+ return self.verify(+ fingerprint=str(credentials.get("fingerprint") or ""),+ username=str(credentials.get("username") or ""),+ )diff --git a/jiuwenswarm/extensions/agentos/auth/ssh_key_issuer.py b/jiuwenswarm/extensions/agentos/auth/ssh_key_issuer.pynew file mode 100644index 0000000000..b9562f0daf--- /dev/null+++ b/jiuwenswarm/extensions/agentos/auth/ssh_key_issuer.py@@ -0,0 +1,92 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Issue short-lived SSH key pairs and register public fingerprints."""++from __future__ import annotations++import logging+import time+from typing import Protocol++from jiuwenswarm.extensions.agentos.auth.ssh_key_registry import (+ KeyRegistry,+ KeyRegistryEntry,+)++logger = logging.getLogger(__name__)+++class SshKeyIssuer(Protocol):+ """Issue short-lived SSH key pairs for TUI / launcher handoff."""++ def issue_ephemeral_key(+ self,+ *,+ user_id: str,+ username: str,+ session_id: str,+ ttl_sec: float,+ ) -> str:+ """Generate a key pair, register the public fingerprint, return private key."""+ ...+++class AgentOSSshKeyIssuer:+ """Generate OpenSSH ephemeral keys and register fingerprints in KeyRegistry."""++ def __init__(+ self,+ registry: KeyRegistry,+ *,+ key_type: str = "ssh-ed25519",+ ) -> None:+ self._registry = registry+ self._key_type = str(key_type or "ssh-ed25519").strip() or "ssh-ed25519"++ @property+ def registry(self) -> KeyRegistry:+ return self._registry++ def issue_ephemeral_key(+ self,+ *,+ user_id: str,+ username: str,+ session_id: str,+ ttl_sec: float,+ ) -> str:+ try:+ import asyncssh+ except ImportError as exc:+ raise RuntimeError(+ "SSH ephemeral key issuance requires optional dependency "+ "`asyncssh>=2.14.0,<2.24`. Install with "+ '`uv sync --extra ssh` / `pip install "jiuwenswarm[ssh]"`.'+ ) from exc++ key = asyncssh.generate_private_key(self._key_type)+ fingerprint = key.get_fingerprint()+ now = time.time()+ ttl = max(0.0, float(ttl_sec))+ self._registry.register(+ KeyRegistryEntry(+ fingerprint=fingerprint,+ user_id=str(user_id or "").strip(),+ username=str(username or user_id or "").strip() or "unknown",+ source="tui_switch",+ session_id=str(session_id or "").strip() or None,+ expires_at=(now + ttl) if ttl > 0 else None,+ created_at=now,+ )+ )+ logger.info(+ "[AgentOSAuth] issued ephemeral SSH key: user_id=%s session=%s ttl=%.0fs fp=%s",+ user_id,+ session_id,+ ttl,+ fingerprint,+ )+ exported = key.export_private_key("openssh")+ if isinstance(exported, bytes):+ return exported.decode("utf-8")+ return str(exported)diff --git a/jiuwenswarm/extensions/agentos/auth/ssh_key_registry.py b/jiuwenswarm/extensions/agentos/auth/ssh_key_registry.pynew file mode 100644index 0000000000..2ba6e6b65b--- /dev/null+++ b/jiuwenswarm/extensions/agentos/auth/ssh_key_registry.py@@ -0,0 +1,57 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""SSH public-key fingerprint registry for AgentOS identity mapping."""++from __future__ import annotations++import time+from dataclasses import dataclass+++@dataclass+class KeyRegistryEntry:+ """Map an SSH public-key fingerprint to a business identity."""++ fingerprint: str+ user_id: str+ username: str+ source: str # "tui_switch" | "container"+ session_id: str | None+ expires_at: float | None+ created_at: float+++class KeyRegistry:+ """In-memory SSH public-key fingerprint -> identity registry."""++ def __init__(self) -> None:+ self._entries: dict[str, KeyRegistryEntry] = {}++ def register(self, entry: KeyRegistryEntry) -> None:+ """Register or overwrite one public-key mapping."""+ self._entries[entry.fingerprint] = entry++ def lookup(self, fingerprint: str) -> KeyRegistryEntry | None:+ """Look up by fingerprint; drop and return None when expired."""+ entry = self._entries.get(fingerprint)+ if entry is None:+ return None+ if self._is_expired(entry):+ self._entries.pop(fingerprint, None)+ return None+ return entry++ def revoke(self, fingerprint: str) -> bool:+ """Revoke one registration. Return True when an entry was removed."""+ return self._entries.pop(fingerprint, None) is not None++ def cleanup_expired(self) -> int:+ """Remove expired entries. Return the number removed."""+ expired_fps = [fp for fp, e in self._entries.items() if self._is_expired(e)]+ for fp in expired_fps:+ self._entries.pop(fp, None)+ return len(expired_fps)++ @staticmethod+ def _is_expired(entry: KeyRegistryEntry) -> bool:+ return entry.expires_at is not None and time.time() >= entry.expires_atdiff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.pyindex 9c40fdd612..2bfeb8bb18 100644--- a/jiuwenswarm/gateway/app_gateway.py+++ b/jiuwenswarm/gateway/app_gateway.py@@ -1123,7 +1123,7 @@ class GatewayServer(BaseWebChannel):matched_path,)- # 触发连接钩子(如发送 connection.ack)+ # 触发连接钩子(GatewayServer 自身 + 外部 ws_channel,如 TuiChannel 鉴权)for hook in self._connect_hooks:try:result = hook(ws)@@ -1138,6 +1138,23 @@ class GatewayServer(BaseWebChannel):describe_ws_exception(e),),)+ ws_channel = getattr(route, "ws_channel", None)+ if ws_channel is not None:+ for hook in getattr(ws_channel, "_connect_hooks", []):+ try:+ result = hook(ws)+ if inspect.isawaitable(result):+ await result+ except Exception as e:+ logger.warning(+ "%s on_connect hook error: %s",+ type(ws_channel).__name__,+ format_ws_diagnostics(+ {"remote": remote, "path": request_path},+ describe_ws_peer(ws),+ describe_ws_exception(e),+ ),+ )# 上报连接事件if route.ws_channel is not None:@@ -1604,6 +1621,7 @@ async def _run_with_telemetry(SlackChannelConfigfrom jiuwenswarm.gateway.channel_manager.im_platforms.wecom.wecom_connect import WecomChannel, WecomConfigfrom jiuwenswarm.gateway.channel_manager.protocol.ssh.ssh_connect import SshChannel, SshChannelConfig+ from jiuwenswarm.extensions.agentos.auth.ssh_key_registry import KeyRegistryfrom jiuwenswarm.common.config import get_configfrom jiuwenswarm.common.cleanup import start_background_cleanupfrom jiuwenswarm.extensions.redis import init_gateway_redis_from_config@@ -2258,6 +2276,20 @@ async def _run_with_telemetry(ssh_channel = Nonessh_task = None+ def _set_agentos_ssh_key_issuer(+ issuer,+ *,+ ephemeral_key_ttl_sec: float = 300.0,+ ) -> None:+ """Inject/clear SshChannel as ephemeral key issuer on AgentOSRouter extension."""+ setter = getattr(agent_server_ext, "set_key_issuer", None)+ if not callable(setter):+ return+ try:+ setter(issuer, ephemeral_key_ttl_sec=ephemeral_key_ttl_sec)+ except Exception as exc: # noqa: BLE001+ logger.warning("[App] failed to set AgentOS SSH key issuer: %s", exc)+_last_channels_conf: dict = {}def _should_restart_channel(channel_name: str, old_conf: dict, new_conf: dict) -> bool:@@ -2809,6 +2841,8 @@ async def _run_with_telemetry(ssh_conf = conf.get("ssh") if isinstance(conf, dict) else Noneawait _stop_channel(ssh_channel, ssh_task, "ssh")ssh_channel, ssh_task = None, None+ # Clear issuer whenever SSH channel is torn down / reconfigured.+ _set_agentos_ssh_key_issuer(None)if isinstance(ssh_conf, dict):# 南向经 agent client(如 agentos_router -> yuanrong)动态解析。@@ -2833,7 +2867,11 @@ async def _run_with_telemetry()else:ssh_config = SshChannelConfig.from_dict({**ssh_conf, "enabled": True})- ssh_channel = SshChannel(ssh_config, _DummyBus())+ ssh_channel = SshChannel(+ ssh_config,+ _DummyBus(),+ key_registry=KeyRegistry(),+ )channel_manager.register_channel(ssh_channel)ssh_task = asyncio.create_task(ssh_channel.start(), name="ssh")@@ -2851,11 +2889,17 @@ async def _run_with_telemetry()ssh_task.add_done_callback(_on_ssh_task_done)+ if ssh_config.auth.enabled:+ _set_agentos_ssh_key_issuer(+ ssh_channel.key_issuer,+ ephemeral_key_ttl_sec=ssh_config.auth.ephemeral_key_ttl_sec,+ )logger.info("[App] SshChannel registered from config.yaml.channels.ssh "- "(listen %s:%s -> MessageHandler; southbound via agent client)",+ "(listen %s:%s -> MessageHandler; southbound via agent client; auth=%s)",ssh_config.listen_host,ssh_config.listen_port,+ ssh_config.auth.enabled,)else:logger.info("[App] channels.ssh missing or invalid, SshChannel disabled")@@ -3092,6 +3136,7 @@ async def _run_with_telemetry(except asyncio.CancelledError:passawait ssh_channel.stop()+ _set_agentos_ssh_key_issuer(None)await cron_registry.stop_all()await channel_manager.stop_dispatch()diff --git a/jiuwenswarm/gateway/channel_manager/protocol/ssh/__init__.py b/jiuwenswarm/gateway/channel_manager/protocol/ssh/__init__.pyindex a3ff8c6ce5..e6d2c63b5a 100644--- a/jiuwenswarm/gateway/channel_manager/protocol/ssh/__init__.py+++ b/jiuwenswarm/gateway/channel_manager/protocol/ssh/__init__.py@@ -6,18 +6,24 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING-__all__ = ["SshChannel", "SshChannelConfig"]+__all__ = ["SshChannel", "SshChannelConfig", "SshAuthConfig", "KeyRegistry"]if TYPE_CHECKING:+ from jiuwenswarm.extensions.agentos.auth.ssh_key_registry import KeyRegistryfrom jiuwenswarm.gateway.channel_manager.protocol.ssh.ssh_connect import (+ SshAuthConfig,SshChannel,SshChannelConfig,)def __getattr__(name: str):- if name in __all__:+ if name in {"SshChannel", "SshChannelConfig", "SshAuthConfig"}:from jiuwenswarm.gateway.channel_manager.protocol.ssh import ssh_connectreturn getattr(ssh_connect, name)+ if name == "KeyRegistry":+ from jiuwenswarm.extensions.agentos.auth.ssh_key_registry import KeyRegistry++ return KeyRegistryraise AttributeError(f"module {__name__!r} has no attribute {name!r}")diff --git a/jiuwenswarm/gateway/channel_manager/protocol/ssh/key_registry.py b/jiuwenswarm/gateway/channel_manager/protocol/ssh/key_registry.pynew file mode 100644index 0000000000..bf0979cf02--- /dev/null+++ b/jiuwenswarm/gateway/channel_manager/protocol/ssh/key_registry.py@@ -0,0 +1,13 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Compatibility re-exports for AgentOS SSH key registry types."""++from __future__ import annotations++from jiuwenswarm.extensions.agentos.auth.ssh_key_issuer import SshKeyIssuer+from jiuwenswarm.extensions.agentos.auth.ssh_key_registry import (+ KeyRegistry,+ KeyRegistryEntry,+)++__all__ = ["KeyRegistry", "KeyRegistryEntry", "SshKeyIssuer"]diff --git a/jiuwenswarm/gateway/channel_manager/protocol/ssh/server.py b/jiuwenswarm/gateway/channel_manager/protocol/ssh/server.pyindex 611e781f2a..92c545eebe 100644--- a/jiuwenswarm/gateway/channel_manager/protocol/ssh/server.py+++ b/jiuwenswarm/gateway/channel_manager/protocol/ssh/server.py@@ -10,6 +10,11 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Awaitable, Callable+from jiuwenswarm.extensions.agentos.auth.ssh_authenticator import SshPublicKeyAuthenticator+from jiuwenswarm.extensions.agentos.auth.ssh_key_registry import (+ KeyRegistry,+ KeyRegistryEntry,+)from jiuwenswarm.gateway.channel_manager.protocol.ssh.config import ProxyConfiglogger = logging.getLogger(__name__)@@ -40,38 +45,97 @@ class SSHAgentHooks:class ProxySSHServer(asyncssh.SSHServer if ASYNCSSH_AVAILABLE else object): # type: ignore[misc]- def __init__(self, config: ProxyConfig) -> None:+ def __init__(+ self,+ config: ProxyConfig,+ key_registry: KeyRegistry | None = None,+ authenticator: SshPublicKeyAuthenticator | None = None,+ auth_enabled: bool = False,+ ) -> None:self.config = config+ self.key_registry = key_registry+ if authenticator is not None:+ self.authenticator = authenticator+ elif key_registry is not None:+ self.authenticator = SshPublicKeyAuthenticator(key_registry)+ else:+ self.authenticator = None+ self.auth_enabled = auth_enabledself.client_username: str | None = None+ self.authenticated_entry: KeyRegistryEntry | None = Nonedef connection_made(self, conn: Any) -> None:conn.set_extra_info(proxy_auth=self)def begin_auth(self, username: str) -> bool:self.client_username = username+ self.authenticated_entry = Nonereturn Truedef password_auth_supported(self) -> bool:- return True+ # When auth is enabled, force public-key auth only.+ return not self.auth_enableddef public_key_auth_supported(self) -> bool:return Truedef validate_public_key(self, username: str, key: Any) -> bool:- del keyself.client_username = username+ self.authenticated_entry = None+ if not self.auth_enabled or self.authenticator is None:+ # Auth disabled: keep permissive behaviour (backward compatible).+ return True+ fingerprint = key.get_fingerprint()+ result = self.authenticator.verify(fingerprint=fingerprint, username=username)+ if not result.success:+ logger.warning(+ "[SSHChannel] public key rejected: fingerprint=%s username=%s error=%s",+ fingerprint,+ username,+ result.error,+ )+ return False+ entry = self.authenticator.lookup_entry(fingerprint)+ if entry is None:+ return False+ self.authenticated_entry = entry+ logger.info(+ "[SSHChannel] public key accepted: user_id=%s username=%s source=%s",+ entry.user_id,+ entry.username,+ entry.source,+ )return Truedef validate_password(self, username: str, password: str) -> bool:- del passwordself.client_username = username- return True+ if not self.auth_enabled:+ # Auth disabled: keep permissive behaviour (backward compatible).+ return True+ # Should not be reached when password_auth_supported returns False.+ del password+ return Falseclass SSHProxy:- def __init__(self, config: ProxyConfig, agent_hooks: SSHAgentHooks | None = None) -> None:+ def __init__(+ self,+ config: ProxyConfig,+ agent_hooks: SSHAgentHooks | None = None,+ key_registry: KeyRegistry | None = None,+ authenticator: SshPublicKeyAuthenticator | None = None,+ auth_enabled: bool = False,+ ) -> None:self.config = configself.agent_hooks = agent_hooks+ self.key_registry = key_registry+ if authenticator is not None:+ self.authenticator = authenticator+ elif key_registry is not None:+ self.authenticator = SshPublicKeyAuthenticator(key_registry)+ else:+ self.authenticator = None+ self.auth_enabled = auth_enabledself._server: Any = Noneasync def start(self) -> None:@@ -84,7 +148,12 @@ class SSHProxy:host_key = await self._ensure_host_key(self.config.host_key_path)self._server = await asyncssh.create_server(- lambda: ProxySSHServer(self.config),+ lambda: ProxySSHServer(+ self.config,+ key_registry=self.key_registry,+ authenticator=self.authenticator,+ auth_enabled=self.auth_enabled,+ ),self.config.listen_host,self.config.listen_port,server_host_keys=[host_key],@@ -145,7 +214,17 @@ class SSHProxy:returnclient_addr = self._client_addr(process)- username = process.get_extra_info("username") or server.client_username or "unknown"++ # Prefer identity from successful public-key registry lookup.+ if server.authenticated_entry is not None:+ user_id = server.authenticated_entry.user_id+ username = server.authenticated_entry.username+ source = server.authenticated_entry.source+ else:+ # Auth disabled (backward compatible).+ user_id = process.get_extra_info("username") or server.client_username or "unknown"+ username = user_id+ source = "none"subsystem = process.subsystemif subsystem:@@ -164,8 +243,10 @@ class SSHProxy:session_id = f"ssh_{uuid.uuid4().hex[:12]}"metadata: dict[str, Any] = {"username": username,+ "user_id": user_id,"client_addr": client_addr,"ssh_session_id": session_id,+ "auth_source": source,**({"command": command} if command else {}),}diff --git a/jiuwenswarm/gateway/channel_manager/protocol/ssh/ssh_connect.py b/jiuwenswarm/gateway/channel_manager/protocol/ssh/ssh_connect.pyindex d123488608..2b496ef7e4 100644--- a/jiuwenswarm/gateway/channel_manager/protocol/ssh/ssh_connect.py+++ b/jiuwenswarm/gateway/channel_manager/protocol/ssh/ssh_connect.py@@ -17,6 +17,9 @@ from typing import Any, Callablefrom jiuwenswarm.common.schema.message import Message, ReqMethodfrom jiuwenswarm.gateway.channel_manager.base import BaseChannel, RobotMessageRouter+from jiuwenswarm.extensions.agentos.auth.ssh_authenticator import SshPublicKeyAuthenticator+from jiuwenswarm.extensions.agentos.auth.ssh_key_issuer import AgentOSSshKeyIssuer, SshKeyIssuer+from jiuwenswarm.extensions.agentos.auth.ssh_key_registry import KeyRegistryfrom jiuwenswarm.gateway.channel_manager.protocol.ssh.config import proxy_config_from_dictfrom jiuwenswarm.gateway.channel_manager.protocol.ssh.server import SSHAgentHooks, SSHProxy@@ -48,6 +51,25 @@ class SshRelaySession:return True+@dataclass+class SshAuthConfig:+ """SSH Channel public-key authentication settings."""++ enabled: bool = False+ ephemeral_key_ttl_sec: float = 300.0+ ephemeral_key_type: str = "ssh-ed25519"+ cleanup_interval_sec: float = 60.0++ @classmethod+ def from_dict(cls, conf: dict[str, Any]) -> "SshAuthConfig":+ return cls(+ enabled=bool(conf.get("enabled", False)),+ ephemeral_key_ttl_sec=float(conf.get("ephemeral_key_ttl_sec", 300.0)),+ ephemeral_key_type=str(conf.get("ephemeral_key_type") or "ssh-ed25519"),+ cleanup_interval_sec=float(conf.get("cleanup_interval_sec", 60.0)),+ )++@dataclassclass SshChannelConfig:"""SSH server channel configuration."""@@ -57,6 +79,7 @@ class SshChannelConfig:listen_port: int = 2222host_key_path: str = ""relay_timeout_sec: float = 3600.0+ auth: SshAuthConfig = field(default_factory=SshAuthConfig)def to_proxy_config(self):raw = {@@ -68,12 +91,14 @@ class SshChannelConfig:@classmethoddef from_dict(cls, conf: dict[str, Any]) -> "SshChannelConfig":+ auth_raw = conf.get("auth")return cls(enabled=bool(conf.get("enabled", False)),listen_host=str(conf.get("listen_host", "0.0.0.0")),listen_port=int(conf.get("listen_port", 2222)),host_key_path=str(conf.get("host_key_path") or ""),relay_timeout_sec=float(conf.get("relay_timeout_sec", 3600.0)),+ auth=SshAuthConfig.from_dict(auth_raw if isinstance(auth_raw, dict) else {}),)@@ -91,13 +116,26 @@ class SshChannel(BaseChannel):name = "ssh"- def __init__(self, config: SshChannelConfig, router: RobotMessageRouter):+ def __init__(+ self,+ config: SshChannelConfig,+ router: RobotMessageRouter,+ key_registry: KeyRegistry | None = None,+ ):super().__init__(config, router)self.config: SshChannelConfig = configself._proxy: SSHProxy | None = Noneself._running = Falseself._on_message_cb: Callable[[Message], Any] | None = Noneself._sessions: dict[str, _SshSession] = {}+ self._key_registry = key_registry or KeyRegistry()+ self._authenticator = SshPublicKeyAuthenticator(self._key_registry)+ self._key_issuer = AgentOSSshKeyIssuer(+ self._key_registry,+ key_type=str(config.auth.ephemeral_key_type or "ssh-ed25519"),+ )+ self._auth_enabled = bool(config.auth.enabled)+ self._cleanup_task: asyncio.Task[Any] | None = None@propertydef channel_id(self) -> str:@@ -107,6 +145,18 @@ class SshChannel(BaseChannel):def clients(self) -> set[Any]:return set(self._sessions.keys())+ @property+ def key_registry(self) -> KeyRegistry:+ return self._key_registry++ @property+ def authenticator(self) -> SshPublicKeyAuthenticator:+ return self._authenticator++ @property+ def key_issuer(self) -> SshKeyIssuer:+ return self._key_issuer+def on_message(self, callback: Callable[[Message], None]) -> None:self._on_message_cb = callback@@ -118,24 +168,72 @@ class SshChannel(BaseChannel):returnhooks = self._build_agent_hooks()- self._proxy = SSHProxy(self.config.to_proxy_config(), agent_hooks=hooks)+ self._proxy = SSHProxy(+ self.config.to_proxy_config(),+ agent_hooks=hooks,+ key_registry=self._key_registry,+ authenticator=self._authenticator,+ auth_enabled=self._auth_enabled,+ )await self._proxy.start()self._running = True+ if self._auth_enabled:+ self._cleanup_task = asyncio.create_task(+ self._cleanup_loop(),+ name="ssh-key-cleanup",+ )logger.info("[SSHChannel] started (listen %s:%s -> MessageHandler; "- "southbound relay via agent client)",+ "southbound relay via agent client; auth=%s)",self.config.listen_host,self.config.listen_port,+ self._auth_enabled,)await self._proxy.wait_closed()async def stop(self) -> None:self._running = False+ cleanup = self._cleanup_task+ self._cleanup_task = None+ if cleanup is not None and not cleanup.done():+ cleanup.cancel()+ try:+ await cleanup+ except asyncio.CancelledError:+ passself._sessions.clear()if self._proxy is not None:await self._proxy.stop()self._proxy = None+ def issue_ephemeral_key(+ self,+ *,+ user_id: str,+ username: str,+ session_id: str,+ ttl_sec: float,+ ) -> str:+ """Delegate to AgentOS SSH key issuer (generate + register fingerprint)."""+ return self._key_issuer.issue_ephemeral_key(+ user_id=user_id,+ username=username,+ session_id=session_id,+ ttl_sec=ttl_sec,+ )++ async def _cleanup_loop(self) -> None:+ """Periodically drop expired ephemeral key registrations."""+ interval = max(1.0, float(self.config.auth.cleanup_interval_sec))+ while self._running:+ await asyncio.sleep(interval)+ removed = self._key_registry.cleanup_expired()+ if removed:+ logger.debug(+ "[SSHChannel] cleaned up %d expired key entries",+ removed,+ )+def _build_agent_hooks(self) -> SSHAgentHooks:return SSHAgentHooks(register_session=self._register_session,@@ -226,6 +324,7 @@ class SshChannel(BaseChannel):returnusername = str(metadata.get("username") or "").strip() or "unknown"+ user_id = str(metadata.get("user_id") or "").strip() or username# ``relay_session`` (with live ``process``) is handed to the# southbound AgentOS router in-process; it is never serialized.params: dict[str, Any] = {@@ -240,7 +339,7 @@ class SshChannel(BaseChannel):type="req",channel_id=self.channel_id,session_id=session_id,- user_id=username,+ user_id=user_id,params=params,timestamp=time.time(),ok=True,diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yamlindex 104a67531e..9e5a77810d 100644--- a/jiuwenswarm/resources/config.yaml+++ b/jiuwenswarm/resources/config.yaml@@ -1212,6 +1212,15 @@ channels:listen_port: 2222host_key_path: ~/.jiuwenswarm/config/ssh_host_keyrelay_timeout_sec: 3600+ auth:+ # 公钥认证开关。false 时保持宽松认证(向后兼容)。+ enabled: false+ # TUI 场景: 临时密钥有效期(秒)+ ephemeral_key_ttl_sec: 300+ # 临时密钥类型+ ephemeral_key_type: "ssh-ed25519"+ # 过期清理间隔(秒)+ cleanup_interval_sec: 60# ========== 细粒度权限管控(tiered_policy)==========#diff --git a/tests/auth/test_ssh_authenticator.py b/tests/auth/test_ssh_authenticator.pynew file mode 100644index 0000000000..992ba4609a--- /dev/null+++ b/tests/auth/test_ssh_authenticator.py@@ -0,0 +1,101 @@+"""SSH public-key authenticator and key issuer."""++from __future__ import annotations++import time++import pytest++from jiuwenswarm.extensions.agentos.auth.credential_authenticator import (+ AuthContext,+ AuthResult,+ CredentialAuthenticator,+)+from jiuwenswarm.extensions.agentos.auth.ssh_authenticator import SshPublicKeyAuthenticator+from jiuwenswarm.extensions.agentos.auth.ssh_key_issuer import AgentOSSshKeyIssuer+from jiuwenswarm.extensions.agentos.auth.ssh_key_registry import (+ KeyRegistry,+ KeyRegistryEntry,+)+++def _register(registry: KeyRegistry, *, fingerprint: str, user_id: str, username: str) -> None:+ now = time.time()+ registry.register(+ KeyRegistryEntry(+ fingerprint=fingerprint,+ user_id=user_id,+ username=username,+ source="tui_switch",+ session_id="sess-1",+ expires_at=now + 60,+ created_at=now,+ )+ )+++def test_ssh_authenticator_is_credential_authenticator():+ auth = SshPublicKeyAuthenticator(KeyRegistry())+ assert isinstance(auth, CredentialAuthenticator)+++def test_verify_accepts_registered_fingerprint_and_username():+ registry = KeyRegistry()+ _register(registry, fingerprint="SHA256:ok", user_id="u1", username="u1")+ auth = SshPublicKeyAuthenticator(registry)+ result = auth.verify(fingerprint="SHA256:ok", username="u1")+ assert result.success is True+ assert result.user_id == "u1"+ assert result.extensions["username"] == "u1"+ assert result.extensions["auth_method"] == "ssh_public_key"+++def test_verify_rejects_unknown_fingerprint():+ auth = SshPublicKeyAuthenticator(KeyRegistry())+ result = auth.verify(fingerprint="SHA256:missing", username="u1")+ assert result.success is False+ assert result.extensions["error_code"] == "UNKNOWN_FINGERPRINT"+++def test_verify_rejects_username_mismatch():+ registry = KeyRegistry()+ _register(registry, fingerprint="SHA256:ok", user_id="u1", username="u1")+ auth = SshPublicKeyAuthenticator(registry)+ result = auth.verify(fingerprint="SHA256:ok", username="other")+ assert result.success is False+ assert result.extensions["error_code"] == "USERNAME_MISMATCH"+++async def test_authenticate_uses_context_credentials():+ registry = KeyRegistry()+ _register(registry, fingerprint="SHA256:ok", user_id="u1", username="u1")+ auth = SshPublicKeyAuthenticator(registry)+ result = await auth.authenticate(+ AuthContext(+ channel_type="ssh",+ credentials={"fingerprint": "SHA256:ok", "username": "u1"},+ )+ )+ assert isinstance(result, AuthResult)+ assert result.success is True+ assert result.user_id == "u1"+++def test_issue_ephemeral_key_registers_fingerprint_for_authenticator():+ asyncssh = pytest.importorskip("asyncssh")+ registry = KeyRegistry()+ issuer = AgentOSSshKeyIssuer(registry)+ private_key = issuer.issue_ephemeral_key(+ user_id="u1",+ username="u1",+ session_id="sess-9",+ ttl_sec=120,+ )+ assert "BEGIN OPENSSH PRIVATE KEY" in private_key+ loaded = asyncssh.import_private_key(private_key.encode("utf-8"))+ fingerprint = loaded.get_fingerprint()+ auth = SshPublicKeyAuthenticator(registry)+ result = auth.verify(fingerprint=fingerprint, username="u1")+ assert result.success is True+ assert result.user_id == "u1"diff --git a/tests/unit_tests/channel/test_ssh_channel.py b/tests/unit_tests/channel/test_ssh_channel.pyindex a895bc3f82..bf6698d373 100644--- a/tests/unit_tests/channel/test_ssh_channel.py+++ b/tests/unit_tests/channel/test_ssh_channel.py@@ -1,7 +1,23 @@# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+from __future__ import annotations++import time+from types import SimpleNamespace++import pytest+from jiuwenswarm.gateway.channel_manager.protocol.ssh.config import proxy_config_from_dict-from jiuwenswarm.gateway.channel_manager.protocol.ssh.ssh_connect import SshChannelConfig+from jiuwenswarm.extensions.agentos.auth.ssh_key_registry import (+ KeyRegistry,+ KeyRegistryEntry,+)+from jiuwenswarm.gateway.channel_manager.protocol.ssh.server import ProxySSHServer, SSHProxy+from jiuwenswarm.gateway.channel_manager.protocol.ssh.ssh_connect import (+ SshAuthConfig,+ SshChannel,+ SshChannelConfig,+)def test_ssh_channel_config_from_dict():@@ -15,12 +31,312 @@ def test_ssh_channel_config_from_dict():assert cfg.enabled is Trueassert cfg.listen_port == 3333assert cfg.relay_timeout_sec == 120.0+ assert cfg.auth.enabled is False+ assert cfg.auth.ephemeral_key_ttl_sec == 300.0proxy = cfg.to_proxy_config()assert proxy.listen_host == "127.0.0.1"assert proxy.listen_port == 3333+def test_ssh_channel_config_parses_auth_block():+ cfg = SshChannelConfig.from_dict(+ {+ "enabled": True,+ "auth": {+ "enabled": True,+ "ephemeral_key_ttl_sec": 120,+ "ephemeral_key_type": "ssh-ed25519",+ "cleanup_interval_sec": 30,+ },+ }+ )+ assert cfg.auth.enabled is True+ assert cfg.auth.ephemeral_key_ttl_sec == 120.0+ assert cfg.auth.ephemeral_key_type == "ssh-ed25519"+ assert cfg.auth.cleanup_interval_sec == 30.0++def test_proxy_config_from_dict_sets_default_host_key_path():proxy = proxy_config_from_dict({"listen_port": 2222})assert proxy.host_key_path.endswith("ssh_host_key")+++def test_key_registry_lookup_and_expiry():+ registry = KeyRegistry()+ now = time.time()+ registry.register(+ KeyRegistryEntry(+ fingerprint="SHA256:alive",+ user_id="u1",+ username="u1",+ source="tui_switch",+ session_id="sess-1",+ expires_at=now + 60,+ created_at=now,+ )+ )+ registry.register(+ KeyRegistryEntry(+ fingerprint="SHA256:expired",+ user_id="u2",+ username="u2",+ source="tui_switch",+ session_id="sess-2",+ expires_at=now - 1,+ created_at=now - 10,+ )+ )++ alive = registry.lookup("SHA256:alive")+ assert alive is not None+ assert alive.user_id == "u1"+ assert registry.lookup("SHA256:expired") is None+ assert registry.lookup("SHA256:missing") is None+++def test_key_registry_cleanup_expired():+ registry = KeyRegistry()+ now = time.time()+ registry.register(+ KeyRegistryEntry(+ fingerprint="SHA256:keep",+ user_id="u1",+ username="u1",+ source="tui_switch",+ session_id=None,+ expires_at=None,+ created_at=now,+ )+ )+ registry.register(+ KeyRegistryEntry(+ fingerprint="SHA256:drop",+ user_id="u2",+ username="u2",+ source="tui_switch",+ session_id="s",+ expires_at=now - 5,+ created_at=now - 10,+ )+ )+ assert registry.cleanup_expired() == 1+ assert registry.lookup("SHA256:keep") is not None+ assert registry.lookup("SHA256:drop") is None+++def test_proxy_auth_disabled_accepts_any_key_and_password():+ server = ProxySSHServer(+ proxy_config_from_dict({}),+ key_registry=KeyRegistry(),+ auth_enabled=False,+ )+ key = SimpleNamespace(get_fingerprint=lambda: "SHA256:anything")+ assert server.password_auth_supported() is True+ assert server.validate_public_key("alice", key) is True+ assert server.validate_password("alice", "secret") is True+ assert server.authenticated_entry is None+++def test_proxy_auth_enabled_rejects_unregistered_key():+ registry = KeyRegistry()+ server = ProxySSHServer(+ proxy_config_from_dict({}),+ key_registry=registry,+ auth_enabled=True,+ )+ key = SimpleNamespace(get_fingerprint=lambda: "SHA256:unknown")+ assert server.password_auth_supported() is False+ assert server.validate_public_key("alice", key) is False+ assert server.validate_password("alice", "secret") is False+ assert server.authenticated_entry is None+++def test_proxy_auth_enabled_accepts_registered_key():+ registry = KeyRegistry()+ now = time.time()+ registry.register(+ KeyRegistryEntry(+ fingerprint="SHA256:ok",+ user_id="user-42",+ username="user-42",+ source="tui_switch",+ session_id="sess-1",+ expires_at=now + 60,+ created_at=now,+ )+ )+ server = ProxySSHServer(+ proxy_config_from_dict({}),+ key_registry=registry,+ auth_enabled=True,+ )+ key = SimpleNamespace(get_fingerprint=lambda: "SHA256:ok")+ assert server.validate_public_key("user-42", key) is True+ assert server.authenticated_entry is not None+ assert server.authenticated_entry.user_id == "user-42"+++def test_proxy_auth_enabled_rejects_registered_key_for_different_username():+ registry = KeyRegistry()+ now = time.time()+ registry.register(+ KeyRegistryEntry(+ fingerprint="SHA256:ok",+ user_id="user-a",+ username="user-a",+ source="tui_switch",+ session_id="sess-1",+ expires_at=now + 60,+ created_at=now,+ )+ )+ server = ProxySSHServer(+ proxy_config_from_dict({}),+ key_registry=registry,+ auth_enabled=True,+ )+ key = SimpleNamespace(get_fingerprint=lambda: "SHA256:ok")++ assert server.validate_public_key("user-b", key) is False+ assert server.authenticated_entry is None+++async def test_handle_ssh_client_uses_authenticated_identity(monkeypatch):+ asyncssh = pytest.importorskip("asyncssh")++ registry = KeyRegistry()+ now = time.time()+ registry.register(+ KeyRegistryEntry(+ fingerprint="SHA256:ok",+ user_id="auth-user",+ username="auth-user",+ source="tui_switch",+ session_id="sess-1",+ expires_at=now + 60,+ created_at=now,+ )+ )+ proxy_server = ProxySSHServer(+ proxy_config_from_dict({}),+ key_registry=registry,+ auth_enabled=True,+ )+ key = SimpleNamespace(get_fingerprint=lambda: "SHA256:ok")+ assert proxy_server.validate_public_key("auth-user", key) is True++ captured: dict = {}++ async def register_session(**kwargs):+ captured["register"] = kwargs++ async def submit_relay(session_id, metadata):+ captured["session_id"] = session_id+ captured["metadata"] = metadata++ async def wait_relay_done(session_id):+ del session_id+ return 0++ async def unregister_session(session_id):+ captured["unregistered"] = session_id++ hooks = SimpleNamespace(+ register_session=register_session,+ submit_relay=submit_relay,+ wait_relay_done=wait_relay_done,+ unregister_session=unregister_session,+ )+ proxy = SSHProxy(+ proxy_config_from_dict({}),+ agent_hooks=hooks,+ key_registry=registry,+ auth_enabled=True,+ )++ conn = SimpleNamespace(get_extra_info=lambda name: proxy_server if name == "proxy_auth" else None)+ channel = SimpleNamespace(get_connection=lambda: conn)+ process = SimpleNamespace(+ channel=channel,+ get_extra_info=lambda name: "ssh-name" if name == "username" else None,+ subsystem=None,+ command=None,+ stdout=SimpleNamespace(write=lambda data: None),+ exit=lambda code: None,+ )++ # Avoid depending on asyncssh.Error path; keep exception type available.+ monkeypatch.setattr(+ "jiuwenswarm.gateway.channel_manager.protocol.ssh.server.asyncssh",+ asyncssh,+ raising=False,+ )+ await proxy._handle_ssh_client(process)++ assert captured["metadata"]["user_id"] == "auth-user"+ assert captured["metadata"]["username"] == "auth-user"+ assert captured["metadata"]["auth_source"] == "tui_switch"+ assert captured["register"]["username"] == "auth-user"+++def test_issue_ephemeral_key_registers_fingerprint():+ asyncssh = pytest.importorskip("asyncssh")++ channel = SshChannel(+ SshChannelConfig(+ enabled=True,+ auth=SshAuthConfig(enabled=True, ephemeral_key_ttl_sec=120),+ ),+ router=SimpleNamespace(),+ key_registry=KeyRegistry(),+ )+ private_key = channel.issue_ephemeral_key(+ user_id="u1",+ username="u1",+ session_id="sess-9",+ ttl_sec=120,+ )+ assert "BEGIN OPENSSH PRIVATE KEY" in private_key+ assert "END OPENSSH PRIVATE KEY" in private_key++ loaded = asyncssh.import_private_key(private_key.encode("utf-8"))+ fingerprint = loaded.get_fingerprint()+ entry = channel.key_registry.lookup(fingerprint)+ assert entry is not None+ assert entry.user_id == "u1"+ assert entry.source == "tui_switch"+ assert entry.session_id == "sess-9"+++async def test_submit_relay_uses_metadata_user_id():+ channel = SshChannel(+ SshChannelConfig(enabled=True),+ router=SimpleNamespace(),+ key_registry=KeyRegistry(),+ )+ process = SimpleNamespace(stdout=SimpleNamespace(write=lambda data: None))+ await channel._register_session(+ session_id="ssh_abc",+ process=process,+ username="auth-user",+ client_addr="127.0.0.1:1",+ )+ seen: list = []++ def on_message(msg):+ seen.append(msg)++ channel.on_message(on_message)+ await channel._submit_relay(+ "ssh_abc",+ {+ "username": "auth-user",+ "user_id": "auth-user",+ "auth_source": "tui_switch",+ },+ )+ assert len(seen) == 1+ assert seen[0].user_id == "auth-user"diff --git a/tests/unit_tests/extensions/test_agentos_router.py b/tests/unit_tests/extensions/test_agentos_router.pyindex de50ee9741..cc651dbedb 100644--- a/tests/unit_tests/extensions/test_agentos_router.py+++ b/tests/unit_tests/extensions/test_agentos_router.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport asynciofrom collections.abc import AsyncIteratorfrom pathlib import Path+from types import SimpleNamespacefrom typing import Anyimport pytest@@ -612,6 +613,110 @@ async def test_switch_to_jiuwenswarm_is_direct_without_create() -> None:assert response["payload"]["ssh_port"] == 2222assert client.get_current_agent_type("u1") == "jiuwenswarm"assert await agent_manager.list_user_agents("u1") == []+ assert "ssh_private_key" not in response["payload"]+++async def test_agent_switch_includes_ephemeral_ssh_private_key_when_issuer_set() -> None:+ yuanrong = FakeYuanRongClient()+ agent_manager = AgentManager()+ client = AgentOSRouterClient(+ yuanrong, FakeRegistryClient(), agent_manager, ssh_channel_endpoint=_ssh_channel()+ )++ class _Issuer:+ def issue_ephemeral_key(self, *, user_id, username, session_id, ttl_sec):+ assert user_id == "u1"+ assert username == "u1"+ assert session_id == "sess-1"+ assert ttl_sec == 120.0+ return "-----BEGIN OPENSSH PRIVATE KEY-----\nTEST\n-----END OPENSSH PRIVATE KEY-----\n"++ client.set_key_issuer(_Issuer(), ephemeral_key_ttl_sec=120.0)+ response = await client.thirdagent_switch(+ user_id="u1",+ agent_type="opencode",+ session_id="sess-1",+ )+ await client.shutdown()++ assert response["ok"] is True+ assert response["payload"]["ssh_private_key"].startswith("-----BEGIN OPENSSH PRIVATE KEY-----")+++async def test_agent_switch_fails_when_key_issuance_raises() -> None:+ yuanrong = FakeYuanRongClient()+ agent_manager = AgentManager()+ client = AgentOSRouterClient(+ yuanrong, FakeRegistryClient(), agent_manager, ssh_channel_endpoint=_ssh_channel()+ )++ class _BrokenIssuer:+ def issue_ephemeral_key(self, *, user_id, username, session_id, ttl_sec):+ raise RuntimeError("asyncssh missing")++ client.set_key_issuer(_BrokenIssuer(), ephemeral_key_ttl_sec=120.0)+ response = await client.thirdagent_switch(+ user_id="u1",+ agent_type="opencode",+ session_id="sess-1",+ )+ await client.shutdown()++ assert response["ok"] is False+ assert response["code"] == "SSH_KEY_ISSUE_FAILED"+ assert "asyncssh missing" in response["error"]+ # Fail fast: no sandbox is created for an unusable switch.+ assert yuanrong.create_calls == 0+++async def test_agent_switch_fails_when_issuer_returns_empty_key() -> None:+ yuanrong = FakeYuanRongClient()+ agent_manager = AgentManager()+ client = AgentOSRouterClient(+ yuanrong, FakeRegistryClient(), agent_manager, ssh_channel_endpoint=_ssh_channel()+ )+ client.set_key_issuer(+ SimpleNamespace(issue_ephemeral_key=lambda **kwargs: ""),+ ephemeral_key_ttl_sec=120.0,+ )++ response = await client.thirdagent_switch(+ user_id="u1",+ agent_type="jiuwenswarm",+ session_id="sess-1",+ )+ await client.shutdown()++ assert response["ok"] is False+ assert response["code"] == "SSH_KEY_ISSUE_FAILED"+++async def test_agent_switch_omits_ssh_private_key_when_issuer_cleared() -> None:+ yuanrong = FakeYuanRongClient()+ agent_manager = AgentManager()+ client = AgentOSRouterClient(+ yuanrong, FakeRegistryClient(), agent_manager, ssh_channel_endpoint=_ssh_channel()+ )+ client.set_key_issuer(+ SimpleNamespace(+ issue_ephemeral_key=lambda **kwargs: "KEY",+ ),+ ephemeral_key_ttl_sec=60.0,+ )+ client.set_key_issuer(None)+ response = await client.thirdagent_switch(+ user_id="u1",+ agent_type="opencode",+ session_id="sess-1",+ )+ await client.shutdown()++ assert response["ok"] is True+ assert "ssh_private_key" not in response["payload"]@pytest.mark.asyncio