Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat: 支持内部 HTTP/SSE 链路 mTLS 认证及证书数据库持久化

whq0ba97e5ce284
diff --git a/.gitignore b/.gitignore
index dba360ab80..fd0dee1ab1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -40,6 +40,8 @@ pnpm-debug.log*
# Environment files
.env
.env_personal
+/deploy/enterprise/.env.custom
+/deploy/enterprise/.link-mtls-test/
!.env.example
# Apple code signing & notarization secrets — NEVER commit (contains private keys!)
diff --git a/deploy/enterprise/.env.example b/deploy/enterprise/.env.example
index e2480b575e..2e151287d6 100644
--- a/deploy/enterprise/.env.example
+++ b/deploy/enterprise/.env.example
@@ -3,6 +3,10 @@
# product 模式:使用容器内置代码,不挂载宿主机目录,用于生产环境
MODE=product
+# 内部链路证书认证,默认 off;显式 enforce 才启用,observe 仅预检。
+# 使用配套 Runtime 镜像;证书由部署工具准备并持久化,不另填证书路径。
+JIUWENSWARM_LINK_MTLS_MODE=off
+
# 仅在 MODE=dev 时生效:jiuwenclaw 项目在宿主机本地代码路径(请填写绝对路径)
# 不设置时,该模块目录不用挂载
CLAW_CODE_PATH=""
diff --git a/deploy/enterprise/README.md b/deploy/enterprise/README.md
index d8e68495b0..8f541e4830 100644
--- a/deploy/enterprise/README.md
+++ b/deploy/enterprise/README.md
@@ -75,6 +75,7 @@ JiuwenClaw_deployTool_<VERSION>_<ARCH>_product/
├── global_vars.sh # 全局常量、默认参数定义脚本
├── gateway_handler.sh # Gateway网关模块部署、运维处理脚本
├── runtime_handler.sh # AgentRuntime 运行时模块部署、运维处理脚本
+├── link_mtls_handler.sh # 可选内部链路证书准备、挂载及认证下发
├── k8s_handler.sh # Kubernetes 集群资源操作核心脚本
├── minio_handler.sh # MinIO 对象存储模块部署运维脚本
├── mysql_handler.sh # MySQL 数据库模块部署运维脚本
@@ -94,6 +95,7 @@ JiuwenClaw_deployTool_<VERSION>_<ARCH>_product/
├── agentserver.template.json # AgentServer 服务模板
├── agentserver.template.env # AgentServer 环境变量配置模板
├── runtime.template.yaml # AgentRuntime 运行时 Kubernetes 资源模板
+ ├── link-mtls.template.yaml # 可选证书挂载辅助容器及 headless Service 片段
├── minio.template.yaml # MinIO 存储 Kubernetes 资源模板
├── mysql.template.yaml # MySQL 数据库 Kubernetes 资源模板
├── nfs.template.yaml # NFS 存储 Kubernetes 资源模板
@@ -110,6 +112,8 @@ JiuwenClaw_deployTool_<VERSION>_<ARCH>_product/
修改配置前,请先查阅配置文件参数说明书 `.env.example`,明确各配置项含义与使用规则;再结合自身实际环境,按需调整配置文件`.env.custom`的参数,完成部署环境与业务场景适配。
+内部链路双向证书认证默认关闭,只有显式配置 `JIUWENSWARM_LINK_MTLS_MODE=enforce` 才启用。安装步骤、数据持久化、安全边界和维护限制统一见[内部链路 mTLS 使用与设计说明](../../docs/zh/HTTP-SSE链路mTLS部署配置.md)。
+
以下为系统运行必需参数,需依据实际大模型服务凭证完整填写:
```
# ====================== 大模型接口配置 ======================
diff --git a/deploy/enterprise/deploy.sh b/deploy/enterprise/deploy.sh
index 23627f3bac..fb9cfe025c 100755
--- a/deploy/enterprise/deploy.sh
+++ b/deploy/enterprise/deploy.sh
@@ -25,6 +25,7 @@ source "manager_handler.sh"
source "web_handler.sh"
source "runtime_handler.sh"
source "patch_handler.sh"
+source "link_mtls_handler.sh"
process_up() {
# MODULES是ALL_MODULES的子集,启动顺序正着来
@@ -55,6 +56,7 @@ process_up() {
render_${fname}_files
else
check_${fname}_up_dependency
+ case "$module" in GATEWAY|RUNTIME|MANAGER) link_mtls_prepare ;; esac
render_${fname}_files
deploy_${fname}
fi
@@ -95,6 +97,7 @@ process_restart() {
main() {
read_env_from_file "${CUSTOM_ENV_FILE}" "DEPLOY_VARS"
parse_args "$@"
+ link_mtls_check
detect_os
check_dependency
process_${CMD}
diff --git a/deploy/enterprise/gateway_handler.sh b/deploy/enterprise/gateway_handler.sh
index 888224dc58..e270978675 100755
--- a/deploy/enterprise/gateway_handler.sh
+++ b/deploy/enterprise/gateway_handler.sh
@@ -106,6 +106,9 @@ render_gateway_files() {
ensure_available_port "GATEWAY_CONFIG_HTTP_NODE_PORT"
gen_gateway_file
+ if [[ "${DEPLOY_VARS[JIUWENSWARM_LINK_MTLS_MODE]:-off}" != off ]]; then
+ link_mtls_render gateway "${CONFIG[GATEWAY_FILE]}"
+ fi
}
deploy_gateway() {
diff --git a/deploy/enterprise/gen_env_custom.sh b/deploy/enterprise/gen_env_custom.sh
index 61dd68150f..dbd4d093a6 100755
--- a/deploy/enterprise/gen_env_custom.sh
+++ b/deploy/enterprise/gen_env_custom.sh
@@ -83,6 +83,8 @@ cat <<EOF
AGENT_RUNTIME_IMAGE="swr.cn-north-4.myhuaweicloud.com/openjiuwen/jiuwenclaw-agent-runtime-${ARCH}:${VERSION}"
MODE=product
+# 内部链路证书认证默认关闭,按需显式改为 enforce。
+JIUWENSWARM_LINK_MTLS_MODE=off
#CLAW_CODE_PATH=""
#RUNTIME_CODE_PATH=""
#CORE_CODE_PATH=""
diff --git a/deploy/enterprise/global_vars.sh b/deploy/enterprise/global_vars.sh
index 810f9441a1..d829d58832 100755
--- a/deploy/enterprise/global_vars.sh
+++ b/deploy/enterprise/global_vars.sh
@@ -102,6 +102,7 @@ declare -ga MODULES=()
declare -A DEPLOY_VARS=(
# for dev mode, mount code purpose
["MODE"]="product"
+ ["JIUWENSWARM_LINK_MTLS_MODE"]="off"
["IS_MOUNT_WEB_CODE"]="false"
["IS_MOUNT_MANAGER_WEB_CODE"]="false"
["CLAW_POD_CODE_PATH"]="/app/jiuwenswarm"
diff --git a/deploy/enterprise/link_mtls_handler.sh b/deploy/enterprise/link_mtls_handler.sh
new file mode 100644
index 0000000000..2f60ae174c
--- /dev/null
+++ b/deploy/enterprise/link_mtls_handler.sh
@@ -0,0 +1,278 @@
+#!/usr/bin/env bash
+# Shell owns deployment/Kubernetes orchestration; the packaged foundation
+# module owns PKI/database operations. Never trace private stdin/stdout.
+
+link_mtls_check() {
+ local mode="${DEPLOY_VARS[JIUWENSWARM_LINK_MTLS_MODE]:-off}" module imports
+ case "$mode" in off|observe|enforce) ;; *) error 'JIUWENSWARM_LINK_MTLS_MODE must be off, observe or enforce' ;; esac
+ [[ "$mode" == enforce && "$CMD" != down ]] || return 0
+ for module in "${MODULES[@]}"; do
+ case "$module" in GATEWAY|RUNTIME|MANAGER)
+ # Import/version check only; never provision during --render-only.
+ imports=$(link_mtls_call imports) || error 'Matching Runtime certificate support is required'
+ DEPLOY_VARS[LINK_SYNC_CODE]=$(printf '%s' "$imports" | jq -er '.helper_code') || error 'Certificate copy helper is missing'
+ return 0
+ ;; esac
+ done
+}
+
+link_mtls_kube() {
+ kubectl --request-timeout=30s -n "${DEPLOY_VARS[NAMESPACE]}" "$@"
+}
+
+link_mtls_resolve_host() {
+ local host="$1" address service namespace service_json
+ service=${host%%.*}
+ namespace=${DEPLOY_VARS[NAMESPACE]}
+ [[ "$host" != *.* ]] || namespace=${host#*.}
+ namespace=${namespace%%.*}
+ if [[ "$service" =~ ^[a-z0-9][a-z0-9-]*$ && "$namespace" =~ ^[a-z0-9][a-z0-9-]*$ ]] &&
+ service_json=$(kubectl --request-timeout=30s -n "$namespace" get service "$service" -o json 2>/dev/null); then
+ address=$(printf '%s' "$service_json" | jq -r '.spec.clusterIP // empty') || return 1
+ if [[ -z "$address" || "$address" == None ]]; then
+ address=$(kubectl --request-timeout=30s -n "$namespace" get endpoints "$service" -o json |
+ jq -er '[.subsets[]?.addresses[]?.ip] | if length == 1 then .[0] else error("DB requires one writable endpoint") end') || return 1
+ fi
+ printf '%s' "$address"
+ return
+ fi
+ address=$(getent ahostsv4 "$host" 2>/dev/null | awk 'NR==1 {print $1}') || true
+ [[ -n "$address" ]] || return 1
+ printf '%s' "$address"
+}
+
+link_mtls_headless() {
+ yq -o=json '.headlessService' "${SCRIPT_DIR}/templates/link-mtls.template.yaml" |
+ jq --arg name "${DEPLOY_VARS[AGENT_SERVER_NAME]:-jiuwenclaw-agentserver}" \
+ --arg ns "${DEPLOY_VARS[NAMESPACE]}" --argjson port "${DEPLOY_VARS[AGENT_SERVER_PORT]}" \
+ '.metadata={name:$name,namespace:$ns} | .spec.ports[0] |= (.port=$port | .targetPort=$port)'
+}
+
+link_mtls_preflight() {
+ local previous
+ previous=$(link_mtls_kube get service "${DEPLOY_VARS[AGENT_SERVER_NAME]:-jiuwenclaw-agentserver}" --ignore-not-found -o json) || return 1
+ if [[ -n "$previous" ]]; then
+ printf '%s' "$previous" | jq -e '.spec.clusterIP == "None" and .spec.selector == {"jiuwenclaw-component":"agentserver"}' >/dev/null || {
+ echo 'Existing AgentServer Service conflicts with the certificate binding' >&2; return 1;
+ }
+ fi
+}
+
+# Keep the private worker input deliberately small. DEPLOY_VARS also contains
+# unrelated product configuration (including multiline integration settings),
+# none of which belongs in the certificate provisioning protocol.
+link_mtls_settings_json() (
+ set +x
+ local key
+ local -a keys=(
+ JIUWENSWARM_LINK_MTLS_MODE NAMESPACE
+ AGENT_RUNTIME_LINK_MTLS_CLUSTER_DOMAIN AGENT_SERVER_NAME
+ GATEWAY_NAME AGENT_RUNTIME_NAME GATEWAY_CONFIG_HTTP_PORT AGENT_RUNTIME_PORT
+ LINK_DB_CONNECT_HOST DB_TYPE DB_HOST DB_PORT
+ GATEWAY_DB_NAME GATEWAY_DB_USER GATEWAY_DB_PASSWORD GATEWAY_PG_SCHEMA
+ RUNTIME_DB_NAME RUNTIME_DB_USER RUNTIME_DB_PASSWORD RUNTIME_PG_SCHEMA
+ __LINK_REQUEST_BODY
+ )
+ for key in "${keys[@]}"; do
+ [[ -n "${DEPLOY_VARS[$key]+present}" ]] || continue
+ printf '%s\0%s\0' "$key" "${DEPLOY_VARS[$key]}"
+ done | jq -Rs '
+ split("\u0000") |
+ if length > 0 and .[-1] == "" then .[:-1] else . end |
+ [range(0; length; 2) as $i | {key: .[$i], value: .[$i + 1]}] |
+ from_entries'
+)
+
+link_mtls_require_database_settings() {
+ local key
+ for key in \
+ GATEWAY_DB_NAME GATEWAY_DB_USER GATEWAY_DB_PASSWORD \
+ RUNTIME_DB_NAME RUNTIME_DB_USER RUNTIME_DB_PASSWORD
+ do
+ if [[ -z "${DEPLOY_VARS[$key]:-}" ]]; then
+ echo "$key must be resolved before certificate preparation" >&2
+ return 1
+ fi
+ done
+}
+
+link_mtls_require_serialized_database_settings() {
+ local settings="$1"
+ printf '%s' "$settings" | jq -e '
+ . as $settings |
+ [
+ "GATEWAY_DB_NAME", "GATEWAY_DB_USER", "GATEWAY_DB_PASSWORD",
+ "RUNTIME_DB_NAME", "RUNTIME_DB_USER", "RUNTIME_DB_PASSWORD"
+ ] as $keys |
+ all($keys[]; . as $key |
+ ($settings[$key] | type == "string" and length > 0))' >/dev/null || {
+ echo 'Serialized mTLS database settings are incomplete' >&2
+ return 1
+ }
+}
+
+link_mtls_worker() (
+ set +x
+ set -o pipefail
+ local action="$1" target="${2:-}" path="${3:-}" existing='{}' role previous endpoint network=host settings
+ [[ "${DEPLOY_VARS[JIUWENSWARM_LINK_MTLS_MODE]:-off}" == enforce ]] || return 1
+ [[ "$action" == imports ]] || link_mtls_require_database_settings || return 1
+ endpoint=${DOCKER_HOST:-}
+ if [[ -n "${DOCKER_CONTEXT:-}" || -z "$endpoint" ]]; then
+ endpoint=$(docker context inspect --format '{{.Endpoints.docker.Host}}') || return 1
+ fi
+ [[ "$endpoint" == unix://* ]] || { echo 'mTLS deployment requires local Docker' >&2; return 1; }
+ if [[ "$action" == imports ]]; then network=none; else
+ DEPLOY_VARS[LINK_DB_CONNECT_HOST]=$(link_mtls_resolve_host "${DEPLOY_VARS[DB_HOST]}") || return 1
+ fi
+ if [[ "$action" == ensure || "$action" == status ]]; then
+ [[ "$action" != ensure ]] || link_mtls_preflight || return 1
+ for role in gateway runtime agentserver manager; do
+ previous=$(link_mtls_kube get secret "jiuwenswarm-link-$role" --ignore-not-found -o json) || return 1
+ existing=$(printf '%s\n%s' "$existing" "${previous:-null}" |
+ jq -cs --arg role "$role" '.[0] + {($role):.[1]}') || return 1
+ done
+ fi
+ local -a args=(run --rm -i --user "$(id -u):$(id -g)" --read-only --cap-drop=ALL
+ --security-opt=no-new-privileges --tmpfs "/tmp:rw,nosuid,nodev,size=64m"
+ --workdir /tmp --entrypoint python --network "$network"
+ -e PYTHONDONTWRITEBYTECODE=1 -e OPENJIUWEN_RUNTIME_LOG_FILE=disabled)
+ if [[ "${DEPLOY_VARS[MODE]}" == dev ]]; then
+ local source="${DEPLOY_VARS[RUNTIME_CODE_PATH]}"
+ [[ "$source" == /* && "$source" != *,* && "$source" != *$'\n'* &&
+ -f "$source/foundation/openjiuwen_runtime/foundation/security/link_material_deploy.py" ]] || {
+ echo 'Matching Runtime foundation source is required' >&2; return 1;
+ }
+ args+=(--mount "type=bind,src=$source/foundation,dst=/app/link-foundation,readonly" -e PYTHONPATH=/app/link-foundation)
+ fi
+ args+=("${DEPLOY_VARS[AGENT_RUNTIME_IMAGE]}" -m openjiuwen_runtime.foundation.security.link_material_deploy)
+ local connect_host=''
+ if [[ "$action" == request || "$action" == wait ]]; then
+ local service="${DEPLOY_VARS[GATEWAY_NAME]}"
+ [[ "$target" != runtime ]] || service="${DEPLOY_VARS[AGENT_RUNTIME_NAME]}"
+ connect_host=$(link_mtls_resolve_host "$service") || return 1
+ fi
+ settings=$(link_mtls_settings_json) || return 1
+ link_mtls_require_serialized_database_settings "$settings" || return 1
+ {
+ printf '%s\n' "$settings"
+ printf '\n%s' "$existing"
+ } | jq -cs --arg action "$action" --arg target "$target" --arg path "$path" --arg host "$connect_host" \
+ '{settings:.[0],existing:.[1],action:$action,target:$target,request_path:$path,connect_host:$host}' |
+ docker "${args[@]}" 2> >(sed -n '/^mTLS deployment stopped: /p' >&2)
+)
+
+link_mtls_call() (
+ set +x
+ set -o pipefail
+ local action="$1" result secret current
+ result=$(link_mtls_worker "$@") || { echo 'mTLS preparation/request failed; no HTTP fallback' >&2; return 1; }
+ if [[ "$action" == ensure ]]; then
+ printf '%s' "$result" | jq -e '
+ (.summary.mtls_deployment_id | type == "string" and length > 0) and
+ ([.secrets[].metadata.name] | sort == ["jiuwenswarm-link-agentserver","jiuwenswarm-link-gateway","jiuwenswarm-link-manager","jiuwenswarm-link-runtime"]) and
+ all(.secrets[]; .kind == "Secret" and (.data | type == "object"))' >/dev/null || {
+ echo 'Invalid certificate preparation response; refusing installation' >&2; return 1;
+ }
+ while IFS= read -r secret; do
+ # create, never apply: no annotation containing private key copies.
+ if ! printf '%s' "$secret" | link_mtls_kube create -f - >/dev/null 2>&1; then
+ current=$(link_mtls_kube get secret "$(printf '%s' "$secret" | jq -er '.metadata.name')" -o json) || return 1
+ printf '%s\n%s' "$secret" "$current" | jq -se '.[0].data == .[1].data' >/dev/null || {
+ echo 'Secret conflicts with database material; refusing overwrite' >&2; return 1;
+ }
+ fi
+ done < <(printf '%s' "$result" | jq -c '.secrets[]')
+ link_mtls_headless | link_mtls_kube apply -f - >/dev/null || return 1
+ fi
+ printf '%s' "$result" | jq '.summary // .'
+)
+
+link_mtls_prepare() {
+ [[ "${DEPLOY_VARS[JIUWENSWARM_LINK_MTLS_MODE]:-off}" == enforce && "${DEPLOY_VARS[RENDER_ONLY]}" != true ]] || return 0
+ [[ "${DEPLOY_VARS[LINK_PREPARED]:-false}" != true ]] || return 0
+ local summary
+ summary=$(link_mtls_call ensure) || error 'Certificate preparation failed. No HTTP fallback.'
+ DEPLOY_VARS[LINK_PREPARED]=true
+ info "mTLS binding ready (DB persisted, ten-year first issuance): ${summary}"
+}
+
+link_mtls_request() (
+ set +x
+ local data="$3"
+ [[ "$data" != @* ]] || data=$(<"${data#@}")
+ DEPLOY_VARS[__LINK_REQUEST_BODY]="$data"
+ link_mtls_call request "$1" "$2"
+)
+
+# Render certificate fragments with the same yq/jq toolchain as other handlers.
+link_mtls_render() (
+ set +x
+ set -o pipefail
+ local role="$1" file="$2" mode="${DEPLOY_VARS[JIUWENSWARM_LINK_MTLS_MODE]:-off}" temporary
+ [[ "$mode" != off ]] || return 0
+ temporary=$(mktemp "${file}.link.XXXXXX") || return 1
+ trap 'rm -f "$temporary"' EXIT
+ yq -o=json '.' "$file" | jq -s \
+ --arg role "$role" --arg mode "$mode" --arg dev "${DEPLOY_VARS[MODE]}" \
+ --arg source "${DEPLOY_VARS[RUNTIME_CODE_PATH]:-}" --arg claw "${DEPLOY_VARS[CLAW_POD_CODE_PATH]:-/app/jiuwenswarm}" \
+ --arg domain "${DEPLOY_VARS[AGENT_RUNTIME_LINK_MTLS_CLUSTER_DOMAIN]:-cluster.local}" \
+ --arg headless "${DEPLOY_VARS[AGENT_SERVER_NAME]:-jiuwenclaw-agentserver}" \
+ --arg port "$([[ "$role" == gateway ]] && printf '%s' "${DEPLOY_VARS[GATEWAY_CONFIG_HTTP_PORT]}" || printf '%s' "${DEPLOY_VARS[AGENT_RUNTIME_PORT]}")" \
+ --arg code "${DEPLOY_VARS[LINK_SYNC_CODE]:-}" \
+ --slurpfile parts <(yq -o=json '.' "${SCRIPT_DIR}/templates/link-mtls.template.yaml") '
+ def put($v): map(select(.name != $v.name)) + [$v];
+ def env($n;$v): .env = ((.env // []) | put({name:$n,value:$v}));
+ def source_mount:
+ .volumeMounts = ((.volumeMounts // []) | put({name:"link-runtime-source",mountPath:"/app/link-runtime-source",readOnly:true}));
+ def python_path($paths): env("PYTHONPATH"; ($paths + [.env[]? | select(.name=="PYTHONPATH") | .value | select(length>0)]) | join(":"));
+ def source_volume:
+ .volumes = ((.volumes // []) | put({name:"link-runtime-source",hostPath:{path:$source,type:"Directory"}}));
+ if $role == "agentserver" then
+ if $mode == "enforce" and $dev == "dev" then
+ .[0] | .rawdata.templates |= map(source_volume) |
+ [.rawdata.templates[].main_container_id] as $ids |
+ .rawdata.containers |= map(if (.container_id as $id | $ids | index($id)) != null then
+ source_mount | python_path([$claw,"/app/link-runtime-source/foundation","/app/link-runtime-source/service"])
+ else . end)
+ else .[0] end
+ else
+ map(if .kind != "Deployment" then . else
+ .spec.template.spec |= (
+ . as $pod |
+ .containers |= map(if .name != ({gateway:"gateway",runtime:"agent-runtime",manager:"manager"}[$role]) then . else
+ env("JIUWENSWARM_LINK_MTLS_MODE";$mode) end) |
+ if $mode != "enforce" then . else
+ [.containers[] | select(.name==({gateway:"gateway",runtime:"agent-runtime",manager:"manager"}[$role]))] as $targets |
+ if ($targets|length) != 1 then error("ambiguous certificate target container") else . end |
+ $targets[0] as $main |
+ (($main.securityContext.runAsUser // $pod.securityContext.runAsUser) != 0 or (($pod.securityContext.fsGroup // 0) != 0)) as $copy |
+ "jiuwenswarm-link-mtls" as $volume |
+ ($volume + (if $copy then "-source" else "" end)) as $src |
+ ("/etc/jiuwenswarm/link-mtls/"+$role) as $mount |
+ .volumes = ((.volumes // []) | put({name:$src,secret:{secretName:("jiuwenswarm-link-"+$role),defaultMode:(if $copy then 292 else 256 end)}})) |
+ (if $copy then
+ .volumes |= put($parts[0].privateVolume) |
+ if any((.containers + (.initContainers // []))[]; .name=="link-material-init" or .name=="link-material-sync") then error("reserved link helper name") else . end |
+ ($parts[0].helper + {image:$main.image,imagePullPolicy:($main.imagePullPolicy // "IfNotPresent"),
+ command:["python","-c",$code],securityContext:(({runAsUser:($main.securityContext.runAsUser // $pod.securityContext.runAsUser),runAsGroup:($main.securityContext.runAsGroup // $pod.securityContext.runAsGroup)} | with_entries(select(.value != null))) + $parts[0].helper.securityContext)}) as $helper |
+ if $code=="" then error("certificate helper not available") else . end |
+ .initContainers = ((.initContainers // []) + [($helper | .name="link-material-init" | .command += ["--once"])]) |
+ .containers += [($helper | .name="link-material-sync")]
+ else . end) |
+ .containers |= map(if .name != $main.name then . else
+ .volumeMounts = ((.volumeMounts // []) | put({name:$volume,mountPath:$mount,readOnly:true})) |
+ (if $copy then env("JIUWENSWARM_LINK_MTLS_PROFILE";$mount+"/private/identity/profile.json") else . end) |
+ (if $role=="runtime" then env("AGENT_RUNTIME_LINK_MTLS_AGENTSERVER_SECRET";"jiuwenswarm-link-agentserver") | env("AGENT_RUNTIME_LINK_MTLS_HEADLESS_SERVICE";$headless) | env("AGENT_RUNTIME_LINK_MTLS_CLUSTER_DOMAIN";$domain)
+ elif $role=="gateway" then env("GATEWAY_CONFIG_PUBLIC_SCHEME";"https") else . end) |
+ (if $role=="gateway" or $role=="runtime" then
+ ("import urllib.request; from openjiuwen_runtime.foundation.security.link_profile import load_service_identity; p=load_service_identity(\u0027"+$role+"\u0027); o=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=p.ssl_context())); r=o.open(\u0027https://127.0.0.1:"+$port+(if $role=="gateway" then "/api/v1/ready" else "/healthz" end)+"\u0027,timeout=3); assert r.status==200") as $probe |
+ reduce ["readinessProbe","livenessProbe","startupProbe"][] as $p (. ; if has($p) then .[$p] |= (del(.httpGet,.tcpSocket,.grpc) | .exec={command:["python","-c",$probe]} | .timeoutSeconds=([(.timeoutSeconds // 1),5]|max)) else . end)
+ else . end) |
+ (if $dev=="dev" then source_mount | python_path(["/app/link-runtime-source/foundation","/app/link-runtime-source/service",(if $role=="runtime" then "/app/link-runtime-source/applications/agent_runtime/src" elif $role=="manager" then "/app/link-runtime-source/applications/manager/manager_server/src" else $claw end)]) else . end)
+ end) | if $dev=="dev" then source_volume else . end
+ end)
+ end)[]
+ end' | yq -p=json -P '.' > "$temporary" || return 1
+ if [[ "$role" == agentserver ]]; then yq -o=json '.' "$temporary" > "$file"; else mv -f "$temporary" "$file"; fi
+)
diff --git a/deploy/enterprise/manager_handler.sh b/deploy/enterprise/manager_handler.sh
index 3eaf1568a3..04968e6b78 100755
--- a/deploy/enterprise/manager_handler.sh
+++ b/deploy/enterprise/manager_handler.sh
@@ -45,6 +45,9 @@ render_manager_files() {
render_secret_configmap
ensure_available_port "MANAGER_SERVER_NODE_PORT" "MANAGER_WEB_NODE_PORT"
gen_manager_server_file
+ if [[ "${DEPLOY_VARS[JIUWENSWARM_LINK_MTLS_MODE]:-off}" != off ]]; then
+ link_mtls_render manager "${CONFIG[MANAGER_SERVER_FILE]}"
+ fi
gen_identity_file
local manager_web_template_file="${CONFIG["MANAGER_WEB_TEMPLATE_FILE"]}"
diff --git a/deploy/enterprise/patch_handler.sh b/deploy/enterprise/patch_handler.sh
index 62a7bfd56d..124d7e4911 100755
--- a/deploy/enterprise/patch_handler.sh
+++ b/deploy/enterprise/patch_handler.sh
@@ -12,6 +12,12 @@ wait_http_ready() {
local port="$2"
local path="$3"
local module="${4:-service}"
+ if [[ "${DEPLOY_VARS[JIUWENSWARM_LINK_MTLS_MODE]:-off}" == enforce ]]; then
+ local role=gateway
+ [[ "$module" != agent-runtime* ]] || role=runtime
+ link_mtls_call wait "$role" "$path"
+ return
+ fi
local elapsed=0
local code="000"
[ -n "${port}" ] || error "${module} NodePort is empty; cannot check readiness"
@@ -37,6 +43,12 @@ post_and_validate() {
local url="$1"
local data="$2"
local module="${3:-}"
+ if [[ "${DEPLOY_VARS[JIUWENSWARM_LINK_MTLS_MODE]:-off}" == enforce ]]; then
+ local path="${url#*://}"
+ path="/${path#*/}"
+ link_mtls_request "$module" "$path" "$data"
+ return
+ fi
local resp_file="$(mktemp)"
local code=$(curl -s --max-time 20 -o "${resp_file}" -w "%{http_code}" \
-X POST "${url}" -H "Content-Type: application/json" -d "${data}" 2>/dev/null) || code="000"
@@ -205,4 +217,4 @@ install_patch()
install_agentserver_patch
install_model_patch
-}
\ No newline at end of file
+}
diff --git a/deploy/enterprise/runtime_handler.sh b/deploy/enterprise/runtime_handler.sh
index 40e7ba3c81..d2126adedb 100755
--- a/deploy/enterprise/runtime_handler.sh
+++ b/deploy/enterprise/runtime_handler.sh
@@ -79,6 +79,10 @@ render_runtime_files() {
gen_runtime_file
render_patch_file
render_agentserver_env_configmap
+ if [[ "${DEPLOY_VARS[JIUWENSWARM_LINK_MTLS_MODE]:-off}" != off ]]; then
+ link_mtls_render runtime "${CONFIG[RUNTIME_FILE]}"
+ link_mtls_render agentserver "${CONFIG[AS_JSON_FILE]}"
+ fi
# agentserver 由 runtime 动态创建并挂载内置 PVC,PVC 渲染归属 runtime
if [[ "${mount_type}" == "pvc" && "${is_external_pvc}" == "false" ]]; then
diff --git a/deploy/enterprise/templates/link-mtls.template.yaml b/deploy/enterprise/templates/link-mtls.template.yaml
new file mode 100644
index 0000000000..6b8f86ff38
--- /dev/null
+++ b/deploy/enterprise/templates/link-mtls.template.yaml
@@ -0,0 +1,35 @@
+# Certificate fragments only; preserve original business fields and fsGroup.
+privateVolume:
+ name: jiuwenswarm-link-mtls
+ emptyDir:
+ medium: Memory
+helper:
+ securityContext:
+ allowPrivilegeEscalation: false
+ capabilities:
+ drop: [ALL]
+ resources:
+ requests:
+ cpu: 5m
+ memory: 16Mi
+ limits:
+ cpu: 100m
+ memory: 64Mi
+ volumeMounts:
+ - name: jiuwenswarm-link-mtls-source
+ mountPath: /run/link-source
+ readOnly: true
+ - name: jiuwenswarm-link-mtls
+ mountPath: /run/link-owned
+headlessService:
+ apiVersion: v1
+ kind: Service
+ spec:
+ clusterIP: None
+ publishNotReadyAddresses: true
+ selector:
+ jiuwenclaw-component: agentserver
+ ports:
+ - name: https
+ port: 8766
+ targetPort: 8766
diff --git a/deploy/enterprise/update_conf.sh b/deploy/enterprise/update_conf.sh
index 3e332ad97a..3e0624ef12 100755
--- a/deploy/enterprise/update_conf.sh
+++ b/deploy/enterprise/update_conf.sh
@@ -1,10 +1,10 @@
#!/bin/bash
+set -euo pipefail
PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
SRC_FILE=${PROJECT_DIR}/jiuwenswarm/resources/config.yaml
-DEST_FILE=${PROJECT_DIR}/deploy/enterprise/templates/gateway-config.template.yaml
+DEST_FILE=${1:-${PROJECT_DIR}/deploy/enterprise/templates/gateway-config.template.yaml}
-rm -f "${DEST_FILE}"
cp -f "${SRC_FILE}" "${DEST_FILE}"
yq eval '.gateway.agent_client.type = "jiuwen"' -i "${DEST_FILE}"
diff --git "a/docs/zh/HTTP-SSE\351\223\276\350\267\257mTLS\351\203\250\347\275\262\351\205\215\347\275\256.md" "b/docs/zh/HTTP-SSE\351\223\276\350\267\257mTLS\351\203\250\347\275\262\351\205\215\347\275\256.md"
new file mode 100644
index 0000000000..d3cdbdecd8
--- /dev/null
+++ "b/docs/zh/HTTP-SSE\351\223\276\350\267\257mTLS\351\203\250\347\275\262\351\205\215\347\275\256.md"
@@ -0,0 +1,354 @@
+# 内部链路双向证书认证:使用指南与设计说明
+
+本文说明 Gateway、Runtime、AgentServer 之间的 HTTP/SSE 链路认证,以及管理服务接入方式。先介绍部署与使用,再说明实现原理、数据保存方式和安全边界。
+
+## 一、如何使用
+
+### 1. 默认关闭,显式开启
+
+功能默认关闭。未配置该变量,或显式配置为 `off`,均不启用链路证书认证:
+
+```ini
+JIUWENSWARM_LINK_MTLS_MODE=off
+```
+
+需要启用时,在部署工具现有的 `.env.custom` 中显式设置:
+
+```ini
+JIUWENSWARM_LINK_MTLS_MODE=enforce
+```
+
+只保留一条同名设置,避免重复赋值造成误解。值为枚举,不使用 `true`、`false` 或 `on`。
+
+| 值 | 行为 | 是否启用认证 |
+| --- | --- | --- |
+| `off`(默认) | 保持原有传输路径,不执行证书生成和材料持久化流程 | 否 |
+| `observe` | 预检本地证书材料;不强制依赖证书、不切换 HTTPS、不实施远端角色认证 | 否 |
+| `enforce` | 部署工具准备证书与绑定材料;受管内部链路启用 HTTPS、双向证书和绑定校验;校验失败不退回明文 | 是 |
+
+“没有设置开关,但目录或数据库里有证书”不会自动启用本功能。反过来,修改 `.env.custom` 也不会立即改变已经运行的进程,需要通过部署流程使设置生效。
+
+### 2. 部署前提
+
+- 使用配套发布的 JiuwenSwarm、Runtime 及基础库。Gateway、Runtime、AgentServer 镜像需要包含本功能;仅修改旧镜像的环境变量不能安装新功能。
+- 源码安装和 CI 必须安装 `pyproject.toml` 声明的 Runtime foundation 依赖,不能只安装 agent-core。跨仓库发布时先合入 Runtime 的配套实现,再构建 JiuwenSwarm;联合验证未合入代码时,应显式安装所验证 Runtime 源码中的 `foundation[link-mtls]`,不要用测试替身代替证书实现。
+- 使用企业部署工具已有的 MySQL 或 PostgreSQL 配置。Gateway 与 Runtime 使用不同数据库;PostgreSQL 也可使用分离的 schema。不得共用同一个数据命名空间。
+- Linux 部署节点需要具备原部署工具依赖(包括 Bash、jq、yq、kubectl),以及本地 Docker daemon。容器中的配套 Runtime 基础库负责证书与数据库操作,不要求为本功能在部署主机安装 Python 虚拟环境。
+- 部署节点可访问数据库及受管服务;kubectl 具有目标命名空间相应资源的读写权限。使用 headless 数据库 Service 时,需能确定唯一可写目标,否则应配置明确的数据库主节点地址。
+- 保持部署节点及各服务节点时间同步。检查服务名称、命名空间、集群 DNS 域及端口,避免安装后无计划地改变证书对应地址。
+
+本功能不要求增加证书管理 Pod,也不要求指定版本之外的主机持久证书目录。
+
+### 3. 无内置 Manager 的部署
+
+以下命令在源码的 `deploy/enterprise` 目录或配套部署包目录执行。命名空间 `example-app` 仅作示例,应替换为实际目标。
+
+已有数据库、存储、镜像和业务配置保持原有配置方式。使用部署工具下发初始业务配置的交付形态:
+
+```ini
+APPLY_PATCH=true
+JIUWENSWARM_LINK_MTLS_MODE=enforce
+```
+
+```bash
+# 源码部署时先同步当前源码配置模板。
+./update_conf.sh
+
+# 可先渲染检查清单;此步骤不会签发证书或向数据库写入材料。
+./deploy.sh up gateway web runtime -n example-app --render-only
+
+# 正式应用清单,并准备、持久化或复用证书。
+./deploy.sh up gateway web runtime -n example-app
+```
+
+该流程不启动 Manager Server、Manager Web 或 Identity Center。配置下发由部署工具使用 `manager` 角色证书完成;`manager` 是协议中的服务角色,不要求运行仓库内置的 Manager 应用。
+
+`.env.custom` 中原有的模型、数据库和存储参数仍须正确配置。链路证书认证不能代替业务参数校验,也不会把空模型配置自动补成有效模型。
+
+源码挂载仍使用已有的 `MODE=dev`、源码路径及节点设置;正式镜像部署使用 `MODE=product`。这些是代码加载方式,不是证书认证开关。生产镜像应打包配套 Runtime foundation 及所需 HTTP/TLS 依赖,不能用源码验证结果推断任意旧镜像均可开启本功能。
+
+### 4. 可选的内置管理链路
+
+如明确使用仓库提供的 Manager/Identity 参考实现,应显式部署 `manager` 模块。例如:
+
+```ini
+APPLY_PATCH=false
+LOGIN_AUTH_SIMULATE=false
+JIUWENSWARM_LINK_MTLS_MODE=enforce
+```
+
+```bash
+./deploy.sh up gateway web manager runtime -n example-app
+```
+
+`APPLY_PATCH=false` 表示不由部署工具执行上述业务补丁下发,不会自动把 `manager` 加入模块列表。本节是可选参考形态,不属于无 Manager 交付的必需步骤。
+
+用户登录、用户与组织权限、企业版入口等是独立配置。本功能认证服务身份,不认证浏览器用户,也不替代业务准入检查。
+
+Manager 原有的多实例模型保持不变:`instance_info.jiuwenclaw_id` 仍由 Manager 按原逻辑为每个实例生成,不能改成 Manager 证书中的固定值。Manager 证书只证明调用方属于 `manager` 服务角色;每个 `jiuwenclaw_id` 再通过 `instance_link_binding` 选择自己的绑定编号、代次、Gateway/Runtime 身份和目标证书指纹。
+
+同一部署工具同时安装的一组 Manager、Gateway 和 Runtime,会在第一次配置同步时自动采用与两个配置地址完全匹配的部署绑定,但不会改写 Manager 已生成的实例 ID。其他实例必须先登记各自的链路绑定;显式登记的两个 mTLS 地址也必须与该实例在 `instance_info` 中的 Gateway/Runtime 配置地址一致。同一 Gateway 或 Runtime 不能同时绑定给两个实例。
+
+本机制明确区分四类标识:
+
+| 名称 | 所属范围 | 是否由 mTLS 创建 |
+| --- | --- | --- |
+| `jiuwenclaw_id` | Manager 业务实例主键 | 否 |
+| `GATEWAY_INSTANCE_ID` | Gateway 主备、Redis Key 等运行身份 | 否 |
+| Runtime `instance_id` | Runtime 进程或副本身份 | 否 |
+| `mtls_deployment_id`、`mtls_binding_id`、`mtls_binding_epoch` | 证书部署连续性及安全绑定 | 是 |
+
+mTLS 不读取或改写前三类既有标识,也不提供另一套客户可配置的实例变量。`mtls_deployment_id` 仅保存在内部 profile 和绑定状态中;请求鉴权只发送带 `Mtls` 前缀的绑定 ID 与代次 Header。
+
+### 5. 哪些设置由工具管理
+
+普通部署只需显式开启 `JIUWENSWARM_LINK_MTLS_MODE=enforce`;证书相关信息由工具从已有部署参数和数据库派生:
+
+| 配置类别 | 来源与处理 |
+| --- | --- |
+| 业务数据库、服务名、命名空间、端口 | 复用原部署参数 |
+| mTLS 部署 ID、绑定 ID、绑定代次 | 首次随机生成并落库,后续读取数据库中的现有值;不由客户填写 |
+| CA 公共证书、角色证书及私钥 | 首次生成,之后从数据库恢复原材料 |
+| AgentServer Secret、headless Service、集群 DNS 域 | 部署层生成并注入 Runtime,由 Runtime 用于创建 AgentServer |
+| 内部 `profile.json` 及必要的 `JIUWENSWARM_LINK_MTLS_PROFILE` 路径 | 工具管理的内部身份文件,不是客户额外手写的配置文件 |
+
+不要通过手填 mTLS 部署/绑定 ID、提高 epoch、替换 profile 或删除表的方式解决身份冲突。这些值不是客户环境变量,也不复用 `GATEWAY_INSTANCE_ID` 或 Manager 的 `jiuwenclaw_id`。
+
+### 6. 如何确认生效
+
+确认部署完成且服务就绪。正常部署日志中会出现公开摘要 `mTLS binding ready`,包含 mTLS 部署/绑定编号、角色证书指纹、到期时间和 `reused` 状态,不包含私钥。
+
+- 首次准备成功:`reused=false`。
+- 使用已有材料:`reused=true`,指纹、绑定代次和到期时间保持不变。
+- 数据库、证书、Secret 或服务地址冲突:部署停止,不以明文 HTTP 继续完成。
+
+可在 Gateway 容器中使用其自身身份检查内部 HTTPS 健康接口;下面使用默认服务名和默认配置端口:
+
+```bash
+kubectl exec -n example-app deployment/jiuwenclaw-gateway -- python -c '
+import urllib.request
+from openjiuwen_runtime.foundation.security.link_profile import load_service_identity
+identity = load_service_identity("gateway")
+opener = urllib.request.build_opener(
+ urllib.request.ProxyHandler({}),
+ urllib.request.HTTPSHandler(context=identity.ssl_context()),
+)
+with opener.open("https://127.0.0.1:8775/api/v1/ready", timeout=5) as response:
+ print(response.status)
+'
+```
+
+预期为 `200`。该检查证明本机 HTTPS 健康路径可用,不代替跨组件业务验收。正常业务还应确认 Runtime 路由、AgentServer 调用及回复链路可用。
+
+有合法 TLS 证书但绑定或角色不符合要求时,应用层返回 `403` 和 `LINK_BINDING_MISMATCH`,并记录拒绝原因。无证书、非受信证书或明文请求可能在 TLS/协议层被直接拒绝,不保证收到 HTTP 状态码或应用层日志。排查时不要导出完整 Secret、私钥、Token 或带密码的数据库连接串。
+
+## 二、升级、重部署与故障处理
+
+### 1. 普通升级复用什么
+
+使用同一数据库和受管地址重新执行普通 `up`,会读取数据库中的现有材料,而不是每次生成一套新证书。
+
+| 情况 | 当前行为 |
+| --- | --- |
+| 普通升级、重复部署 | 复用原私钥和证书,绑定 ID、epoch、到期时间不变 |
+| 数据库材料完整,证书 Secret 缺失 | 从数据库创建缺失的同一份材料,不重新签发 |
+| 材料已入库,后续资源安装失败 | 后续重试读取已提交材料,校验通过后继续 |
+| Secret 与数据库不一致 | 停止,不默认选择一方覆盖另一方 |
+| 受管地址或 SAN 要求与已有材料不符 | 停止,要求按受控迁移处理 |
+| 证书过期、状态已撤销、材料不完整或版本不兼容 | 停止,不通过普通部署重新签发或重新激活 |
+| 只有旧公开绑定记录或旧版证书材料 | 不自动接管,要求明确的迁移方案 |
+| 数据库和可用备份均丢失 | 无法保证恢复原私钥与原身份 |
+
+新增材料字段以兼容补列处理,不要求重建业务表。历史 Link-Auth 数据不作为本机制的授权依据,也不由本功能删除。
+
+数据库备份和恢复必须纳入证书材料保护范围。不要用删除命名空间、Secret 或数据库来代替普通升级。
+
+### 2. 有效期与续期限制
+
+首次签发有效期为十个公历年;重复部署不会把到期时间向后延长。不同安装使用随机生成的私钥,不使用写死种子或固定公共私钥。
+
+当前没有自动续期服务,也没有交付跨组件证书轮换、解绑重绑和撤销的一键协调流程。CA 私钥在首次生成后不持久保存;更换身份需要新的受控签发与信任更新流程,不能假设仍可用原 CA 在线续签。
+
+发生私钥泄漏、临近到期或确需改变绑定时,应按维护方案协调数据库、Secret、信任关系和全部相关进程。仅编辑某个数据库字段或某份文件不能构成完整换证。对绑定或证书代次的变更,现有进程会拒绝不一致状态;不承诺透明热换证和存量会话无中断。
+
+### 3. 关闭与回退
+
+默认不启用,和已经启用后的回退是两种情况。已有 enforce 部署不能仅把一个组件改为 `off`;其他组件仍可能要求 HTTPS 和证书。
+
+如确需回退,应在维护窗口协调所有相关组件、已创建的 AgentServer、调用方地址及部署清单。仅修改 `.env.custom` 不会立即更新现有进程。关闭功能不等于撤销或删除已有证书,不建议为回退清空证书数据库。
+
+## 三、客户管理服务如何接入
+
+客户可实现自己的管理服务,其角色仍称为 `manager`。需由受控交付流程为该服务提供对应的 manager 角色材料,仅授予实际需要的管理权限,不应向浏览器或普通用户发放该私钥。Manager 角色证书是服务身份,不属于某一个 `jiuwenclaw_id`;一个 Manager 可以保存多条实例绑定。
+
+使用配套 Runtime foundation 的异步客户端示例:
+
+```python
+import asyncio
+import httpx
+from openjiuwen_runtime.foundation.security.link_profile import load_service_identity
+
+
+async def main():
+ identity = load_service_identity("manager")
+ # binding 由客户 Manager 按 jiuwenclaw_id 从自己的绑定库中读取。
+ binding = load_instance_binding("customer-instance-id")
+ url = identity.endpoint(binding.gateway_url, role="gateway")
+ headers = {
+ "X-Jiuwenswarm-Mtls-Binding-Id": binding.mtls_binding_id,
+ "X-Jiuwenswarm-Mtls-Binding-Epoch": str(binding.mtls_binding_epoch),
+ }
+ async with httpx.AsyncClient(
+ trust_env=False,
+ timeout=10,
+ **identity.client_kwargs(
+ role="gateway",
+ expected_fingerprints={binding.gateway_cert_fingerprint},
+ ca_file=binding.trust_bundle_file,
+ ),
+ ) as client:
+ response = await client.get(url, headers=headers)
+ response.raise_for_status()
+ print(response.status_code)
+
+
+asyncio.run(main())
+```
+
+前提是该进程已通过受控挂载取得 Manager 身份和目标实例信任包;示例中的 `load_instance_binding` 是客户管理服务自己的持久化读取逻辑,不由 JiuwenSwarm 提供。此代码不负责颁发证书或从数据库导出私钥。业务配置下发继续使用对应接口的原有业务请求结构。
+
+使用其他语言或 TLS 客户端时,须同时落实:服务端 CA 与 SAN 校验、目标角色指纹校验、正确的客户端角色证书和绑定头。不得仅校验“同一个 CA”或仅转发几个 Header。
+
+每条绑定至少需要保存 `jiuwenclaw_id`、`mtls_binding_id`、`mtls_binding_epoch`、Manager/Gateway/Runtime/AgentServer 证书指纹和信任包引用。Manager 发起配置写请求时,必须同时按实例选择绑定 Header、目标信任包和目标角色证书指纹,不能复用另一实例的绑定信息。
+
+Manager 与目标实例可使用共同受控 CA,也可以为每个实例挂载独立信任包;无论哪种方式,目标 Gateway/Runtime 都必须明确信任该 Manager 证书,Manager 也必须按绑定记录精确校验目标叶证书指纹。只使用一个全局 CA 而不做实例级目标指纹校验,不满足本设计。
+
+仓库内置 Manager 的参考登记接口为:
+
+```text
+PUT /api/v1/instances/{jiuwenclaw_id}/link-binding
+```
+
+请求中的 `{jiuwenclaw_id}` 必须是 Manager 已创建的业务实例 ID;接口不会修改该 ID,也不会把内部 `mtls_deployment_id` 写回 `instance_info`。请求体结构如下,示例值均为占位值:
+
+```json
+{
+ "mtls_binding_id": "deployment-binding-id",
+ "mtls_binding_epoch": 1,
+ "mtls_gateway_endpoint": "gateway-service-a:8775",
+ "mtls_runtime_endpoint": "runtime-service-a:8091",
+ "manager_cert_fingerprint": "64位SHA-256小写十六进制指纹",
+ "gateway_cert_fingerprint": "64位SHA-256小写十六进制指纹",
+ "runtime_cert_fingerprint": "64位SHA-256小写十六进制指纹",
+ "agentserver_cert_fingerprint": "64位SHA-256小写十六进制指纹",
+ "trust_bundle_ref": "file:///受控挂载路径/ca.crt",
+ "updated_by": "operator"
+}
+```
+
+登记顺序分为两类:
+
+1. 同一部署工具共同安装的 Manager、Gateway、Runtime:Manager 保持随机生成实例 ID;首次配置同步按 Gateway/Runtime 地址严格匹配部署 profile 后自动登记同一 binding,不要求人工复制 ID。
+2. 其他受管实例:先让 Manager 使用其已安装的信任链完成只读健康探测,再为 Manager 返回的业务实例 ID 调用绑定登记接口,最后执行该实例的配置同步。若目标使用独立 CA,必须在健康探测前把对应 CA 纳入受控信任配置;不得为通过探测而关闭 TLS 校验。
+
+绑定登记是幂等的:协议差异不影响地址匹配,登记时统一按 `host:port` 校验并保存;同一实例、同一 binding 和同一批证书材料可安全重放。地址不是合法 HTTP(S) 服务 authority、与 `instance_info` 不一致,或活动绑定的任一其他字段不同,均返回冲突。Manager 实际发请求时还会再次确认请求目标与绑定地址一致。解绑会递增 epoch 并释放 Gateway/Runtime 唯一占用,但数据库状态变化本身不会让已装载的证书立即失效,仍须配套完成材料替换和进程重启。
+
+## 四、实现原理
+
+### 1. 部署时的证书准备
+
+1. 部署工具读取已有服务、数据库和命名空间参数,预检已有证书资源及服务形态。
+2. 使用配套 Runtime 镜像在部署节点执行一次性处理命令,不新增独立的证书管理 Pod 或 Runtime 签发任务。
+3. 首次安装生成绑定编号、CA 和四种角色材料;已有安装读取并校验数据库材料。
+4. 先提交 Gateway 数据库中的完整材料,再同步 Runtime 公开绑定状态,随后创建缺失的 Kubernetes Secret。
+5. 渲染证书挂载、受管 HTTPS 地址和携带身份的探针,再进入原有组件部署与业务配置流程。
+
+代码职责沿用项目现有分层:`deploy/enterprise/link_mtls_handler.sh` 和 `templates/link-mtls.template.yaml` 负责部署编排与清单渲染;Runtime 的 `foundation/security` 负责证书、绑定和数据库材料处理。一次性材料命令在配套镜像内执行,不是部署目录中的独立 Python 脚本,也不是常驻服务。
+
+Gateway 与 Runtime 数据库、Kubernetes 资源之间没有全局事务。上述顺序通过“先提交、后发布、重试复用、冲突停止”减少身份分叉,不表示任意中途失败都能无需检查地跨系统回滚。
+
+### 2. 服务角色与请求授权
+
+| 调用目标 | 允许的角色/用途 |
+| --- | --- |
+| Gateway 配置接收接口 | `manager` |
+| Runtime 会话 route、touch、cleanup、config_refresh | `gateway` |
+| Runtime 配置下发接口 | `manager` |
+| AgentServer 业务接口 | `gateway` |
+| 约定的内部健康接口 | 已绑定的 `manager`、`gateway`、`runtime`;仍要求有效客户端证书 |
+
+四种角色各用不同私钥。`agentserver` 角色证书用于服务端;同一绑定中的多个 AgentServer 可以共享这份角色证书,表达的是角色身份而非每个 Pod 的唯一身份。
+
+每个请求先完成 TLS 双向证书校验,再校验实际 TLS 对端证书的角色指纹,以及以下绑定信息:
+
+| Header | 含义 |
+| --- | --- |
+| `X-Jiuwenswarm-Mtls-Binding-Id` | 当前部署绑定编号 |
+| `X-Jiuwenswarm-Mtls-Binding-Epoch` | 当前绑定代次 |
+
+这些 Header 不能代替证书,且不承载业务实例 ID。Manager 的 `jiuwenclaw_id` 继续留在原有 API 路径或业务请求中,只用于选择 `instance_link_binding`;目标必须同时匹配所选记录的 `mtls_binding_id`、`mtls_binding_epoch`、Manager 证书角色和证书指纹。知道实例编号、篡改 Header,或者持有同 CA 下其他角色的证书,不等于获得目标接口权限。服务端使用真实 TLS 对端证书,不信任请求自行声明的代理证书头。
+
+SSE 存续期间也会重新检查绑定资料;撤销或信任变化触发拒绝/关闭。此机制是进程读到有效变更后的拒绝能力,不等于已实现向所有进程自动分发撤销的控制服务。
+
+### 3. HTTPS 地址与动态 AgentServer
+
+部署工具只协调声明过的受管服务地址。已声明的 Gateway/Runtime 地址由解析器在 enforce 模式下使用同端口 HTTPS,不需要逐项手工替换受管 URL。
+
+未声明的外部地址必须显式为 `https://`,并通过对应 CA、SAN 和角色指纹校验。浏览器入口、模型厂商 API、外部 A2A 服务和用户登录服务不会被本功能全局改写成 HTTPS。
+
+Runtime 通过 headless Service 下的 Pod DNS 返回 AgentServer 地址,证书 SAN 覆盖该 DNS 范围,而不是预先登记动态 Pod IP。不能通过关闭 SAN 校验解决域名不匹配。
+
+### 4. Runtime 如何注入材料
+
+Runtime 创建 AgentServer 时,向主容器注入 AgentServer 专用 Secret 和身份配置,不向 JiuwenBox 注入这份证书,也不会把 Gateway 或 manager 私钥作为普通业务环境变量传给 AgentServer。
+
+保留原有 command、args、业务卷和权限配置。在需要适配非 root 或 fsGroup 的情况下,同一 Pod 内可使用受限的初始化/同步辅助容器,把投影材料复制到受控的内存卷;它们只处理文件副本,不签发、不续期,不是新的证书管理服务。
+
+## 五、数据保存与安全边界
+
+### 1. 保存位置
+
+| 位置 | 保存内容 |
+| --- | --- |
+| Gateway DB 的 `link_binding_state`,`service_role=gateway` 记录 | 当前公开绑定及可恢复的完整角色材料 |
+| Runtime DB 的 `link_binding_state`,`service_role=runtime` 记录 | Runtime 公开绑定、指纹、代次和 AgentServer Secret 引用;不保存整套角色私钥 |
+| Kubernetes Secret | `jiuwenswarm-link-gateway`、`jiuwenswarm-link-runtime`、`jiuwenswarm-link-agentserver`、`jiuwenswarm-link-manager`,各保存对应角色材料 |
+| Pod 内文件 | 角色私钥、证书、CA 公共证书及内部 profile 的只读挂载/受控副本 |
+| 可选 Manager 的 `instance_link_binding` | 每个 Manager 业务实例到部署绑定、目标角色指纹和信任包引用的映射;普通部署恢复不依赖 Manager 数据库 |
+
+没有要求客户额外维护主机持久证书目录;不表示证书只存在数据库中,运行时仍需要 Secret 和文件副本。
+
+### 2. 数据结构说明
+
+复用功能表 `link_binding_state`,不创建另一套并行的证书材料表。主要字段包括:
+
+| 字段 | 作用 |
+| --- | --- |
+| `service_role` | 本服务记录与角色 |
+| `mtls_deployment_id`、`mtls_binding_id`、`mtls_binding_epoch` | mTLS 内部部署连续性、绑定编号与绑定代次;均不复用业务/进程实例 ID |
+| `protocol_version` | 绑定协议结构版本,与软件版本号、证书有效期不同 |
+| `local_cert_pem`、`local_cert_fingerprint` | 本服务公开证书和指纹 |
+| `peer_trust_bundle_pem`、`private_key_ref` | CA 公共材料和运行时私钥引用 |
+| `agentserver_secret_ref`、`status` | AgentServer 材料引用和绑定状态 |
+| `material_schema_version`、`material_epoch` | 可恢复材料格式及对应代次 |
+| `certificate_materials` | Gateway 中的完整角色材料;TEXT/MySQL LONGTEXT,不作为普通业务响应返回 |
+
+首次使用创建功能表。如果业务进程已先创建同名的公开状态投影,部署阶段只为该功能表补充可空的材料列,不重建业务表。现有记录缺少可恢复材料、版本不兼容或与当前身份冲突时停止,不能把“记录不完整”当成新安装并直接重签。
+
+本设计不创建、读取、写入或迁移 `link_identity`。如测试环境曾运行未合入的早期实现并留下同名表,当前代码会直接忽略它;部署工具不会主动删除未知历史表。
+
+应用启动按公开状态核对 mTLS ID、指纹、epoch 和 active 状态;这些 ID 不作为客户环境变量,服务也不能自行覆盖数据库授权状态。
+
+### 3. 私钥与运维权限
+
+数据库在本方案中是可信的秘密保存边界。`certificate_materials` 包含可恢复私钥,没有由应用额外加密;读取敏感列、数据库备份或相应 Secret 的主体可能取得服务身份。Kubernetes Secret 的 Base64 编码也不是加密。
+
+需要限制数据库账号、备份访问、Secret RBAC 和部署执行权限,并按环境要求配置数据库传输与存储加密。普通 API 不返回私钥,不等于数据库管理员无法读取私钥。十年有效期是运维取舍,不代表内部网络不存在泄漏风险。
+
+角色私钥隔离不等于节点 root、特权容器或整个数据库失陷后的防护。当前方案也不代替用户登录、业务级用户/组织/Agent 授权、外部 A2A 访问控制和模型平台鉴权。
+
+### 4. 当前支持与限制
+
+支持首次十年签发、数据库持久化、普通升级复用、受管材料恢复、HTTP/SSE 双向证书与角色/绑定验证及拒绝日志。
+
+不提供自动续期、旧材料自动导入、跨组件一键轮换/解绑/撤销编排,也不承诺透明热换证。多实例 Manager 的绑定选择和精确目标指纹校验由协议与参考实现支持;远端实例的证书颁发、信任包挂载、首次登记及高可用切换仍需结合客户拓扑和运维体系完成。
diff --git a/jiuwenswarm/common/local_env_config.py b/jiuwenswarm/common/local_env_config.py
index b613fba9fd..9bcaae57b3 100644
--- a/jiuwenswarm/common/local_env_config.py
+++ b/jiuwenswarm/common/local_env_config.py
@@ -43,9 +43,7 @@ _DEFAULT_HEADERS_ALIASES = (
)
# Huawei MaaS / OfficeClaw: use the protocol-specific header as a fallback when
# ``default_headers`` is missing from the tip seal.
-_DEFAULT_HEADERS_FALLBACK_ALIASES = (
- "OFFICE_CLAW_HUAWEI_MAAS_HEADERS_JSON",
-)
+_DEFAULT_HEADERS_FALLBACK_ALIASES = ("OFFICE_CLAW_HUAWEI_MAAS_HEADERS_JSON",)
logger = logging.getLogger(__name__)
@@ -84,11 +82,24 @@ SPAWN_ENV_KEYS: frozenset[str] = frozenset(
"DISABLED_TOOLS",
# Code-mode generated-code co-author header switch; process shared.
"JIUWENSWARM_CODE_COAUTHOR_HEADER_ENABLED",
+ # HTTP/SSE service-to-service mTLS. These values are process-scoped;
+ # certificate paths point to files mounted by the deployment layer.
+ "JIUWENSWARM_LINK_MTLS_MODE",
+ "JIUWENSWARM_LINK_MTLS_PROFILE",
+ "JIUWENSWARM_LINK_MTLS_CA_FILE",
+ "JIUWENSWARM_LINK_MTLS_CERT_FILE",
+ "JIUWENSWARM_LINK_MTLS_KEY_FILE",
# launchEnv / config.yaml ${EXTENSION_DIRS}; process-shared (relay RELAYCLAW_SHARED_ENV_KEYS TBD).
"EXTENSION_DIRS",
}
)
+# Service credentials are protected process configuration, NOT browser/research
+# tool credentials. Runtime injects each AgentServer's own profile explicitly.
+LINK_SERVICE_ENV_KEYS = frozenset(
+ key for key in SPAWN_ENV_KEYS if key.startswith("JIUWENSWARM_LINK_")
+)
+
BUSINESS_MIRROR_KEYS: frozenset[str] = frozenset(
{
# A. sync agents[].env schema
@@ -194,7 +205,9 @@ def canonical_product_env_key(name: str) -> str:
"""Map ``JIUWENCLAW_*`` → ``JIUWENSWARM_*``; leave other keys unchanged."""
key = str(name)
if key.startswith(_LEGACY_PRODUCT_ENV_PREFIX):
- return _CANONICAL_PRODUCT_ENV_PREFIX + key[len(_LEGACY_PRODUCT_ENV_PREFIX):]
+ return _CANONICAL_PRODUCT_ENV_PREFIX + key.removeprefix(
+ _LEGACY_PRODUCT_ENV_PREFIX
+ )
return key
@@ -202,7 +215,9 @@ def legacy_product_env_key(name: str) -> str | None:
"""Return the relay ``JIUWENCLAW_*`` alias for a ``JIUWENSWARM_*`` key."""
key = str(name)
if key.startswith(_CANONICAL_PRODUCT_ENV_PREFIX):
- return _LEGACY_PRODUCT_ENV_PREFIX + key[len(_CANONICAL_PRODUCT_ENV_PREFIX):]
+ return _LEGACY_PRODUCT_ENV_PREFIX + key.removeprefix(
+ _CANONICAL_PRODUCT_ENV_PREFIX
+ )
return None
@@ -310,11 +325,15 @@ def resolve_env_ns(
if service_id is None and agent_id is None and bound is not None:
return bound
sid = normalize_env_ns_id(
- service_id if service_id is not None else (bound[0] if bound else _DEFAULT_SERVICE_ID),
+ service_id
+ if service_id is not None
+ else (bound[0] if bound else _DEFAULT_SERVICE_ID),
default=_DEFAULT_SERVICE_ID,
)
aid = normalize_env_ns_id(
- agent_id if agent_id is not None else (bound[1] if bound else _DEFAULT_AGENT_ID),
+ agent_id
+ if agent_id is not None
+ else (bound[1] if bound else _DEFAULT_AGENT_ID),
default=_DEFAULT_AGENT_ID,
)
return sid, aid
@@ -616,8 +635,10 @@ def clear_agent_env_ns(service_id: str, agent_id: str) -> None:
clear_staged=True,
)
if (
- normalize_env_ns_id(service_id, default=_DEFAULT_SERVICE_ID) == _DEFAULT_SERVICE_ID
- and normalize_env_ns_id(agent_id, default=_DEFAULT_AGENT_ID) == _DEFAULT_AGENT_ID
+ normalize_env_ns_id(service_id, default=_DEFAULT_SERVICE_ID)
+ == _DEFAULT_SERVICE_ID
+ and normalize_env_ns_id(agent_id, default=_DEFAULT_AGENT_ID)
+ == _DEFAULT_AGENT_ID
):
pop_track_b_bare_from_environ()
@@ -874,11 +895,11 @@ def export_agent_environ(
out: dict[str, str] = {}
tip = effective_tip(service_id, agent_id)
for k, v in tip.items():
- if v is None:
+ if v is None or k in LINK_SERVICE_ENV_KEYS:
continue
out[str(k)] = str(v)
for k in SPAWN_ENV_KEYS:
- if k in os.environ:
+ if k in os.environ and k not in LINK_SERVICE_ENV_KEYS:
out[k] = os.environ[k]
for k in PROCESS_UNIQUE_ENV_KEYS:
if k in os.environ:
@@ -896,6 +917,8 @@ def export_spawn_environ() -> dict[str, str]:
"""
out: dict[str, str] = {}
for key in SPAWN_ENV_KEYS | PROCESS_UNIQUE_ENV_KEYS:
+ if key in LINK_SERVICE_ENV_KEYS:
+ continue
value = os.environ.get(key)
if value is not None:
out[key] = value
@@ -1023,9 +1046,7 @@ def _ingest_legacy_guard_keys_into_baseline() -> None:
):
if key not in os.environ:
continue
- _process_baseline.setdefault(
- key, _plaintext_tip_value(key, os.environ[key])
- )
+ _process_baseline.setdefault(key, _plaintext_tip_value(key, os.environ[key]))
def ingest_bare_business_into_tip(*, force: bool = False) -> None:
diff --git a/jiuwenswarm/common/security/link_mtls.py b/jiuwenswarm/common/security/link_mtls.py
new file mode 100644
index 0000000000..0cf9cdb83d
--- /dev/null
+++ b/jiuwenswarm/common/security/link_mtls.py
@@ -0,0 +1,158 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""HTTP/SSE internal-link mTLS configuration shared by Gateway and AgentServer.
+
+The feature is deliberately opt-in. With the default ``off`` mode this module
+does not create SSL contexts, rewrite URLs, or change the existing HTTP path.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import os
+import ssl
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Mapping
+from urllib.parse import urlsplit
+
+from openjiuwen_runtime.foundation.security.link_mtls_config import (
+ MODE_ENV,
+ MTLSDeploymentIdentity,
+ LinkMTLSMode,
+)
+from openjiuwen_runtime.foundation.security.link_profile import (
+ LinkProfile,
+ LinkProfileError,
+ load_service_identity,
+)
+
+logger = logging.getLogger(__name__)
+
+LinkMTLSError = LinkProfileError
+
+
+def _env(name: str) -> str:
+ return (os.getenv(name) or "").strip()
+
+
+@dataclass(frozen=True)
+class LinkMTLSConfig:
+ mode: LinkMTLSMode
+
+ profile: LinkProfile | None = None
+ ca_file: str | None = None
+ cert_file: str | None = None
+ key_file: str | None = None
+ identity: MTLSDeploymentIdentity | None = None
+
+ @classmethod
+ def from_env(cls, *, role: str = "gateway") -> "LinkMTLSConfig":
+ try:
+ mode = LinkMTLSMode(_env(MODE_ENV) or "off")
+ except ValueError as exc:
+ raise LinkMTLSError(f"{MODE_ENV} must be off, observe or enforce") from exc
+
+ shared = {}
+ if mode is LinkMTLSMode.OFF:
+ return cls(mode=mode, **shared)
+ try:
+ if role not in {"gateway", "agentserver"}:
+ raise LinkMTLSError("unsupported JiuwenSwarm service role")
+ profile = load_service_identity(role)
+ except (ValueError, OSError) as exc:
+ if mode is LinkMTLSMode.ENFORCE:
+ raise LinkMTLSError(str(exc)) from exc
+ logger.warning("link mTLS observe preflight failed: %s", exc)
+ return cls(mode=mode, **shared)
+ if mode is LinkMTLSMode.OBSERVE:
+ logger.info(
+ "link mTLS observe material preflight passed; business transport unchanged"
+ )
+ return cls(mode=mode, **shared)
+ return cls(
+ mode=mode,
+ profile=profile,
+ ca_file=profile.ca_file,
+ cert_file=profile.cert_file,
+ key_file=profile.key_file,
+ identity=MTLSDeploymentIdentity(
+ profile.mtls_deployment_id,
+ profile.mtls_binding_id,
+ profile.mtls_binding_epoch,
+ ),
+ **shared,
+ )
+
+ def resolve_endpoint(self, url: str, *, role: str) -> str:
+ if self.profile is not None:
+ return self.profile.endpoint(url, role=role, enforced=self.enforced)
+ self.require_secure_url(url, label=f"{role} URL")
+ return url
+
+ def client_kwargs(self, *, role: str) -> dict:
+ if not self.enforced:
+ return {}
+ if self.profile is None:
+ raise LinkMTLSError("enforce requires a pinned deployment profile")
+ return self.profile.client_kwargs(role=role)
+
+ def authorize_request(self, request) -> None:
+ if self.enforced:
+ if self.profile is None:
+ raise LinkMTLSError("enforce requires a pinned deployment profile")
+ self.profile.authorize(request.scope, request.headers)
+
+ @property
+ def enforced(self) -> bool:
+ return self.mode is LinkMTLSMode.ENFORCE
+
+ def client_ssl_context(self) -> ssl.SSLContext | None:
+ if not self.ca_file or not self.cert_file or not self.key_file:
+ return None
+ context = ssl.create_default_context(
+ purpose=ssl.Purpose.SERVER_AUTH,
+ cafile=self.ca_file,
+ )
+ context.minimum_version = ssl.TLSVersion.TLSv1_2
+ context.check_hostname = True
+ context.verify_mode = ssl.CERT_REQUIRED
+ context.load_cert_chain(certfile=self.cert_file, keyfile=self.key_file)
+ return context
+
+ def uvicorn_ssl_kwargs(self) -> dict[str, object]:
+ if not self.enforced:
+ return {}
+ if self.profile is None:
+ raise LinkMTLSError("enforce requires a pinned deployment profile")
+ return self.profile.server_kwargs()
+
+ def require_secure_url(self, url: str, *, label: str) -> None:
+ if self.enforced and urlsplit(url).scheme.lower() != "https":
+ raise LinkMTLSError(
+ f"{label} must use https:// when {MODE_ENV}=enforce: {url!r}"
+ )
+
+ def binding_headers(self) -> dict[str, str]:
+ if self.profile is not None:
+ return self.profile.headers()
+ return self.identity.headers() if self.identity is not None else {}
+
+ def cert_fingerprint(self) -> str:
+ """Return a stable SHA-256 fingerprint for the configured public cert."""
+ if not self.cert_file:
+ return ""
+ return hashlib.sha256(
+ ssl.PEM_cert_to_DER_cert(Path(self.cert_file).read_text())
+ ).hexdigest()
+
+
+def validate_incoming_binding(
+ headers: Mapping[str, str], config: LinkMTLSConfig
+) -> None:
+ """Validate application binding metadata after the mTLS handshake."""
+ if config.enforced:
+ raise LinkMTLSError(
+ "header-only validation is unsafe; use authorize_request with TLS peer scope"
+ )
diff --git a/jiuwenswarm/gateway/config/enterprise/link_binding_state.py b/jiuwenswarm/gateway/config/enterprise/link_binding_state.py
new file mode 100644
index 0000000000..3a55a4555a
--- /dev/null
+++ b/jiuwenswarm/gateway/config/enterprise/link_binding_state.py
@@ -0,0 +1,102 @@
+# coding: utf-8
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Persist the Gateway's effective HTTP/SSE certificate binding state."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+from openjiuwen_runtime.foundation.security.link_material_store import (
+ assert_binding_state_compatible,
+ assert_managed_state,
+)
+
+from jiuwenswarm.common.security.link_mtls import (
+ LinkMTLSConfig,
+ LinkMTLSError,
+ LinkMTLSMode,
+)
+from jiuwenswarm.gateway.config.enterprise.tables.link_binding_state_models import (
+ LINK_BINDING_STATE_TABLE,
+)
+
+LOCAL_SERVICE_ROLE = "gateway"
+PROTOCOL_VERSION = "0.0.1"
+
+
+def _utc_now() -> datetime:
+ return datetime.now(timezone.utc).replace(tzinfo=None)
+
+
+async def sync_local_link_binding_state(db: Any, config: LinkMTLSConfig) -> Any | None:
+ """Idempotently persist the active public identity; ``off`` writes nothing."""
+ if config.mode is LinkMTLSMode.OFF:
+ return None
+ if not config.identity or not config.cert_file or not config.ca_file:
+ # Observe mode may intentionally run an incomplete material preflight.
+ return None
+
+ now = _utc_now()
+ payload = {
+ "service_role": "gateway",
+ "mtls_deployment_id": config.identity.mtls_deployment_id,
+ "mtls_binding_id": config.identity.mtls_binding_id,
+ "protocol_version": PROTOCOL_VERSION,
+ "mtls_binding_epoch": config.identity.mtls_binding_epoch,
+ "local_cert_pem": Path(config.cert_file).read_text(encoding="utf-8"),
+ "local_cert_fingerprint": config.cert_fingerprint(),
+ "private_key_ref": config.key_file or "",
+ "peer_trust_bundle_pem": Path(config.ca_file).read_text(encoding="utf-8"),
+ "status": "active",
+ "updated_at": now,
+ }
+ row = await db.get(LINK_BINDING_STATE_TABLE, {"service_role": LOCAL_SERVICE_ROLE})
+ managed = await assert_managed_state(
+ db,
+ LOCAL_SERVICE_ROLE,
+ config.identity,
+ payload["local_cert_fingerprint"],
+ required=bool(
+ config.profile and config.profile.current().get("persistence") == "database"
+ ),
+ )
+ if managed:
+ return (
+ row # Deployment owns the authorized state; service startup is read-only.
+ )
+ assert_binding_state_compatible(
+ row, config.identity, payload["local_cert_fingerprint"]
+ )
+ if row is None:
+ return await db.create(
+ LINK_BINDING_STATE_TABLE,
+ {"created_at": now, **payload},
+ )
+ previous_epoch = int(getattr(row, "mtls_binding_epoch", 0) or 0)
+ filters = {"service_role": LOCAL_SERVICE_ROLE}
+ if hasattr(row, "mtls_binding_epoch"):
+ filters["mtls_binding_epoch"] = previous_epoch
+ filters["status"] = getattr(row, "status", "active")
+ updated = await db.update(LINK_BINDING_STATE_TABLE, filters, payload)
+ # DBHandler.update re-reads with the OLD filters, so an epoch change may
+ # return None even after a successful conditional update.
+ if hasattr(row, "mtls_binding_epoch"):
+ updated = await db.get(
+ LINK_BINDING_STATE_TABLE, {"service_role": LOCAL_SERVICE_ROLE}
+ )
+ checked_fields = (
+ "mtls_binding_id",
+ "mtls_binding_epoch",
+ "status",
+ "local_cert_fingerprint",
+ )
+ if updated is None or any(
+ getattr(updated, key, None) != payload.get(key) for key in checked_fields
+ ):
+ raise LinkMTLSError(
+ "link binding state changed concurrently; restart with the current profile"
+ )
+ return updated
diff --git a/jiuwenswarm/gateway/config/enterprise/tables/link_binding_state_models.py b/jiuwenswarm/gateway/config/enterprise/tables/link_binding_state_models.py
new file mode 100644
index 0000000000..8a5db50533
--- /dev/null
+++ b/jiuwenswarm/gateway/config/enterprise/tables/link_binding_state_models.py
@@ -0,0 +1,55 @@
+# coding: utf-8
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Gateway local HTTP/SSE certificate binding state, unrelated to Identity Center.
+
+This application projection exposes only public certificate material and
+private-key references. The deployment-owned extension of the same table may
+store the recoverable all-role bundle in ``certificate_materials``; application
+ORM access deliberately omits that sensitive column.
+"""
+
+from __future__ import annotations
+
+from openjiuwen_runtime.foundation.db.table_def import (
+ ColumnDefinition,
+ IndexDefinition,
+ TableDefinition,
+)
+
+LINK_BINDING_STATE_TABLE = "link_binding_state"
+
+LINK_BINDING_STATE_TABLE_DEF = TableDefinition(
+ table_name=LINK_BINDING_STATE_TABLE,
+ columns=[
+ ColumnDefinition(
+ "service_role", "string", length=32, primary_key=True, nullable=False
+ ),
+ ColumnDefinition("mtls_deployment_id", "string", length=64, nullable=False),
+ ColumnDefinition("mtls_binding_id", "string", length=64, nullable=False),
+ ColumnDefinition("protocol_version", "string", length=32, nullable=False),
+ ColumnDefinition("mtls_binding_epoch", "integer", nullable=False),
+ ColumnDefinition("local_cert_pem", "text", nullable=False),
+ ColumnDefinition(
+ "local_cert_fingerprint", "string", length=128, nullable=False
+ ),
+ ColumnDefinition("private_key_ref", "string", length=512, nullable=False),
+ ColumnDefinition("peer_trust_bundle_pem", "text", nullable=False),
+ ColumnDefinition(
+ "status", "string", length=32, nullable=False, default="active"
+ ),
+ ColumnDefinition("created_at", "datetime", nullable=False),
+ ColumnDefinition("updated_at", "datetime", nullable=False),
+ ],
+ indexes=[
+ IndexDefinition(
+ ["mtls_deployment_id"],
+ unique=True,
+ name="uq_link_binding_state_mtls_deployment_id",
+ ),
+ IndexDefinition(
+ ["mtls_binding_id"], unique=True, name="uq_link_binding_state_binding_id"
+ ),
+ IndexDefinition(["status"], unique=False, name="ix_link_binding_state_status"),
+ ],
+)
diff --git a/jiuwenswarm/gateway/config/enterprise/tables/table_init.py b/jiuwenswarm/gateway/config/enterprise/tables/table_init.py
index 99a07119e1..5136c26a04 100644
--- a/jiuwenswarm/gateway/config/enterprise/tables/table_init.py
+++ b/jiuwenswarm/gateway/config/enterprise/tables/table_init.py
@@ -8,36 +8,37 @@ from __future__ import annotations
from openjiuwen_runtime.foundation.db.handler import DBHandler
from openjiuwen_runtime.foundation.db.table_def import TableDefinition
+from .a2a_migration import ensure_dispatch_user_column
from .a2a_models import (
A2A_OUTBOUND_DISPATCH_TABLE_DEF,
A2A_OUTBOUND_RUNTIME_STATE_TABLE_DEF,
A2A_OUTBOUND_USER_STATE_TABLE_DEF,
)
-from .a2a_migration import ensure_dispatch_user_column
from .application_config_models import (
LOG_MASKING_RULE_TABLE_DEF,
LOGGING_CONFIG_TABLE_DEF,
- TASK_MEMORY_CONFIG_TABLE_DEF,
MEMORY_CONFIG_TABLE_DEF,
+ TASK_MEMORY_CONFIG_TABLE_DEF,
)
from .cron_job_models import CRON_JOB_TABLE_DEF
-from .session_map_models import SESSION_MAP_TABLE_DEF
+from .instance_resource_models import INSTANCE_AGENT_RESOURCE_TABLE_DEF
from .key_models import (
GATEWAY_ENC_KEYPAIR_TABLE_DEF,
GATEWAY_SIGN_KEYPAIR_TABLE_DEF,
MANAGER_SIGN_PUBKEY_TABLE_DEF,
)
-from .instance_resource_models import INSTANCE_AGENT_RESOURCE_TABLE_DEF
+from .link_binding_state_models import LINK_BINDING_STATE_TABLE_DEF
+from .session_map_models import SESSION_MAP_TABLE_DEF
from .template_models import (
A2A_ACCESS_POLICY_TEMPLATE_TABLE_DEF,
A2A_OUTBOUND_TEMPLATE_TABLE_DEF,
AGENT_TEMPLATE_TABLE_DEF,
EMBEDDING_TEMPLATE_TABLE_DEF,
EXTENSION_CONFIG_TEMPLATE_TABLE_DEF,
+ MCP_TEMPLATE_TABLE_DEF,
MODEL_TEMPLATE_TABLE_DEF,
PERMISSIONS_TEMPLATE_TABLE_DEF,
SKILL_PREBUILT_TEMPLATE_TABLE_DEF,
- MCP_TEMPLATE_TABLE_DEF,
)
ALL_TABLE_DEFINITIONS: tuple[TableDefinition, ...] = (
@@ -63,6 +64,7 @@ ALL_TABLE_DEFINITIONS: tuple[TableDefinition, ...] = (
MEMORY_CONFIG_TABLE_DEF,
CRON_JOB_TABLE_DEF,
SESSION_MAP_TABLE_DEF,
+ LINK_BINDING_STATE_TABLE_DEF,
)
diff --git a/jiuwenswarm/gateway/routing/http_agent_client.py b/jiuwenswarm/gateway/routing/http_agent_client.py
index 61a4cc0d59..9c5a4e7a54 100644
--- a/jiuwenswarm/gateway/routing/http_agent_client.py
+++ b/jiuwenswarm/gateway/routing/http_agent_client.py
@@ -20,6 +20,7 @@ from jiuwenswarm.common.e2a.constants import (
from jiuwenswarm.common.e2a.models import E2AEnvelope
from jiuwenswarm.common.e2a.wire_codec import parse_agent_server_wire_chunk
from jiuwenswarm.common.schema.agent import AgentResponse, AgentResponseChunk
+from jiuwenswarm.common.security.link_mtls import LinkMTLSConfig
from jiuwenswarm.gateway.routing.agent_client import (
AGENT_REQUEST_TIMEOUT_SECONDS,
AgentServerClient,
@@ -127,6 +128,7 @@ class HttpSseAgentServerClient(AgentServerClient):
*,
timeout_s: float = AGENT_REQUEST_TIMEOUT_SECONDS,
http_client: httpx.AsyncClient | None = None,
+ link_mtls_config: LinkMTLSConfig | None = None,
) -> None:
self._timeout_s = float(timeout_s)
self._http = http_client
@@ -142,6 +144,17 @@ class HttpSseAgentServerClient(AgentServerClient):
self._stream_lock = asyncio.Lock()
self._cancelled_request_ids: set[str] = set()
self._inflight_stream_ids: set[str] = set()
+ self._link_mtls = link_mtls_config
+
+ def _link_config(self) -> LinkMTLSConfig:
+ if self._link_mtls is None:
+ self._link_mtls = LinkMTLSConfig.from_env()
+ return self._link_mtls
+
+ def _request_headers(self, headers: dict[str, str] | None = None) -> dict[str, str]:
+ merged = dict(headers or {})
+ merged.update(self._link_config().binding_headers())
+ return merged
def set_or_update_server_config(
self,
@@ -178,23 +191,30 @@ class HttpSseAgentServerClient(AgentServerClient):
def _ensure_http(self) -> httpx.AsyncClient:
if self._http is None:
+ link_mtls = self._link_config()
self._http = httpx.AsyncClient(
timeout=httpx.Timeout(self._timeout_s, connect=_CONNECT_TIMEOUT_SECONDS),
limits=httpx.Limits(max_connections=20, max_keepalive_connections=10),
follow_redirects=False,
trust_env=False,
+ **link_mtls.client_kwargs(role="agentserver"),
)
self._owns_http = True
return self._http
def _resolve_api_root(self, base_url: str | None) -> str:
if base_url:
+ # Enterprise routing may supply a per-Pod endpoint without calling
+ # connect() first. Apply the same downgrade protection here so an
+ # enforce-mode request can never bypass HTTPS through base_url.
+ base_url = self._link_config().resolve_endpoint(base_url, role="agentserver")
return normalize_agent_http_base(base_url)
if not self._running or not self._api_root:
raise RuntimeError("未连接 AgentServer HTTP,请先调用 connect(uri)")
return self._api_root
async def connect(self, uri: str) -> None:
+ uri = self._link_config().resolve_endpoint(uri, role="agentserver")
if self._running:
await self.disconnect()
scheme = (urlsplit(uri).scheme or "").lower()
@@ -205,10 +225,14 @@ class HttpSseAgentServerClient(AgentServerClient):
)
self._base_url = uri.rstrip("/")
self._api_root = normalize_agent_http_base(uri)
+ self._link_config().require_secure_url(uri, label="AgentServer URL")
self._ensure_http()
health_url = f"{self._api_root}/health"
logger.info("[HttpSseAgentServerClient] 正在连接: %s", health_url)
- response = await self._http.get(health_url, headers={"Accept": "application/json"})
+ response = await self._http.get(
+ health_url,
+ headers=self._request_headers({"Accept": "application/json"}),
+ )
payload: dict[str, Any] = {}
try:
parsed = response.json()
@@ -273,7 +297,7 @@ class HttpSseAgentServerClient(AgentServerClient):
response = await http.request(
assembled.verb,
assembled.url,
- headers=assembled.headers,
+ headers=self._request_headers(assembled.headers),
json=assembled.json_body,
params=assembled.query,
)
@@ -345,7 +369,7 @@ class HttpSseAgentServerClient(AgentServerClient):
async with http.stream(
assembled.verb,
assembled.url,
- headers=assembled.headers,
+ headers=self._request_headers(assembled.headers),
json=assembled.json_body,
params=assembled.query,
timeout=timeout,
@@ -409,7 +433,9 @@ class HttpSseAgentServerClient(AgentServerClient):
async with http.stream(
"GET",
url,
- headers={"X-Jiuwen-Push-Consumer": "gateway"},
+ headers=self._request_headers(
+ {"X-Jiuwen-Push-Consumer": "gateway"}
+ ),
timeout=timeout,
) as response:
response.raise_for_status()
diff --git a/jiuwenswarm/gateway/storage_assembly/db_connection.py b/jiuwenswarm/gateway/storage_assembly/db_connection.py
index 95c79aa418..b0542d537d 100644
--- a/jiuwenswarm/gateway/storage_assembly/db_connection.py
+++ b/jiuwenswarm/gateway/storage_assembly/db_connection.py
@@ -68,6 +68,12 @@ class GatewayDbConnection:
db = self._db_obj or self._bind_database()
# ``Database.ensure_ready`` 已调用 ``init_all_tables``(幂等)。
handler = await db.ensure_ready(log_prefix="gateway_storage")
+ from jiuwenswarm.common.security.link_mtls import LinkMTLSConfig
+ from jiuwenswarm.gateway.config.enterprise.link_binding_state import (
+ sync_local_link_binding_state,
+ )
+
+ await sync_local_link_binding_state(handler, LinkMTLSConfig.from_env())
self._handler = handler
return handler
diff --git a/jiuwenswarm/server/agent_http_routes.py b/jiuwenswarm/server/agent_http_routes.py
index 7ed4a8924c..ac2c2b5a94 100644
--- a/jiuwenswarm/server/agent_http_routes.py
+++ b/jiuwenswarm/server/agent_http_routes.py
@@ -551,6 +551,16 @@ def wants_stream(request: Any, params: dict[str, Any]) -> bool:
def build_fastapi_app(server: AgentHTTPServer) -> Any:
"""构建 FastAPI 应用并注册全部路由。"""
+ from jiuwenswarm.common.security.link_mtls import (
+ LinkMTLSConfig,
+ )
+
+ link_mtls = LinkMTLSConfig.from_env(role="agentserver")
+ response_type = EventSourceResponse
+ if link_mtls.enforced:
+ from jiuwenswarm.server.transports.link_sse_response import LinkEventSourceResponse
+
+ response_type = LinkEventSourceResponse
app = FastAPI(
title="JiuwenSwarm AgentServer HTTP API",
version="1.0.0",
@@ -570,6 +580,11 @@ def build_fastapi_app(server: AgentHTTPServer) -> Any:
allow_headers=["*"],
)
+ if link_mtls.enforced:
+ from openjiuwen_runtime.foundation.security.link_stream_guard import LinkBindingMiddleware
+
+ app.add_middleware(LinkBindingMiddleware, authorize=link_mtls.authorize_request)
+
def _make_endpoint(spec: RouteSpec) -> Callable:
async def endpoint(request: Request) -> JSONResponse:
params = await collect_params(request)
@@ -607,12 +622,14 @@ def build_fastapi_app(server: AgentHTTPServer) -> Any:
name=f"{spec.verb} {spec.path}",
)
- _register_special_routes(app, server)
+ _register_special_routes(app, server, response_type=response_type)
logger.info("[AgentHTTPRoutes] 已注册 %d 条声明式路由 + 特殊路由", len(ROUTES))
return app
-def _register_special_routes(app: Any, server: AgentHTTPServer) -> None:
+def _register_special_routes(
+ app: Any, server: AgentHTTPServer, *, response_type=EventSourceResponse,
+) -> None:
"""注册流式与通用透传接口。"""
@app.get(f"{API_PREFIX}/health")
@@ -645,8 +662,9 @@ def _register_special_routes(app: Any, server: AgentHTTPServer) -> None:
qp = request.query_params
session_filter = qp.get("session_id") or ctx.session_id
channel_filter = qp.get("channel_id")
- # 信任边界假设:此头仅由内部 Gateway 设置,可被伪造;若端点可能暴露给
- # 不受信任客户端,需改用 mTLS/共享密钥等强验证。
+ # 该头只表达 Gateway 是否支持反向 RPC,不再单独承担身份认证:
+ # enforce 模式下本请求已先经过 mTLS 与 binding guard;off/observe 模式
+ # 继续保留旧兼容语义,部署侧不得把本内部端点暴露给不受信任网络。
reverse_rpc_capable = (
request.headers.get("x-jiuwen-push-consumer") == "gateway"
)
@@ -695,14 +713,14 @@ def _register_special_routes(app: Any, server: AgentHTTPServer) -> None:
registry.unregister(subscriber_id)
# sse_starlette 自带 ping(默认 15s 注释帧)保活,无需自行实现心跳。
- return EventSourceResponse(_events(), headers={"X-Request-Id": ctx.request_id})
+ return response_type(_events(), headers={"X-Request-Id": ctx.request_id})
async def _chat(request: Request, method: str) -> Any:
params = await collect_params(request)
ctx = request_context(request)
session_id = ctx.session_id or params.get("session_id")
if wants_stream(request, params):
- return EventSourceResponse(
+ return response_type(
server.iter_stream(
method,
params,
@@ -744,7 +762,7 @@ def _register_special_routes(app: Any, server: AgentHTTPServer) -> None:
async def history_stream(request: Request) -> Any: # noqa: ANN202
params = await collect_params(request)
ctx = request_context(request)
- return EventSourceResponse(
+ return response_type(
server.iter_stream(
ReqMethod.HISTORY_GET.value,
params,
@@ -781,7 +799,7 @@ def _register_special_routes(app: Any, server: AgentHTTPServer) -> None:
params.pop("method", None)
session_id = ctx.session_id or params.get("session_id")
if wants_stream(request, params):
- return EventSourceResponse(
+ return response_type(
server.iter_stream(
method,
params,
@@ -831,7 +849,7 @@ def _register_special_routes(app: Any, server: AgentHTTPServer) -> None:
# 信封自称流式:必须走 SSE。用非流式 sink 接会静默丢内容 ——
# 业务层全程 send_chunk,而 UnaryHTTPSink 只记 send_unary/send_wire 的帧,
# 结果是 HTTP 200 + data:null,调用方拿到"成功"却什么也没有。
- return EventSourceResponse(
+ return response_type(
server.iter_raw_envelope(
json.dumps(envelope, ensure_ascii=False), request_id=request_id
),
diff --git a/jiuwenswarm/server/agent_http_server.py b/jiuwenswarm/server/agent_http_server.py
index 5f33a0fa41..17a90cf678 100644
--- a/jiuwenswarm/server/agent_http_server.py
+++ b/jiuwenswarm/server/agent_http_server.py
@@ -693,7 +693,12 @@ class AgentHTTPServer:
"""
import uvicorn
- bindable = self._find_bindable_port()
+ from jiuwenswarm.common.security.link_mtls import LinkMTLSConfig, LinkMTLSError
+
+ link_mtls = LinkMTLSConfig.from_env(role="agentserver")
+ if link_mtls.enforced and not is_port_available(self._host, self._port):
+ raise LinkMTLSError("enforce listener port is occupied; refusing automatic port drift")
+ bindable = self._port if link_mtls.enforced else self._find_bindable_port()
if bindable is None:
logger.error(
"[AgentHTTPServer] 端口 %s:%s 起连续 %d 个候选均被占用,HTTP 入口未启动"
@@ -712,6 +717,11 @@ class AgentHTTPServer:
self._port = bindable
app = self.build_app()
+ if link_mtls.mode.value == "observe":
+ logger.info(
+ "[AgentHTTPServer] link mTLS observe preflight complete; "
+ "data path remains HTTP"
+ )
config = uvicorn.Config(
app,
host=self._host,
@@ -719,6 +729,7 @@ class AgentHTTPServer:
log_level="info",
access_log=False,
lifespan="on",
+ **link_mtls.uvicorn_ssl_kwargs(),
)
self._server = uvicorn.Server(config)
@@ -753,7 +764,8 @@ class AgentHTTPServer:
return False
logger.info(
- "[AgentHTTPServer] 已启动: http://%s:%s%s", self._host, self._port, API_PREFIX
+ "[AgentHTTPServer] 已启动: %s://%s:%s%s",
+ "https" if link_mtls.enforced else "http", self._host, self._port, API_PREFIX
)
return True
diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.py
index 8df058be7c..e1d450f3b6 100644
--- a/jiuwenswarm/server/agent_ws_server.py
+++ b/jiuwenswarm/server/agent_ws_server.py
@@ -443,7 +443,7 @@ class AgentWebSocketServer:
# ---------- 生命周期 ----------
- async def start(self) -> None:
+ async def start(self, *, listen: bool = True) -> None:
"""启动 WebSocket 服务端,开始监听连接。优先使用 legacy.server.serve 以与 Gateway 的 legacy client 握手兼容.
注: persistent checkpointer 的初始化历史在 ``legacy_serve`` 之前同步 await,
@@ -460,31 +460,34 @@ class AgentWebSocketServer:
# Reset harness package state to native on service startup
reset_harness_packages_state()
- try:
- from websockets.legacy.server import serve as legacy_serve
- self._server = await legacy_serve(
- self._connection_handler,
- self._host,
- self._port,
- process_request=self._process_request,
- ping_interval=self._ping_interval,
- ping_timeout=self._ping_timeout,
- max_size=AGENT_WS_MAX_MESSAGE_BYTES,
- )
- except ImportError:
- import websockets
- self._server = await websockets.serve(
- self._connection_handler,
- self._host,
- self._port,
- process_request=self._process_request,
- ping_interval=self._ping_interval,
- ping_timeout=self._ping_timeout,
- max_size=AGENT_WS_MAX_MESSAGE_BYTES,
+ if listen:
+ try:
+ from websockets.legacy.server import serve as legacy_serve
+ self._server = await legacy_serve(
+ self._connection_handler,
+ self._host,
+ self._port,
+ process_request=self._process_request,
+ ping_interval=self._ping_interval,
+ ping_timeout=self._ping_timeout,
+ max_size=AGENT_WS_MAX_MESSAGE_BYTES,
+ )
+ except ImportError:
+ import websockets
+ self._server = await websockets.serve(
+ self._connection_handler,
+ self._host,
+ self._port,
+ process_request=self._process_request,
+ ping_interval=self._ping_interval,
+ ping_timeout=self._ping_timeout,
+ max_size=AGENT_WS_MAX_MESSAGE_BYTES,
+ )
+ logger.info(
+ "[AgentWebSocketServer] 已启动: ws://%s:%s", self._host, self._port
)
- logger.info(
- "[AgentWebSocketServer] 已启动: ws://%s:%s", self._host, self._port
- )
+ else:
+ logger.info("[AgentServer] handler initialized without an unauthenticated WS listener")
# 启动端到端预热:interface_deep import → checkpointer → 临时 DeepAgent → query。
# 拆成两个 task:
# - _startup_warmup_task 承载阶段1/2(import+checkpointer),快速有界,
@@ -1527,4 +1530,3 @@ class AgentWebSocketServer:
"[AgentServer] Built model cache with %d models, default=%s",
len(self._model_cache), first_name
)
-
diff --git a/jiuwenswarm/server/app_agentserver.py b/jiuwenswarm/server/app_agentserver.py
index aed919f6f8..5a06c68af7 100644
--- a/jiuwenswarm/server/app_agentserver.py
+++ b/jiuwenswarm/server/app_agentserver.py
@@ -218,6 +218,8 @@ async def _run(host: str, port: int) -> None:
async def _run_with_telemetry(host: str, port: int, telemetry_lifecycle) -> None:
+ from jiuwenswarm.common.security.link_mtls import LinkMTLSConfig
+ link_mtls = LinkMTLSConfig.from_env(role="agentserver") # fail before starting any listener
from openjiuwen.core.runner import Runner
from jiuwenswarm.server.agent_ws_server import AgentWebSocketServer
from jiuwenswarm.agents.harness.team.remote_member_bootstrap import run_teammate_bootstrap_daemon
@@ -315,7 +317,10 @@ async def _run_with_telemetry(host: str, port: int, telemetry_lifecycle) -> None
host=host,
port=port
)
- await server.start()
+ if link_mtls.enforced:
+ await server.start(listen=False)
+ else:
+ await server.start()
# ---------- ProactiveEngine 初始化 ----------
# 适配逻辑(建专用 agent + 触发主 agent 回调)封装在 proactive_adapter,
@@ -337,7 +342,7 @@ async def _run_with_telemetry(host: str, port: int, telemetry_lifecycle) -> None
)
http_enabled, http_host, http_port = resolve_http_server_settings(host)
- if http_enabled:
+ if http_enabled or link_mtls.enforced:
candidate = AgentHTTPServer(server, host=http_host, port=http_port)
# start() 自身不抛异常;失败返回 False,WebSocket 主链路不受影响。
http_server = candidate if await candidate.start() else None
@@ -346,10 +351,20 @@ async def _run_with_telemetry(host: str, port: int, telemetry_lifecycle) -> None
"[AgentServer] HTTP 入口未开启(config.yaml http_server.enabled 或 AGENT_HTTP_ENABLED)"
)
except Exception as exc: # noqa: BLE001 - HTTP 入口不可用不应阻断 WS 主链路
+ if link_mtls.enforced:
+ await server.stop()
+ raise RuntimeError("AgentServer enforce HTTPS startup failed; no WS fallback") from exc
logger.error("[AgentServer] HTTP 入口启动失败,仅 WebSocket 可用: %s", exc, exc_info=True)
http_server = None
- if http_server is not None:
+ if link_mtls.enforced and http_server is None:
+ await server.stop()
+ raise RuntimeError("AgentServer enforce requires a working HTTPS listener")
+
+ if link_mtls.enforced:
+ logger.info("[AgentServer] ready: https://%s:%s/api/v1; plaintext WS disabled",
+ host, http_server.port)
+ elif http_server is not None:
logger.info(
"[AgentServer] ready: ws://%s:%s + http://%s:%s/api/v1 Ctrl+C to stop",
host,
diff --git a/jiuwenswarm/server/transports/link_sse_response.py b/jiuwenswarm/server/transports/link_sse_response.py
new file mode 100644
index 0000000000..0426fffea4
--- /dev/null
+++ b/jiuwenswarm/server/transports/link_sse_response.py
@@ -0,0 +1,25 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""Close an interrupted SSE producer deterministically in enforced link mode."""
+
+import logging
+
+import anyio
+from sse_starlette.sse import EventSourceResponse
+
+logger = logging.getLogger(__name__)
+
+
+class LinkEventSourceResponse(EventSourceResponse):
+ async def __call__(self, scope, receive, send):
+ try:
+ await super().__call__(scope, receive, send)
+ finally:
+ # Cancellation may occur in send(), outside the producer's next().
+ # Cancelling the task alone then leaves its generator suspended at
+ # yield. Do not depend on Python GC to run subscription cleanup.
+ close = getattr(self.body_iterator, "aclose", None)
+ if close is not None:
+ with anyio.move_on_after(2, shield=True) as cleanup:
+ await close()
+ if cleanup.cancel_called:
+ logger.warning("link SSE producer cleanup exceeded deadline")
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_service.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_service.py
index 26cff22b2e..078d1976d5 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_service.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_service.py
@@ -8,6 +8,8 @@ from __future__ import annotations
import logging
+from jiuwenswarm.common.security.link_mtls import LinkMTLSConfig
+
from ...infrastructure.config import Settings, get_settings
logger = logging.getLogger(__name__)
@@ -22,7 +24,8 @@ def resolve_public_endpoint(cfg: Settings | None = None) -> str:
cfg = cfg or get_settings()
port = int(cfg.gateway_config_http_port or 8775)
host = (cfg.gateway_config_public_host or "").strip() or "127.0.0.1"
- return f"{cfg.gateway_config_public_scheme}://{host}:{port}"
+ scheme = "https" if LinkMTLSConfig.from_env().enforced else cfg.gateway_config_public_scheme
+ return f"{scheme}://{host}:{port}"
def resolve_manager_http_base(cfg: Settings | None = None) -> str:
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/http/app.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/http/app.py
index 21a90b4a33..1c4f76f678 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/http/app.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/http/app.py
@@ -2,15 +2,33 @@
from __future__ import annotations
-from fastapi import APIRouter, FastAPI
+import logging
+
+from fastapi import APIRouter, FastAPI, Request
+from fastapi.responses import JSONResponse
from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
+from jiuwenswarm.common.security.link_mtls import (
+ LinkMTLSConfig,
+ LinkMTLSError,
+)
+
from ..infrastructure.config import get_settings
from ..routers.application_config_routers import application_config_router
from ..routers.instance_resource_routers import instance_resource_router
from ..routers.instance_routers import instance_router
from ..routers.template_routers import templates_router
+logger = logging.getLogger(__name__)
+
+# Log only fixed reasons, never arbitrary exception text or request data.
+_SAFE_LINK_REJECTION_REASONS = frozenset({
+ "request binding does not match authenticated deployment",
+ "peer certificate is not authorized for this binding and role",
+ "authenticated TLS peer certificate is missing",
+ "link binding is not active",
+})
+
def create_app() -> FastAPI:
"""Gateway 本机配置接收接口(每网关独立 DB,无路径级实例段)。"""
@@ -19,6 +37,22 @@ def create_app() -> FastAPI:
ProxyHeadersMiddleware,
trusted_hosts=get_settings().gateway_config_forwarded_allow_ips,
)
+ link_mtls = LinkMTLSConfig.from_env()
+
+ @app.middleware("http")
+ async def link_binding_guard(request: Request, call_next):
+ try:
+ link_mtls.authorize_request(request)
+ except LinkMTLSError as exc:
+ reason = str(exc)
+ logger.warning(
+ "[ManagerConfigReceiver] rejected link binding: %s",
+ reason if reason in _SAFE_LINK_REJECTION_REASONS else "link authorization failed",
+ )
+ return JSONResponse(status_code=403, content={
+ "ok": False, "error": {"code": "LINK_BINDING_MISMATCH", "message": str(exc)},
+ })
+ return await call_next(request)
@app.get("/api/health", tags=["System"])
async def system_health() -> dict[str, str]:
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/http/server.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/http/server.py
index f73036a731..35beffdc8a 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/http/server.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/http/server.py
@@ -7,6 +7,8 @@ import logging
from uvicorn import Config, Server
+from jiuwenswarm.common.security.link_mtls import LinkMTLSConfig
+
from ..infrastructure.config import get_settings
from .app import create_app
@@ -29,6 +31,12 @@ class ConfigReceiverServer:
return
# 嵌套在 Gateway 进程内:关掉 uvicorn 默认 log_config / access_log,
# 避免 AccessFormatter 与主进程 logging 冲突(expected 5 args, got 0)。
+ link_mtls = LinkMTLSConfig.from_env()
+ if link_mtls.mode.value == "observe":
+ logger.info(
+ "[ManagerConfigReceiver] link mTLS observe preflight complete; "
+ "data path remains HTTP"
+ )
config = Config(
self._app,
host=self._host,
@@ -39,6 +47,7 @@ class ConfigReceiverServer:
access_log=False,
# Proxy headers are handled by create_app() with the configured trust list.
proxy_headers=False,
+ **link_mtls.uvicorn_ssl_kwargs(),
)
self._server = Server(config)
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/public_endpoint.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/public_endpoint.py
index 411ff6f01d..4eb1b7488e 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/public_endpoint.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/public_endpoint.py
@@ -3,6 +3,8 @@
from __future__ import annotations
+from jiuwenswarm.common.security.link_mtls import LinkMTLSConfig
+
from .config import Settings, get_settings
@@ -15,4 +17,5 @@ def resolve_public_endpoint(cfg: Settings | None = None) -> str:
cfg = cfg or get_settings()
port = int(cfg.gateway_config_http_port or 8775)
host = (cfg.gateway_config_public_host or "").strip() or "127.0.0.1"
- return f"{cfg.gateway_config_public_scheme}://{host}:{port}"
+ scheme = "https" if LinkMTLSConfig.from_env().enforced else cfg.gateway_config_public_scheme
+ return f"{scheme}://{host}:{port}"
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/runtime_notify.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/runtime_notify.py
index db1fb5c005..1cfe62b460 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/runtime_notify.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/runtime_notify.py
@@ -14,6 +14,7 @@ from typing import Any
import httpx
from jiuwenswarm.common.local_env_config import read_env
+from jiuwenswarm.common.security.link_mtls import LinkMTLSConfig
logger = logging.getLogger(__name__)
@@ -24,6 +25,14 @@ _config_update_handle: asyncio.TimerHandle | None = None
def trigger_runtime_config_update() -> None:
"""企业配置变更:防抖后请求 agent-runtime 强制刷新(日落老 Pod + 按新配置重建)。"""
base = read_env("GATEWAY_RUNTIME_MANAGER_URL", "").strip()
+ if not base:
+ try:
+ link = LinkMTLSConfig.from_env()
+ if link.profile and "runtime" in link.profile.current().get("endpoints", {}):
+ base = "link://runtime"
+ except Exception:
+ logger.exception("[ManagerConfigReceiver] invalid runtime link profile")
+ return
if not base:
logger.debug(
"[ManagerConfigReceiver] GATEWAY_RUNTIME_MANAGER_URL unset, skip runtime notify"
@@ -65,8 +74,13 @@ def _schedule_agentserver_refresh() -> None:
)
-async def _request_agentserver_refresh() -> None:
+async def _request_agentserver_refresh(
+ link_mtls_config: LinkMTLSConfig | None = None,
+) -> None:
base = read_env("GATEWAY_RUNTIME_MANAGER_URL", "").strip().rstrip("/")
+ link_mtls = link_mtls_config or LinkMTLSConfig.from_env()
+ if not base and link_mtls.profile:
+ base = "link://runtime"
if not base:
return
try:
@@ -84,12 +98,19 @@ async def _request_agentserver_refresh() -> None:
"rawdata": {},
}
try:
+ base = link_mtls.resolve_endpoint(base, role="runtime")
+ url = f"{base}/api/session/config_refresh"
async with httpx.AsyncClient(
timeout=httpx.Timeout(timeout, connect=min(5.0, timeout)),
follow_redirects=False,
trust_env=False,
+ **link_mtls.client_kwargs(role="runtime"),
) as client:
- resp = await client.post(url, json=body)
+ resp = await client.post(
+ url,
+ json=body,
+ headers=link_mtls.binding_headers(),
+ )
if resp.status_code != 200:
logger.warning(
"[ManagerConfigReceiver] agentserver refresh failed status=%s body=%s",
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/session_route_client.py b/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/session_route_client.py
index c81748fe3f..1c49320132 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/session_route_client.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/session_route_client.py
@@ -10,6 +10,7 @@ from dataclasses import dataclass
import httpx
from jiuwenswarm.common.local_env_config import read_env
+from jiuwenswarm.common.security.link_mtls import LinkMTLSConfig
logger = logging.getLogger(__name__)
@@ -25,6 +26,9 @@ class RouteResult:
pod_sse_url: str
pod_id: str
request_id: str
+ mtls_deployment_id: str = ""
+ mtls_binding_id: str = ""
+ mtls_binding_epoch: int = 0
class RouteError(Exception):
@@ -59,10 +63,26 @@ class RuntimeSessionRouteClient:
base_url: str | None = None,
timeout_seconds: float | None = None,
http_client: httpx.AsyncClient | None = None,
+ link_mtls_config: LinkMTLSConfig | None = None,
) -> None:
- root = (base_url or read_env("GATEWAY_RUNTIME_MANAGER_URL", "http://127.0.0.1:8091")).strip().rstrip("/")
+ root = (
+ (
+ base_url
+ or read_env("GATEWAY_RUNTIME_MANAGER_URL", "http://127.0.0.1:8091")
+ )
+ .strip()
+ .rstrip("/")
+ )
if not root:
root = "http://127.0.0.1:8091"
+ self._link_mtls = link_mtls_config or LinkMTLSConfig.from_env()
+ if (
+ self._link_mtls.profile is not None
+ and base_url is None
+ and not read_env("GATEWAY_RUNTIME_MANAGER_URL", "")
+ ):
+ root = "link://runtime"
+ root = self._link_mtls.resolve_endpoint(root, role="runtime")
self._route_url = f"{root}/api/session/route"
self._touch_url = f"{root}/api/session/touch"
if http_client is not None:
@@ -82,6 +102,7 @@ class RuntimeSessionRouteClient:
timeout=httpx.Timeout(timeout, connect=min(5.0, timeout)),
follow_redirects=False,
trust_env=False,
+ **self._link_mtls.client_kwargs(role="runtime"),
)
self._owns_http = True
@@ -142,7 +163,16 @@ class RuntimeSessionRouteClient:
pod_sse_url,
request_id,
)
- return RouteResult(pod_sse_url=pod_sse_url, pod_id=pod_id, request_id=request_id)
+ result = RouteResult(
+ pod_sse_url=pod_sse_url,
+ pod_id=pod_id,
+ request_id=request_id,
+ mtls_deployment_id=str(rawdata.get("mtls_deployment_id") or "").strip(),
+ mtls_binding_id=str(rawdata.get("mtls_binding_id") or "").strip(),
+ mtls_binding_epoch=_positive_int(rawdata.get("mtls_binding_epoch")),
+ )
+ self._validate_route_binding(result)
+ return result
async def touch(self, *, session_id: str, request_id: str) -> bool:
"""保活。返回 False 表示会话已过期,编排应重新 ``route``。"""
@@ -168,21 +198,49 @@ class RuntimeSessionRouteClient:
async def _post(self, url: str, envelope: dict) -> dict:
try:
- response = await self._http.post(url, json=envelope)
+ response = await self._http.post(
+ url,
+ json=envelope,
+ headers=self._link_mtls.binding_headers(),
+ )
except httpx.RequestError as exc:
logger.warning("[SessionRoute] transport error: url=%s error=%s", url, exc)
- raise RetryableRouteError(f"request failed: {exc}", code="TRANSPORT") from exc
+ raise RetryableRouteError(
+ f"request failed: {exc}", code="TRANSPORT"
+ ) from exc
body = _json_object(response)
if response.status_code >= 400 or body.get("ok") is False:
raise _error_from_response(response, body)
return body
+ def _validate_route_binding(self, result: RouteResult) -> None:
+ identity = self._link_mtls.identity
+ if not self._link_mtls.enforced or identity is None:
+ return
+ if (
+ result.mtls_deployment_id != identity.mtls_deployment_id
+ or result.mtls_binding_id != identity.mtls_binding_id
+ or result.mtls_binding_epoch != identity.mtls_binding_epoch
+ ):
+ raise FatalRouteError(
+ "runtime route response link binding mismatch",
+ code="LINK_BINDING_MISMATCH",
+ )
+
def _rawdata(body: dict) -> dict:
raw = body.get("rawdata")
return raw if isinstance(raw, dict) else body
+def _positive_int(value: object) -> int:
+ try:
+ parsed = int(value or 0)
+ except (TypeError, ValueError):
+ return 0
+ return parsed if parsed > 0 else 0
+
+
def _json_object(response: httpx.Response) -> dict:
try:
payload = response.json()
@@ -213,4 +271,9 @@ def _error_from_response(response: httpx.Response, body: dict) -> RouteError:
cls = RetryableRouteError
else:
cls = FatalRouteError
- return cls(message, code=code, retry_after=retry_after_int, status_code=response.status_code)
+ return cls(
+ message,
+ code=code,
+ retry_after=retry_after_int,
+ status_code=response.status_code,
+ )
diff --git a/pyproject.toml b/pyproject.toml
index 56658a72ad..33099f95f6 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -19,6 +19,8 @@ dependencies = [
"loguru>=0.7.3",
"markdown>=3.4,<4",
"openjiuwen @ git+https://gitcode.com/openJiuwen/agent-core.git@dev-stable",
+ # Gateway/AgentServer share the reviewed Runtime foundation implementation.
+ "openjiuwen-runtime-foundation[link-mtls] @ git+https://gitcode.com/openJiuwen/agent-runtime.git@develop#subdirectory=foundation",
"openjiuwen_deepsearch @ git+https://gitcode.com/openJiuwen/deepsearch.git@dev-stable#subdirectory=deepsearch",
"pgvector>=0.4.2",
"portalocker>=3.2.0",
@@ -117,6 +119,7 @@ shell-ast = []
test = [
"a2a-sdk[http-server]==1.0.0",
"asyncssh>=2.14.0,<2.24",
+ "pywebview>=5.4",
"pytest>=8.3.5",
"pytest-asyncio>=1.0.0",
"pytest-html>=4.1.1",
@@ -196,6 +199,7 @@ jiuwenswarm-tui = { path = "./packages/jiuwenswarm-tui" }
test = [
"a2a-sdk[http-server]==1.0.0",
"asyncssh>=2.14.0,<2.24",
+ "pywebview>=5.4",
"pytest>=8.3.5",
"pytest-asyncio>=1.0.0",
"pytest-html>=4.1.1",
diff --git a/tests/fixtures/link_mtls.py b/tests/fixtures/link_mtls.py
new file mode 100644
index 0000000000..3b70872ae1
--- /dev/null
+++ b/tests/fixtures/link_mtls.py
@@ -0,0 +1,62 @@
+"""Temporary TLS fixtures built from the production issuer; not an installer."""
+
+import json
+import os
+import shutil
+import tempfile
+
+from openjiuwen_runtime.foundation.security.link_certificate_bundle import (
+ issue_bundle,
+ materialize_role,
+)
+from openjiuwen_runtime.foundation.security.link_profile import LinkProfileError
+
+
+def atomic_json(path, value):
+ fd, name = tempfile.mkstemp(dir=path.parent, prefix=".fixture-")
+ try:
+ with os.fdopen(fd, "w") as stream:
+ json.dump(value, stream)
+ os.replace(name, path)
+ finally:
+ if os.path.exists(name):
+ os.unlink(name)
+
+
+def provision(
+ output,
+ *,
+ mtls_deployment_id,
+ endpoints,
+ mtls_binding_epoch=1,
+ test_sans=None,
+):
+ if output.exists():
+ raise LinkProfileError("output already exists")
+ bundle = issue_bundle(
+ mtls_deployment_id=mtls_deployment_id,
+ endpoints=endpoints,
+ mtls_binding_epoch=mtls_binding_epoch,
+ sans=test_sans,
+ )
+ output.mkdir(mode=0o700)
+ for role in bundle["materials"]:
+ path = materialize_role(bundle, role, output / role)
+ data = json.loads(path.read_text())
+ # Socket tests have no service database. Persistence has separate tests.
+ data.pop("persistence", None)
+ atomic_json(path, data)
+ return {
+ "directory": str(output),
+ "mtls_deployment_id": mtls_deployment_id,
+ "mtls_binding_id": bundle["mtls_binding_id"],
+ "mtls_binding_epoch": mtls_binding_epoch,
+ }
+
+
+def install(bundle, role):
+ from openjiuwen_runtime.foundation.security import link_profile as profiles
+
+ target = profiles.DEFAULT_IDENTITY_ROOT / role
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copytree(bundle / role, target)
diff --git a/tests/integration/test_link_mtls_http_sse_e2e.py b/tests/integration/test_link_mtls_http_sse_e2e.py
new file mode 100644
index 0000000000..3426e43e7d
--- /dev/null
+++ b/tests/integration/test_link_mtls_http_sse_e2e.py
@@ -0,0 +1,911 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Real-socket HTTP/SSE mTLS checks for the Gateway internal clients."""
+
+from __future__ import annotations
+
+import asyncio
+import ipaddress
+import json
+import ssl
+import sys
+from contextlib import asynccontextmanager
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+from typing import AsyncIterator
+
+import httpx
+import pytest
+import uvicorn
+from cryptography import x509
+from cryptography.hazmat.primitives import hashes, serialization
+from cryptography.hazmat.primitives.asymmetric import rsa
+from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
+from fastapi import FastAPI, Request
+from fastapi.responses import JSONResponse, StreamingResponse
+
+from jiuwenswarm.common.e2a.constants import E2A_WIRE_SERVER_PUSH_KEY
+from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fields
+from jiuwenswarm.common.e2a.wire_codec import encode_agent_chunk_for_wire
+from jiuwenswarm.common.schema.agent import AgentResponseChunk
+from jiuwenswarm.common.schema.message import ReqMethod
+from jiuwenswarm.common.security.link_mtls import (
+ MTLSDeploymentIdentity,
+ LinkMTLSConfig,
+ LinkMTLSError,
+ LinkMTLSMode,
+)
+from jiuwenswarm.gateway.routing.http_agent_client import HttpSseAgentServerClient
+
+_EXT_DIR = (
+ Path(__file__).resolve().parents[2]
+ / "packages"
+ / "jiuwenclaw-ee"
+ / "gateway"
+ / "extensions"
+ / "runtime_management_extension"
+)
+if str(_EXT_DIR) not in sys.path:
+ sys.path.insert(0, str(_EXT_DIR))
+
+from session_route_client import ( # noqa: E402
+ FatalRouteError,
+ RetryableRouteError,
+ RuntimeSessionRouteClient,
+)
+
+_IDENTITY = MTLSDeploymentIdentity("deployment-local-e2e", "binding-local-e2e", 7)
+
+
[email protected](autouse=True)
+def reset_sse_test_process_shutdown(monkeypatch):
+ # Tests run several Uvicorn servers sequentially in one interpreter;
+ # production roles each have their own process. sse-starlette keeps this
+ # global flag after the previous test's server exits.
+ from sse_starlette.sse import AppStatus
+
+ monkeypatch.setattr(AppStatus, "should_exit", False)
+
+
+def _write_private_key(path: Path, key: rsa.RSAPrivateKey) -> None:
+ path.write_bytes(
+ key.private_bytes(
+ serialization.Encoding.PEM,
+ serialization.PrivateFormat.PKCS8,
+ serialization.NoEncryption(),
+ )
+ )
+
+
+def _new_ca(
+ directory: Path, name: str
+) -> tuple[Path, rsa.RSAPrivateKey, x509.Certificate]:
+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)])
+ now = datetime.now(UTC)
+ cert = (
+ x509.CertificateBuilder()
+ .subject_name(subject)
+ .issuer_name(subject)
+ .public_key(key.public_key())
+ .serial_number(x509.random_serial_number())
+ .not_valid_before(now - timedelta(minutes=1))
+ .not_valid_after(now + timedelta(days=1))
+ .add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True)
+ .add_extension(
+ x509.KeyUsage(
+ digital_signature=True,
+ key_encipherment=False,
+ content_commitment=False,
+ data_encipherment=False,
+ key_agreement=False,
+ key_cert_sign=True,
+ crl_sign=True,
+ encipher_only=False,
+ decipher_only=False,
+ ),
+ critical=True,
+ )
+ .sign(key, hashes.SHA256())
+ )
+ cert_path = directory / f"{name}.crt"
+ cert_path.write_bytes(cert.public_bytes(serialization.Encoding.PEM))
+ return cert_path, key, cert
+
+
+def _new_leaf(
+ directory: Path,
+ name: str,
+ ca_key: rsa.RSAPrivateKey,
+ ca_cert: x509.Certificate,
+ *,
+ server: bool = False,
+ client: bool = False,
+ include_ip_san: bool = True,
+) -> tuple[Path, Path]:
+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ now = datetime.now(UTC)
+ usages = []
+ if server:
+ usages.append(ExtendedKeyUsageOID.SERVER_AUTH)
+ if client:
+ usages.append(ExtendedKeyUsageOID.CLIENT_AUTH)
+ builder = (
+ x509.CertificateBuilder()
+ .subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)]))
+ .issuer_name(ca_cert.subject)
+ .public_key(key.public_key())
+ .serial_number(x509.random_serial_number())
+ .not_valid_before(now - timedelta(minutes=1))
+ .not_valid_after(now + timedelta(hours=1))
+ .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
+ .add_extension(x509.ExtendedKeyUsage(usages), critical=False)
+ )
+ if server:
+ subject_names: list[x509.GeneralName] = [x509.DNSName("localhost")]
+ if include_ip_san:
+ subject_names.append(x509.IPAddress(ipaddress.ip_address("127.0.0.1")))
+ builder = builder.add_extension(
+ x509.SubjectAlternativeName(subject_names),
+ critical=False,
+ )
+ cert = builder.sign(ca_key, hashes.SHA256())
+ cert_path = directory / f"{name}.crt"
+ key_path = directory / f"{name}.key"
+ cert_path.write_bytes(cert.public_bytes(serialization.Encoding.PEM))
+ _write_private_key(key_path, key)
+ return cert_path, key_path
+
+
+def _profile_config(certs, *, role, identity=_IDENTITY, wrong=False, dns=False):
+ from openjiuwen_runtime.foundation.security.link_profile import (
+ LinkProfile,
+ cert_fingerprint,
+ )
+
+ from tests.fixtures.link_mtls import atomic_json
+
+ prefix = (
+ "wrong"
+ if wrong
+ else (
+ "dns_only"
+ if dns
+ else {"agentserver": "server", "runtime": "runtime", "gateway": "gateway"}[
+ role
+ ]
+ )
+ )
+ path = (
+ certs["server_ca"].parent
+ / f"{role}-{identity.mtls_binding_epoch}-{prefix}.json"
+ )
+ pins = {
+ r: [cert_fingerprint(str(certs[p + "_cert"]))]
+ for r, p in (
+ ("agentserver", "server"),
+ ("runtime", "runtime"),
+ ("gateway", "gateway"),
+ )
+ }
+ if wrong:
+ pins["gateway"] = [cert_fingerprint(str(certs["wrong_cert"]))]
+ if dns:
+ pins[role] = [cert_fingerprint(str(certs["dns_only_cert"]))]
+ atomic_json(
+ path,
+ {
+ "version": 1,
+ "status": "active",
+ "role": role,
+ "mtls_deployment_id": identity.mtls_deployment_id,
+ "mtls_binding_id": identity.mtls_binding_id,
+ "mtls_binding_epoch": identity.mtls_binding_epoch,
+ "endpoints": {},
+ "peers": pins,
+ "tls": {
+ "ca_file": str(certs["server_ca"]),
+ "cert_file": str(certs[prefix + "_cert"]),
+ "key_file": str(certs[prefix + "_key"]),
+ },
+ },
+ )
+ p = LinkProfile.load(str(path))
+ return LinkMTLSConfig(
+ mode=LinkMTLSMode.ENFORCE,
+ profile=p,
+ ca_file=p.ca_file,
+ cert_file=p.cert_file,
+ key_file=p.key_file,
+ identity=identity,
+ )
+
+
+def _server_config(certs, *, role="agentserver"):
+ return _profile_config(certs, role=role)
+
+
+def _client_config(certs, *, identity=_IDENTITY, wrong_role=False):
+ return _profile_config(certs, role="gateway", identity=identity, wrong=wrong_role)
+
+
+def link_certificates(tmp_path: Path) -> dict[str, Path]:
+ server_ca, server_ca_key, server_ca_cert = _new_ca(tmp_path, "server-ca")
+ gateway_ca, gateway_ca_key, gateway_ca_cert = (
+ server_ca,
+ server_ca_key,
+ server_ca_cert,
+ )
+ runtime_cert, runtime_key = _new_leaf(
+ tmp_path, "runtime", server_ca_key, server_ca_cert, server=True, client=True
+ )
+ wrong_ca, wrong_ca_key, wrong_ca_cert = _new_ca(tmp_path, "wrong-role-ca")
+ server_cert, server_key = _new_leaf(
+ tmp_path, "server", server_ca_key, server_ca_cert, server=True
+ )
+ dns_only_cert, dns_only_key = _new_leaf(
+ tmp_path,
+ "server-dns-only",
+ server_ca_key,
+ server_ca_cert,
+ server=True,
+ include_ip_san=False,
+ )
+ gateway_cert, gateway_key = _new_leaf(
+ tmp_path, "gateway", gateway_ca_key, gateway_ca_cert, client=True
+ )
+ wrong_cert, wrong_key = _new_leaf(
+ tmp_path, "wrong", wrong_ca_key, wrong_ca_cert, client=True
+ )
+ return {
+ "runtime_cert": runtime_cert,
+ "runtime_key": runtime_key,
+ "server_ca": server_ca,
+ "gateway_ca": gateway_ca,
+ "wrong_ca": wrong_ca,
+ "server_cert": server_cert,
+ "server_key": server_key,
+ "dns_only_cert": dns_only_cert,
+ "dns_only_key": dns_only_key,
+ "gateway_cert": gateway_cert,
+ "gateway_key": gateway_key,
+ "wrong_cert": wrong_cert,
+ "wrong_key": wrong_key,
+ }
+
+
+@asynccontextmanager
+async def _serve(
+ app: FastAPI,
+ *,
+ ssl_kwargs: dict[str, object] | None = None,
+) -> AsyncIterator[str]:
+ config = uvicorn.Config(
+ app,
+ host="127.0.0.1",
+ port=0,
+ access_log=False,
+ log_level="warning",
+ lifespan="off",
+ **(ssl_kwargs or {}),
+ )
+ server = uvicorn.Server(config)
+ task = asyncio.create_task(server.serve())
+ for _ in range(100):
+ if server.started and server.servers:
+ break
+ if task.done():
+ await task
+ await asyncio.sleep(0.02)
+ else:
+ server.should_exit = True
+ await task
+ raise RuntimeError("uvicorn did not start")
+ port = server.servers[0].sockets[0].getsockname()[1]
+ scheme = "https" if ssl_kwargs else "http"
+ try:
+ yield f"{scheme}://127.0.0.1:{port}"
+ finally:
+ server.should_exit = True
+ await asyncio.wait_for(task, timeout=5)
+
+
+def _binding_guard(app: FastAPI, config: LinkMTLSConfig) -> None:
+ @app.middleware("http")
+ async def guard(request: Request, call_next): # noqa: ANN001, ANN202
+ try:
+ config.authorize_request(request)
+ except LinkMTLSError as exc:
+ return JSONResponse(
+ status_code=403,
+ content={"ok": False, "error": {"message": str(exc)}},
+ )
+ return await call_next(request)
+
+
+def _runtime_app(config: LinkMTLSConfig, agent_url: str) -> FastAPI:
+ app = FastAPI()
+ _binding_guard(app, config)
+
+ @app.post("/api/session/route")
+ async def route() -> dict:
+ return {
+ "ok": True,
+ "rawdata": {
+ "pod_sse_url": agent_url,
+ "pod_id": "agent-1",
+ **_IDENTITY.headers(),
+ "mtls_deployment_id": _IDENTITY.mtls_deployment_id,
+ "mtls_binding_id": _IDENTITY.mtls_binding_id,
+ "mtls_binding_epoch": _IDENTITY.mtls_binding_epoch,
+ },
+ }
+
+ @app.post("/api/session/touch")
+ async def touch() -> dict:
+ return {"ok": True, "rawdata": {"touched": True}}
+
+ return app
+
+
+def _agent_app(config: LinkMTLSConfig) -> FastAPI:
+ app = FastAPI()
+ _binding_guard(app, config)
+
+ @app.get("/api/v1/health")
+ async def health() -> dict:
+ return {"ok": True, "data": {"status": "ready"}}
+
+ @app.get("/api/v1/sessions")
+ async def sessions() -> dict:
+ return {"request_id": "unary-1", "ok": True, "data": {"sessions": []}}
+
+ @app.post("/api/v1/chat/completions")
+ async def chat() -> StreamingResponse:
+ async def frames() -> AsyncIterator[str]:
+ for sequence, (content, complete) in enumerate(
+ (("hello", False), ("", True))
+ ):
+ wire = encode_agent_chunk_for_wire(
+ AgentResponseChunk(
+ request_id="stream-1",
+ channel_id="web",
+ payload={"content": content},
+ is_complete=complete,
+ ),
+ response_id="stream-1",
+ sequence=sequence,
+ )
+ yield f"event: e2a.chunk\ndata: {json.dumps(wire)}\n\n"
+
+ return StreamingResponse(frames(), media_type="text/event-stream")
+
+ @app.get("/api/v1/events/stream")
+ async def events() -> StreamingResponse:
+ async def frames() -> AsyncIterator[str]:
+ payload = {
+ "request_id": "push-1",
+ "metadata": {E2A_WIRE_SERVER_PUSH_KEY: True},
+ "data": {"event": "ready"},
+ }
+ yield f"event: e2a.chunk\ndata: {json.dumps(payload)}\n\n"
+
+ return StreamingResponse(frames(), media_type="text/event-stream")
+
+ return app
+
+
+async def test_enforce_real_mtls_runtime_and_agent_http_sse(
+ link_certificates: dict[str, Path],
+) -> None:
+ certs = link_certificates
+ server_config = _server_config(certs)
+ client_config = _client_config(certs)
+
+ async with _serve(
+ _agent_app(server_config), ssl_kwargs=server_config.uvicorn_ssl_kwargs()
+ ) as agent_url:
+ async with _serve(
+ _runtime_app(_server_config(certs, role="runtime"), agent_url),
+ ssl_kwargs=_server_config(certs, role="runtime").uvicorn_ssl_kwargs(),
+ ) as runtime_url:
+ route_client = RuntimeSessionRouteClient(
+ base_url=runtime_url, link_mtls_config=client_config
+ )
+ result = await route_client.route(
+ session_id="session-1",
+ group_id="group-1",
+ bot_id="bot-1",
+ request_id="route-1",
+ user_id="user-1",
+ )
+ assert result.pod_sse_url == agent_url
+ assert result.mtls_binding_epoch == _IDENTITY.mtls_binding_epoch
+ assert await route_client.touch(
+ session_id="session-1", request_id="touch-1"
+ )
+ await route_client.aclose()
+
+ push_received = asyncio.Event()
+ agent_client = HttpSseAgentServerClient(link_mtls_config=client_config)
+
+ async def on_push(payload: dict) -> None:
+ assert payload["request_id"] == "push-1"
+ push_received.set()
+
+ agent_client.set_server_push_handler(on_push)
+ await agent_client.connect(agent_url)
+ unary = e2a_from_agent_fields(
+ request_id="unary-1",
+ channel_id="web",
+ session_id="session-1",
+ req_method=ReqMethod.SESSION_LIST,
+ params={},
+ is_stream=False,
+ user_id="user-1",
+ )
+ assert (await agent_client.send_request(unary)).ok is True
+ stream = e2a_from_agent_fields(
+ request_id="stream-1",
+ channel_id="web",
+ session_id="session-1",
+ req_method=ReqMethod.CHAT_SEND,
+ params={"query": "hello"},
+ is_stream=True,
+ user_id="user-1",
+ )
+ chunks = [chunk async for chunk in agent_client.send_request_stream(stream)]
+ assert chunks[0].payload["content"] == "hello"
+ assert chunks[-1].is_complete is True
+ await asyncio.wait_for(push_received.wait(), timeout=3)
+ await agent_client.disconnect()
+
+
+async def test_enforce_reconnects_across_multiple_agentservers_in_one_binding(
+ link_certificates: dict[str, Path],
+) -> None:
+ certs = link_certificates
+ server_config = _server_config(certs)
+ client_config = _client_config(certs)
+ async with _serve(
+ _agent_app(server_config), ssl_kwargs=server_config.uvicorn_ssl_kwargs()
+ ) as first_url:
+ async with _serve(
+ _agent_app(server_config), ssl_kwargs=server_config.uvicorn_ssl_kwargs()
+ ) as second_url:
+ client = HttpSseAgentServerClient(link_mtls_config=client_config)
+ try:
+ for index, url in enumerate((first_url, second_url), start=1):
+ await client.connect(url)
+ request = e2a_from_agent_fields(
+ request_id=f"multi-{index}",
+ channel_id="web",
+ session_id="session-1",
+ req_method=ReqMethod.SESSION_LIST,
+ params={},
+ is_stream=False,
+ user_id="user-1",
+ )
+ assert (await client.send_request(request)).ok is True
+ await client.disconnect()
+ finally:
+ await client.disconnect()
+
+
+async def test_enforce_rejects_missing_wrong_role_and_stale_binding(
+ link_certificates: dict[str, Path],
+) -> None:
+ certs = link_certificates
+ server_config = _server_config(certs, role="runtime")
+ async with _serve(
+ _runtime_app(server_config, "https://agent.invalid"),
+ ssl_kwargs=server_config.uvicorn_ssl_kwargs(),
+ ) as runtime_url:
+ server_trust = ssl.create_default_context(cafile=str(certs["server_ca"]))
+ async with httpx.AsyncClient(verify=server_trust, trust_env=False) as client:
+ with pytest.raises(httpx.HTTPError):
+ await client.post(f"{runtime_url}/api/session/route", json={})
+
+ wrong = _client_config(certs, wrong_role=True)
+ async with httpx.AsyncClient(
+ verify=wrong.client_ssl_context(), trust_env=False
+ ) as client:
+ with pytest.raises(httpx.HTTPError):
+ await client.post(
+ f"{runtime_url}/api/session/route",
+ json={},
+ headers=wrong.binding_headers(),
+ )
+
+ stale = _client_config(
+ certs,
+ identity=MTLSDeploymentIdentity(
+ _IDENTITY.mtls_deployment_id,
+ _IDENTITY.mtls_binding_id,
+ _IDENTITY.mtls_binding_epoch - 1,
+ ),
+ )
+ route_client = RuntimeSessionRouteClient(
+ base_url=runtime_url, link_mtls_config=stale
+ )
+ with pytest.raises(FatalRouteError):
+ await route_client.route(
+ session_id="session-1",
+ group_id="group-1",
+ bot_id="bot-1",
+ request_id="stale-1",
+ )
+ await route_client.aclose()
+
+ with pytest.raises(LinkMTLSError, match="explicitly use https"):
+ RuntimeSessionRouteClient(
+ base_url="http://127.0.0.1:8091",
+ link_mtls_config=_client_config(certs),
+ )
+
+
+async def test_enforce_rejects_wrong_server_dns_san(
+ link_certificates: dict[str, Path],
+) -> None:
+ certs = link_certificates
+ server_config = _profile_config(certs, role="runtime", dns=True)
+ async with _serve(
+ _runtime_app(server_config, "https://agent.invalid"),
+ ssl_kwargs=server_config.uvicorn_ssl_kwargs(),
+ ) as runtime_url:
+ route_client = RuntimeSessionRouteClient(
+ base_url=runtime_url,
+ link_mtls_config=_client_config(certs),
+ )
+ try:
+ with pytest.raises(RetryableRouteError, match="request failed"):
+ await route_client.route(
+ session_id="session-1",
+ group_id="group-1",
+ bot_id="bot-1",
+ request_id="wrong-san-1",
+ )
+ finally:
+ await route_client.aclose()
+
+
[email protected]("mode", [LinkMTLSMode.OFF, LinkMTLSMode.OBSERVE])
+async def test_off_and_observe_keep_plain_http_compatible(
+ link_certificates: dict[str, Path], mode: LinkMTLSMode
+) -> None:
+ certs = link_certificates
+ config = LinkMTLSConfig(mode=mode)
+ if mode is LinkMTLSMode.OBSERVE:
+ config = LinkMTLSConfig(
+ mode=mode,
+ ca_file=str(certs["server_ca"]),
+ cert_file=str(certs["gateway_cert"]),
+ key_file=str(certs["gateway_key"]),
+ identity=_IDENTITY,
+ )
+ async with _serve(_agent_app(config)) as agent_url:
+ async with _serve(_runtime_app(config, agent_url)) as runtime_url:
+ route_client = RuntimeSessionRouteClient(
+ base_url=runtime_url, link_mtls_config=config
+ )
+ result = await route_client.route(
+ session_id="session-1",
+ group_id="group-1",
+ bot_id="bot-1",
+ request_id=f"{mode.value}-1",
+ )
+ assert result.pod_sse_url == agent_url
+ await route_client.aclose()
+
+ agent_client = HttpSseAgentServerClient(link_mtls_config=config)
+ await agent_client.connect(agent_url)
+ await agent_client.disconnect()
+
+
+async def test_actual_agent_http_routes_guard_and_ext_over_tls(
+ link_certificates, monkeypatch
+):
+ from jiuwenswarm.common.request_ext import (
+ INTERNAL_HEADER_NAME,
+ encode_internal_header,
+ )
+ from jiuwenswarm.server.agent_http_routes import build_fastapi_app
+
+ config = _server_config(link_certificates)
+ monkeypatch.setattr(
+ LinkMTLSConfig, "from_env", classmethod(lambda cls, **kwargs: config)
+ )
+ seen = []
+
+ class BusinessProbe:
+ async def invoke_unary(self, method, params, **kwargs):
+ seen.append(kwargs)
+ return {"ok": True, "data": {"sessions": []}}, 200
+
+ app = build_fastapi_app(BusinessProbe())
+ client_config = _client_config(link_certificates)
+ async with _serve(app, ssl_kwargs=config.uvicorn_ssl_kwargs()) as url:
+ async with httpx.AsyncClient(
+ **client_config.client_kwargs(role="agentserver")
+ ) as client:
+ headers = {
+ **client_config.binding_headers(),
+ INTERNAL_HEADER_NAME: encode_internal_header(
+ {"X-Tenant-Id": "tenant-a"}
+ ),
+ }
+ assert (
+ await client.get(url + "/api/v1/health", headers=headers)
+ ).status_code == 200
+ assert (
+ await client.get(url + "/api/v1/sessions", headers=headers)
+ ).status_code == 200
+ assert seen[0]["request_ext"] == {"X-Tenant-Id": "tenant-a"}
+ assert (await client.get(url + "/api/v1/sessions")).status_code == 403
+
+
[email protected]("change", ["revoke", "remove_pin"])
[email protected]("idle", [False, True])
+async def test_actual_chat_stream_rechecks_binding_and_cleans_up(
+ link_certificates, monkeypatch, change, idle
+):
+ from jiuwenswarm.server.agent_http_routes import build_fastapi_app
+ from tests.fixtures.link_mtls import atomic_json
+
+ config = _server_config(link_certificates)
+ gateway = _client_config(link_certificates)
+ release, cleaned = asyncio.Event(), asyncio.Event()
+
+ class Business:
+ async def iter_stream(self, *args, **kwargs):
+ try:
+ yield {"event": "probe.ready", "data": "ready"}
+ await release.wait()
+ yield {"event": "must-not-leak", "data": "after revoke"}
+ finally:
+ cleaned.set()
+
+ monkeypatch.setattr(
+ LinkMTLSConfig, "from_env", classmethod(lambda cls, **kwargs: config)
+ )
+ app = build_fastapi_app(Business())
+ async with _serve(app, ssl_kwargs=config.uvicorn_ssl_kwargs()) as url:
+ async with httpx.AsyncClient(
+ trust_env=False, timeout=3, **gateway.client_kwargs(role="agentserver")
+ ) as client:
+ async with client.stream(
+ "POST",
+ url + "/api/v1/chat/completions",
+ headers=gateway.binding_headers(),
+ json={"query": "probe", "enable_streaming": True},
+ ) as response:
+ assert response.status_code == 200
+ lines = response.aiter_lines()
+ async for line in lines:
+ if line == "event: probe.ready":
+ break
+ else:
+ pytest.fail("missing first event")
+ data = json.loads(config.profile.path.read_text())
+ if change == "revoke":
+ data["status"] = "revoked"
+ else:
+ data["peers"]["gateway"] = ["0" * 64]
+ atomic_json(config.profile.path, data)
+ if not idle:
+ release.set()
+
+ async def consume():
+ return [line async for line in lines]
+
+ remaining = await asyncio.wait_for(consume(), 3)
+ assert not any("must-not-leak" in line for line in remaining)
+ await asyncio.wait_for(cleaned.wait(), 1)
+ assert (
+ release.is_set() is not idle
+ ) # idle case did not need another chunk
+
+
+async def test_idle_push_stream_revocation_unregisters_subscriber(
+ link_certificates, monkeypatch
+):
+ from jiuwenswarm.server.agent_http_routes import build_fastapi_app
+ from jiuwenswarm.server.transports import push_registry
+ from tests.fixtures.link_mtls import atomic_json
+
+ registry = push_registry.PushRegistry()
+ monkeypatch.setattr(push_registry, "get_push_registry", lambda: registry)
+ config = _server_config(link_certificates)
+ gateway = _client_config(link_certificates)
+ monkeypatch.setattr(
+ LinkMTLSConfig, "from_env", classmethod(lambda cls, **kwargs: config)
+ )
+ app = build_fastapi_app(object())
+ async with _serve(app, ssl_kwargs=config.uvicorn_ssl_kwargs()) as url:
+ async with httpx.AsyncClient(
+ trust_env=False, timeout=3, **gateway.client_kwargs(role="agentserver")
+ ) as client:
+ async with client.stream(
+ "GET",
+ url + "/api/v1/events/stream",
+ headers={
+ **gateway.binding_headers(),
+ "X-Jiuwen-Push-Consumer": "gateway",
+ },
+ ) as response:
+ assert response.status_code == 200
+ lines = response.aiter_lines()
+ async for line in lines:
+ if line == "event: gateway.push_ready":
+ break
+ assert len(registry._subscribers) == 1
+ data = json.loads(config.profile.path.read_text())
+ data["status"] = "revoked"
+ atomic_json(config.profile.path, data)
+
+ async def consume():
+ return [line async for line in lines]
+
+ await asyncio.wait_for(consume(), 3)
+ assert not registry._subscribers
+ assert registry._reverse_rpc_owner_id is None
+
+
+async def test_agent_enforce_port_conflict_refuses_automatic_port_drift(
+ link_certificates, monkeypatch
+):
+ import socket
+
+ from jiuwenswarm.server.agent_http_server import AgentHTTPServer
+
+ config = _server_config(link_certificates)
+ monkeypatch.setattr(
+ LinkMTLSConfig, "from_env", classmethod(lambda cls, **kwargs: config)
+ )
+ sock = socket.socket()
+ sock.bind(("127.0.0.1", 0))
+ port = sock.getsockname()[1]
+ server = AgentHTTPServer(object(), host="127.0.0.1", port=port)
+ try:
+ with pytest.raises(LinkMTLSError, match="occupied"):
+ await server.start()
+ assert server.port == port
+ assert server._server is None
+ finally:
+ sock.close()
+
+
+async def test_actual_gateway_receiver_requires_manager_role(tmp_path, monkeypatch):
+ from openjiuwen_runtime.foundation.security import link_profile as profiles
+ from openjiuwen_runtime.foundation.security.link_profile import LinkProfile
+
+ from tests.fixtures.link_mtls import install, provision
+
+ extensions = (
+ Path(__file__).resolve().parents[2]
+ / "packages/jiuwenclaw-ee/gateway/extensions"
+ )
+ monkeypatch.syspath_prepend(str(extensions))
+ from manager_config_receiver.http.app import create_app
+
+ provision(
+ tmp_path / "bundle",
+ mtls_deployment_id="gateway-guard",
+ endpoints={"gateway": "127.0.0.1:8775"},
+ )
+ gateway = LinkProfile.load(str(tmp_path / "bundle/gateway/profile.json"))
+ manager = LinkProfile.load(str(tmp_path / "bundle/manager/profile.json"))
+ monkeypatch.setattr(profiles, "DEFAULT_IDENTITY_ROOT", tmp_path / "installed")
+ install(tmp_path / "bundle", "gateway")
+ monkeypatch.delenv("JIUWENSWARM_LINK_MTLS_PROFILE", raising=False)
+ monkeypatch.setenv("JIUWENSWARM_LINK_MTLS_MODE", "enforce")
+ config = LinkMTLSConfig.from_env()
+ app = create_app()
+
+ @app.post("/review-probe")
+ async def probe():
+ return {"ok": True}
+
+ async with _serve(app, ssl_kwargs=config.uvicorn_ssl_kwargs()) as url:
+ async with httpx.AsyncClient(**manager.client_kwargs(role="gateway")) as client:
+ assert (await client.get(url + "/api/health")).status_code == 200
+ assert (
+ await client.post(url + "/review-probe", headers=manager.headers())
+ ).status_code == 200
+ async with httpx.AsyncClient(
+ **gateway.client_kwargs(role="gateway")
+ ) as wrong_role:
+ assert (
+ await wrong_role.post(url + "/review-probe", headers=gateway.headers())
+ ).status_code == 403
+
+
+async def test_agent_handler_initializes_without_plaintext_websocket(monkeypatch):
+ from types import SimpleNamespace
+ from unittest.mock import AsyncMock
+
+ import websockets.legacy.server
+
+ from jiuwenswarm.server import agent_ws_server as module
+
+ serve_spy = AsyncMock(
+ side_effect=AssertionError("plaintext listener must not start")
+ )
+ monkeypatch.setattr(websockets.legacy.server, "serve", serve_spy)
+ monkeypatch.setattr(module, "reset_harness_packages_state", lambda: None)
+ monkeypatch.setattr(
+ module, "get_config", lambda: {"startup": {"warmup": {"enabled": False}}}
+ )
+ server = SimpleNamespace(
+ _server=None,
+ _trigger_before_ws_server_start_hook=AsyncMock(),
+ _bootstrap_internal_jiuwenbox=AsyncMock(),
+ _start_loop_lag_monitor=AsyncMock(),
+ )
+ await module.AgentWebSocketServer.start(server, listen=False)
+ serve_spy.assert_not_awaited()
+ server._bootstrap_internal_jiuwenbox.assert_awaited_once()
+
+
+async def test_installed_agent_and_gateway_identities_without_profile_env(
+ tmp_path, monkeypatch
+):
+ from openjiuwen_runtime.foundation.security import link_profile as profiles
+
+ from jiuwenswarm.server.agent_http_routes import build_fastapi_app
+ from tests.fixtures.link_mtls import install, provision
+
+ for key in (
+ "JIUWENSWARM_LINK_MTLS_PROFILE",
+ "JIUWENSWARM_LINK_MTLS_CA_FILE",
+ "JIUWENSWARM_LINK_MTLS_CERT_FILE",
+ "JIUWENSWARM_LINK_MTLS_KEY_FILE",
+ ):
+ monkeypatch.delenv(key, raising=False)
+ bundle = tmp_path / "bundle"
+ provision(
+ bundle,
+ mtls_deployment_id="no-handwritten-state",
+ endpoints={"agentserver": "127.0.0.1:8766"},
+ )
+ monkeypatch.setattr(profiles, "DEFAULT_IDENTITY_ROOT", tmp_path / "installed")
+ install(bundle, "agentserver")
+ install(bundle, "gateway")
+ monkeypatch.setenv("JIUWENSWARM_LINK_MTLS_MODE", "enforce")
+ gateway = LinkMTLSConfig.from_env()
+ agent = LinkMTLSConfig.from_env(role="agentserver")
+ assert gateway.profile.role == "gateway" and agent.profile.role == "agentserver"
+
+ class BusinessProbe:
+ async def invoke_unary(self, method, params, **kwargs):
+ return {"ok": True, "data": {"sessions": []}}, 200
+
+ app = build_fastapi_app(BusinessProbe())
+ async with _serve(app, ssl_kwargs=agent.uvicorn_ssl_kwargs()) as url:
+ actual_gateway_client = HttpSseAgentServerClient()
+ try:
+ await actual_gateway_client.connect(url)
+ async with httpx.AsyncClient(
+ **gateway.client_kwargs(role="agentserver")
+ ) as client:
+ assert (
+ await client.get(
+ url + "/api/v1/sessions", headers=gateway.binding_headers()
+ )
+ ).status_code == 200
+ assert (await client.get(url + "/api/v1/sessions")).status_code == 403
+ finally:
+ await actual_gateway_client.disconnect()
diff --git a/tests/integration/test_manager_config_receiver_link_mtls.py b/tests/integration/test_manager_config_receiver_link_mtls.py
new file mode 100644
index 0000000000..89f7202205
--- /dev/null
+++ b/tests/integration/test_manager_config_receiver_link_mtls.py
@@ -0,0 +1,190 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Gateway config receiver rejection logging, including real TLS requests."""
+
+from __future__ import annotations
+
+import asyncio
+import importlib
+import logging
+import socket
+import sys
+from pathlib import Path
+from types import ModuleType
+
+import httpx
+import pytest
+import uvicorn
+from fastapi.testclient import TestClient
+
+from jiuwenswarm.common.security.link_mtls import (
+ LinkMTLSConfig,
+ LinkMTLSError,
+ LinkMTLSMode,
+)
+
+
+def receiver_module(monkeypatch, caplog):
+ # Match the dynamic extension namespace without running registration hooks.
+ parent_name = "jiuwenswarm.loaded_extension"
+ package_name = parent_name + ".manager_config_receiver"
+ extension_root = (
+ Path(__file__).resolve().parents[2]
+ / "packages"
+ / "jiuwenclaw-ee/gateway/extensions/manager_config_receiver"
+ )
+ for name, paths in ((parent_name, []), (package_name, [str(extension_root)])):
+ if name not in sys.modules:
+ package = ModuleType(name)
+ package.__path__ = paths
+ monkeypatch.setitem(sys.modules, name, package)
+ module = importlib.import_module(package_name + ".http.app")
+ monkeypatch.setattr(module.logger, "handlers", [caplog.handler])
+ monkeypatch.setattr(module.logger, "propagate", False)
+ monkeypatch.setattr(module.logger, "level", logging.WARNING)
+ return module
+
+
+ "reason",
+ [
+ "request binding does not match authenticated deployment",
+ "peer certificate is not authorized for this binding and role",
+ "authenticated TLS peer certificate is missing",
+ "link binding is not active",
+ "sensitive-exception-detail\nFORGED-LOG",
+ ],
+)
+def test_rejection_logs_only_fixed_reason(receiver_module, monkeypatch, caplog, reason):
+ class RejectConfig:
+ def authorize_request(self, request):
+ raise LinkMTLSError(reason)
+
+ monkeypatch.setattr(
+ receiver_module.LinkMTLSConfig, "from_env", lambda: RejectConfig()
+ )
+ with TestClient(receiver_module.create_app()) as client:
+ response = client.post(
+ "/api/v1/private-path-marker?token=private-query-marker",
+ headers={
+ "Authorization": "Bearer private-token-marker",
+ "X-Jiuwenswarm-Mtls-Binding-Id": "private-binding-marker",
+ "X-Forwarded-Client-Cert": "private-certificate-marker",
+ },
+ json={"private_key": "private-key-marker"},
+ )
+ assert response.status_code == 403
+ # Observability only: preserve the existing error response contract.
+ assert response.json() == {
+ "ok": False,
+ "error": {"code": "LINK_BINDING_MISMATCH", "message": reason},
+ }
+ records = [r for r in caplog.records if r.name == receiver_module.logger.name]
+ assert len(records) == 1
+ record = records[0]
+ expected = (
+ reason
+ if reason in receiver_module._SAFE_LINK_REJECTION_REASONS
+ else "link authorization failed"
+ )
+ assert (
+ record.getMessage()
+ == "[ManagerConfigReceiver] rejected link binding: " + expected
+ )
+ assert record.levelno == logging.WARNING and record.exc_info is None
+ assert "private-" not in record.getMessage()
+ assert "sensitive-exception-detail" not in record.getMessage()
+ assert "FORGED-LOG" not in record.getMessage()
+
+
[email protected]("mode", ["off", "observe"])
+def test_non_enforce_health_unchanged_without_rejection_log(
+ receiver_module, monkeypatch, caplog, tmp_path, mode
+):
+ monkeypatch.setenv("JIUWENSWARM_LINK_MTLS_MODE", mode)
+ monkeypatch.setenv("JIUWENSWARM_LINK_MTLS_PROFILE", str(tmp_path / "absent.json"))
+ with TestClient(receiver_module.create_app()) as client:
+ response = client.get("/api/v1/ready")
+ assert response.status_code == 200 and response.json() == {"status": "ready"}
+ assert not any(r.name == receiver_module.logger.name for r in caplog.records)
+
+
+async def test_actual_tls_receiver_logs_binding_and_role_rejections(
+ receiver_module, monkeypatch, caplog, tmp_path
+):
+ from openjiuwen_runtime.foundation.security.link_certificate_bundle import (
+ issue_bundle,
+ materialize_role,
+ )
+ from openjiuwen_runtime.foundation.security.link_profile import LinkProfile
+
+ bundle = issue_bundle(
+ mtls_deployment_id="test-rejection-logs",
+ endpoints={},
+ sans={"gateway": ["127.0.0.1"]},
+ )
+ profiles = {
+ role: LinkProfile.load(str(materialize_role(bundle, role, tmp_path / role)))
+ for role in ("gateway", "runtime", "manager")
+ }
+ config = LinkMTLSConfig(mode=LinkMTLSMode.ENFORCE, profile=profiles["gateway"])
+ monkeypatch.setattr(receiver_module.LinkMTLSConfig, "from_env", lambda: config)
+ app = receiver_module.create_app()
+ sock = socket.socket()
+ sock.bind(("127.0.0.1", 0))
+ base = f"https://127.0.0.1:{sock.getsockname()[1]}"
+ server = uvicorn.Server(
+ uvicorn.Config(
+ app,
+ lifespan="off",
+ access_log=False,
+ log_level="warning",
+ **profiles["gateway"].server_kwargs(),
+ )
+ )
+ task = asyncio.create_task(server.serve(sockets=[sock]))
+ try:
+ for _ in range(300):
+ if server.started:
+ break
+ if task.done():
+ await task
+ await asyncio.sleep(0.01)
+ assert server.started
+ for role in ("manager", "runtime"):
+ profile = profiles[role]
+ async with httpx.AsyncClient(
+ trust_env=False, timeout=5, **profile.client_kwargs(role="gateway")
+ ) as client:
+ healthy = await client.get(
+ base + "/api/v1/ready", headers=profile.headers()
+ )
+ assert healthy.status_code == 200
+ headers = profile.headers()
+ if role == "manager":
+ allowed = await client.get(
+ base + "/api/v1/__link_binding_probe__", headers=headers
+ )
+ assert allowed.status_code == 404 # Passed auth; no write or route.
+ headers["X-Jiuwenswarm-Mtls-Binding-Id"] = "private-binding-marker"
+ response = await client.get(
+ base + "/api/v1/__link_binding_probe__", headers=headers
+ )
+ assert response.status_code == 403
+ assert response.json()["error"]["code"] == "LINK_BINDING_MISMATCH"
+ healthy = await client.get(
+ base + "/api/v1/ready", headers=profile.headers()
+ )
+ assert healthy.status_code == 200
+ finally:
+ server.should_exit = True
+ await asyncio.wait_for(task, 5)
+ sock.close()
+ records = [r for r in caplog.records if r.name == receiver_module.logger.name]
+ assert [r.getMessage() for r in records] == [
+ "[ManagerConfigReceiver] rejected link binding: request binding does not match authenticated deployment",
+ "[ManagerConfigReceiver] rejected link binding: peer certificate is not authorized for this binding and role",
+ ]
+ assert all(r.levelno == logging.WARNING and r.exc_info is None for r in records)
diff --git a/tests/unit_tests/common/test_link_mtls.py b/tests/unit_tests/common/test_link_mtls.py
new file mode 100644
index 0000000000..d270aa7083
--- /dev/null
+++ b/tests/unit_tests/common/test_link_mtls.py
@@ -0,0 +1,156 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+from __future__ import annotations
+
+import pytest
+from fastapi.testclient import TestClient
+from openjiuwen_runtime.foundation.security.link_mtls_config import (
+ MTLS_BINDING_EPOCH_HEADER,
+ MTLS_BINDING_ID_HEADER,
+)
+
+from jiuwenswarm.common.security.link_mtls import (
+ MTLSDeploymentIdentity,
+ LinkMTLSConfig,
+ LinkMTLSError,
+ LinkMTLSMode,
+ validate_incoming_binding,
+)
+
+
+def test_default_mode_is_off_and_ignores_unused_paths(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.delenv("JIUWENSWARM_LINK_MTLS_MODE", raising=False)
+ monkeypatch.setenv("JIUWENSWARM_LINK_MTLS_CA_FILE", "/missing/ca.pem")
+
+ config = LinkMTLSConfig.from_env()
+
+ assert config.mode is LinkMTLSMode.OFF
+ assert config.client_ssl_context() is None
+ assert config.uvicorn_ssl_kwargs() == {}
+ assert config.binding_headers() == {}
+
+
+def test_invalid_mode_is_rejected(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("JIUWENSWARM_LINK_MTLS_MODE", "optional")
+ with pytest.raises(LinkMTLSError, match="off, observe or enforce"):
+ LinkMTLSConfig.from_env()
+
+
+def test_enforce_requires_pinned_profile(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("JIUWENSWARM_LINK_MTLS_MODE", "enforce")
+ for name in (
+ "JIUWENSWARM_LINK_MTLS_CA_FILE",
+ "JIUWENSWARM_LINK_MTLS_CERT_FILE",
+ "JIUWENSWARM_LINK_MTLS_KEY_FILE",
+ ):
+ monkeypatch.delenv(name, raising=False)
+ monkeypatch.delenv("JIUWENSWARM_LINK_MTLS_PROFILE", raising=False)
+ with pytest.raises(LinkMTLSError, match="not installed"):
+ LinkMTLSConfig.from_env()
+
+
+def test_mtls_binding_headers_do_not_expose_deployment_id() -> None:
+ identity = MTLSDeploymentIdentity("deployment-1", "binding-1", 3)
+ assert identity.headers() == {
+ MTLS_BINDING_ID_HEADER: "binding-1",
+ MTLS_BINDING_EPOCH_HEADER: "3",
+ }
+
+
+def test_incoming_binding_mismatch_is_rejected() -> None:
+ config = LinkMTLSConfig(
+ mode=LinkMTLSMode.ENFORCE,
+ identity=MTLSDeploymentIdentity("deployment-1", "binding-1", 2),
+ )
+ with pytest.raises(LinkMTLSError, match="header-only validation is unsafe"):
+ validate_incoming_binding(
+ {
+ MTLS_BINDING_ID_HEADER: "binding-1",
+ MTLS_BINDING_EPOCH_HEADER: "1",
+ },
+ config,
+ )
+
+
+def test_enforce_rejects_plain_http() -> None:
+ config = LinkMTLSConfig(mode=LinkMTLSMode.ENFORCE)
+ with pytest.raises(LinkMTLSError, match="must use https"):
+ config.require_secure_url("http://runtime:8091", label="runtime")
+
+
+def test_agent_http_binding_guard_rejects_missing_and_stale_headers(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from jiuwenswarm.server.agent_http_routes import build_fastapi_app
+
+ config = LinkMTLSConfig(
+ mode=LinkMTLSMode.ENFORCE,
+ identity=MTLSDeploymentIdentity("deployment-1", "binding-1", 2),
+ )
+ monkeypatch.setattr(
+ LinkMTLSConfig, "from_env", classmethod(lambda cls, **kwargs: config)
+ )
+ client = TestClient(build_fastapi_app(object()))
+
+ assert client.get("/api/v1/health").status_code == 403
+ assert (
+ client.get(
+ "/api/v1/health",
+ headers={
+ MTLS_BINDING_ID_HEADER: "binding-1",
+ MTLS_BINDING_EPOCH_HEADER: "1",
+ },
+ ).status_code
+ == 403
+ )
+ assert (
+ client.get(
+ "/api/v1/health",
+ headers=config.binding_headers(),
+ ).status_code
+ == 403
+ ) # Correct headers cannot substitute for a TLS peer certificate.
+
+
[email protected]("mode", ["off", "observe"])
+def test_non_enforce_incomplete_profile_does_not_change_business(monkeypatch, mode):
+ monkeypatch.setenv("JIUWENSWARM_LINK_MTLS_MODE", mode)
+ monkeypatch.setenv("JIUWENSWARM_LINK_MTLS_PROFILE", "/not-installed/profile.json")
+ monkeypatch.setenv("JIUWENCLAW_ID", "existing-instance")
+ c = LinkMTLSConfig.from_env()
+ assert (
+ c.resolve_endpoint("http://runtime:8091", role="runtime")
+ == "http://runtime:8091"
+ )
+ assert c.binding_headers() == {} and c.client_kwargs(role="runtime") == {}
+ assert c.uvicorn_ssl_kwargs() == {}
+
+
+def test_profile_is_not_business_override_or_tool_child_credential(monkeypatch):
+ import os
+
+ from jiuwenswarm.common.local_env_config import (
+ LINK_SERVICE_ENV_KEYS,
+ export_agent_environ,
+ export_spawn_environ,
+ set_os_environ,
+ )
+
+ monkeypatch.setenv("JIUWENSWARM_LINK_MTLS_PROFILE", "/service/gateway/profile.json")
+ monkeypatch.setenv("JIUWENSWARM_LINK_MTLS_MODE", "enforce")
+ monkeypatch.setenv("JIUWENSWARM_LINK_MTLS_KEY_FILE", "/service/gateway/tls.key")
+ set_os_environ(
+ "JIUWENSWARM_LINK_MTLS_PROFILE",
+ "/untrusted/profile.json",
+ service_id="link-test",
+ agent_id="link-agent",
+ )
+ assert (
+ os.environ["JIUWENSWARM_LINK_MTLS_PROFILE"] == "/service/gateway/profile.json"
+ )
+ assert not (LINK_SERVICE_ENV_KEYS & export_spawn_environ().keys())
+ assert not (
+ LINK_SERVICE_ENV_KEYS & export_agent_environ("link-test", "link-agent").keys()
+ )
diff --git a/tests/unit_tests/gateway/test_http_agent_client.py b/tests/unit_tests/gateway/test_http_agent_client.py
index f1ff3f65ae..4aa083291c 100644
--- a/tests/unit_tests/gateway/test_http_agent_client.py
+++ b/tests/unit_tests/gateway/test_http_agent_client.py
@@ -11,9 +11,14 @@ import pytest
from jiuwenswarm.common.e2a.constants import E2A_WIRE_SERVER_PUSH_KEY
from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fields
from jiuwenswarm.common.e2a.wire_codec import encode_agent_chunk_for_wire
+from jiuwenswarm.common.request_ext import INTERNAL_HEADER_NAME, decode_internal_header
from jiuwenswarm.common.schema.agent import AgentResponseChunk
from jiuwenswarm.common.schema.message import ReqMethod
-from jiuwenswarm.common.request_ext import INTERNAL_HEADER_NAME, decode_internal_header
+from jiuwenswarm.common.security.link_mtls import (
+ MTLSDeploymentIdentity,
+ LinkMTLSConfig,
+ LinkMTLSMode,
+)
from jiuwenswarm.gateway.routing.agent_rest_map import (
RestAssemblyError,
assemble_rest_request,
@@ -197,8 +202,84 @@ async def test_connect_rejects_websocket_url():
await client.connect("ws://127.0.0.1:18092")
+async def test_enforce_agent_client_rejects_plain_http():
+ config = LinkMTLSConfig(
+ mode=LinkMTLSMode.ENFORCE,
+ identity=MTLSDeploymentIdentity("deployment-1", "binding-1", 4),
+ )
+ client = HttpSseAgentServerClient(link_mtls_config=config)
+ with pytest.raises(ValueError, match="must use https"):
+ await client.connect("http://127.0.0.1:8766")
+
+
+async def test_enforce_agent_client_rejects_plain_http_per_pod_base_url():
+ config = LinkMTLSConfig(
+ mode=LinkMTLSMode.ENFORCE,
+ identity=MTLSDeploymentIdentity("deployment-1", "binding-1", 4),
+ )
+ client = HttpSseAgentServerClient(
+ http_client=httpx.AsyncClient(
+ transport=httpx.MockTransport(
+ lambda request: httpx.Response(200, json={"ok": True})
+ )
+ ),
+ link_mtls_config=config,
+ )
+ envelope = e2a_from_agent_fields(
+ request_id="r1",
+ channel_id="web",
+ req_method=ReqMethod.SESSION_LIST,
+ params={},
+ )
+ try:
+ with pytest.raises(ValueError, match="must use https"):
+ await client.send_request(
+ envelope,
+ base_url="http://agent-pod.agentserver-headless:8766",
+ )
+ finally:
+ await client.disconnect()
+
+
+async def test_enforce_agent_client_sends_binding_headers():
+ captured: dict[str, str] = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured.update(request.headers)
+ return httpx.Response(
+ 200,
+ json={"ok": True, "data": {"status": "ready"}},
+ )
+
+ http = httpx.AsyncClient(transport=httpx.MockTransport(handler))
+ config = LinkMTLSConfig(
+ mode=LinkMTLSMode.ENFORCE,
+ identity=MTLSDeploymentIdentity("deployment-1", "binding-1", 4),
+ )
+ client = HttpSseAgentServerClient(
+ http_client=http,
+ link_mtls_config=config,
+ )
+ try:
+ await client.connect("https://agent.example:8766")
+ assert captured["x-jiuwenswarm-mtls-binding-id"] == "binding-1"
+ assert captured["x-jiuwenswarm-mtls-binding-epoch"] == "4"
+ assert {name for name in captured if name.startswith("x-jiuwenswarm-")} == {
+ "x-jiuwenswarm-mtls-binding-id",
+ "x-jiuwenswarm-mtls-binding-epoch",
+ }
+ finally:
+ await client.disconnect()
+ await http.aclose()
+
+
def _sse_blob(wire: dict) -> bytes:
- return f"event: e2a.chunk\ndata: {json.dumps(wire, ensure_ascii=False)}\n\n".encode("utf-8")
+ return f"event: e2a.chunk\ndata: {json.dumps(wire, ensure_ascii=False)}\n\n".encode(
+ "utf-8"
+ )
def _http_json(payload: dict) -> bytes:
@@ -213,7 +294,9 @@ async def _start_interrupt_stub():
interrupt_received = asyncio.Event()
interrupt_paths: list[str] = []
- async def _handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
+ async def _handle(
+ reader: asyncio.StreamReader, writer: asyncio.StreamWriter
+ ) -> None:
try:
header = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), timeout=5)
request_line = header.split(b"\r\n", 1)[0].decode("ascii", errors="replace")
@@ -227,7 +310,9 @@ async def _start_interrupt_stub():
if path.endswith("/health"):
writer.write(
- _http_json({"ok": True, "data": {"status": "ready"}, "request_id": "h1"})
+ _http_json(
+ {"ok": True, "data": {"status": "ready"}, "request_id": "h1"}
+ )
)
elif path.endswith("/actions/interrupt"):
interrupt_paths.append(path)
@@ -381,7 +466,11 @@ def test_default_agent_url_websocket_when_type_default(monkeypatch):
{
"request_id": "r2",
"ok": False,
- "error": {"code": "NOT_FOUND", "message": "missing", "details": {"k": 1}},
+ "error": {
+ "code": "NOT_FOUND",
+ "message": "missing",
+ "details": {"k": 1},
+ },
},
False,
{"error": "missing", "code": "NOT_FOUND", "k": 1},
@@ -401,7 +490,9 @@ def test_default_agent_url_websocket_when_type_default(monkeypatch):
],
)
def test_http_unary_unwrap_shapes(payload, expect_ok, expect_payload):
- resp = http_unary_to_agent_response(payload, channel_id="web", request_id="fallback")
+ resp = http_unary_to_agent_response(
+ payload, channel_id="web", request_id="fallback"
+ )
assert resp.ok is expect_ok
assert resp.channel_id == "web"
for key, value in expect_payload.items():
@@ -431,11 +522,11 @@ async def test_iter_sse_skips_keepalive_event_and_bad_json():
"\n"
"data: [1,2]\n"
"\n"
- "data: {\"a\": 1}\n"
+ 'data: {"a": 1}\n'
"\n"
- "data: {\"ok\": true, \"n\": 2}\n"
+ 'data: {"ok": true, "n": 2}\n'
"\n"
- "data: {\"trail\": true}\n"
+ 'data: {"trail": true}\n'
)
frames = [frame async for frame in iter_sse_data_frames(_LineResponse(blob))]
assert frames == [{"a": 1}, {"ok": True, "n": 2}, {"trail": True}]
@@ -443,7 +534,7 @@ async def test_iter_sse_skips_keepalive_event_and_bad_json():
@pytest.mark.asyncio
async def test_iter_sse_joins_multiline_data():
- blob = "data: {\n" 'data: "ok": true\n' "data: }\n" "\n"
+ blob = 'data: {\ndata: "ok": true\ndata: }\n\n'
frames = [frame async for frame in iter_sse_data_frames(_LineResponse(blob))]
assert frames == [{"ok": True}]
@@ -488,7 +579,9 @@ async def test_connect_rejects_wss_and_empty_scheme():
"health",
[
lambda _r: httpx.Response(503, json={"ok": False, "error": {"code": "DOWN"}}),
- lambda _r: httpx.Response(200, json={"ok": False, "data": {"status": "starting"}}),
+ lambda _r: httpx.Response(
+ 200, json={"ok": False, "data": {"status": "starting"}}
+ ),
lambda _r: httpx.Response(200, json={"status": "ready"}),
lambda _r: httpx.Response(200, content=b"not-json"),
lambda _r: httpx.Response(200, json=["nope"]),
@@ -664,7 +757,9 @@ async def test_push_loop_only_forwards_server_push_frames():
received.append(frame)
got.set()
- async def _handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
+ async def _handle(
+ reader: asyncio.StreamReader, writer: asyncio.StreamWriter
+ ) -> None:
try:
header = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), timeout=5)
request_line = header.split(b"\r\n", 1)[0].decode("ascii", errors="replace")
@@ -725,7 +820,9 @@ async def test_push_loop_backs_off_after_clean_stream_end(monkeypatch):
async def on_push(_frame: dict) -> None:
return None
- async def _handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
+ async def _handle(
+ reader: asyncio.StreamReader, writer: asyncio.StreamWriter
+ ) -> None:
nonlocal stream_hits
try:
header = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), timeout=5)
@@ -798,7 +895,9 @@ async def test_send_request_with_base_url_skips_connect():
@pytest.mark.asyncio
async def test_send_request_base_url_5xx_raises():
def handler(request: httpx.Request) -> httpx.Response:
- return httpx.Response(502, json={"ok": False, "error": {"message": "bad gateway"}})
+ return httpx.Response(
+ 502, json={"ok": False, "error": {"message": "bad gateway"}}
+ )
client = HttpSseAgentServerClient(
http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler))
@@ -830,7 +929,9 @@ async def _start_trailing_sse_stub(*, first_rid: str = "chat-old"):
release_trailing = asyncio.Event()
paths: list[str] = []
- async def _handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
+ async def _handle(
+ reader: asyncio.StreamReader, writer: asyncio.StreamWriter
+ ) -> None:
try:
header = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), timeout=5)
request_line = header.split(b"\r\n", 1)[0].decode("ascii", errors="replace")
@@ -846,7 +947,9 @@ async def _start_trailing_sse_stub(*, first_rid: str = "chat-old"):
if path.endswith("/health"):
writer.write(
- _http_json({"ok": True, "data": {"status": "ready"}, "request_id": "h1"})
+ _http_json(
+ {"ok": True, "data": {"status": "ready"}, "request_id": "h1"}
+ )
)
elif path.endswith("/chat/completions"):
req_rid = first_rid
@@ -950,6 +1053,9 @@ async def test_new_stream_supersedes_old_stream_trailing_chunks():
client = HttpSseAgentServerClient()
old_yielded: list[str] = []
new_yielded: list[str] = []
+ old_consumed = asyncio.Event()
+ new_consumed = asyncio.Event()
+ tasks = []
try:
await client.connect(base)
old_env = e2a_from_agent_fields(
@@ -973,27 +1079,36 @@ async def test_new_stream_supersedes_old_stream_trailing_chunks():
async for chunk in client.send_request_stream(old_env):
payload = chunk.payload or {}
old_yielded.append(str(payload.get("content") or ""))
+ old_consumed.set()
old_task = asyncio.create_task(_consume_old())
+ tasks.append(old_task)
await asyncio.wait_for(first_sent.wait(), timeout=5)
+ # A server write does not imply the client has consumed the first frame.
+ # Establish the old stream before superseding it, independent of scheduling.
+ await asyncio.wait_for(old_consumed.wait(), timeout=5)
first_sent.clear()
async def _consume_new() -> None:
async for chunk in client.send_request_stream(new_env):
payload = chunk.payload or {}
new_yielded.append(str(payload.get("content") or ""))
+ new_consumed.set()
new_task = asyncio.create_task(_consume_new())
+ tasks.append(new_task)
await asyncio.wait_for(first_sent.wait(), timeout=5)
+ await asyncio.wait_for(new_consumed.wait(), timeout=5)
release_trailing.set()
- await asyncio.sleep(0.15)
- old_task.cancel()
- new_task.cancel()
- await asyncio.gather(old_task, new_task, return_exceptions=True)
+ await asyncio.wait_for(asyncio.gather(*tasks), timeout=5)
assert "first" in old_yielded
assert "STALE_TAIL" not in old_yielded
+ assert new_yielded == ["first", "STALE_TAIL"]
finally:
release_trailing.set()
+ for task in tasks:
+ task.cancel()
+ await asyncio.gather(*tasks, return_exceptions=True)
await client.disconnect()
server.close()
await server.wait_closed()
diff --git a/tests/unit_tests/gateway/test_link_binding_state.py b/tests/unit_tests/gateway/test_link_binding_state.py
new file mode 100644
index 0000000000..5a52eb8f0e
--- /dev/null
+++ b/tests/unit_tests/gateway/test_link_binding_state.py
@@ -0,0 +1,169 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from openjiuwen_runtime.foundation.db.sqlite_handler import SQLiteHandler
+
+from jiuwenswarm.common.security.link_mtls import (
+ MTLSDeploymentIdentity,
+ LinkMTLSConfig,
+ LinkMTLSError,
+ LinkMTLSMode,
+)
+from jiuwenswarm.gateway.config.enterprise.link_binding_state import (
+ LOCAL_SERVICE_ROLE,
+ PROTOCOL_VERSION,
+ sync_local_link_binding_state,
+)
+from jiuwenswarm.gateway.config.enterprise.tables.link_binding_state_models import (
+ LINK_BINDING_STATE_TABLE,
+ LINK_BINDING_STATE_TABLE_DEF,
+)
+
+
+class _FakeDb:
+ def __init__(self, row: object | None = None) -> None:
+ self.row = row
+ self.created: tuple[str, dict[str, object]] | None = None
+ self.updated: tuple[str, dict[str, object], dict[str, object]] | None = None
+
+ async def get(self, table: str, filters: dict[str, object]) -> object | None:
+ assert table == LINK_BINDING_STATE_TABLE
+ assert filters == {"service_role": LOCAL_SERVICE_ROLE}
+ return self.row
+
+ async def create(self, table: str, data: dict[str, object]) -> object:
+ self.created = (table, data)
+ return SimpleNamespace(**data)
+
+ async def update(
+ self,
+ table: str,
+ filters: dict[str, object],
+ data: dict[str, object],
+ ) -> object:
+ self.updated = (table, filters, data)
+ return SimpleNamespace(**data)
+
+
+def _config(tmp_path: Path) -> LinkMTLSConfig:
+ from tests.fixtures.link_mtls import provision
+
+ provision(
+ tmp_path / "bundle",
+ mtls_deployment_id="claw-1",
+ endpoints={"gateway": "127.0.0.1:8775"},
+ )
+ ca = tmp_path / "bundle/gateway/ca.crt"
+ cert = tmp_path / "bundle/gateway/tls.crt"
+ key = tmp_path / "bundle/gateway/tls.key"
+ return LinkMTLSConfig(
+ mode=LinkMTLSMode.ENFORCE,
+ ca_file=str(ca),
+ cert_file=str(cert),
+ key_file=str(key),
+ identity=MTLSDeploymentIdentity("claw-1", "binding-1", 7),
+ )
+
+
+async def test_sync_local_link_binding_state_creates_public_record(
+ tmp_path: Path,
+) -> None:
+ db = _FakeDb()
+ config = _config(tmp_path)
+
+ await sync_local_link_binding_state(db, config)
+
+ assert db.created is not None
+ table, row = db.created
+ assert table == LINK_BINDING_STATE_TABLE
+ assert row["service_role"] == "gateway"
+ assert row["mtls_deployment_id"] == "claw-1"
+ assert row["mtls_binding_id"] == "binding-1"
+ assert row["mtls_binding_epoch"] == 7
+ assert row["protocol_version"] == PROTOCOL_VERSION
+ assert row["local_cert_pem"] == Path(config.cert_file).read_text()
+ assert row["peer_trust_bundle_pem"] == Path(config.ca_file).read_text()
+ assert row["private_key_ref"] == config.key_file
+ assert "PRIVATE KEY" not in str(row)
+
+
+async def test_sync_local_link_binding_state_updates_existing_record(
+ tmp_path: Path,
+) -> None:
+ config = _config(tmp_path)
+ db = _FakeDb(
+ row=SimpleNamespace(
+ status="active",
+ mtls_deployment_id=config.identity.mtls_deployment_id,
+ mtls_binding_id=config.identity.mtls_binding_id,
+ mtls_binding_epoch=config.identity.mtls_binding_epoch,
+ local_cert_fingerprint=config.cert_fingerprint(),
+ )
+ )
+
+ await sync_local_link_binding_state(db, config)
+
+ assert db.created is None
+ assert db.updated is not None
+ assert db.updated[1] == {
+ "service_role": LOCAL_SERVICE_ROLE,
+ "mtls_binding_epoch": 7,
+ "status": "active",
+ }
+ assert db.updated[2]["mtls_binding_epoch"] == 7
+
+
+async def test_sync_local_link_binding_state_off_does_not_access_db() -> None:
+ class _FailDb:
+ def __getattr__(self, name: str) -> object:
+ raise AssertionError(f"unexpected DB access: {name}")
+
+ result = await sync_local_link_binding_state(
+ _FailDb(),
+ LinkMTLSConfig(mode=LinkMTLSMode.OFF),
+ )
+ assert result is None
+
+
+async def test_link_binding_state_round_trip_with_real_sqlite(tmp_path: Path) -> None:
+ handler = SQLiteHandler(str(tmp_path / "gateway.db"))
+ await handler.init_database()
+ await handler.connect()
+ try:
+ await handler.init_table(LINK_BINDING_STATE_TABLE_DEF)
+ config = _config(tmp_path)
+ await sync_local_link_binding_state(handler, config)
+ row = await handler.get(
+ LINK_BINDING_STATE_TABLE,
+ {"service_role": LOCAL_SERVICE_ROLE},
+ )
+ assert row is not None
+ assert row.mtls_deployment_id == "claw-1"
+ assert row.mtls_binding_id == "binding-1"
+ assert row.mtls_binding_epoch == 7
+ assert row.local_cert_pem.startswith("-----BEGIN CERTIFICATE-----")
+ assert row.private_key_ref.endswith("tls.key")
+ from dataclasses import replace
+
+ updated = replace(
+ config, identity=MTLSDeploymentIdentity("claw-1", "binding-2", 8)
+ )
+ await sync_local_link_binding_state(handler, updated)
+ with pytest.raises(LinkMTLSError, match="older than persisted"):
+ await sync_local_link_binding_state(handler, config)
+ row = await handler.get(
+ LINK_BINDING_STATE_TABLE, {"service_role": LOCAL_SERVICE_ROLE}
+ )
+ assert row.mtls_binding_epoch == 8
+ assert row.mtls_binding_id == "binding-2"
+ finally:
+ await handler.disconnect()
diff --git a/tests/unit_tests/gateway/test_log_masking.py b/tests/unit_tests/gateway/test_log_masking.py
index 5cf2e01e8c..c3bdb69168 100644
--- a/tests/unit_tests/gateway/test_log_masking.py
+++ b/tests/unit_tests/gateway/test_log_masking.py
@@ -300,7 +300,6 @@ async def test_reload_log_masking_rule_loads_gdb_without_jiuwenclaw_id(monkeypat
monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")
monkeypatch.delenv("JIUWENCLAW_ID", raising=False)
- monkeypatch.delenv("JIUWENSWARM_ID", raising=False)
monkeypatch.setattr(engine_mod, "settings", Settings())
LogMaskingEngine.reset_for_tests()
diff --git a/tests/unit_tests/gateway/test_runtime_notify.py b/tests/unit_tests/gateway/test_runtime_notify.py
index cfe6d95da1..7603495a33 100644
--- a/tests/unit_tests/gateway/test_runtime_notify.py
+++ b/tests/unit_tests/gateway/test_runtime_notify.py
@@ -10,6 +10,11 @@ from pathlib import Path
import httpx
import pytest
+from jiuwenswarm.common.security.link_mtls import (
+ LinkMTLSConfig,
+ LinkMTLSMode,
+)
+
_RECEIVER_DIR = (
Path(__file__).resolve().parents[3]
/ "packages"
@@ -53,9 +58,16 @@ async def test_request_agentserver_refresh_posts_empty_payload(
async def __aexit__(self, *args):
return None
- async def post(self, url: str, *, json: dict | None = None):
+ async def post(
+ self,
+ url: str,
+ *,
+ json: dict | None = None,
+ headers: dict | None = None,
+ ):
captured["url"] = url
captured["body"] = json
+ captured["headers"] = headers
class _Resp:
status_code = 200
@@ -63,7 +75,9 @@ async def test_request_agentserver_refresh_posts_empty_payload(
@staticmethod
def json() -> dict:
- return {"rawdata": {"ok": True, "scopes_refreshed": 1, "pods_sunset": 2}}
+ return {
+ "rawdata": {"ok": True, "scopes_refreshed": 1, "pods_sunset": 2}
+ }
return _Resp()
@@ -74,3 +88,67 @@ async def test_request_agentserver_refresh_posts_empty_payload(
assert captured["url"] == "http://runtime-manager:8091/api/session/config_refresh"
assert captured["body"]["type"] == "config_refresh"
assert captured["body"]["rawdata"] == {}
+ assert captured["headers"] == {}
+
+
+async def test_request_agentserver_refresh_enforce_sends_binding_headers(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("GATEWAY_RUNTIME_MANAGER_URL", "http://runtime-manager:8091")
+ captured: dict = {}
+
+ class _FakeAsyncClient:
+ def __init__(self, **kwargs) -> None:
+ captured["client_kwargs"] = kwargs
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *args):
+ return None
+
+ async def post(
+ self,
+ url: str,
+ *,
+ json: dict | None = None,
+ headers: dict | None = None,
+ ):
+ captured.update(url=url, body=json, headers=headers)
+
+ class _Resp:
+ status_code = 200
+ text = ""
+
+ @staticmethod
+ def json() -> dict:
+ return {"rawdata": {"cleaned": 1}}
+
+ return _Resp()
+
+ monkeypatch.setattr(httpx, "AsyncClient", _FakeAsyncClient)
+ from openjiuwen_runtime.foundation.security.link_profile import LinkProfile
+
+ from tests.fixtures.link_mtls import provision
+
+ provision(
+ tmp_path / "bundle",
+ mtls_deployment_id="deployment-1",
+ mtls_binding_epoch=2,
+ endpoints={"runtime": "runtime-manager:8091"},
+ )
+ p = LinkProfile.load(str(tmp_path / "bundle/gateway/profile.json"))
+ config = LinkMTLSConfig(
+ mode=LinkMTLSMode.ENFORCE,
+ profile=p,
+ )
+
+ await _request_agentserver_refresh(config)
+
+ assert captured["url"] == "https://runtime-manager:8091/api/session/config_refresh"
+ assert captured["body"]["type"] == "config_refresh"
+ assert captured["body"]["rawdata"] == {}
+ assert captured["headers"] == p.headers()
+ assert "transport" in captured["client_kwargs"]
diff --git a/tests/unit_tests/gateway/test_session_route.py b/tests/unit_tests/gateway/test_session_route.py
index 5fdf628f11..bf07d4c932 100644
--- a/tests/unit_tests/gateway/test_session_route.py
+++ b/tests/unit_tests/gateway/test_session_route.py
@@ -11,6 +11,13 @@ from pathlib import Path
import httpx
import pytest
+import pytest_asyncio
+
+from jiuwenswarm.common.security.link_mtls import (
+ MTLSDeploymentIdentity,
+ LinkMTLSConfig,
+ LinkMTLSMode,
+)
_EXT_DIR = (
Path(__file__).resolve().parents[3]
@@ -50,7 +57,7 @@ def _ok_body() -> dict:
}
+@pytest_asyncio.fixture
async def client_factory():
clients: list = []
https: list[httpx.AsyncClient] = []
@@ -59,10 +66,15 @@ async def client_factory():
handler: Callable[[httpx.Request], httpx.Response],
*,
base_url: str = "http://runtime-manager:8091",
+ link_mtls_config: LinkMTLSConfig | None = None,
) -> RuntimeSessionRouteClient:
http = httpx.AsyncClient(transport=httpx.MockTransport(handler))
https.append(http)
- client = RuntimeSessionRouteClient(base_url=base_url, http_client=http)
+ client = RuntimeSessionRouteClient(
+ base_url=base_url,
+ http_client=http,
+ link_mtls_config=link_mtls_config,
+ )
clients.append(client)
return client
@@ -96,13 +108,71 @@ async def test_route_success(client_factory) -> None:
assert captured["body"]["metadata"]["request_id"] == "req-1"
+async def test_enforce_sends_binding_headers_and_validates_route(
+ client_factory,
+) -> None:
+ identity = MTLSDeploymentIdentity("deployment-1", "binding-1", 3)
+ config = LinkMTLSConfig(mode=LinkMTLSMode.ENFORCE, identity=identity)
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert request.headers["X-Jiuwenswarm-Mtls-Binding-Id"] == "binding-1"
+ assert request.headers["X-Jiuwenswarm-Mtls-Binding-Epoch"] == "3"
+ body = _ok_body()
+ body["rawdata"].update(
+ {
+ "pod_sse_url": "https://agent.example:8766/api/v1",
+ "mtls_deployment_id": "deployment-1",
+ "mtls_binding_id": "binding-1",
+ "mtls_binding_epoch": 3,
+ }
+ )
+ return httpx.Response(200, json=body)
+
+ result = await client_factory(
+ handler,
+ base_url="https://runtime.example:8091",
+ link_mtls_config=config,
+ ).route(**_ROUTE_KW)
+ assert result.mtls_binding_epoch == 3
+
+
+async def test_enforce_rejects_stale_route_binding(client_factory) -> None:
+ config = LinkMTLSConfig(
+ mode=LinkMTLSMode.ENFORCE,
+ identity=MTLSDeploymentIdentity("deployment-1", "binding-1", 3),
+ )
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ body = _ok_body()
+ body["rawdata"].update(
+ {
+ "pod_sse_url": "https://agent.example:8766/api/v1",
+ "mtls_deployment_id": "deployment-1",
+ "mtls_binding_id": "binding-1",
+ "mtls_binding_epoch": 2,
+ }
+ )
+ return httpx.Response(200, json=body)
+
+ with pytest.raises(FatalRouteError, match="binding mismatch"):
+ await client_factory(
+ handler,
+ base_url="https://runtime.example:8091",
+ link_mtls_config=config,
+ ).route(**_ROUTE_KW)
+
+
@pytest.mark.asyncio
async def test_route_strips_base_url_slash(client_factory) -> None:
def handler(request: httpx.Request) -> httpx.Response:
assert str(request.url) == "http://runtime-manager:8091/api/session/route"
return httpx.Response(200, json=_ok_body())
- await client_factory(handler, base_url="http://runtime-manager:8091/").route(**_ROUTE_KW)
+ await client_factory(handler, base_url="http://runtime-manager:8091/").route(
+ **_ROUTE_KW
+ )
@pytest.mark.asyncio
@@ -114,7 +184,9 @@ async def test_route_missing_args_skips_http(client_factory) -> None:
return httpx.Response(200, json=_ok_body())
with pytest.raises(FatalRouteError) as exc:
- await client_factory(handler).route(session_id="", group_id="g", bot_id="b", request_id="r")
+ await client_factory(handler).route(
+ session_id="", group_id="g", bot_id="b", request_id="r"
+ )
assert exc.value.code == "VALIDATION"
assert called["n"] == 0
@@ -130,7 +202,9 @@ async def test_route_missing_args_skips_http(client_factory) -> None:
(400, "VALIDATION", None, FatalRouteError),
],
)
-async def test_route_error_codes(client_factory, status, code, retry_after, exc_type) -> None:
+async def test_route_error_codes(
+ client_factory, status, code, retry_after, exc_type
+) -> None:
body: dict = {"ok": False, "error_code": code, "error_message": code}
if retry_after is not None:
body["retry_after"] = retry_after
@@ -185,7 +259,10 @@ async def test_touch_expired_returns_false(client_factory) -> None:
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, json={"ok": True, "rawdata": {"touched": False}})
- assert await client_factory(handler).touch(session_id="sess-gone", request_id="req-1") is False
+ assert (
+ await client_factory(handler).touch(session_id="sess-gone", request_id="req-1")
+ is False
+ )
@pytest.mark.asyncio
@@ -277,7 +354,9 @@ async def test_reads_url_from_env(monkeypatch: pytest.MonkeyPatch) -> None:
@pytest.mark.asyncio
-async def test_blank_url_and_bad_timeout_fall_back(monkeypatch: pytest.MonkeyPatch) -> None:
+async def test_blank_url_and_bad_timeout_fall_back(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
monkeypatch.setenv("GATEWAY_RUNTIME_MANAGER_URL", " ")
monkeypatch.setenv("GATEWAY_RUNTIME_MANAGER_TIMEOUT", "not-a-number")
client = RuntimeSessionRouteClient()
diff --git a/tests/unit_tests/test_link_mtls_db_deploy.py b/tests/unit_tests/test_link_mtls_db_deploy.py
new file mode 100644
index 0000000000..a9e9e4205e
--- /dev/null
+++ b/tests/unit_tests/test_link_mtls_db_deploy.py
@@ -0,0 +1,440 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""Exercise the actual shell/template boundary without Docker or cluster writes."""
+
+import copy
+import json
+import os
+import shlex
+import shutil
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+import pytest
+import yaml
+from openjiuwen_runtime.foundation.security import link_material_sync
+from openjiuwen_runtime.foundation.security.link_material_deploy import deployment_plan
+
+DIRECTORY = Path(__file__).resolve().parents[2] / "deploy/enterprise"
+
+
+def run_handler(settings, command, overrides=""):
+ bash = shutil.which("bash")
+ if (
+ not bash
+ or int(
+ subprocess.check_output([bash, "-c", "echo ${BASH_VERSINFO[0]}"], text=True)
+ )
+ < 4
+ ):
+ pytest.skip("Bash 4+ required")
+ if not shutil.which("jq") or not shutil.which("yq"):
+ pytest.skip("jq and mikefarah/yq required")
+ script = (
+ "declare -A DEPLOY_VARS\n"
+ "while IFS= read -r -d '' key && IFS= read -r -d '' value; do DEPLOY_VARS[$key]=$value; done\n"
+ "SCRIPT_DIR=" + shlex.quote(str(DIRECTORY)) + "\n"
+ 'source "$SCRIPT_DIR/link_mtls_handler.sh"\n' + overrides + "\n" + command
+ )
+ data = "".join(str(k) + "\0" + str(v) + "\0" for k, v in settings.items())
+ return subprocess.run(
+ [bash, "-c", script], input=data, text=True, capture_output=True, timeout=30
+ )
+
+
+def overlay(document, role, settings):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "workload.yaml"
+ path.write_text(
+ yaml.safe_dump_all(document if isinstance(document, list) else [document])
+ )
+ result = run_handler(
+ settings,
+ "link_mtls_render " + shlex.quote(role) + " " + shlex.quote(str(path)),
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+ result = list(yaml.safe_load_all(path.read_text()))
+ return result if isinstance(document, list) else result[0]
+
+
+def overlay_agent_template(document, settings):
+ return overlay(document, "agentserver", settings)
+
+
+def settings():
+ return {
+ "NAMESPACE": "cert-test",
+ "GATEWAY_NAME": "jiuwenclaw-gateway",
+ "AGENT_RUNTIME_NAME": "jiuwenclaw-agent-runtime",
+ "GATEWAY_CONFIG_HTTP_PORT": "8775",
+ "AGENT_RUNTIME_PORT": "8091",
+ "AGENT_SERVER_PORT": "8766",
+ "AGENT_SERVER_NAME": "jiuwenclaw-agentserver",
+ "DB_TYPE": "mysql",
+ "DB_HOST": "database",
+ "DB_PORT": "3306",
+ "GATEWAY_DB_NAME": "gateway_cert_test",
+ "GATEWAY_DB_USER": "gateway-user",
+ "GATEWAY_DB_PASSWORD": "gateway-password",
+ "RUNTIME_DB_NAME": "runtime_cert_test",
+ "RUNTIME_DB_USER": "runtime-user",
+ "RUNTIME_DB_PASSWORD": "runtime-password",
+ "MODE": "dev",
+ "RUNTIME_CODE_PATH": "/example/runtime",
+ "JIUWENSWARM_LINK_MTLS_MODE": "enforce",
+ "LINK_SYNC_CODE": Path(link_material_sync.__file__).read_text(),
+ }
+
+
+def workload(role, *, uid=0, fs_group=0):
+ container = {
+ "name": {
+ "gateway": "gateway",
+ "runtime": "agent-runtime",
+ "manager": "manager",
+ }[role],
+ "image": "test:21s",
+ "command": ["custom"],
+ "args": ["unchanged"],
+ "securityContext": {"runAsUser": uid, "runAsGroup": 1000},
+ "volumeMounts": [{"name": "business", "mountPath": "/data"}],
+ "readinessProbe": {
+ "httpGet": {"path": "/healthz", "port": 8091},
+ "timeoutSeconds": 2,
+ },
+ }
+ return {
+ "kind": "Deployment",
+ "spec": {
+ "template": {
+ "spec": {
+ "securityContext": {"fsGroup": fs_group},
+ "containers": [container, {"name": "unrelated", "image": "other"}],
+ "volumes": [
+ {"name": "business", "nfs": {"server": "nfs", "path": "/data"}}
+ ],
+ }
+ }
+ },
+ }
+
+
[email protected]("role", ["gateway", "runtime", "manager"])
[email protected]("mode", ["off", "observe", "enforce"])
+def test_overlay_preserves_business_fields_and_role_isolation(settings, role, mode):
+ settings["JIUWENSWARM_LINK_MTLS_MODE"] = mode
+ original = [workload(role)]
+ before = copy.deepcopy(original)
+ rendered = overlay(original, role, settings)
+ assert original == before
+ spec = rendered[0]["spec"]["template"]["spec"]
+ main, unrelated = spec["containers"]
+ assert main["command"] == ["custom"] and main["args"] == ["unchanged"]
+ assert unrelated == before[0]["spec"]["template"]["spec"]["containers"][1]
+ assert spec["volumes"][0] == before[0]["spec"]["template"]["spec"]["volumes"][0]
+ if mode == "off":
+ assert rendered == before
+ elif mode == "observe":
+ assert "httpGet" in main["readinessProbe"]
+ assert not any("secret" in v for v in spec["volumes"])
+ else:
+ assert spec["securityContext"] == {"fsGroup": 0}
+ assert (
+ next(v for v in spec["volumes"] if "secret" in v)["secret"]["defaultMode"]
+ == 0o400
+ )
+ assert "PRIVATE KEY" not in json.dumps(rendered)
+ if role != "manager":
+ assert "httpGet" not in main["readinessProbe"]
+ assert "exec" in main["readinessProbe"]
+
+
[email protected]("uid,group", [(1000, 1000), (None, 1000), (0, 1000)])
+def test_private_copy_does_not_chown_business_volumes(settings, uid, group):
+ spec = overlay([workload("runtime", uid=uid, fs_group=group)], "runtime", settings)[
+ 0
+ ]["spec"]["template"]["spec"]
+ assert spec["securityContext"] == {"fsGroup": group}
+ assert len(spec["containers"]) == 3
+ main, unrelated, helper = spec["containers"]
+ assert helper["securityContext"].get("runAsUser") == uid
+ assert len(helper["volumeMounts"]) == 2
+ assert not any(m["mountPath"] == "/data" for m in helper["volumeMounts"])
+ assert not any("volumeMounts" in c for c in [unrelated])
+ assert any(
+ v["name"] == "JIUWENSWARM_LINK_MTLS_PROFILE"
+ and "/private/identity/" in v["value"]
+ for v in main["env"]
+ )
+
+
+def test_agent_template_changes_only_main_source_package(settings):
+ template = {
+ "type": "config_sync",
+ "rawdata": {
+ "templates": [
+ {
+ "main_container_id": "as",
+ "fsGroup": 0,
+ "volumes": [
+ {"name": "data", "nfs": {"server": "nfs", "path": "/data"}}
+ ],
+ }
+ ],
+ "containers": [
+ {
+ "container_id": "as",
+ "name": "agent",
+ "command": ["agent"],
+ "args": ["custom"],
+ },
+ {"container_id": "box", "name": "jiuwenbox"},
+ ],
+ },
+ }
+ result = overlay_agent_template(template, settings)
+ assert result["rawdata"]["containers"][1] == template["rawdata"]["containers"][1]
+ assert (
+ result["rawdata"]["templates"][0]["volumes"][0]
+ == template["rawdata"]["templates"][0]["volumes"][0]
+ )
+ assert result["rawdata"]["containers"][0]["command"] == ["agent"]
+ assert result["rawdata"]["containers"][0]["args"] == ["custom"]
+ assert "tls.key" not in json.dumps(result)
+
+
+def test_sans_use_headless_dns_not_pod_ip(settings):
+ plan = deployment_plan(settings)
+ assert plan["endpoints"]["runtime"] == "jiuwenclaw-agent-runtime:8091"
+ assert plan["sans"]["agentserver"] == [
+ "*.jiuwenclaw-agentserver.cert-test.svc.cluster.local"
+ ]
+
+
+def test_database_service_endpoint_precedes_host_dns(settings):
+ """Do not let stale host DNS select a different headless DB endpoint."""
+ overrides = r"""
+ getent() { printf '%s\n' '192.0.2.99 STREAM stale'; }
+ kubectl() {
+ case "$*" in
+ *'-n cert-test get service database -o json')
+ printf '%s' '{"spec":{"clusterIP":"None"}}'
+ ;;
+ *'-n cert-test get endpoints database -o json')
+ printf '%s' '{"subsets":[{"addresses":[{"ip":"10.24.1.55"}]}]}'
+ ;;
+ *) return 99 ;;
+ esac
+ }
+ """
+ result = run_handler(
+ settings,
+ "link_mtls_resolve_host database.cert-test.svc.cluster.local",
+ overrides,
+ )
+ assert result.returncode == 0, result.stderr
+ assert result.stdout == "10.24.1.55"
+
+
+def test_external_database_host_falls_back_to_host_dns(settings):
+ overrides = r"""
+ kubectl() { return 1; }
+ getent() { printf '%s\n' '198.51.100.20 STREAM external'; }
+ """
+ result = run_handler(
+ settings,
+ "link_mtls_resolve_host mysql.customer.example",
+ overrides,
+ )
+ assert result.returncode == 0, result.stderr
+ assert result.stdout == "198.51.100.20"
+
+
[email protected]("uid,gid", [(0, 0), (1234, 2345)])
[email protected]("action", ["imports", "ensure", "status", "request", "wait"])
+def test_image_worker_matches_deployer_uid_without_relaxing_isolation(
+ monkeypatch, settings, tmp_path, uid, gid, action
+):
+ binary, capture = tmp_path / "docker", tmp_path / "capture.json"
+ binary.write_text(
+ f"#!{sys.executable}\nimport sys,json\n"
+ f"open({str(capture)!r},'w').write(json.dumps({{'args':sys.argv[1:],'message':json.load(sys.stdin)}}))\n"
+ "print('{\"checked\":true}')\n"
+ )
+ binary.chmod(0o700)
+ monkeypatch.setenv("PATH", str(tmp_path) + os.pathsep + os.environ["PATH"])
+ monkeypatch.setenv("DOCKER_HOST", "unix:///test.sock")
+ monkeypatch.delenv("DOCKER_CONTEXT", raising=False)
+ settings = {
+ **settings,
+ "MODE": "product",
+ "AGENT_RUNTIME_IMAGE": "runtime:21s",
+ "DB_HOST": "database",
+ "GATEWAY_DB_PASSWORD": "private-test-password",
+ "UNRELATED_PRIVATE_VALUE": "must-not-enter-worker-protocol\nwith-a-second-line",
+ }
+ overrides = (
+ f'id() {{ if [[ "$1" == -u ]]; then echo {uid}; else echo {gid}; fi; }}\n'
+ "link_mtls_resolve_host() { echo 127.0.0.1; }\n"
+ "link_mtls_preflight() { :; }\n"
+ "link_mtls_kube() { :; }"
+ )
+ result = run_handler(
+ settings, f"link_mtls_worker {action} gateway /api/v1/ready", overrides
+ )
+ assert result.returncode == 0, result.stderr
+ captured = json.loads(capture.read_text())
+ args = captured["args"]
+ assert args[args.index("--user") + 1] == f"{uid}:{gid}"
+ assert "--read-only" in args and "--cap-drop=ALL" in args
+ assert "--security-opt=no-new-privileges" in args
+ assert args[args.index("--network") + 1] == (
+ "none" if action == "imports" else "host"
+ )
+ assert "--privileged" not in args and not any("docker.sock" in a for a in args)
+ assert "private-test-password" not in " ".join(args) + result.stdout + result.stderr
+ assert captured["message"]["settings"]["GATEWAY_DB_NAME"] == "gateway_cert_test"
+ assert captured["message"]["settings"]["RUNTIME_DB_NAME"] == "runtime_cert_test"
+ assert (
+ captured["message"]["settings"]["GATEWAY_DB_PASSWORD"]
+ == "private-test-password"
+ )
+ assert captured["message"]["settings"]["RUNTIME_DB_PASSWORD"] == (
+ settings["RUNTIME_DB_PASSWORD"]
+ )
+ assert "UNRELATED_PRIVATE_VALUE" not in captured["message"]["settings"]
+ assert args[-2:] == [
+ "-m",
+ "openjiuwen_runtime.foundation.security.link_material_deploy",
+ ]
+ assert json.loads(result.stdout) == {"checked": True}
+
+
+ "missing",
+ [
+ "GATEWAY_DB_NAME",
+ "GATEWAY_DB_USER",
+ "GATEWAY_DB_PASSWORD",
+ "RUNTIME_DB_NAME",
+ "RUNTIME_DB_USER",
+ "RUNTIME_DB_PASSWORD",
+ ],
+)
+def test_worker_rejects_unresolved_database_setting_before_docker(settings, missing):
+ settings[missing] = ""
+ overrides = """docker() { echo unexpected-docker >&2; return 99; }
+ link_mtls_resolve_host() { echo 127.0.0.1; }"""
+ result = run_handler(settings, "link_mtls_worker ensure", overrides)
+ assert result.returncode != 0
+ assert f"{missing} must be resolved before certificate preparation" in result.stderr
+ assert "unexpected-docker" not in result.stderr
+
+
+def test_worker_rejects_serialized_database_setting_loss_before_docker(settings):
+ settings["MODE"] = "product"
+ overrides = """
+ link_mtls_settings_json() {
+ printf '%s' '{"GATEWAY_DB_NAME":"gateway","GATEWAY_DB_USER":"user","GATEWAY_DB_PASSWORD":"password","RUNTIME_DB_NAME":"runtime","RUNTIME_DB_USER":"user","RUNTIME_DB_PASSWORD":null}'
+ }
+ link_mtls_resolve_host() { echo 127.0.0.1; }
+ docker() {
+ if [[ "$1" == context ]]; then
+ echo unix:///var/run/docker.sock
+ return
+ fi
+ echo unexpected-docker >&2
+ return 99
+ }
+ """
+ result = run_handler(
+ settings,
+ "link_mtls_worker request gateway /api/v1/ready",
+ overrides,
+ )
+ assert result.returncode != 0
+ assert "Serialized mTLS database settings are incomplete" in result.stderr
+ assert "unexpected-docker" not in result.stderr
+
+
+def test_conflicting_headless_service_stops_before_writes(settings):
+ overrides = """link_mtls_kube() {
+ [[ "$1" == get && "$2" == service ]] || return 99
+ printf '%s' '{"spec":{"clusterIP":"10.0.0.8","selector":{"app":"other"}}}'
+ }"""
+ result = run_handler(settings, "link_mtls_preflight", overrides)
+ assert result.returncode != 0
+ assert "conflicts with the certificate binding" in result.stderr
+
+
[email protected]("same", [True, False])
+def test_concurrent_secret_create_accepts_only_db_winner(settings, same):
+ secrets = [
+ {
+ "kind": "Secret",
+ "metadata": {"name": "jiuwenswarm-link-" + role},
+ "data": {"test": "committed"},
+ }
+ for role in ("gateway", "runtime", "agentserver", "manager")
+ ]
+ worker = json.dumps({"secrets": secrets, "summary": {"mtls_deployment_id": "test"}})
+ current = json.dumps({"data": {"test": "committed" if same else "other"}})
+ overrides = (
+ "link_mtls_worker() { printf '%s' " + shlex.quote(worker) + "; }\n"
+ "link_mtls_kube() { case \"$1\" in create) return 1;; get) printf '%s' "
+ + shlex.quote(current)
+ + ";; apply) cat >/dev/null;; *) return 99;; esac; }"
+ )
+ result = run_handler(settings, "link_mtls_call ensure", overrides)
+ assert (result.returncode == 0) == same
+ if not same:
+ assert "Secret conflicts with database material" in result.stderr
+
+
+def test_partial_worker_result_cannot_mark_deployment_ready(settings):
+ overrides = """link_mtls_worker() { echo '{"secrets":[],"summary":{"mtls_deployment_id":"x"}}'; }
+ link_mtls_kube() { echo unexpected-write >&2; return 99; }"""
+ result = run_handler(settings, "link_mtls_call ensure", overrides)
+ assert result.returncode != 0 and "unexpected-write" not in result.stderr
+
+
+def test_deployment_directory_has_one_native_entry_and_one_customer_document():
+ assert not list(DIRECTORY.glob("*.py"))
+ docs = DIRECTORY.parents[1] / "docs/zh"
+ assert len(list(docs.glob("HTTP-SSE链路mTLS部署*.md"))) == 1
+
+
+ "mode,command,module",
+ [
+ ("off", "up", "GATEWAY"),
+ ("observe", "up", "RUNTIME"),
+ ("enforce", "down", "GATEWAY"),
+ ("enforce", "up", "WEB"),
+ ],
+)
+def test_unrelated_operations_do_not_require_certificate_image(
+ settings, mode, command, module
+):
+ settings["JIUWENSWARM_LINK_MTLS_MODE"] = mode
+ overrides = f"CMD={command}; MODULES=({module})\nlink_mtls_call() {{ echo unexpected-image >&2; return 99; }}"
+ result = run_handler(settings, "link_mtls_check", overrides)
+ assert result.returncode == 0 and "unexpected-image" not in result.stderr
+
+
[email protected]("edition", ["dev", "product"])
+def test_generated_customer_config_explicitly_defaults_off(tmp_path, edition):
+ script = tmp_path / "gen_env_custom.sh"
+ shutil.copyfile(DIRECTORY / script.name, script)
+ result = subprocess.run(
+ ["bash", str(script), "amd64", "test-version", edition],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ assert result.returncode == 0, result.stderr
+ config = (tmp_path / ".env.custom").read_text()
+ assert config.count("JIUWENSWARM_LINK_MTLS_MODE=") == 1
+ assert "JIUWENSWARM_LINK_MTLS_MODE=off" in config
diff --git a/tests/unit_tests/test_link_mtls_full_render.py b/tests/unit_tests/test_link_mtls_full_render.py
new file mode 100644
index 0000000000..43e0a269cf
--- /dev/null
+++ b/tests/unit_tests/test_link_mtls_full_render.py
@@ -0,0 +1,153 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""Execute ordinary shell render; simulate only Linux/CLI boundaries, no cluster.
+
+Optional LINK_TEST_DEPLOY_ZIP supplies release IMAGE values only, never customer
+passwords. Docker execution is deliberately replaced by the real Python worker.
+This is not an image-runtime or Kubernetes integration test.
+"""
+
+import json
+import os
+import shutil
+import subprocess
+import sys
+import zipfile
+from pathlib import Path
+
+import pytest
+import yaml
+
+SOURCE = Path(__file__).resolve().parents[2] / "deploy/enterprise"
+
+
[email protected]("mode", [None, "off", "observe", "enforce"])
[email protected]("patch", ["true", "false"])
+def test_ordinary_source_render_without_db_or_cluster_writes(tmp_path, mode, patch):
+ bash = shutil.which("bash")
+ if not bash or int(subprocess.check_output([bash, "-c", "echo ${BASH_VERSINFO[0]}"], text=True)) < 4:
+ pytest.skip("Bash 4+ required")
+ if not shutil.which("yq") or not shutil.which("jq"):
+ pytest.skip("mikefarah/yq and jq required")
+ tool, binary, claw = (tmp_path / name for name in ("tool", "bin", "claw"))
+ shutil.copytree(SOURCE, tool, ignore=shutil.ignore_patterns("conf", ".env.custom*", ".link-mtls-test"))
+ # Use the ordinary source generator, not a stale release-generated template.
+ subprocess.run(
+ [bash, str(SOURCE / "update_conf.sh"), str(tool / "templates/gateway-config.template.yaml")],
+ check=True,
+ capture_output=True,
+ timeout=15,
+ )
+ binary.mkdir()
+ for name in ("runtime_management_extension", "manager_config_receiver"):
+ p = claw / "packages/jiuwenclaw-ee/gateway/extensions" / name
+ p.mkdir(parents=True)
+ (p / "extension.yaml").write_text("dependencies: {}\n")
+ images = "\n".join(
+ f'{name}_IMAGE="example/{name.lower()}:21s"'
+ for name in (
+ "GATEWAY",
+ "AGENT_RUNTIME",
+ "AGENT_SERVER",
+ "WEB",
+ "MANAGER_SERVER",
+ "MANAGER_WEB",
+ "IDENTITY",
+ "JIUWENBOX",
+ )
+ )
+ if os.getenv("LINK_TEST_DEPLOY_ZIP"):
+ with zipfile.ZipFile(os.environ["LINK_TEST_DEPLOY_ZIP"]) as archive:
+ path = next(p for p in archive.namelist() if p.endswith("/.env.custom"))
+ images = "\n".join(
+ line
+ for line in archive.read(path).decode().splitlines()
+ if "_IMAGE=" in line and not line.startswith("#")
+ )
+ runtime = os.getenv("LINK_TEST_RUNTIME_SOURCE")
+ if not runtime:
+ pytest.skip("matching Runtime checkout needed for source-render test")
+ mode_config = "" if mode is None else f"JIUWENSWARM_LINK_MTLS_MODE={mode}\n"
+ config = (
+ images + f"\nMODE=dev\nCLAW_CODE_PATH={claw}\nRUNTIME_CODE_PATH={runtime}\n"
+ f"APPLY_PATCH={patch}\n"
+ + mode_config
+ + "DB_TYPE=mysql\nDB_HOST=unreachable.invalid\nDB_PORT=3306\nDB_USER=test\nDB_PASSWORD=test\n"
+ "JIUWENSWARM_EDITION=enterprise\nCURRENT_NODE_NAME=test-node\n"
+ "IS_UP_MANAGER_WEB=true\nIS_MOUNT_WEB_CODE=true\nIS_MOUNT_MANAGER_WEB_CODE=true\n"
+ "LOGIN_AUTH_SIMULATE=false\nNFS_SERVER_ADDR=unreachable.invalid\n"
+ )
+ (tool / ".env.custom").write_text(config)
+ stub = f"""#!{sys.executable}
+import asyncio, base64, json, os, sys
+from pathlib import Path
+name=Path(sys.argv[0]).name
+args=sys.argv[1:]
+with open(os.environ['CLI_TRACE'], 'a') as trace:
+ trace.write(json.dumps([name, *args])+'\\n')
+if name == 'uname': print('Linux'); sys.exit()
+if name == 'base64':
+ print(base64.b64encode(sys.stdin.buffer.read()).decode(),end=''); sys.exit()
+if name == 'kubectl':
+ assert args[:2] == ['create','configmap'] and '--dry-run=client' in args, 'cluster access forbidden'
+ data={{}}
+ for arg in args:
+ if arg.startswith('--from-env-file='):
+ data.update(line.split('=',1) for line in Path(arg.split('=',1)[1]).read_text().splitlines() if '=' in line)
+ if arg.startswith('--from-file='):
+ k,p=arg.split('=',1)[1].split('=',1); data[k]=Path(p).read_text()
+ result = {{'apiVersion':'v1','kind':'ConfigMap','metadata':{{'name':'render-only'}},'data':data}}
+ print(json.dumps(result)); sys.exit()
+assert name == 'docker'
+if args[0] == 'context': print('unix:///test-only.sock'); sys.exit()
+assert args[args.index('--user')+1] == str(os.geteuid())+':'+str(os.getegid())
+msg=json.load(sys.stdin)
+assert msg['action'] == 'imports', 'DB/PKI action forbidden in render-only'
+assert args[args.index('--network')+1] == 'none'
+assert args[-2:] == ['-m', 'openjiuwen_runtime.foundation.security.link_material_deploy']
+root=next(a.split(',')[1][4:] for a in args if a.startswith('type=bind,src=') and 'dst=/app/link-foundation' in a)
+sys.path.insert(0,root)
+from openjiuwen_runtime.foundation.security.link_material_deploy import dispatch
+print(json.dumps(asyncio.run(dispatch(msg))))
+"""
+ for name in ("docker", "kubectl", "base64", "uname"):
+ path = binary / name
+ path.write_text(stub)
+ path.chmod(0o700)
+ args = [bash, "deploy.sh", "up", "gateway", "web", "runtime"]
+ if patch == "false":
+ args.append("manager")
+ trace = tmp_path / "calls.jsonl"
+ process = subprocess.run(
+ [bash, "-c", 'umask 077\nexec "$@"', "private-render", *args, "-n", "link-test", "--render-only"],
+ cwd=tool,
+ timeout=90,
+ env={**os.environ, "PATH": str(binary) + os.pathsep + os.environ["PATH"], "CLI_TRACE": str(trace)},
+ capture_output=True,
+ text=True,
+ )
+ assert process.returncode == 0, process.stdout[-5000:] + process.stderr[-2000:]
+ files = list((tool / "conf").iterdir())
+ assert files and all("PRIVATE KEY" not in p.read_text() for p in files if p.is_file())
+ gateway = list(yaml.safe_load_all((tool / "conf/gateway.yaml").read_text()))
+ runtime_yaml = list(yaml.safe_load_all((tool / "conf/runtime.yaml").read_text()))
+ for docs in (gateway, runtime_yaml):
+ dep = next(d for d in docs if d and d.get("kind") == "Deployment")
+ volumes = dep["spec"]["template"]["spec"]["volumes"]
+ assert any(v["name"].startswith("jiuwenswarm-link-mtls") for v in volumes) == (mode == "enforce")
+ assert (tool / "conf/manager-server.yaml").exists() == (patch == "false")
+ assert (tool / "conf/identity.yaml").exists() == (patch == "false")
+ if patch == "false":
+ manager_docs = list(yaml.safe_load_all((tool / "conf/manager-server.yaml").read_text()))
+ manager = next(d for d in manager_docs if d and d.get("kind") == "Deployment")
+ spec = manager["spec"]["template"]["spec"]
+ container = next(c for c in spec["containers"] if c["name"] == "manager")
+ link_env = {v["name"]: v.get("value") for v in container.get("env", [])}
+ if mode in ("observe", "enforce"):
+ assert link_env["JIUWENSWARM_LINK_MTLS_MODE"] == mode
+ assert any(
+ v.get("secret", {}).get("secretName") == "jiuwenswarm-link-manager" for v in spec.get("volumes", [])
+ ) == (mode == "enforce")
+ assert (tool / ".env.custom").read_text() == config
+ if mode in (None, "off"):
+ calls = [json.loads(line) for line in trace.read_text().splitlines()]
+ assert not any(call[0] == "docker" for call in calls)
diff --git a/tests/unit_tests/test_link_profile_deploy_guard.py b/tests/unit_tests/test_link_profile_deploy_guard.py
new file mode 100644
index 0000000000..bc37be1130
--- /dev/null
+++ b/tests/unit_tests/test_link_profile_deploy_guard.py
@@ -0,0 +1,29 @@
+"""No cluster access: execute deployment guards against an isolated tool copy."""
+
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+
[email protected]("apply_patch", ["true", "false"])
[email protected]("mode", ["off", "enforce"])
+def test_k8s_guard_precedes_dependency_or_cluster_operations(tmp_path, apply_patch, mode):
+ bash = shutil.which("bash")
+ if not bash:
+ pytest.skip("bash is required by the deployment tool")
+ major = subprocess.check_output([bash, "-c", "echo ${BASH_VERSINFO[0]}"], text=True).strip()
+ if int(major) < 4:
+ pytest.skip("the upstream deployment tool requires Bash 4+ associative arrays")
+ source = Path(__file__).resolve().parents[2] / "deploy/enterprise"
+ target = tmp_path / "deploy"
+ shutil.copytree(source, target)
+ config = f"APPLY_PATCH={apply_patch}\nJIUWENSWARM_LINK_MTLS_MODE={mode}\n"
+ (target / ".env.custom").write_text(config)
+ # Help must never provision, query a DB or require a deployment image.
+ result = subprocess.run([bash, "deploy.sh", "--help"], cwd=target, capture_output=True, text=True, timeout=10)
+ assert result.returncode == 0
+ assert "Usage:" in result.stdout
+ assert (target / ".env.custom").read_text() == config
+ assert not (target / "conf").exists()
diff --git a/uv.lock b/uv.lock
index 6f8ce83dc8..02c79234a4 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1,5 +1,5 @@
version = 1
-revision = 2
+revision = 3
requires-python = ">=3.11, <3.14"
resolution-markers = [
"python_full_version >= '3.13' and sys_platform == 'win32'",
@@ -154,15 +154,27 @@ name = "aiologic"
version = "0.16.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "sniffio", marker = "python_full_version < '3.13'" },
- { name = "typing-extensions", marker = "python_full_version < '3.13'" },
- { name = "wrapt", marker = "python_full_version < '3.13'" },
+ { name = "sniffio" },
+ { name = "typing-extensions" },
+ { name = "wrapt" },
]
sdist = { url = "https://files.pythonhosted.org/packages/a8/13/50b91a3ea6b030d280d2654be97c48b6ed81753a50286ee43c646ba36d3c/aiologic-0.16.0.tar.gz", hash = "sha256:c267ccbd3ff417ec93e78d28d4d577ccca115d5797cdbd16785a551d9658858f", size = 225952, upload-time = "2025-11-27T23:48:41.195Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/f6/27/206615942005471499f6fbc36621582e24d0686f33c74b2d018fcfd4fe67/aiologic-0.16.0-py3-none-any.whl", hash = "sha256:e00ce5f68c5607c864d26aec99c0a33a83bdf8237aa7312ffbb96805af67d8b6", size = 135193, upload-time = "2025-11-27T23:48:40.099Z" },
]
+[[package]]
+name = "aiomysql"
+version = "0.2.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "pymysql" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/67/76/2c5b55e4406a1957ffdfd933a94c2517455291c97d2b81cec6813754791a/aiomysql-0.2.0.tar.gz", hash = "sha256:558b9c26d580d08b8c5fd1be23c5231ce3aeff2dadad989540fee740253deb67", size = 114706, upload-time = "2023-06-11T19:57:53.608Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/42/87/c982ee8b333c85b8ae16306387d703a1fcdfc81a2f3f15a24820ab1a512d/aiomysql-0.2.0-py3-none-any.whl", hash = "sha256:b7c26da0daf23a5ec5e0b133c03d20657276e4eae9b73e040b72787f6f6ade0a", size = 44215, upload-time = "2023-06-11T19:57:51.09Z" },
+]
+
[[package]]
name = "aiosignal"
version = "1.4.0"
@@ -750,7 +762,7 @@ name = "clr-loader"
version = "0.2.10"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "cffi", marker = "sys_platform == 'win32'" },
+ { name = "cffi" },
]
sdist = { url = "https://files.pythonhosted.org/packages/18/24/c12faf3f61614b3131b5c98d3bf0d376b49c7feaa73edca559aeb2aee080/clr_loader-0.2.10.tar.gz", hash = "sha256:81f114afbc5005bafc5efe5af1341d400e22137e275b042a8979f3feb9fc9446", size = 83605, upload-time = "2026-01-03T23:13:06.984Z" }
wheels = [
@@ -993,8 +1005,8 @@ name = "culsans"
version = "0.11.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "aiologic", marker = "python_full_version < '3.13'" },
- { name = "typing-extensions", marker = "python_full_version < '3.13'" },
+ { name = "aiologic" },
+ { name = "typing-extensions" },
]
sdist = { url = "https://files.pythonhosted.org/packages/d9/e3/49afa1bc180e0d28008ec6bcdf82a4072d1c7a41032b5b759b60814ca4b0/culsans-0.11.0.tar.gz", hash = "sha256:0b43d0d05dce6106293d114c86e3fb4bfc63088cfe8ff08ed3fe36891447fe33", size = 107546, upload-time = "2025-12-31T23:15:38.196Z" }
wheels = [
@@ -2000,6 +2012,7 @@ dependencies = [
{ name = "numpy" },
{ name = "openjiuwen" },
{ name = "openjiuwen-deepsearch" },
+ { name = "openjiuwen-runtime-foundation", extra = ["link-mtls"] },
{ name = "opentelemetry-api" },
{ name = "opentelemetry-exporter-otlp-proto-grpc" },
{ name = "opentelemetry-exporter-otlp-proto-http" },
@@ -2009,6 +2022,7 @@ dependencies = [
{ name = "portalocker" },
{ name = "psutil" },
{ name = "pydantic" },
+ { name = "pydantic-settings" },
{ name = "pymysql" },
{ name = "python-json-logger" },
{ name = "python-multipart" },
@@ -2065,6 +2079,7 @@ harmony = [
{ name = "pgvector" },
{ name = "pillow" },
{ name = "pydantic" },
+ { name = "pydantic-settings" },
{ name = "python-multipart" },
{ name = "python-socks" },
{ name = "python-telegram-bot" },
@@ -2090,6 +2105,7 @@ test = [
{ name = "pytest-cov" },
{ name = "pytest-html" },
{ name = "pytest-mock" },
+ { name = "pywebview" },
{ name = "pyyaml" },
]
tui = [
@@ -2110,6 +2126,7 @@ dev = [
{ name = "pytest-cov" },
{ name = "pytest-html" },
{ name = "pytest-mock" },
+ { name = "pywebview" },
{ name = "pyyaml" },
{ name = "ruff" },
]
@@ -2129,6 +2146,7 @@ test = [
{ name = "pytest-cov" },
{ name = "pytest-html" },
{ name = "pytest-mock" },
+ { name = "pywebview" },
{ name = "pyyaml" },
]
@@ -2181,6 +2199,7 @@ requires-dist = [
{ name = "openjiuwen", marker = "extra == 'harmony'", git = "https://gitcode.com/openJiuwen/agent-core.git?rev=dev-stable" },
{ name = "openjiuwen", extras = ["postgres", "zmq"], marker = "extra == 'distribute'" },
{ name = "openjiuwen-deepsearch", git = "https://gitcode.com/openJiuwen/deepsearch.git?subdirectory=deepsearch&rev=dev-stable" },
+ { name = "openjiuwen-runtime-foundation", extras = ["link-mtls"], git = "https://gitcode.com/openJiuwen/agent-runtime.git?subdirectory=foundation&rev=develop" },
{ name = "opentelemetry-api", specifier = ">=1.28.0" },
{ name = "opentelemetry-api", marker = "extra == 'harmony'", specifier = ">=1.28.0" },
{ name = "opentelemetry-exporter-otlp-proto-grpc", specifier = ">=1.28.0" },
@@ -2197,6 +2216,8 @@ requires-dist = [
{ name = "psutil", specifier = ">=7.2.2" },
{ name = "pydantic", specifier = ">=2.0" },
{ name = "pydantic", marker = "extra == 'harmony'", specifier = ">=2.0" },
+ { name = "pydantic-settings", specifier = ">=2.0" },
+ { name = "pydantic-settings", marker = "extra == 'harmony'", specifier = ">=2.0" },
{ name = "pyinstaller", marker = "extra == 'dev'", specifier = ">=6.0.0" },
{ name = "pymysql", specifier = ">=1.1.0" },
{ name = "pytest", marker = "extra == 'test'", specifier = ">=8.3.5" },
@@ -2213,6 +2234,7 @@ requires-dist = [
{ name = "python-telegram-bot", marker = "extra == 'harmony'", specifier = ">=20.0" },
{ name = "pywebview", marker = "extra == 'desktop'", specifier = ">=5.4" },
{ name = "pywebview", marker = "extra == 'dev'", specifier = ">=5.4" },
+ { name = "pywebview", marker = "extra == 'test'", specifier = ">=5.4" },
{ name = "pyyaml", specifier = ">=6.0" },
{ name = "pyyaml", marker = "extra == 'harmony'", specifier = ">=6.0" },
{ name = "pyyaml", marker = "extra == 'test'", specifier = ">=6.0" },
@@ -2249,6 +2271,7 @@ dev = [
{ name = "pytest-cov", specifier = ">=7.0.0" },
{ name = "pytest-html", specifier = ">=4.1.1" },
{ name = "pytest-mock", specifier = ">=3.14.0" },
+ { name = "pywebview", specifier = ">=5.4" },
{ name = "pyyaml", specifier = ">=6.0" },
{ name = "ruff", specifier = ">=0.11.2" },
]
@@ -2268,6 +2291,7 @@ test = [
{ name = "pytest-cov", specifier = ">=7.0.0" },
{ name = "pytest-html", specifier = ">=4.1.1" },
{ name = "pytest-mock", specifier = ">=3.14.0" },
+ { name = "pywebview", specifier = ">=5.4" },
{ name = "pyyaml", specifier = ">=6.0" },
]
@@ -2712,7 +2736,7 @@ name = "macholib"
version = "1.16.4"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "altgraph", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" },
+ { name = "altgraph" },
]
sdist = { url = "https://files.pythonhosted.org/packages/10/2f/97589876ea967487978071c9042518d28b958d87b17dceb7cdc1d881f963/macholib-1.16.4.tar.gz", hash = "sha256:f408c93ab2e995cd2c46e34fe328b130404be143469e41bc366c807448979362", size = 59427, upload-time = "2025-11-22T08:28:38.373Z" }
wheels = [
@@ -3366,6 +3390,32 @@ dependencies = [
{ name = "tldextract" },
]
+[[package]]
+name = "openjiuwen-runtime-foundation"
+version = "0.1.0"
+source = { git = "https://gitcode.com/openJiuwen/agent-runtime.git?subdirectory=foundation&rev=develop#bf82a24c78e7ab8ab469b4b41aa62944bda8d8db" }
+dependencies = [
+ { name = "aiohttp" },
+ { name = "aiomysql" },
+ { name = "aiosqlite" },
+ { name = "build" },
+ { name = "cryptography" },
+ { name = "greenlet" },
+ { name = "pydantic" },
+ { name = "pydantic-settings" },
+ { name = "pymysql" },
+ { name = "pyyaml" },
+ { name = "redis" },
+ { name = "sqlalchemy" },
+]
+
+[package.optional-dependencies]
+link-mtls = [
+ { name = "httpcore" },
+ { name = "httpx" },
+ { name = "uvicorn" },
+]
+
[[package]]
name = "openpyxl"
version = "3.1.5"
@@ -3670,7 +3720,7 @@ name = "pexpect"
version = "4.9.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "ptyprocess", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" },
+ { name = "ptyprocess" },
]
sdist = { url = "https://files.pythonhosted.org/packages/42/92/cc564bf6381ff43ce1f4d06852fc19a2f11d180f23dc32d9588bee2f149d/pexpect-4.9.0.tar.gz", hash = "sha256:ee7d41123f3c9911050ea2c2dac107568dc43b2d3b0c7557a33212c398ead30f", size = 166450, upload-time = "2023-11-25T09:07:26.339Z" }
wheels = [
@@ -4382,11 +4432,11 @@ wheels = [
[[package]]
name = "pymysql"
-version = "1.2.0"
+version = "1.1.1"
source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/c9/bc/1c6a92f385940f727daeecf3bacaf186e03875dff57197801046c583bcf0/pymysql-1.2.0.tar.gz", hash = "sha256:6c7b17ca686988104d7426c27895b455cdeea3e9d3ceb1270f0c3704fead8c33", size = 49021, upload-time = "2026-05-19T08:26:22.302Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/b3/8f/ce59b5e5ed4ce8512f879ff1fa5ab699d211ae2495f1adaa5fbba2a1eada/pymysql-1.1.1.tar.gz", hash = "sha256:e127611aaf2b417403c60bf4dc570124aeb4a57f5f37b8e95ae399a42f904cd0", size = 47678, upload-time = "2024-05-21T11:03:43.722Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/c4/bd/2534e130295c8cfd4f0a2e31623baab7502278f1e97bcfe61db75656a77f/pymysql-1.2.0-py3-none-any.whl", hash = "sha256:62169ce6d5510f08e140c5e7990ee884a9764024e4a9a27b2cc11f1099322ae0", size = 45716, upload-time = "2026-05-19T08:26:20.974Z" },
+ { url = "https://files.pythonhosted.org/packages/0c/94/e4181a1f6286f545507528c78016e00065ea913276888db2262507693ce5/PyMySQL-1.1.1-py3-none-any.whl", hash = "sha256:4de15da4c61dc132f4fb9ab763063e693d521a80fd0e87943b9a453dd4c19d6c", size = 44972, upload-time = "2024-05-21T11:03:41.216Z" },
]
[[package]]
@@ -4406,7 +4456,7 @@ name = "pyobjc-framework-cocoa"
version = "12.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "pyobjc-core", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" },
+ { name = "pyobjc-core" },
]
sdist = { url = "https://files.pythonhosted.org/packages/02/a3/16ca9a15e77c061a9250afbae2eae26f2e1579eb8ca9462ae2d2c71e1169/pyobjc_framework_cocoa-12.1.tar.gz", hash = "sha256:5556c87db95711b985d5efdaaf01c917ddd41d148b1e52a0c66b1a2e2c5c1640", size = 2772191, upload-time = "2025-11-14T10:13:02.069Z" }
wheels = [
@@ -4421,8 +4471,8 @@ name = "pyobjc-framework-quartz"
version = "12.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "pyobjc-core", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" },
- { name = "pyobjc-framework-cocoa", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" },
+ { name = "pyobjc-core" },
+ { name = "pyobjc-framework-cocoa" },
]
sdist = { url = "https://files.pythonhosted.org/packages/94/18/cc59f3d4355c9456fc945eae7fe8797003c4da99212dd531ad1b0de8a0c6/pyobjc_framework_quartz-12.1.tar.gz", hash = "sha256:27f782f3513ac88ec9b6c82d9767eef95a5cf4175ce88a1e5a65875fee799608", size = 3159099, upload-time = "2025-11-14T10:21:24.31Z" }
wheels = [
@@ -4437,8 +4487,8 @@ name = "pyobjc-framework-security"
version = "12.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "pyobjc-core", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" },
- { name = "pyobjc-framework-cocoa", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" },
+ { name = "pyobjc-core" },
+ { name = "pyobjc-framework-cocoa" },
]
sdist = { url = "https://files.pythonhosted.org/packages/80/aa/796e09a3e3d5cee32ebeebb7dcf421b48ea86e28c387924608a05e3f668b/pyobjc_framework_security-12.1.tar.gz", hash = "sha256:7fecb982bd2f7c4354513faf90ba4c53c190b7e88167984c2d0da99741de6da9", size = 168044, upload-time = "2025-11-14T10:22:06.334Z" }
wheels = [
@@ -4453,8 +4503,8 @@ name = "pyobjc-framework-uniformtypeidentifiers"
version = "12.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "pyobjc-core", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" },
- { name = "pyobjc-framework-cocoa", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" },
+ { name = "pyobjc-core" },
+ { name = "pyobjc-framework-cocoa" },
]
sdist = { url = "https://files.pythonhosted.org/packages/65/b8/dd9d2a94509a6c16d965a7b0155e78edf520056313a80f0cd352413f0d0b/pyobjc_framework_uniformtypeidentifiers-12.1.tar.gz", hash = "sha256:64510a6df78336579e9c39b873cfcd03371c4b4be2cec8af75a8a3d07dff607d", size = 17030, upload-time = "2025-11-14T10:23:02.222Z" }
wheels = [
@@ -4466,8 +4516,8 @@ name = "pyobjc-framework-webkit"
version = "12.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "pyobjc-core", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" },
- { name = "pyobjc-framework-cocoa", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" },
+ { name = "pyobjc-core" },
+ { name = "pyobjc-framework-cocoa" },
]
sdist = { url = "https://files.pythonhosted.org/packages/14/10/110a50e8e6670765d25190ca7f7bfeecc47ec4a8c018cb928f4f82c56e04/pyobjc_framework_webkit-12.1.tar.gz", hash = "sha256:97a54dd05ab5266bd4f614e41add517ae62cdd5a30328eabb06792474b37d82a", size = 284531, upload-time = "2025-11-14T10:23:40.287Z" }
wheels = [
@@ -4768,7 +4818,7 @@ name = "pythonnet"
version = "3.0.5"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "clr-loader", marker = "sys_platform == 'win32'" },
+ { name = "clr-loader" },
]
sdist = { url = "https://files.pythonhosted.org/packages/9a/d6/1afd75edd932306ae9bd2c2d961d603dc2b52fcec51b04afea464f1f6646/pythonnet-3.0.5.tar.gz", hash = "sha256:48e43ca463941b3608b32b4e236db92d8d40db4c58a75ace902985f76dac21cf", size = 239212, upload-time = "2024-12-13T08:30:44.393Z" }
wheels = [
@@ -4935,7 +4985,7 @@ name = "qtpy"
version = "2.4.3"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "packaging", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" },
+ { name = "packaging" },
]
sdist = { url = "https://files.pythonhosted.org/packages/70/01/392eba83c8e47b946b929d7c46e0f04b35e9671f8bb6fc36b6f7945b4de8/qtpy-2.4.3.tar.gz", hash = "sha256:db744f7832e6d3da90568ba6ccbca3ee2b3b4a890c3d6fbbc63142f6e4cdf5bb", size = 66982, upload-time = "2025-02-11T15:09:25.759Z" }
wheels = [
@@ -4944,14 +4994,14 @@ wheels = [
[[package]]
name = "redis"
-version = "7.4.0"
+version = "7.1.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "async-timeout", marker = "python_full_version < '3.11.3'" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/7b/7f/3759b1d0d72b7c92f0d70ffd9dc962b7b7b5ee74e135f9d7d8ab06b8a318/redis-7.4.0.tar.gz", hash = "sha256:64a6ea7bf567ad43c964d2c30d82853f8df927c5c9017766c55a1d1ed95d18ad", size = 4943913, upload-time = "2026-03-24T09:14:37.53Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/43/c8/983d5c6579a411d8a99bc5823cc5712768859b5ce2c8afe1a65b37832c81/redis-7.1.0.tar.gz", hash = "sha256:b1cc3cfa5a2cb9c2ab3ba700864fb0ad75617b41f01352ce5779dabf6d5f9c3c", size = 4796669, upload-time = "2025-11-19T15:54:39.961Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/74/3a/95deec7db1eb53979973ebd156f3369a72732208d1391cd2e5d127062a32/redis-7.4.0-py3-none-any.whl", hash = "sha256:a9c74a5c893a5ef8455a5adb793a31bb70feb821c86eccb62eebef5a19c429ec", size = 409772, upload-time = "2026-03-24T09:14:35.968Z" },
+ { url = "https://files.pythonhosted.org/packages/89/f0/8956f8a86b20d7bb9d6ac0187cf4cd54d8065bc9a1a09eb8011d4d326596/redis-7.1.0-py3-none-any.whl", hash = "sha256:23c52b208f92b56103e17c5d06bdc1a6c2c0b3106583985a76a18f83b265de2b", size = 354159, upload-time = "2025-11-19T15:54:38.064Z" },
]
[[package]]
@@ -5272,8 +5322,8 @@ name = "secretstorage"
version = "3.5.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "cryptography", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" },
- { name = "jeepney", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" },
+ { name = "cryptography" },
+ { name = "jeepney" },
]
sdist = { url = "https://files.pythonhosted.org/packages/1c/03/e834bcd866f2f8a49a85eaff47340affa3bfa391ee9912a952a1faa68c7b/secretstorage-3.5.0.tar.gz", hash = "sha256:f04b8e4689cbce351744d5537bf6b1329c6fc68f91fa666f60a380edddcd11be", size = 19884, upload-time = "2025-11-23T19:02:53.191Z" }
wheels = [