diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index aabfa3e53a7..6c347d81304 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -13,30 +13,30 @@ }, "limits": { "testFileCount": 76, - "liveFileCount": 187, + "liveFileCount": 188, "direct": { "expectCalls": 1329, "matcherAssertions": 1314, "nodeAssertions": 109, - "namedAssertionHelpers": 433, + "namedAssertionHelpers": 434, "failCalls": 0, "throwGuards": 50, "objectFieldAssertions": 184, - "assertionPoints": 2090, + "assertionPoints": 2091, "generatedProbeBlocks": 91, "generatedProbeConditions": 214 }, "unique": { - "expectCalls": 1759, - "matcherAssertions": 1739, + "expectCalls": 1765, + "matcherAssertions": 1745, "nodeAssertions": 132, - "namedAssertionHelpers": 680, + "namedAssertionHelpers": 687, "failCalls": 1, - "throwGuards": 531, + "throwGuards": 533, "objectFieldAssertions": 267, - "assertionPoints": 3350, - "generatedProbeBlocks": 220, - "generatedProbeConditions": 728 + "assertionPoints": 3365, + "generatedProbeBlocks": 221, + "generatedProbeConditions": 729 }, "fileMetricOrder": [ "directExpectCalls", @@ -84,7 +84,7 @@ "test/e2e/live/managed-image-activation-e2e.test.ts": [0,0,12,25,0], "test/e2e/live/managed-image-multiarch-startup.test.ts": [1,3,1,9,0], "test/e2e/live/managed-image-protected-runtime.test.ts": [0,0,39,81,16], - "test/e2e/live/mcp-bridge.test.ts": [39,138,193,518,46], + "test/e2e/live/mcp-bridge.test.ts": [39,139,199,533,47], "test/e2e/live/messaging-compatible-endpoint.test.ts": [13,19,13,28,2], "test/e2e/live/messaging-providers.test.ts": [0,11,6,51,11], "test/e2e/live/native-runtime-qualification-case.test.ts": [0,0,9,84,0], diff --git a/ci/e2e-assertion-growth-exceptions.json b/ci/e2e-assertion-growth-exceptions.json index 030b9112700..f99175b65ee 100644 --- a/ci/e2e-assertion-growth-exceptions.json +++ b/ci/e2e-assertion-growth-exceptions.json @@ -1,5 +1,5 @@ { - "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.\n\nPR #12718 is the prerequisite for the PR #12382 budget transition recorded below. The exception matches only PR #12382 and both budget digests. A changed base or candidate budget invalidates it. The independent check reads trusted base policy, so this prerequisite must land on main before #12382 uses the exception. Remove after #12382 merges.\n\nMaintainer Prekshi Vyas (@prekshivyas) approved this exact refreshed PR #12382 transition on 2026-10-08: base budget SHA-256 53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441 to candidate budget SHA-256 8162408384d7a6b97ef0062042c73d4bc9486f54d2dfa6c0c5732e42d1060e2a. Acceptance record: https://github.com/NVIDIA/NemoClaw/pull/12840#issuecomment-6066319444. It includes one additional unique assertion point and one generated probe condition. This refresh preserves the #12608 concurrent-gateway-ports reduction and the previously reviewed runtime assertion changes. The independent check is not waived: the refreshed exception must land on main before enforcement can accept it. A different PR or budget digest remains rejected. Remove after #12382 merges.\n\nPR #12777 adds exactly two approved live assertions for native host-local inference success and sibling provider isolation. Deterministic behavior remains in unit/integration tests. Approval transcription: https://github.com/NVIDIA/NemoClaw/pull/12777#issuecomment-6048385152. The independent check reads trusted base policy; this entry does not disable it. Remove after #12777 merges.\n\nThe #12777 budget digests account for main #12608 removing seven assertions from concurrent-gateway-ports. The candidate preserves that reduction and adds only the same two approved inference-routing assertions. No other file budget increases.\n\nPR #12886 approved the provider-smoke transition extracted by #12955. Approval: https://github.com/NVIDIA/NemoClaw/pull/12886#issuecomment-6083839176. The unchanged change digest binds the same nine assertion points and companion inventory. This entry supports local preliminary validation and the Slice 2 consumer. Independent CI for the prerequisite requires its own maintainer approval record; this entry does not approve that PR.\n\nPR #12958 extracts the same approved provider-smoke budget transition for #12955. Its exact, unedited maintainer approval is https://github.com/NVIDIA/NemoClaw/pull/12958#issuecomment-6093851571. This candidate entry supports static hooks; the independent check continues to verify the PR-specific approval on GitHub. Remove after #12958 merges.\n\nPR #13203 adds the approved 19 assertion points for real authenticated and credentialless DCode native-local requests, credential isolation and sibling denial. Approval: https://github.com/NVIDIA/NemoClaw/pull/13203#issuecomment-6180239679. This exact change digest supports local hooks and candidate CI. Independent enforcement still verifies the PR-specific maintainer approval on GitHub. Remove after #13203 merges.\n\nPR #13201 adds one generated probe block and one counted probe condition in the existing full E2E owner to verify the selected sandbox agent endpoint, API, model and credential reference. Rebecca Sliter approved this exact delta: https://github.com/NVIDIA/NemoClaw/pull/13201#issuecomment-6180464605. This entry supports local validation; the independent check must verify the maintainer record. Remove after #13201 merges.\n\nPR #13293 consolidates OpenClaw native-local scenarios into the existing switching owner and removes duplicated deterministic metadata checks and the redundant mock curl probe. Suite totals fall by 16 expect calls and 10 assertion points without adding live files. Only the owning file transitive allocation grows because it now imports existing live helpers. Maintainer authorization: https://github.com/NVIDIA/NemoClaw/pull/13293#issuecomment-6211036786. This exact transition supports candidate CI; independent enforcement still verifies the maintainer record.\n\nPR #13007 retains the same ten Pi native-local live assertion points approved at https://github.com/NVIDIA/NemoClaw/pull/13007#issuecomment-6175787892. The exact change digest is unchanged against its replacement OpenClaw parent #13293. This entry supports local checks against that stacked base; independent enforcement still checks the authenticated PR approval.\n\nPR #13582 adds eight live assertion points for the WSL2 IPv6 native-local policy boundary. Only openclaw-inference-switch.test.ts increases, by seven direct expectations and the existing onboard-success helper. Deterministic CIDR and receipt coverage remain in source tests. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13582#issuecomment-6308860348. Independent enforcement verifies that PR-specific record. Remove this preliminary local exception after merge.\n\nPR #13645 adds three approved live assertion points for engine-down uninstall diagnostics inside rebuild-openclaw. Exact approval: https://github.com/NVIDIA/NemoClaw/pull/13645#issuecomment-6429899630. This entry enables candidate CI; independent enforcement still verifies the PR-specific maintainer record. Remove after merge.\n\nPR #13771 adds four Hermes OpenRouter rebuild assertions and a bounded diagnostic probe. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13771#issuecomment-6427647915. The independent PR check verifies that comment. Remove after #13771 merges.\n\nPR #13873 adds two live command assertions for the CLI build and native Hermes Discord qualification when consuming protected evidence from an older trusted producer. Approval: https://github.com/NVIDIA/NemoClaw/pull/13873#issuecomment-6488667052. The parser and identity cases stay in e2e-support tests. Remove after #13873 merges.\n\nPR #13651 moves the native NVIDIA Discord rebuild proof from hermes-discord to hermes-inference-switch, which receives the public endpoint credential. The native switch target also checks status through its installed credential verifier after rebuild. This adds four assertion points for the live status and restored-provider boundary; deterministic rejection and command-failure cases remain in fast tests. This entry permits the approved transition in local and candidate checks; independent enforcement verifies the maintainer record at https://github.com/NVIDIA/NemoClaw/pull/13651#issuecomment-6377201610. The typed helper extraction retains every live predicate and the same unique and transitive totals; the direct census decreases because the phase now lives in the existing helper.\n\nPR #13635 adds the approved protected-runtime deadline companion and five unique assertion points, one generated probe block, and one probe condition. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13635#issuecomment-6383152261. This entry supports local hooks and candidate CI; independent enforcement verifies the PR-specific GitHub approval. Remove after #13635 merges.\n\nPR #13596 adds four live assertion points to the existing double-onboard target for #13595: the managed OpenClaw state volume exists before `nemoclaw uninstall`, uninstall succeeds, the volume is gone afterwards, and same-name onboarding succeeds. Deterministic removal and failure cases remain in fast tests. This entry permits the approved transition in local and candidate checks; independent enforcement verifies the maintainer record at https://github.com/NVIDIA/NemoClaw/pull/13596#issuecomment-6365742624. Remove after #13596 merges.\n\nPR #13515 extends dashboard-remote-bind with Hermes host-listener coverage. The dashboard remains remotely reachable, API health works on loopback, and the non-loopback API port refuses TCP connections. Approval: https://github.com/NVIDIA/NemoClaw/pull/13515#issuecomment-6295553350. This entry supports local and candidate checks; independent enforcement verifies the authenticated maintainer record.\n\nPR #13515 also checks Hermes loopback API health and non-loopback refusal after stop/start, preserving the onboarding assertions. The combined delta is approved at https://github.com/NVIDIA/NemoClaw/pull/13515#issuecomment-6298021751.\n\nPR #13515 verifies the Hermes API forward identity before health probes after onboarding and restart. These two additional process-ownership assertions are approved at https://github.com/NVIDIA/NemoClaw/pull/13515#issuecomment-6322568985.\n\nPR #13927 reuses the verified public HTTPS fixture transport for two Podman inference targets. Direct and unique assertion counts are unchanged. Each target gains eleven transitive assertion points from existing package and tunnel prerequisites; the extracted Anthropic response helper adds one live companion file. This exact transition supports local validation. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13927#issuecomment-6524030655. Independent enforcement verifies this PR-specific record. Remove after merge.\n\nPR #14062 adds one live Ollama cleanup helper, three existing port-validation guards reached by gpu-double-onboard, and one shared shell probe. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14062#issuecomment-6582340290. This entry supports local hooks and candidate CI; independent enforcement verifies the PR-specific approval. Remove after merge.\n\nPR #13607 adds two live assertions and one read-only configuration probe to the existing balanced OpenClaw egress case for unavailable-search replies. The refreshed delta removes the unrelated public-fetch precondition guard while retaining both live assertions and the probe. Approved delta: https://github.com/NVIDIA/NemoClaw/pull/13607#issuecomment-6327887365. Remove after #13607 merges.\n\nPR #14000 replaces #12872 and retains one approved assertion point for owning-gateway connect sessions. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14000#issuecomment-6506269922. This entry enables candidate CI; independent enforcement verifies the PR-specific approval.\n\nPR #14122 retains the production bearerless provider-validation proof and private-publication proof in both Express targets. Spark and Station each request health on the two allowed addresses and require connection refusal on all discovered unintended addresses. Four added Spark assertions protect its separate physical-host path; deterministic URL construction remains in the support tests. The combined delta adds seven assertion points and one generated probe relative to main. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14122#issuecomment-6661407269. Independent enforcement verifies this PR-specific approval. Remove after merge.\n\nPR #14252 adds twelve live assertion points to the existing sandbox-survival owner for first-invocation cold public OpenClaw recovery, native and forwarded health, and retained sandbox/container identities on Docker and native Podman. Existing raw OpenShell survival evidence and target timeouts are unchanged. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14252#issuecomment-6676328443. This entry supports local and candidate checks; independent enforcement verifies the PR-specific approval record. Remove after merge.\n\nPR #14303 replaces #14201 and retains its two assertion points in hermes-root-entrypoint-smoke for qualification through the real entrypoint before gateway readiness. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14303#issuecomment-6713570086. This entry supports local hooks and candidate CI. Independent enforcement still verifies the PR-specific maintainer record. Remove after merge.\n\nPR #14512 adds24 net assertion points for native Switchyard cross-provider authorization, continuation policy enforcement, provider failure/recovery and a second credential scan. Three redundant proposed checks were omitted and two existing fixture-output checks remain covered by fast tests. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14512#issuecomment-6932725987. This branch entry supports local preliminary validation; independent CI verifies the PR-specific record. Remove after #14512 merges.\n\nPR #14512 retains its approved 24 assertion points and adds two generated conditions for bounded NULL diagnostics and PTY socket-state validation during sandbox retirement. Three unnecessary conditions were removed. Exact refreshed transition approved by Rebecca Sliter: https://github.com/NVIDIA/NemoClaw/pull/14512#issuecomment-6989339885. Independent enforcement still verifies this unedited maintainer record on GitHub.", + "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.\n\nPR #12718 is the prerequisite for the PR #12382 budget transition recorded below. The exception matches only PR #12382 and both budget digests. A changed base or candidate budget invalidates it. The independent check reads trusted base policy, so this prerequisite must land on main before #12382 uses the exception. Remove after #12382 merges.\n\nMaintainer Prekshi Vyas (@prekshivyas) approved this exact refreshed PR #12382 transition on 2026-10-08: base budget SHA-256 53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441 to candidate budget SHA-256 8162408384d7a6b97ef0062042c73d4bc9486f54d2dfa6c0c5732e42d1060e2a. Acceptance record: https://github.com/NVIDIA/NemoClaw/pull/12840#issuecomment-6066319444. It includes one additional unique assertion point and one generated probe condition. This refresh preserves the #12608 concurrent-gateway-ports reduction and the previously reviewed runtime assertion changes. The independent check is not waived: the refreshed exception must land on main before enforcement can accept it. A different PR or budget digest remains rejected. Remove after #12382 merges.\n\nPR #12777 adds exactly two approved live assertions for native host-local inference success and sibling provider isolation. Deterministic behavior remains in unit/integration tests. Approval transcription: https://github.com/NVIDIA/NemoClaw/pull/12777#issuecomment-6048385152. The independent check reads trusted base policy; this entry does not disable it. Remove after #12777 merges.\n\nThe #12777 budget digests account for main #12608 removing seven assertions from concurrent-gateway-ports. The candidate preserves that reduction and adds only the same two approved inference-routing assertions. No other file budget increases.\n\nPR #12886 approved the provider-smoke transition extracted by #12955. Approval: https://github.com/NVIDIA/NemoClaw/pull/12886#issuecomment-6083839176. The unchanged change digest binds the same nine assertion points and companion inventory. This entry supports local preliminary validation and the Slice 2 consumer. Independent CI for the prerequisite requires its own maintainer approval record; this entry does not approve that PR.\n\nPR #12958 extracts the same approved provider-smoke budget transition for #12955. Its exact, unedited maintainer approval is https://github.com/NVIDIA/NemoClaw/pull/12958#issuecomment-6093851571. This candidate entry supports static hooks; the independent check continues to verify the PR-specific approval on GitHub. Remove after #12958 merges.\n\nPR #13203 adds the approved 19 assertion points for real authenticated and credentialless DCode native-local requests, credential isolation and sibling denial. Approval: https://github.com/NVIDIA/NemoClaw/pull/13203#issuecomment-6180239679. This exact change digest supports local hooks and candidate CI. Independent enforcement still verifies the PR-specific maintainer approval on GitHub. Remove after #13203 merges.\n\nPR #13201 adds one generated probe block and one counted probe condition in the existing full E2E owner to verify the selected sandbox agent endpoint, API, model and credential reference. Rebecca Sliter approved this exact delta: https://github.com/NVIDIA/NemoClaw/pull/13201#issuecomment-6180464605. This entry supports local validation; the independent check must verify the maintainer record. Remove after #13201 merges.\n\nPR #13293 consolidates OpenClaw native-local scenarios into the existing switching owner and removes duplicated deterministic metadata checks and the redundant mock curl probe. Suite totals fall by 16 expect calls and 10 assertion points without adding live files. Only the owning file transitive allocation grows because it now imports existing live helpers. Maintainer authorization: https://github.com/NVIDIA/NemoClaw/pull/13293#issuecomment-6211036786. This exact transition supports candidate CI; independent enforcement still verifies the maintainer record.\n\nPR #13007 retains the same ten Pi native-local live assertion points approved at https://github.com/NVIDIA/NemoClaw/pull/13007#issuecomment-6175787892. The exact change digest is unchanged against its replacement OpenClaw parent #13293. This entry supports local checks against that stacked base; independent enforcement still checks the authenticated PR approval.\n\nPR #13582 adds eight live assertion points for the WSL2 IPv6 native-local policy boundary. Only openclaw-inference-switch.test.ts increases, by seven direct expectations and the existing onboard-success helper. Deterministic CIDR and receipt coverage remain in source tests. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13582#issuecomment-6308860348. Independent enforcement verifies that PR-specific record. Remove this preliminary local exception after merge.\n\nPR #13645 adds three approved live assertion points for engine-down uninstall diagnostics inside rebuild-openclaw. Exact approval: https://github.com/NVIDIA/NemoClaw/pull/13645#issuecomment-6429899630. This entry enables candidate CI; independent enforcement still verifies the PR-specific maintainer record. Remove after merge.\n\nPR #13771 adds four Hermes OpenRouter rebuild assertions and a bounded diagnostic probe. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13771#issuecomment-6427647915. The independent PR check verifies that comment. Remove after #13771 merges.\n\nPR #13873 adds two live command assertions for the CLI build and native Hermes Discord qualification when consuming protected evidence from an older trusted producer. Approval: https://github.com/NVIDIA/NemoClaw/pull/13873#issuecomment-6488667052. The parser and identity cases stay in e2e-support tests. Remove after #13873 merges.\n\nPR #13651 moves the native NVIDIA Discord rebuild proof from hermes-discord to hermes-inference-switch, which receives the public endpoint credential. The native switch target also checks status through its installed credential verifier after rebuild. This adds four assertion points for the live status and restored-provider boundary; deterministic rejection and command-failure cases remain in fast tests. This entry permits the approved transition in local and candidate checks; independent enforcement verifies the maintainer record at https://github.com/NVIDIA/NemoClaw/pull/13651#issuecomment-6377201610. The typed helper extraction retains every live predicate and the same unique and transitive totals; the direct census decreases because the phase now lives in the existing helper.\n\nPR #13635 adds the approved protected-runtime deadline companion and five unique assertion points, one generated probe block, and one probe condition. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13635#issuecomment-6383152261. This entry supports local hooks and candidate CI; independent enforcement verifies the PR-specific GitHub approval. Remove after #13635 merges.\n\nPR #13596 adds four live assertion points to the existing double-onboard target for #13595: the managed OpenClaw state volume exists before `nemoclaw uninstall`, uninstall succeeds, the volume is gone afterwards, and same-name onboarding succeeds. Deterministic removal and failure cases remain in fast tests. This entry permits the approved transition in local and candidate checks; independent enforcement verifies the maintainer record at https://github.com/NVIDIA/NemoClaw/pull/13596#issuecomment-6365742624. Remove after #13596 merges.\n\nPR #13515 extends dashboard-remote-bind with Hermes host-listener coverage. The dashboard remains remotely reachable, API health works on loopback, and the non-loopback API port refuses TCP connections. Approval: https://github.com/NVIDIA/NemoClaw/pull/13515#issuecomment-6295553350. This entry supports local and candidate checks; independent enforcement verifies the authenticated maintainer record.\n\nPR #13515 also checks Hermes loopback API health and non-loopback refusal after stop/start, preserving the onboarding assertions. The combined delta is approved at https://github.com/NVIDIA/NemoClaw/pull/13515#issuecomment-6298021751.\n\nPR #13515 verifies the Hermes API forward identity before health probes after onboarding and restart. These two additional process-ownership assertions are approved at https://github.com/NVIDIA/NemoClaw/pull/13515#issuecomment-6322568985.\n\nPR #13927 reuses the verified public HTTPS fixture transport for two Podman inference targets. Direct and unique assertion counts are unchanged. Each target gains eleven transitive assertion points from existing package and tunnel prerequisites; the extracted Anthropic response helper adds one live companion file. This exact transition supports local validation. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13927#issuecomment-6524030655. Independent enforcement verifies this PR-specific record. Remove after merge.\n\nPR #14062 adds one live Ollama cleanup helper, three existing port-validation guards reached by gpu-double-onboard, and one shared shell probe. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14062#issuecomment-6582340290. This entry supports local hooks and candidate CI; independent enforcement verifies the PR-specific approval. Remove after merge.\n\nPR #13607 adds two live assertions and one read-only configuration probe to the existing balanced OpenClaw egress case for unavailable-search replies. The refreshed delta removes the unrelated public-fetch precondition guard while retaining both live assertions and the probe. Approved delta: https://github.com/NVIDIA/NemoClaw/pull/13607#issuecomment-6327887365. Remove after #13607 merges.\n\nPR #14000 replaces #12872 and retains one approved assertion point for owning-gateway connect sessions. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14000#issuecomment-6506269922. This entry enables candidate CI; independent enforcement verifies the PR-specific approval.\n\nPR #14122 retains the production bearerless provider-validation proof and private-publication proof in both Express targets. Spark and Station each request health on the two allowed addresses and require connection refusal on all discovered unintended addresses. Four added Spark assertions protect its separate physical-host path; deterministic URL construction remains in the support tests. The combined delta adds seven assertion points and one generated probe relative to main. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14122#issuecomment-6661407269. Independent enforcement verifies this PR-specific approval. Remove after merge.\n\nPR #14252 adds twelve live assertion points to the existing sandbox-survival owner for first-invocation cold public OpenClaw recovery, native and forwarded health, and retained sandbox/container identities on Docker and native Podman. Existing raw OpenShell survival evidence and target timeouts are unchanged. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14252#issuecomment-6676328443. This entry supports local and candidate checks; independent enforcement verifies the PR-specific approval record. Remove after merge.\n\nPR #14303 replaces #14201 and retains its two assertion points in hermes-root-entrypoint-smoke for qualification through the real entrypoint before gateway readiness. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14303#issuecomment-6713570086. This entry supports local hooks and candidate CI. Independent enforcement still verifies the PR-specific maintainer record. Remove after merge.\n\nPR #14512 adds24 net assertion points for native Switchyard cross-provider authorization, continuation policy enforcement, provider failure/recovery and a second credential scan. Three redundant proposed checks were omitted and two existing fixture-output checks remain covered by fast tests. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14512#issuecomment-6932725987. This branch entry supports local preliminary validation; independent CI verifies the PR-specific record. Remove after #14512 merges.\n\nPR #14512 retains its approved 24 assertion points and adds two generated conditions for bounded NULL diagnostics and PTY socket-state validation during sandbox retirement. Three unnecessary conditions were removed. Exact refreshed transition approved by Rebecca Sliter: https://github.com/NVIDIA/NemoClaw/pull/14512#issuecomment-6989339885. Independent enforcement still verifies this unedited maintainer record on GitHub.\n\nPR #14517 adds real shared-host MCP policy and credential composition proof with distinct paths and credentials, differing add-time DNS inputs, own-path success, configured-peer credential withholding, unconfigured-path denial, and owned cleanup. The delta adds 15 unique assertion points and one companion file. The two configured-peer assertion points require OpenShell enforcement; support tests cover status classification and rejection of simulated credential leaks or unintended peer authorization. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14517#issuecomment-7004275478. This branch entry supports preliminary local and candidate checks; independent enforcement verifies the recorded approval. Remove after merge.", "schemaVersion": 1, "exceptions": [ { @@ -162,6 +162,10 @@ { "pullRequest": 14512, "changeSha256": "1c9e32751f5d5acd4c5ace6003bdd42db5ef753b3b4bc1c050717dae74b717ca" + }, + { + "pullRequest": 14517, + "changeSha256": "c12a7992f1a458b46416744bed676734e231812d4738f93d81a716ea282db426" } ] } diff --git a/docs/manage-sandboxes/add-mcp-server.mdx b/docs/manage-sandboxes/add-mcp-server.mdx index 581c596ef84..de51ececd9d 100644 --- a/docs/manage-sandboxes/add-mcp-server.mdx +++ b/docs/manage-sandboxes/add-mcp-server.mdx @@ -150,7 +150,7 @@ NemoClaw records the normalized host and every validated address as OpenShell po The raw bearer value passes transiently to the OpenShell provider and remains absent from NemoClaw state, sandbox configuration, command arguments, and logs. The sandbox configuration contains only an OpenShell resolver placeholder for `LOCAL_MCP_TOKEN`, not the raw bearer value. You can unset the host variable after `mcp add` returns because OpenShell retains the credential. -To replace it, remove and re-add the server with the replacement exported under the same host variable name. `mcp remove` detaches the provider, and sandbox destroy may leave the detached provider for explicit operator cleanup. +To replace it, follow [Rotate a Credential](manage-mcp-servers#rotate-a-credential), including explicit cleanup of the retained provider before re-adding. Inspect the registration after the add returns: @@ -208,7 +208,12 @@ Deep Agents Code supports at most 64 managed MCP servers in one sandbox. Endpoint paths cannot contain percent escapes, backslashes, semicolons, or OpenShell glob metacharacters. Endpoint URLs cannot use port `0`. -NemoClaw resolves hostnames before registration and pins the validated addresses in the generated policy. +NemoClaw validates current DNS answers before registration. +If another managed server shares the hostname and port, a public add reuses its previously recorded public pins. +Otherwise, the generated policy pins the validated DNS addresses. +Reused pins can differ from the current DNS answers. +NemoClaw refuses the add before mutation if sibling pin sets conflict or trusted-private pins would need to change. +Refer to [Refresh Shared-Host Registrations](manage-mcp-servers#refresh-shared-host-registrations) to change pins for every registration on that hostname and port. Public endpoints need no trusted-private declaration. Private endpoints require a trust declaration and can use only RFC1918, CGNAT, or IPv6 unique local addresses. Supply the declaration with `--trusted-private-host` or the generic `NEMOCLAW_TRUSTED_PRIVATE_HOSTS` environment variable. diff --git a/docs/manage-sandboxes/manage-mcp-servers.mdx b/docs/manage-sandboxes/manage-mcp-servers.mdx index bfbee1704c3..4169834f621 100644 --- a/docs/manage-sandboxes/manage-mcp-servers.mdx +++ b/docs/manage-sandboxes/manage-mcp-servers.mdx @@ -139,20 +139,37 @@ The bare `mcp list` and `mcp status` forms never probe, so they stay fast. Endpo ## Rotate a Credential -Export the replacement under the same host environment name used by `mcp add`, remove the native registration, and add it again so NemoClaw creates a fresh provider binding: +Before removal, inspect the live policy with `openshell policy get --full my-sandbox`. +Record the server's current denied-tool selectors from the `tool` fields of its `tools/call` deny rules. +These selectors can differ from the original add options after `mcp update`. +Keep the URL, credential variable name, and reviewed `--trusted-private-host` declaration. + +Export the replacement under the same host environment name used by `mcp add`, then remove the native registration: ```bash export GITHUB_MCP_TOKEN='replacement-value' $$nemoclaw my-sandbox mcp remove github +``` + +`remove` deletes the agent-native registration and detaches the exact managed provider, but preserves the provider object. +Confirm that no sandbox uses that provider before you delete it with `openshell provider delete `. +Add the server again to create a fresh provider binding. +Append one `--deny-tool ''` option for each recorded selector to this command: + +```bash $$nemoclaw my-sandbox mcp add github \ --url https://api.githubcopilot.com/mcp/ \ --env GITHUB_MCP_TOKEN unset GITHUB_MCP_TOKEN ``` -`remove` deletes the agent-native registration and detaches the exact managed provider, but conservatively preserves the provider object. Remove that preserved provider explicitly after confirming no sandbox uses it; then `add` creates a new provider with the replacement credential and reconnects the native registration. +Inspect the live policy again and confirm that its denied-tool selectors match your record. +Tool discovery does not verify denied-tool enforcement. -For a trusted-private entry, pass the same reviewed `--trusted-private-host` value to `add`; NemoClaw resolves and records the replacement pins again. For a public entry, `add` resolves the hostname and creates a policy for the current validated public addresses. +For a trusted-private entry, pass the same reviewed `--trusted-private-host` value to `add`. +For a public entry, `add` validates current DNS answers, then reuses previously recorded public pins if another managed server shares the hostname and port. +Remove-and-add therefore does not independently refresh shared public pins. +Refer to [Change Endpoint Pins](#change-endpoint-pins) for pin changes. The raw value passes only through the OpenShell provider command's process environment and is not added to argv, NemoClaw state, or sandbox config. Revoke the old credential upstream after the new add succeeds. @@ -174,7 +191,12 @@ $$nemoclaw my-sandbox mcp update doordash \ The command changes only the live OpenShell policy. It does not change the agent-native endpoint, credential reference, provider, attachment, or agent adapter. Live policy is the enforcement source of truth; NemoClaw does not retain a second denied-tool intent record. -NemoClaw validates the current source entry and endpoint pins, removes the existing route, and then applies the replacement. This keeps an interrupted stricter update fail-closed. If replacement activation fails, the MCP route remains blocked and the error prints the exact `mcp update` command to retry. Rebuild captures and restores the complete live policy, including denied-tool rules, without regenerating it from registry state. +NemoClaw validates the current source entry and endpoint pins before replacing the route. +For public endpoints, it validates current DNS answers and checks that the retained recorded pins are public IP addresses. +Conflicting sibling pins stop the update before route removal. +This keeps an interrupted stricter update fail-closed. +If replacement activation fails, the MCP route remains blocked and the error prints the exact `mcp update` command to retry. +Rebuild captures and restores the complete live policy, including denied-tool rules, without regenerating it from registry state. Clear every denied-tool rule explicitly: @@ -204,21 +226,30 @@ Correct a reported source conflict before retrying. If the write cannot be confirmed, inspect `mcp status` and the live OpenShell policy before retrying. Successful tool discovery verifies that the endpoint is reachable through its existing credential binding. -For a trusted-private server, review every destination change before NemoClaw records new pins. Neither status, restart, rebuild, nor restore changes the recorded address set. +### Refresh Shared-Host Registrations -If the endpoint moves to another address, remove and re-add the server: +Registrations on one hostname and port must use identical address pins, even when their paths and credentials differ. +A per-server refresh stops before mutation if its new DNS answers differ from a sibling's recorded pins or the siblings already disagree. +Adding or re-adding one public registration reuses the sibling pins instead of refreshing them. -```bash -export LOCAL_MCP_TOKEN='replace-with-secret-manager-value' -$$nemoclaw my-sandbox mcp remove local-tools -$$nemoclaw my-sandbox mcp add local-tools \ - --url https://mcp-host.corp.example/mcp \ - --env LOCAL_MCP_TOKEN \ - --trusted-private-host mcp-host.corp.example -unset LOCAL_MCP_TOKEN -``` +To change the shared pin set, plan an interruption for every affected registration. +Before the first removal, record every server's endpoint options and current denied-tool selectors from live policy. +Re-export each credential from your secret manager. +Remove every registration on that hostname and port, and complete the [retained-provider cleanup](#rotate-a-credential) for each one. +Add the servers again with their endpoint options and recorded selectors, passing one `--deny-tool` option per selector. +The first public add records current validated DNS addresses; later adds reuse that set. +Confirm that each restored live denied-tool list matches your record. +Run `mcp status --tools` for each server and confirm readiness and successful discovery. +If DNS still differs from the recorded pins, coordinate the endpoint's DNS before repeating the procedure. + +### Change Trusted-Private Pins + +For a trusted-private server, review every destination change before NemoClaw records new pins. Neither status, restart, rebuild, nor restore changes the recorded address set. -Removing the server deletes the agent-native entry, removes its generated key from the current OpenShell policy, and detaches the provider. The provider itself is preserved for explicit cleanup. The re-add performs a new DNS preflight and records the reviewed exact address set. +If the endpoint moves, follow [Rotate a Credential](#rotate-a-credential) to preserve current denied-tool selectors and replace the registration. +Pass the reviewed `--trusted-private-host` declaration and every recorded `--deny-tool` selector on re-add. +The re-add performs a new DNS preflight and records the reviewed address set. +For registrations sharing a hostname and port, follow [Refresh Shared-Host Registrations](#refresh-shared-host-registrations) so their reviewed pins agree. ## Remove a Server diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 3e753049ed4..aadf215a360 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -3048,6 +3048,10 @@ $$nemoclaw my-assistant mcp list [--json] Add an MCP Streamable HTTP server to a sandbox. Pass `--url` for the MCP endpoint and the required single `--env KEY` bearer credential for the sandbox-side MCP client. Pass repeatable `--deny-tool ` options to block matching `tools/call` requests at the OpenShell proxy. The generated deny rules match tool names only and do not inspect arguments. Pass a repeatable `--trusted-private-host ` option to admit an exact RFC1918, CGNAT, or IPv6 unique local destination for the current command. The declaration must equal the normalized host from `--url`. For managed MCP, use a DNS hostname for an IPv6 unique local address because NemoClaw has not qualified direct IPv6-literal MCP URLs. You can supply exact hosts through `NEMOCLAW_TRUSTED_PRIVATE_HOSTS` instead, and NemoClaw combines the variable with command options. NemoClaw records the resulting exact trust intent and address pins, so restart, rebuild, and restore do not depend on the ambient environment. NemoClaw registers that credential in an OpenShell provider, installs a generated OpenShell `protocol: mcp` policy for the target endpoint, attaches the provider to the running sandbox, and writes only an OpenShell resolver placeholder for the recorded key into the agent configuration. Inline `--env KEY=VALUE` is rejected because it would expose the value in NemoClaw process arguments. Load the variable from a secret manager or masked prompt, export it without recording the value in shell history, and pass only `--env KEY`. All endpoints must use HTTPS. The full URL and path are persisted and displayed, so URLs cannot contain userinfo, query strings, fragments, known secret-shaped path material, percent-escaped or glob-style paths, or port zero. Server names must start with a letter and contain at most 64 letters, digits, hyphens, or underscores, and endpoint hostnames must use canonical lowercase DNS labels. NemoClaw rejects invalid names and endpoints before it writes lifecycle state or changes OpenShell resources. NemoClaw generates a narrow `protocol: mcp` policy for the destination, literal path, adapter binaries, pinned addresses, explicit MCP methods, and a 131,072-byte request-body limit. OpenShell `0.0.116` evaluates that policy before replacing the attached provider placeholder in the allowed request header. NemoClaw imports the endpointless `nemoclaw-mcp-v1` profile and binds the dedicated provider to that endpoint with `credential_binding.provider`. OpenShell withholds the credential before the binding is active and outside the bound host, port, and path. The sandbox client connects directly through OpenShell's existing egress path, and NemoClaw does not run a host-side MCP data-plane bridge, proxy, relay, or listener. After the add commits, NemoClaw freshly verifies the exact generated policy, expected provider attachment, recorded provider ID, `nemoclaw-mcp-v1` type, valid resource version, and exactly one credential key matching the recorded key. If those readiness checks pass, it sends a differential pair of wire-level MCP `initialize` requests from inside the sandbox — one with the placeholder header and one with an unresolvable control bearer — to verify that OpenShell resolves the credential on egress; otherwise it reports an inconclusive `probe skipped` result and sends no request. Neither outcome fails the committed add, and `--no-probe` skips this check. For full setup details, see [Add an MCP Server](../manage-sandboxes/mcp-servers/add-an-mcp-server). +For public registrations, NemoClaw validates current DNS answers, then reuses previously recorded public pins if another managed server shares the hostname and port. +Conflicting sibling pins or trusted-private pin changes stop the add before mutation. +Refer to [Change Endpoint Pins](../manage-sandboxes/mcp-servers/manage-mcp-servers#change-endpoint-pins) for coordinated recovery. + Credential-bound managed definitions may share a normalized endpoint only when they intentionally share one credential binding. NemoClaw rejects the same endpoint with different credential bindings; use a distinct endpoint URL when different credentials are required. The generated policy is also binary-scoped: the selected agent's adapter binaries are allowed, while an interactive `/usr/bin/curl` request to the same endpoint is denied. @@ -3112,7 +3116,11 @@ Update the denied-tool list or refresh public address pins for one registered MC Both operations use the live OpenShell policy and preserve the agent-native endpoint, credential reference, provider, attachment, and agent adapter. Pass one or more `--deny-tool ` options, or pass `--clear-deny-tools` to remove every denied-tool rule. Use only one mode per command: `--deny-tool`, `--clear-deny-tools`, or `--refresh-public-pins`. -Live OpenShell policy is the enforcement source of truth; NemoClaw does not persist duplicate MCP intent. A denied-tool update validates the current source and address pins, removes the current route, and applies the replacement. If activation fails, the route remains blocked and the error prints the exact `mcp update` retry command. Rebuild captures and restores the complete live policy, including denied-tool rules. +Live OpenShell policy is the enforcement source of truth; NemoClaw does not persist duplicate MCP intent. +A denied-tool update validates the current source and address pins, then checks sibling pin agreement before replacing the route. +For public endpoints, NemoClaw validates current DNS answers and checks that the retained recorded pins are public IP addresses. +If activation fails, the route remains blocked and the error prints the exact `mcp update` retry command. +Rebuild captures and restores the complete live policy, including denied-tool rules. ```bash $$nemoclaw my-assistant mcp update github --deny-tool 'delete_*' --deny-tool 'admin_*' @@ -3129,12 +3137,14 @@ $$nemoclaw my-assistant mcp update github --refresh-public-pins Public-pin refresh requires matching current sources and existing exact public pins. It preserves all other policy fields, including denied tools, methods, binary grants, and credential bindings. It rejects private or special-use answers, address ranges, and conflicting sources before writing. +It also refuses a refresh that would disagree with sibling pins on the same hostname and port. +Refer to [Refresh Shared-Host Registrations](../manage-sandboxes/mcp-servers/manage-mcp-servers#refresh-shared-host-registrations) for coordinated pin changes. If the update is not confirmed, inspect status and the live policy before retrying. Restart, rebuild, and restore do not refresh pins. ### `$$nemoclaw mcp status` -Inspect MCP server state for one server or for all servers discovered from the agent-native configuration. Status joins that source with the live OpenShell policy, provider, attachment, and credential-key shape; no MCP registry row is consulted or created. Status also compares current DNS answers with recorded pins without changing the policy. Text output reports `public address pins:` or `private address pins:` with `match`, `drift`, or `unresolved`; public targets that resolve to private or special-use addresses report `rejected`. JSON output reports the state, recorded pins, and validated current pins when available in `publicTarget` or `trustedPrivateTarget`. Public drift directs you to `mcp update --refresh-public-pins`, which changes only the live endpoint address pins. Trusted-private drift still requires review and remove-and-add approval. When a single server is named, status requests a differential wire-level credential-resolution probe. It sends no probe traffic unless the policy binding is present, the expected provider attachment is confirmed, and the live provider has the `nemoclaw-mcp-v1` type, a valid resource version, and exactly one credential key matching the source placeholder; a readiness failure reports `unknown` with a `probe skipped` detail. When ready, the same MCP `initialize` is sent from inside the sandbox once with the recorded resolver placeholder header and once with a deliberately-unresolvable control bearer. Classification uses the two HTTP status codes plus curl exit codes for transport, timeout, and policy-denial outcomes; response bodies are never captured or printed. A `verified` verdict requires the placeholder request to be accepted (HTTP 2xx) while the control is rejected — the only outcome that proves a valid credential was on the wire. Identical HTTP 400, 401, or 403 rejections raise a warning that names the hypotheses — the placeholder forwarded verbatim, an expired or revoked credential that resolved correctly, or (for HTTP 400) endpoint request validation — and tells you to verify the stored credential first. For HTTP 401 or 403, a confirmed-valid credential means the host is not rewriting placeholders and agent runtimes receive the same auth failure and skip the server; HTTP 400 remains inconclusive because the endpoint may reject the probe request itself. Every other outcome — differing rejections (an endpoint may reject two different literal bearers differently), endpoints that skip authentication, endpoint outages, policy denials, and unreachable sandboxes — reports as `unknown` rather than blaming the credential rewrite, and a source URL that fails the current authenticated-endpoint boundary is never probed. +Inspect MCP server state for one server or for all servers discovered from the agent-native configuration. Status joins that source with the live OpenShell policy, provider, attachment, and credential-key shape; no MCP registry row is consulted or created. Status also compares current DNS answers with recorded pins without changing the policy. Text output reports `public address pins:` or `private address pins:` with `match`, `drift`, or `unresolved`; public targets that resolve to private or special-use addresses report `rejected`. JSON output reports the state, recorded pins, and validated current pins when available in `publicTarget` or `trustedPrivateTarget`. Public drift directs you to `mcp update --refresh-public-pins`, which changes only the live endpoint address pins and refuses changes that conflict with sibling pins on the same hostname and port. Trusted-private drift still requires review and remove-and-add approval. When a single server is named, status requests a differential wire-level credential-resolution probe. It sends no probe traffic unless the policy binding is present, the expected provider attachment is confirmed, and the live provider has the `nemoclaw-mcp-v1` type, a valid resource version, and exactly one credential key matching the source placeholder; a readiness failure reports `unknown` with a `probe skipped` detail. When ready, the same MCP `initialize` is sent from inside the sandbox once with the recorded resolver placeholder header and once with a deliberately-unresolvable control bearer. Classification uses the two HTTP status codes plus curl exit codes for transport, timeout, and policy-denial outcomes; response bodies are never captured or printed. A `verified` verdict requires the placeholder request to be accepted (HTTP 2xx) while the control is rejected, the only outcome that proves a valid credential was on the wire. Identical HTTP 400, 401, or 403 rejections raise a warning that names the hypotheses, the placeholder forwarded verbatim, an expired or revoked credential that resolved correctly, or (for HTTP 400) endpoint request validation, and tells you to verify the stored credential first. For HTTP 401 or 403, a confirmed-valid credential means the host is not rewriting placeholders and agent runtimes receive the same auth failure and skip the server; HTTP 400 remains inconclusive because the endpoint may reject the probe request itself. Every other outcome, differing rejections (an endpoint may reject two different literal bearers differently), endpoints that skip authentication, endpoint outages, policy denials, and unreachable sandboxes, reports as `unknown` rather than blaming the credential rewrite, and a source URL that fails the current authenticated-endpoint boundary is never probed. `mcp status` exits with status `2` when the managed MCP projection is a symbolic link, FIFO, or diff --git a/docs/reference/troubleshoot-mcp-servers.mdx b/docs/reference/troubleshoot-mcp-servers.mdx index 1fc1e709520..2e87e777892 100644 --- a/docs/reference/troubleshoot-mcp-servers.mdx +++ b/docs/reference/troubleshoot-mcp-servers.mdx @@ -15,19 +15,8 @@ Use the reported status or lifecycle error to choose the matching remediation. If `mcp status ` reports identical placeholder and control rejections, first confirm the stored credential is valid. Restart validates and reloads the current provider-backed registration; it never consumes an exported replacement credential. -To replace the credential, follow the conservative remove and re-add procedure: - -```bash -export ='replacement-value' -$$nemoclaw mcp remove -# Confirm no sandbox uses the retained provider named by remove, then delete it. -openshell provider delete -$$nemoclaw mcp add --url --env -unset -``` - -Preserve the original denied-tool selectors and `--trusted-private-host` declaration on the re-add. -See [Rotate a Credential](../manage-sandboxes/mcp-servers/manage-mcp-servers#rotate-a-credential) for the complete provider-cleanup sequence. +To replace the credential, follow [Rotate a Credential](../manage-sandboxes/mcp-servers/manage-mcp-servers#rotate-a-credential). +That procedure preserves current denied-tool selectors before removal and verifies them after re-add. For identical HTTP 401 or 403 responses, a confirmed-valid credential means the OpenShell gateway on this host is not rewriting the recorded resolver placeholder on egress. Every agent request receives the same authentication failure even when provider, attachment, readiness, and adapter checks report healthy. @@ -51,11 +40,12 @@ Inspect the OpenShell gateway's ephemeral CA generation and CA-file initializati ## Provider Is Missing During Restart -If restart reports a missing provider, remove the native registration and re-add it with the same URL, credential environment name, denied-tool selectors, and trusted-private declaration. Restart does not recreate providers. +If restart reports a missing provider, follow [Rotate a Credential](../manage-sandboxes/mcp-servers/manage-mcp-servers#rotate-a-credential) to replace the registration and preserve current denied-tool selectors. +Restart does not recreate providers. ## Provider Uses the Legacy Generic Profile -If restart or rebuild reports that the provider uses the profile-less legacy `generic` type, remove that server and add it again with the recorded credential variable exported. +If restart or rebuild reports that the provider uses the profile-less legacy `generic` type, follow [Rotate a Credential](../manage-sandboxes/mcp-servers/manage-mcp-servers#rotate-a-credential). OpenShell cannot bind that provider to an MCP endpoint, and NemoClaw accepts it only for cleanup. ## Rebuild Cannot Prove a Credential Handle @@ -71,14 +61,7 @@ $$nemoclaw mcp status --json ``` If status cannot reach the sandbox, repair the reported gateway condition first. -Export the replacement under the same environment-variable name, then remove and re-add the server so a fresh provider binding and agent placeholder are created: - -```bash -export ='replacement-value' -$$nemoclaw mcp remove -$$nemoclaw mcp add --url --env -unset -``` +Follow [Rotate a Credential](../manage-sandboxes/mcp-servers/manage-mcp-servers#rotate-a-credential) to preserve current denied-tool selectors and create a fresh provider binding and agent placeholder. Run status again. OpenShell can retain the same `s…` stable handle after a provider update; verify endpoint authorization with the named `mcp status` probe. @@ -109,7 +92,7 @@ Keep the registration unchanged while status remains unavailable, conflicting, o For an interrupted `mcp add` that does not report an unknown outcome, inspect the native source and live status first. If no native registration exists, rerun the original command with the same URL, environment-variable name, and any `--deny-tool` options. -If the native registration exists, remove it and then re-add it after re-exporting the credential. +If the native registration exists, follow [Rotate a Credential](../manage-sandboxes/mcp-servers/manage-mcp-servers#rotate-a-credential) to preserve current denied-tool selectors during replacement. To abandon the transaction, run `mcp remove --force`. NemoClaw disables the native agent entry first and cleans only live resources whose ownership it can prove. It preserves the workspace provider and reports any residual policy or attachment cleanup. @@ -432,7 +415,9 @@ $$nemoclaw mcp status --tools ``` The refresh preserves all other policy fields, including denied tools, and retains the existing agent configuration and credentials. -Successful tool discovery verifies recovery. +If another managed registration uses the same hostname and port, refresh refuses DNS answers that differ from its pins before changing policy. +Follow [Refresh Shared-Host Registrations](../manage-sandboxes/mcp-servers/manage-mcp-servers#refresh-shared-host-registrations) to coordinate that change. +Successful tool discovery verifies endpoint reachability. Status, restart, rebuild, and restore preserve the live pins. If refresh cannot confirm a write, inspect status and the live OpenShell policy before retrying. @@ -444,17 +429,7 @@ Retry status after DNS recovers. If status reports `private address pins: drift`, review the endpoint address change before updating access. Status, restart, rebuild, and restore do not add new trusted-private addresses. -Remove and re-add the server with the same trusted host to perform a new preflight and record new pins: - -```bash -export LOCAL_MCP_TOKEN='replace-with-secret-manager-value' -$$nemoclaw mcp remove -$$nemoclaw mcp add \ - --url https://mcp-host.corp.example/mcp \ - --env LOCAL_MCP_TOKEN \ - --trusted-private-host mcp-host.corp.example -unset LOCAL_MCP_TOKEN -``` +Follow [Change Trusted-Private Pins](../manage-sandboxes/mcp-servers/manage-mcp-servers#change-trusted-private-pins) to replace the registration with reviewed pins and preserve its current denied-tool selectors. A `CONNECT 403` after an address change can mean that OpenShell rejected a current DNS answer outside `allowed_ips`. Do not add a provider's complete address range or broaden the policy to bypass the denial. diff --git a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts index 350f52f2652..816c72f5360 100644 --- a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts +++ b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts @@ -58,6 +58,7 @@ import { waitForDetachedMcpCredential, } from "./mcp-bridge-provider"; import { createMcpProviderAdapterBoundary } from "./mcp-bridge-provider-inspection"; +import { alignMcpTargetWithSharedHostPins } from "./mcp-bridge/shared-host-pins"; import { assertNoAmbiguousMcpCredentialTarget, assertNoAmbiguousMcpCredentialTargets, @@ -95,6 +96,9 @@ import { import { waitForMcpBridgeConditionAsync } from "./mcp-bridge/timing"; function sameMcpAddIntent(existing: McpSourceEntry, requested: McpSourceEntry): boolean { + const existingPins = existing.trustedPrivateHost + ? (existing.allowedIps ?? []) + : [...(existing.allowedIps ?? [])].sort(); return ( existing.server === requested.server && existing.agent === requested.agent && @@ -105,10 +109,8 @@ function sameMcpAddIntent(existing: McpSourceEntry, requested: McpSourceEntry): existing.trustedPrivateHost === requested.trustedPrivateHost && (existing.denyTools?.length ?? 0) === (requested.denyTools?.length ?? 0) && (existing.denyTools ?? []).every((tool, index) => tool === requested.denyTools?.[index]) && - (existing.allowedIps?.length ?? 0) === (requested.allowedIps?.length ?? 0) && - (existing.allowedIps ?? []).every( - (address, index) => address === requested.allowedIps?.[index], - ) && + existingPins.length === (requested.allowedIps?.length ?? 0) && + existingPins.every((address, index) => address === requested.allowedIps?.[index]) && existing.env.length === requested.env.length && existing.env.every((name, index) => name === requested.env[index]) ); @@ -148,7 +150,7 @@ function replayMcpAddTarget( ); } } - const target = { addresses: [...recordedPins] }; + const target = { addresses: [...recordedPins].sort() }; // Public policy pins are part of the committed transaction. Validate them // again, but do not replace them with a later DNS answer during an exact // retry; OpenShell must continue enforcing the originally admitted set. @@ -633,6 +635,15 @@ export async function refreshMcpBridgePublicPins( } const url = new URL(normalizeMcpServerUrl(entry.url)); const target = await preflightMcpServerUrlResolvedTarget(url); + const aligned = alignMcpTargetWithSharedHostPins({ + operation: "refresh", + sandboxName, + server, + url: url.toString(), + target, + bridges: observed.bridges, + }); + if (!aligned.ok) throw new McpBridgeError(aligned.message, 2); assertMcpCredentialBoundaryRuntimeVersion(); await ensureSandboxGatewaySelected(sandboxName, runtimeSelection); const provider = await assertMcpProviderRecoverable(entry, runtimeSelection); @@ -648,7 +659,7 @@ export async function refreshMcpBridgePublicPins( "The agent MCP registration changed during public-pin refresh. No policy was changed.", ); } - await refreshMcpPublicPolicyPins(sandboxName, entry, target, runtimeSelection); + await refreshMcpPublicPolicyPins(sandboxName, entry, aligned.target, runtimeSelection); console.log(` Refreshed public address pins for MCP server '${server}'.`); }); } @@ -676,12 +687,22 @@ async function updateMcpBridgeDenyToolsUnlocked( throw new McpBridgeError(`MCP server '${server}' not found on sandbox '${sandboxName}'.`); } assertAuthenticatedBridgeEntry(storedEntry); - const target = (await preflightMcpEntryTargets([storedEntry])).get(server); - if (!target || target.addresses.length === 0) { + const resolved = (await preflightMcpEntryTargets([storedEntry])).get(server); + if (!resolved || resolved.addresses.length === 0) { throw new McpBridgeError( `MCP server '${server}' has no validated address pins. No policy was changed.`, ); } + const aligned = alignMcpTargetWithSharedHostPins({ + operation: "update", + sandboxName, + server, + url: storedEntry.url, + target: resolved, + bridges: observed.bridges, + }); + if (!aligned.ok) throw new McpBridgeError(aligned.message, 2); + const target = aligned.target; const { denyTools: _previousDenyTools, ...entryWithoutDenyTools } = storedEntry; const updatedEntry: McpSourceEntry = { ...entryWithoutDenyTools, @@ -778,6 +799,24 @@ async function addMcpBridgeUnlocked( trustedPrivateHosts: matchingTrustedPrivateHosts, requireTrustedPrivateEndpoint: explicitTrustedPrivateHosts.length > 0, }); + // A host that publishes several addresses can answer each add differently, + // and OpenShell rejects endpoints that share a host and port but list + // different allowed IPs. Keep a new server's pins equal to its siblings'. + const aligned = alignMcpTargetWithSharedHostPins({ + operation: "add", + sandboxName, + server: options.server, + url: normalizedUrl, + target, + bridges: observed.bridges, + }); + if (!aligned.ok) throw new McpBridgeError(aligned.message, 2); + target = aligned.target; + if (aligned.reusedFrom.length > 0) { + console.log( + ` Reusing the address pins already recorded for MCP server ${aligned.reusedFrom.map((name) => `'${name}'`).join(", ")} on ${urlHost}.`, + ); + } } const envNames = uniqueEnvNames(options.env); diff --git a/src/lib/actions/sandbox/mcp-bridge-contracts.ts b/src/lib/actions/sandbox/mcp-bridge-contracts.ts index fadac7ca70e..662cb7ab806 100644 --- a/src/lib/actions/sandbox/mcp-bridge-contracts.ts +++ b/src/lib/actions/sandbox/mcp-bridge-contracts.ts @@ -49,8 +49,10 @@ export interface McpSourceEntry { denyTools?: string[]; /** Where the current agent registration was observed. */ source?: "native" | "legacy" | "legacy-registry" | "policy"; - /** Live policy endpoint differs from the agent-native URL. */ + /** Live policy cannot be reconciled with the agent registration. */ policyConflict?: string; + /** Differing live policy authority, or null when it cannot be determined. */ + policyEndpointConflict?: string | null; } export interface McpBridgeAddOptions extends ParsedMcpAddArgs {} diff --git a/src/lib/actions/sandbox/mcp-bridge-input-targets.test.ts b/src/lib/actions/sandbox/mcp-bridge-input-targets.test.ts index 309f6e48ba9..e6cece792a8 100644 --- a/src/lib/actions/sandbox/mcp-bridge-input-targets.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-input-targets.test.ts @@ -398,6 +398,7 @@ const expectFailure = phase === "policy-url-mismatch" || stableUnauthorized || u let authorizationProbe; if (phase === "provider-hostless") delete process.env.GITHUB_TOKEN; const providerId = "11111111-2222-4333-8444-555555555555"; +const recordedPins = ["8.8.8.8", "1.1.1.1"]; const state = { policy: ["policy", "policy-url-mismatch", "provider", "provider-hostless", "attachment"].includes(seedPhase) ? "capability" : seedPhase === "bound-policy" || seedPhase === "adapter" ? "bound" : "absent", provider: ["provider", "provider-hostless", "attachment", "bound-policy", "adapter"].includes(seedPhase), @@ -419,7 +420,7 @@ const commandTransport = require("./src/lib/adapters/sandbox/command-transport.j const entry = () => ({ server: "github", agent: "openclaw", adapter: "openclaw-config", url: "https://8.8.8.8/mcp", env: ["GITHUB_TOKEN"], - allowedIps: ["8.8.8.8"], providerName: "alpha-mcp-github", + allowedIps: recordedPins, providerName: "alpha-mcp-github", ...(state.provider ? { providerId } : {}), policyName: "mcp-bridge-github", source: "native", }); @@ -462,7 +463,7 @@ replace(policies, "getPresetContentGatewayState", (_sandbox, content) => { if (state.policy === "absent") return "absent"; if (phase === "policy-url-mismatch") return "drift"; const expected = content.includes("credential_binding") ? "bound" : "capability"; - return state.policy === expected && content.includes("8.8.8.8") ? "match" : "drift"; + return state.policy === expected && content.includes("8.8.8.8") && content.includes("1.1.1.1") ? "match" : "drift"; }); replace(policies, "applyPresetContent", (_sandbox, _name, content) => { state.policy = content.includes("credential_binding") ? "bound" : "capability"; @@ -490,7 +491,7 @@ require("./src/lib/actions/sandbox/mcp-bridge.js").addMcpBridge("alpha", { server: "github", url: "https://8.8.8.8/mcp", env: [{ name: "GITHUB_TOKEN" }], }).then(() => { if (expectFailure) process.exit(2); - process.stdout.write(JSON.stringify({ state }), () => process.exit(0)); + process.stdout.write(JSON.stringify({ state, recordedPins }), () => process.exit(0)); }, async (error) => { if (!expectFailure) { process.stderr.write(String(error && error.stack || error), () => process.exit(1)); @@ -502,7 +503,7 @@ require("./src/lib/actions/sandbox/mcp-bridge.js").addMcpBridge("alpha", { } process.stdout.write(JSON.stringify({ message: String(error && error.message || error), - state, authorizationProbe, beforeOrdinaryRemoval, + state, authorizationProbe, beforeOrdinaryRemoval, recordedPins, }), () => process.exit(0)); }); `; @@ -524,7 +525,9 @@ require("./src/lib/actions/sandbox/mcp-bridge.js").addMcpBridge("alpha", { const outcome = trailingJsonPayload<{ message?: string; state: Record; + recordedPins: string[]; }>(result.stdout); + expect(outcome.recordedPins).toEqual(["8.8.8.8", "1.1.1.1"]); expect(outcome).toMatchObject( phase === "policy-url-mismatch" ? { diff --git a/src/lib/actions/sandbox/mcp-bridge-provider-inspection.test.ts b/src/lib/actions/sandbox/mcp-bridge-provider-inspection.test.ts index 833039d7425..9e11bc73e1d 100644 --- a/src/lib/actions/sandbox/mcp-bridge-provider-inspection.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-provider-inspection.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import dns from "node:dns/promises"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -12,7 +13,9 @@ import { getMcpProviderInspectionRuntimeSelection, resolveSandboxConfigRuntimeSelection, inspectMcpProvider, + preflightMcpEntryTargets, } from "./mcp-bridge-provider-inspection"; +import type { McpSourceEntry } from "./mcp-bridge-contracts"; import * as gatewayTargets from "./gateway-target"; const temporaryDirectories: string[] = []; @@ -269,3 +272,48 @@ describe("MCP provider absence inspection", () => { }, ); }); + +describe("existing MCP target preflight", () => { + const entry: McpSourceEntry = { + server: "tools", + agent: "openclaw", + adapter: "openclaw-config", + url: "https://mcp.example.test/tools", + env: ["TOOLS_TOKEN"], + allowedIps: ["8.8.8.8"], + providerName: "alpha-mcp-tools", + providerId: "11111111-2222-4333-8444-555555555555", + policyName: "mcp-bridge-tools", + }; + + it("replays sorted public pins without mutating recorded order after fresh DNS validation", async () => { + const pins = ["8.8.8.8", "1.1.1.1"]; + const lookup = vi + .spyOn(dns, "lookup") + .mockResolvedValue([{ address: "9.9.9.9", family: 4 }] as never); + const targets = await preflightMcpEntryTargets([{ ...entry, allowedIps: pins }]); + expect(targets.get("tools")).toEqual({ addresses: ["1.1.1.1", "8.8.8.8"] }); + expect(pins).toEqual(["8.8.8.8", "1.1.1.1"]); + expect(lookup).toHaveBeenCalled(); + }); + + it("rejects an invalid recorded public pin instead of replacing it with DNS", async () => { + vi.spyOn(dns, "lookup").mockResolvedValue([{ address: "1.1.1.1", family: 4 }] as never); + await expect( + preflightMcpEntryTargets([{ ...entry, allowedIps: ["127.0.0.1"] }]), + ).rejects.toThrow(/private, local, or special-use address pin/); + }); + + it("still rejects private DNS before replaying recorded public pins", async () => { + vi.spyOn(dns, "lookup").mockResolvedValue([{ address: "10.20.30.40", family: 4 }] as never); + await expect(preflightMcpEntryTargets([entry])).rejects.toThrow( + /private, local, or special-use/, + ); + }); + + it("keeps fresh public resolution for legacy entries without recorded pins", async () => { + vi.spyOn(dns, "lookup").mockResolvedValue([{ address: "1.1.1.1", family: 4 }] as never); + const targets = await preflightMcpEntryTargets([{ ...entry, allowedIps: undefined }]); + expect(targets.get("tools")).toEqual({ addresses: ["1.1.1.1"] }); + }); +}); diff --git a/src/lib/actions/sandbox/mcp-bridge-provider-inspection.ts b/src/lib/actions/sandbox/mcp-bridge-provider-inspection.ts index 1bc8c24de0d..faf4e96c724 100644 --- a/src/lib/actions/sandbox/mcp-bridge-provider-inspection.ts +++ b/src/lib/actions/sandbox/mcp-bridge-provider-inspection.ts @@ -33,7 +33,10 @@ import type { SandboxEntry } from "../../state/registry/types"; import type { McpSourceEntry } from "./mcp-bridge-contracts"; import { getKnownSandboxTarget, getPersistedSandboxTargetGateway } from "./gateway-target"; import { McpBridgeError } from "./mcp-bridge-contracts"; -import type { McpBridgeTargetValidation } from "./mcp-bridge-url-validation"; +import { + parseMcpUrlWithValidatedTarget, + type McpBridgeTargetValidation, +} from "./mcp-bridge-url-validation"; import { assertAuthenticatedBridgeEntry, preflightMcpServerUrlResolvedTarget, @@ -516,7 +519,13 @@ export async function preflightMcpEntryTargets( }; return [entry.server, target] as const; } - const target = await preflightMcpServerUrlResolvedTarget(new URL(normalized)); + const resolved = await preflightMcpServerUrlResolvedTarget(new URL(normalized)); + // Existing registrations replay policy pins; changing them requires an + // explicit public-pin refresh, including during teardown rollback. + const target = entry.allowedIps?.length + ? { addresses: [...entry.allowedIps].sort() } + : resolved; + parseMcpUrlWithValidatedTarget(normalized, target); return [entry.server, target] as const; }), ); diff --git a/src/lib/actions/sandbox/mcp-bridge-restart-recovery.test.ts b/src/lib/actions/sandbox/mcp-bridge-restart-recovery.test.ts index c6af0b20922..1ea2600a030 100644 --- a/src/lib/actions/sandbox/mcp-bridge-restart-recovery.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-restart-recovery.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import dns from "node:dns/promises"; import { beforeEach, describe, expect, it, vi } from "vitest"; const mocks = vi.hoisted(() => ({ @@ -73,7 +74,8 @@ vi.mock("./mcp-bridge-status", async (importOriginal) => ({ ...(await importOriginal()), statusMcpBridge: mocks.status, })); -vi.mock("./mcp-bridge-validation", () => ({ +vi.mock("./mcp-bridge-validation", async (importOriginal) => ({ + ...(await importOriginal()), assertAuthenticatedBridgeEntry: vi.fn(), assertMcpCredentialBoundaryRuntimeVersion: vi.fn(), resolveCredentialEnv: vi.fn(() => ({})), @@ -81,6 +83,7 @@ vi.mock("./mcp-bridge-validation", () => ({ })); import { restartMcpBridge, restoreExistingMcpBridgeRuntime } from "./mcp-bridge-restart"; +import { applyGeneratedPolicy } from "./mcp-bridge-policy"; const entries = ["first", "second"].map((server) => ({ server, @@ -246,6 +249,45 @@ describe("OpenClaw MCP partial-mutation recovery", () => { ); }); + it("restores shared-host policy pins through real preflight despite differing DNS answers", async () => { + const shared = entries.map((entry) => ({ + ...entry, + url: `https://mcp.example.test/${entry.server}`, + allowedIps: ["8.8.8.8", "1.1.1.1"], + })); + const { preflightMcpEntryTargets } = await vi.importActual< + typeof import("./mcp-bridge-provider-inspection") + >("./mcp-bridge-provider-inspection"); + mocks.preflightTargets.mockImplementationOnce(preflightMcpEntryTargets); + mocks.register.mockReset().mockResolvedValue(undefined); + const lookup = vi + .spyOn(dns, "lookup") + .mockResolvedValueOnce([{ address: "1.1.1.1", family: 4 }] as never) + .mockResolvedValue([{ address: "9.9.9.9", family: 4 }] as never); + try { + await restoreExistingMcpBridgeRuntime("alpha", shared, { + lifecyclePhase: "teardown-rollback", + }); + expect(lookup).toHaveBeenCalledTimes(2); + expect( + vi + .mocked(applyGeneratedPolicy) + .mock.calls.map((call) => [call[1].server, call[2].addresses]), + ).toEqual([ + ["first", ["1.1.1.1", "8.8.8.8"]], + ["first", ["1.1.1.1", "8.8.8.8"]], + ["second", ["1.1.1.1", "8.8.8.8"]], + ["second", ["1.1.1.1", "8.8.8.8"]], + ]); + expect(shared.map((entry) => entry.allowedIps)).toEqual([ + ["8.8.8.8", "1.1.1.1"], + ["8.8.8.8", "1.1.1.1"], + ]); + } finally { + lookup.mockRestore(); + } + }); + it("reloads successful restoration using its recorded runtime", async () => { const runtimeSelection = { gatewayName: "recorded-gateway", diff --git a/src/lib/actions/sandbox/mcp-bridge-source.test.ts b/src/lib/actions/sandbox/mcp-bridge-source.test.ts index e5a96f60aa1..6d54b30700d 100644 --- a/src/lib/actions/sandbox/mcp-bridge-source.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-source.test.ts @@ -57,6 +57,7 @@ import { inspectLegacyBridgeState, inspectPolicyOnlyMcpEntry, inspectSourceBridgeState, + joinMcpEntriesToOpenShell, } from "./mcp-bridge-source"; const sandbox = { @@ -439,6 +440,48 @@ network_policies: ).toContain("differs from live policy endpoint"); }); + it.each([ + ["matching endpoint", "api.githubcopilot.com", 443, "/mcp/", undefined], + ["different host", "other.example.com", 443, "/mcp/", "other.example.com:443"], + ["different path", "api.githubcopilot.com", 443, "/renamed", "api.githubcopilot.com:443"], + ["different port", "api.githubcopilot.com", 8443, "/mcp/", "api.githubcopilot.com:8443"], + ["unknown port", "api.githubcopilot.com", null, "/mcp/", null], + ])( + "retains endpoint identity with invalid denied tools and a %s", + async (_label, host, port, endpointPath, conflict) => { + mocks.capturePolicy.mockResolvedValue(`network_policies: + mcp_bridge_github: + endpoints: + - host: ${host} + port: ${port} + path: ${endpointPath} + protocol: mcp + allowed_ips: ["8.8.8.8"] + deny_rules: + - method: tools/call + tool: "invalid selector!" +`); + const bridges = await joinMcpEntriesToOpenShell( + sandbox, + { + github: { + server: "github", + agent: "openclaw", + url: "https://api.githubcopilot.com/mcp/", + env: ["GITHUB_TOKEN"], + policyName: "mcp-bridge-github", + }, + }, + runtimeSelection, + ); + expect(bridges.github.policyConflict).toBe( + "Live policy contains invalid denied-tool selectors.", + ); + expect(bridges.github.policyEndpointConflict).toBe(conflict); + expect(bridges.github.allowedIps).toEqual(["8.8.8.8"]); + }, + ); + it("redacts credentials and strips terminal controls from source-read failures", async () => { mocks.executeSandboxExecCommand.mockReturnValue({ status: 2, diff --git a/src/lib/actions/sandbox/mcp-bridge-source.ts b/src/lib/actions/sandbox/mcp-bridge-source.ts index 16da02ee02e..7fa10537360 100644 --- a/src/lib/actions/sandbox/mcp-bridge-source.ts +++ b/src/lib/actions/sandbox/mcp-bridge-source.ts @@ -648,6 +648,18 @@ async function enrichFromPolicy( ...(provider.exists === true && provider.id ? { providerId: provider.id } : {}), ...(denyTools.length > 0 && entry.source !== "legacy-registry" ? { denyTools } : {}), ...(policyConflict ? { policyConflict } : {}), + ...(endpointConflict + ? { + policyEndpointConflict: + host && + typeof endpoint.port === "number" && + Number.isInteger(endpoint.port) && + endpoint.port > 0 && + endpoint.port <= 65535 + ? `${host}:${endpoint.port}` + : null, + } + : {}), }; } diff --git a/src/lib/actions/sandbox/mcp-bridge-update.test.ts b/src/lib/actions/sandbox/mcp-bridge-update.test.ts index 593a48b65cc..f7c571e1c6e 100644 --- a/src/lib/actions/sandbox/mcp-bridge-update.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-update.test.ts @@ -102,6 +102,126 @@ describe("source-backed MCP denied-tool policy updates", () => { } }); + it.each([ + ["shared public pins", false, false], + ["trusted-private sibling", true, false], + ["conflicting sibling pins", false, true], + ["sibling with invalid denied tools", false, false, true], + ["sibling with endpoint path drift", false, false, false, true], + ])( + "refuses a public-pin refresh that would diverge from %s", + async ( + _label, + trustedPrivate, + conflicting, + policyConflict = false, + endpointConflict = false, + ) => { + const sibling: McpSourceEntry = { + ...entry, + server: "peer", + providerName: "alpha-mcp-peer", + providerId: "22222222-3333-4444-8555-666666666666", + policyName: "mcp-bridge-peer", + url: "https://mcp.example.test/peer", + env: ["PEER_TOKEN"], + ...(policyConflict + ? { policyConflict: "Live policy contains invalid denied-tool selectors." } + : {}), + ...(endpointConflict ? { policyEndpointConflict: "mcp.example.test:443" } : {}), + ...(trustedPrivate + ? { trustedPrivateHost: "mcp.example.test", allowedIps: ["10.20.30.40"] } + : {}), + }; + const bridges = { + github: entry, + peer: sibling, + ...(conflicting + ? { + third: { + ...sibling, + server: "third", + providerName: "alpha-mcp-third", + providerId: "33333333-4444-4555-8666-777777777777", + policyName: "mcp-bridge-third", + url: "https://mcp.example.test/third", + env: ["THIRD_TOKEN"], + allowedIps: ["9.9.9.9"], + }, + } + : {}), + }; + mocks.inspectSourceBridgeState.mockReturnValueOnce({ + bridges, + sources: { native: bridges, legacy: {} }, + }); + const lookup = vi + .spyOn(dns, "lookup") + .mockResolvedValue([{ address: "1.1.1.1", family: 4 }] as never); + try { + await expect(refreshMcpBridgePublicPins("alpha", "github")).rejects.toThrow( + /not refreshed.*mcp\.example\.test:443/, + ); + expect(mocks.ensureSandboxGatewaySelected).not.toHaveBeenCalled(); + expect(mocks.assertMcpProviderRecoverable).not.toHaveBeenCalled(); + expect(mocks.refreshMcpPublicPolicyPins).not.toHaveBeenCalled(); + expect(mocks.removeGeneratedPolicy).not.toHaveBeenCalled(); + } finally { + lookup.mockRestore(); + } + }, + ); + + it.each([ + ["matching shared pins", "https://mcp.example.test/peer", "8.8.8.8"], + ["another hostname", "https://other.example.test/peer", "1.1.1.1"], + ["another port", "https://mcp.example.test:8443/peer", "1.1.1.1"], + ["an unknown unrelated authority", "https://other.example.test/peer", "1.1.1.1", null], + [ + "an unrelated host conflict", + "https://other.example.test/peer", + "1.1.1.1", + "other.example.test:443", + ], + [ + "an unrelated port conflict", + "https://mcp.example.test:8443/peer", + "1.1.1.1", + "mcp.example.test:8443", + ], + ])( + "preserves public-pin refresh with %s", + async (_label, url, address, policyEndpointConflict?: string | null) => { + const sibling = { + ...entry, + server: "peer", + providerName: "alpha-mcp-peer", + providerId: "22222222-3333-4444-8555-666666666666", + policyName: "mcp-bridge-peer", + url, + policyEndpointConflict, + env: ["PEER_TOKEN"], + }; + const bridges = { github: entry, peer: sibling }; + mocks.inspectSourceBridgeState.mockReturnValueOnce({ + bridges, + sources: { native: bridges, legacy: {} }, + }); + const lookup = vi.spyOn(dns, "lookup").mockResolvedValue([{ address, family: 4 }] as never); + try { + await refreshMcpBridgePublicPins("alpha", "github"); + expect(mocks.refreshMcpPublicPolicyPins).toHaveBeenCalledWith( + "alpha", + entry, + { addresses: [address] }, + { gatewayName: "nemoclaw-9090", workspace: "default" }, + ); + } finally { + lookup.mockRestore(); + } + }, + ); + it("refuses public-pin refresh when the native registration changes during DNS resolution (#10464)", async () => { const lookup = vi .spyOn(dns, "lookup") @@ -167,6 +287,158 @@ describe("source-backed MCP denied-tool policy updates", () => { } }); + it.each([ + ["replace", ["--deny-tool", "delete_*"]], + ["clear", ["--clear-deny-tools"]], + ])("keeps shared public pins when denied tools %s after DNS drift", async (_mode, flags) => { + const peer = { + ...entry, + server: "peer", + url: "https://mcp.example.test/peer", + env: ["PEER_TOKEN"], + providerName: "alpha-mcp-peer", + providerId: "22222222-3333-4444-8555-666666666666", + policyName: "mcp-bridge-peer", + }; + const bridges = { github: entry, peer }; + mocks.inspectSourceBridgeState.mockReturnValueOnce({ + bridges, + sources: { native: bridges, legacy: {} }, + }); + mocks.preflightMcpEntryTargets.mockResolvedValueOnce( + new Map([["github", { addresses: ["1.1.1.1"] }]]), + ); + + await dispatchMcpBridgeCommand("alpha", ["update", "github", ...flags]); + + expect(mocks.applyGeneratedPolicy).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ allowedIps: ["8.8.8.8"], env: ["GITHUB_TOKEN"] }), + { addresses: ["8.8.8.8"] }, + { runtimeSelection: { gatewayName: "nemoclaw-9090", workspace: "default" } }, + ); + expect(mocks.removeGeneratedPolicy.mock.invocationCallOrder[0]).toBeLessThan( + mocks.applyGeneratedPolicy.mock.invocationCallOrder[0], + ); + }); + + it.each([ + ["conflicting public pins on replace", ["delete_*"], ["9.9.9.9"], false, true], + ["conflicting public pins on clear", [], ["9.9.9.9"], false, true], + ["trusted-private sibling on replace", ["delete_*"], ["10.20.30.40"], true, false], + ["trusted-private sibling on clear", [], ["10.20.30.40"], true, false], + ["invalid public sibling pins on replace", ["delete_*"], ["127.0.0.1"], false, false], + ["invalid public sibling pins on clear", [], ["127.0.0.1"], false, false], + ["sibling with invalid denied tools on replace", ["delete_*"], ["9.9.9.9"], false, true, true], + ["sibling with invalid denied tools on clear", [], ["9.9.9.9"], false, true, true], + [ + "sibling with endpoint path drift on replace", + ["delete_*"], + ["9.9.9.9"], + false, + false, + false, + true, + ], + ["sibling with endpoint path drift on clear", [], ["9.9.9.9"], false, false, false, true], + ])( + "rejects denied-tool changes before mutation with %s", + async ( + _label, + denyTools, + pins, + privatePeer, + conflict, + policyConflict = false, + endpointConflict = false, + ) => { + const peer = { + ...entry, + server: "peer", + url: "https://mcp.example.test/peer", + env: ["PEER_TOKEN"], + providerName: "alpha-mcp-peer", + providerId: "22222222-3333-4444-8555-666666666666", + policyName: "mcp-bridge-peer", + allowedIps: pins, + ...(endpointConflict ? { policyEndpointConflict: "mcp.example.test:443" } : {}), + ...(policyConflict + ? { policyConflict: "Live policy contains invalid denied-tool selectors." } + : {}), + ...(privatePeer ? { trustedPrivateHost: "mcp.example.test" } : {}), + }; + const bridges = { + github: entry, + peer, + ...(conflict + ? { + third: { + ...peer, + policyConflict: undefined, + server: "third", + url: "https://mcp.example.test/third", + env: ["THIRD_TOKEN"], + providerName: "alpha-mcp-third", + providerId: "33333333-4444-4555-8666-777777777777", + policyName: "mcp-bridge-third", + allowedIps: ["8.8.8.8"], + }, + } + : {}), + }; + mocks.inspectSourceBridgeState.mockReturnValue({ + bridges, + sources: { native: bridges, legacy: {} }, + }); + await expect(updateMcpBridgeDenyTools("alpha", "github", denyTools)).rejects.toThrow( + /not updated|private, local, or special-use address pin/, + ); + expect(mocks.ensureSandboxGatewaySelected).not.toHaveBeenCalled(); + expect(mocks.assertMcpProviderRecoverable).not.toHaveBeenCalled(); + expect(mocks.removeGeneratedPolicy).not.toHaveBeenCalled(); + expect(mocks.applyGeneratedPolicy).not.toHaveBeenCalled(); + }, + ); + + it.each([ + ["replace", ["delete_*"], "https://other.example.test/peer", null], + ["clear", [], "https://other.example.test/peer", null], + ["replace", ["delete_*"], "https://other.example.test/peer", "other.example.test:443"], + ["clear", [], "https://other.example.test/peer", "other.example.test:443"], + ["replace", ["delete_*"], "https://mcp.example.test:8443/peer", "mcp.example.test:8443"], + ["clear", [], "https://mcp.example.test:8443/peer", "mcp.example.test:8443"], + ])( + "permits denied-tool %s despite an unrelated endpoint conflict", + async (_mode, denyTools, url, policyEndpointConflict) => { + const peer = { + ...entry, + server: "peer", + url, + policyEndpointConflict, + allowedIps: ["9.9.9.9"], + }; + const before = structuredClone(peer); + const bridges = { github: entry, peer }; + mocks.inspectSourceBridgeState.mockReturnValueOnce({ + bridges, + sources: { native: bridges, legacy: {} }, + }); + await updateMcpBridgeDenyTools("alpha", "github", denyTools); + expect(mocks.removeGeneratedPolicy).toHaveBeenCalledExactlyOnceWith("alpha", entry, { + runtimeSelection: { gatewayName: "nemoclaw-9090", workspace: "default" }, + }); + expect(mocks.applyGeneratedPolicy).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ server: "github" }), + { addresses: ["8.8.8.8"] }, + { runtimeSelection: { gatewayName: "nemoclaw-9090", workspace: "default" } }, + ); + expect(mocks.applyGeneratedPolicy).toHaveBeenCalledTimes(1); + expect(mocks.applyGeneratedPolicy.mock.calls[0][1].denyTools ?? []).toEqual(denyTools); + expect(peer).toEqual(before); + }, + ); + it("removes the old route before applying and publishing the live replacement (#11115)", async () => { await updateMcpBridgeDenyTools("alpha", "github", ["submit_*", "delete_repo"]); diff --git a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts new file mode 100644 index 00000000000..a659fd9de7c --- /dev/null +++ b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts @@ -0,0 +1,559 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { trailingJsonPayload } from "../../../../../test/helpers/host-process-harness"; + +import type { McpSourceEntry } from "../mcp-bridge-contracts"; +import { alignMcpTargetWithSharedHostPins } from "./shared-host-pins"; + +function entry(server: string, overrides: Partial = {}): McpSourceEntry { + return { + server, + agent: "deepagents", + url: `https://mcp.example.test/${server}`, + env: [`${server.toUpperCase()}_TOKEN`], + policyName: `mcp-bridge-${server}`, + allowedIps: ["8.8.8.8"], + ...overrides, + }; +} + +function align( + bridges: Record, + addresses: string[], + url = "https://mcp.example.test/two", + target: Partial<{ trustedPrivateHost: string }> = {}, +) { + return alignMcpTargetWithSharedHostPins({ + operation: "add", + sandboxName: "alpha", + server: "two", + url, + target: { addresses, ...target }, + bridges, + }); +} + +describe("MCP shared-host address pins", () => { + it("leaves the target alone when no other server uses the host and port", () => { + const target = { addresses: ["1.1.1.1"] }; + expect( + alignMcpTargetWithSharedHostPins({ + operation: "add", + sandboxName: "alpha", + server: "two", + url: "https://mcp.example.test/two", + target, + bridges: { + other: entry("other", { url: "https://elsewhere.example.test/mcp" }), + sameHostOtherPort: entry("sameHostOtherPort", { + url: "https://mcp.example.test:8443/mcp", + }), + }, + }), + ).toEqual({ ok: true, target, reusedFrom: [] }); + }); + + it("reuses the recorded pins when the new answer is a different address of the same host (#13800)", () => { + const aligned = align({ one: entry("one", { allowedIps: ["8.8.8.8"] }) }, ["1.1.1.1"]); + expect(aligned).toEqual({ + ok: true, + target: { addresses: ["8.8.8.8"] }, + reusedFrom: ["one"], + }); + }); + + it("treats an explicit default port as the same endpoint", () => { + const aligned = align({ one: entry("one", { url: "https://mcp.example.test:443/one" }) }, [ + "1.1.1.1", + ]); + expect(aligned).toMatchObject({ ok: true, reusedFrom: ["one"] }); + }); + + it("keeps the target when its answer already equals the recorded pins", () => { + const target = { addresses: ["1.1.1.1", "8.8.8.8"] }; + const aligned = alignMcpTargetWithSharedHostPins({ + operation: "add", + sandboxName: "alpha", + server: "two", + url: "https://mcp.example.test/two", + target, + bridges: { one: entry("one", { allowedIps: ["8.8.8.8", "1.1.1.1"] }) }, + }); + expect(aligned).toEqual({ ok: true, target, reusedFrom: [] }); + }); + + it("reuses one pin set recorded by several servers", () => { + const aligned = align( + { one: entry("one"), three: entry("three", { allowedIps: ["8.8.8.8"] }) }, + ["1.1.1.1"], + ); + expect(aligned).toMatchObject({ ok: true, reusedFrom: ["one", "three"] }); + }); + + it("ignores the server being added and unpinned siblings without endpoint conflicts", () => { + const aligned = align( + { + two: entry("two", { allowedIps: ["9.9.9.9"] }), + unpinned: entry("unpinned", { allowedIps: undefined }), + }, + ["1.1.1.1"], + ); + expect(aligned).toEqual({ ok: true, target: { addresses: ["1.1.1.1"] }, reusedFrom: [] }); + }); + + it.each(["add", "update", "refresh"] as const)( + "refuses %s when a sibling's live endpoint differs only by path", + (operation) => { + const refused = alignMcpTargetWithSharedHostPins({ + operation, + sandboxName: "alpha", + server: "two", + url: "https://mcp.example.test/two", + target: { addresses: ["1.1.1.1"] }, + bridges: { + one: entry("one", { + policyConflict: "Agent URL differs from live policy endpoint at /renamed.", + policyEndpointConflict: "mcp.example.test:443", + }), + }, + }); + expect(refused.ok).toBe(false); + expect(refused.ok ? "" : refused.message).toMatch( + /live policy endpoint.*'one'.*Resolve.*conflict.*mcp\.example\.test:443/, + ); + }, + ); + + it.each([ + { url: "https://other.example.test/one", policyEndpointConflict: "mcp.example.test:443" }, + { allowedIps: undefined, policyEndpointConflict: "mcp.example.test:443" }, + { policyEndpointConflict: null }, + ])( + "refuses unresolved live authority before filtering sibling $url / $allowedIps", + (overrides) => { + const refused = align({ one: entry("one", overrides) }, ["1.1.1.1"]); + expect(refused.ok).toBe(false); + }, + ); + + it.each([ + ["add", "https://other.example.test/one", null], + ["update", "https://other.example.test/one", null], + ["refresh", "https://other.example.test/one", null], + ["add", "https://mcp.example.test:8443/one", null], + ["update", "https://mcp.example.test:8443/one", null], + ["refresh", "https://mcp.example.test:8443/one", null], + ["add", "https://other.example.test/one", "other.example.test:443"], + ["update", "https://other.example.test/one", "other.example.test:443"], + ["refresh", "https://other.example.test/one", "other.example.test:443"], + ["add", "https://mcp.example.test:8443/one", "mcp.example.test:8443"], + ["update", "https://mcp.example.test:8443/one", "mcp.example.test:8443"], + ["refresh", "https://mcp.example.test:8443/one", "mcp.example.test:8443"], + ] as const)("permits %s despite an unrelated endpoint conflict at %s", (operation, url, live) => { + const bridges = { + one: entry("one", { url, policyEndpointConflict: live, allowedIps: ["9.9.9.9"] }), + }; + const before = structuredClone(bridges); + const target = { addresses: ["1.1.1.1"] }; + expect( + alignMcpTargetWithSharedHostPins({ + operation, + sandboxName: "alpha", + server: "two", + url: "https://mcp.example.test/two", + target, + bridges, + }), + ).toEqual({ ok: true, target, reusedFrom: [] }); + expect(bridges).toEqual(before); + }); + + it.each(["add", "update", "refresh"] as const)( + "rejects %s when a sibling with invalid denied tools records conflicting pins", + (operation) => { + const refused = alignMcpTargetWithSharedHostPins({ + operation, + sandboxName: "alpha", + server: "two", + url: "https://mcp.example.test/two", + target: { addresses: ["1.1.1.1"] }, + bridges: { + one: entry("one"), + three: entry("three", { + allowedIps: ["9.9.9.9"], + policyConflict: "Live policy contains invalid denied-tool selectors.", + }), + }, + }); + expect(refused.ok).toBe(false); + expect(refused.ok ? "" : refused.message).toMatch( + /'one': 8\.8\.8\.8; 'three': 9\.9\.9\.9.*nemoclaw alpha mcp remove /, + ); + }, + ); + + it("reuses public pins despite a sibling's invalid denied tools", () => { + expect( + align( + { + one: entry("one", { + policyConflict: "Live policy contains invalid denied-tool selectors.", + }), + }, + ["1.1.1.1"], + ), + ).toEqual({ ok: true, target: { addresses: ["8.8.8.8"] }, reusedFrom: ["one"] }); + }); + + it("names the servers and pins when existing servers already disagree", () => { + const refused = align( + { + one: entry("one", { allowedIps: ["8.8.8.8"] }), + three: entry("three", { allowedIps: ["8.8.4.4"] }), + }, + ["1.1.1.1"], + ); + expect(refused).toMatchObject({ ok: false }); + expect(refused.ok ? "" : refused.message).toMatch( + /'two' was not added.*mcp\.example\.test:443.*'one': 8\.8\.8\.8; 'three': 8\.8\.4\.4.*nemoclaw alpha mcp remove /, + ); + }); + + it("refuses to reuse or replace trusted-private pins", () => { + const privateSibling = entry("one", { + url: "https://mcp.corp.example/one", + allowedIps: ["10.20.30.40"], + trustedPrivateHost: "mcp.corp.example", + policyConflict: "Live policy contains invalid denied-tool selectors.", + }); + const privateTarget = align( + { one: privateSibling }, + ["10.20.30.41"], + "https://mcp.corp.example/two", + { trustedPrivateHost: "mcp.corp.example" }, + ); + expect(privateTarget.ok ? "" : privateTarget.message).toMatch( + /'one' records 10\.20\.30\.40.*does not reuse or replace trusted-private pins/, + ); + const publicTarget = align( + { one: privateSibling }, + ["1.1.1.1"], + "https://mcp.corp.example/two", + ); + expect(publicTarget.ok ? "" : publicTarget.message).toMatch( + /does not reuse or replace trusted-private pins/, + ); + }); + + it.each([ + [ + "conflicting public pins", + { one: entry("one"), three: entry("three", { allowedIps: ["8.8.4.4"] }) }, + ], + ["trusted-private mismatch", { one: entry("one", { trustedPrivateHost: "mcp.example.test" }) }], + ])("explains complete retained-provider recovery for %s", (_label, bridges) => { + const refused = align(bridges, ["1.1.1.1"]); + expect(refused.ok).toBe(false); + const message = refused.ok ? "" : refused.message; + expect(message).toContain("re-export the affected credential variables"); + expect(message).toContain("Removal preserves providers"); + expect(message).toContain("explicit provider cleanup"); + expect(message).toContain("no other sandbox uses them"); + expect(message).toMatch( + /Before removing.*follow .*manage-mcp-servers#rotate-a-credential to record current denied-tool selectors/, + ); + expect(message).toContain("Re-add with the recorded selectors"); + }); + + it("accepts trusted-private siblings whose pins already match", () => { + const privateSibling = entry("one", { + url: "https://mcp.corp.example/one", + allowedIps: ["10.20.30.40"], + trustedPrivateHost: "mcp.corp.example", + }); + const target = { addresses: ["10.20.30.40"], trustedPrivateHost: "mcp.corp.example" }; + expect( + alignMcpTargetWithSharedHostPins({ + operation: "add", + sandboxName: "alpha", + server: "two", + url: "https://mcp.corp.example/two", + target, + bridges: { one: privateSibling }, + }), + ).toEqual({ ok: true, target, reusedFrom: [] }); + }); + + it("rejects recorded public pins that are private or special-use", () => { + expect(() => align({ one: entry("one", { allowedIps: ["127.0.0.1"] }) }, ["1.1.1.1"])).toThrow( + /private, local, or special-use address pin/, + ); + }); +}); + +describe("mcp add on a host that rotates DNS answers (#13800)", () => { + function runAdd(options: { + siblings: Record; + dnsAnswer: string; + livePolicy?: Record; + }) { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-mcp-shared-host-")); + const sourceRequireHook = path.resolve("test/helpers/onboard-script-mocks.cjs"); + const script = ` +process.env.HOME = ${JSON.stringify(home)}; +process.env.T_MCP_02 = "host-only-secret"; +require("node:dns/promises").lookup = async () => [{ address: ${JSON.stringify(options.dnsAnswer)}, family: 4 }]; +const replace = (module, name, value) => Object.defineProperty(module, name, { + configurable: true, enumerable: true, value, writable: true, +}); +const registry = require("./src/lib/state/registry.js"); +const policies = require("./src/lib/policy/index.js"); +const adapters = require("./src/lib/actions/sandbox/mcp-bridge-adapters.js"); +const policy = require("./src/lib/actions/sandbox/mcp-bridge-policy.js"); +const provider = require("./src/lib/actions/sandbox/mcp-bridge-provider.js"); +const processRecovery = require("./src/lib/actions/sandbox/process-recovery.js"); +const state = require("./src/lib/actions/sandbox/mcp-bridge-state.js"); +const sourceState = require("./src/lib/actions/sandbox/mcp-bridge-source.js"); +const providerInspection = require("./src/lib/actions/sandbox/mcp-bridge-provider-inspection.js"); +const livePolicy = ${JSON.stringify(options.livePolicy ?? null)}; +const validation = require("./src/lib/actions/sandbox/mcp-bridge-validation.js"); +let appliedTarget; +let mutated = false; +const policyMutations = []; +replace(policies, "getPresetContentGatewayState", () => "absent"); +replace(adapters, "assertAgentMcpMutationRuntimeCapability", () => {}); +replace(adapters, "inspectAgentAdapterRegistration", () => ({ state: "absent" })); +replace(adapters, "registerAgentAdapterAtCurrentCredentialRevision", () => { mutated = true; return "v1"; }); +replace(policy, "applyGeneratedPolicy", (_sandbox, updatedEntry, target) => { mutated = true; policyMutations.push(updatedEntry.server); appliedTarget = target; }); +replace(state, "ensureSandboxGatewaySelected", async () => {}); +replace(validation, "assertMcpCredentialBoundaryRuntimeVersion", () => {}); +replace(provider, "assertNoProviderCredentialCollisions", () => {}); +replace(provider, "getMcpProviderInspectionRuntimeSelection", () => ({ gatewayName: "nemoclaw-9090", workspace: "default" })); +replace(provider, "ensureMcpBridgeProviderProfile", () => {}); +replace(provider, "inspectMcpProvider", () => ({ + credentialKeys: null, exists: false, id: null, resourceVersion: null, type: null, +})); +replace(provider, "inspectMcpProviderAttachments", () => ({ attachments: [] })); +replace(provider, "upsertMcpProvider", () => { + mutated = true; + return { + action: "created", + inspection: { + credentialKeys: ["T_MCP_02"], exists: true, + id: "11111111-2222-4333-8444-555555555555", resourceVersion: 1, type: "nemoclaw-mcp-v1", + }, + }; +}); +replace(provider, "attachProvider", () => {}); +replace(provider, "refreshMcpProviderEnvironment", () => {}); +replace(provider, "observeMcpCredentialRevision", () => "v1"); +replace(provider, "waitForAttachedMcpCredential", () => "v1"); +replace(processRecovery, "restartSandboxGateway", () => ({ + ok: true, restarted: true, healthPassed: true, forwardRecovered: true, +})); +if (livePolicy) { + replace(policies, "captureRecordedSandboxBasePolicy", async () => JSON.stringify(livePolicy)); + replace(providerInspection, "inspectMcpProvider", async () => ({ + credentialKeys: null, exists: false, id: null, resourceVersion: null, type: null, + })); +} +replace(sourceState, "inspectSourceBridgeState", async (sandbox, runtimeSelection) => ({ + bridges: livePolicy + ? await sourceState.joinMcpEntriesToOpenShell(sandbox, ${JSON.stringify(options.siblings)}, runtimeSelection) + : ${JSON.stringify(options.siblings)}, + sources: { native: {}, legacy: {} }, +})); +registry.registerSandbox({ + name: "alpha", agent: "openclaw", gatewayName: "nemoclaw-9090", gatewayPort: 9090, +}); +const finish = (error) => process.stdout.write(JSON.stringify({ + message: error ? String(error.message || error) : null, + appliedAddresses: appliedTarget ? appliedTarget.addresses : null, + mutated, + policyMutations, +}), () => process.exit(0)); +require("./src/lib/actions/sandbox/mcp-bridge.js").addMcpBridge("alpha", { + server: "two", + url: "https://mcp.example.test/mcp/two", + env: [{ name: "T_MCP_02" }], +}).then(() => finish(null), finish); +`; + try { + const result = spawnSync(process.execPath, ["-e", script], { + cwd: process.cwd(), + encoding: "utf8", + env: { + ...process.env, + HOME: home, + NODE_OPTIONS: [process.env.NODE_OPTIONS, `--require=${sourceRequireHook}`] + .filter(Boolean) + .join(" "), + }, + timeout: 30_000, + }); + expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); + expect(`${result.stdout}\n${result.stderr}`).not.toContain("host-only-secret"); + return trailingJsonPayload<{ + message: string | null; + appliedAddresses: string[] | null; + mutated: boolean; + policyMutations: string[]; + }>(result.stdout); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + } + + const sibling = (server: string, allowedIps: string[]) => ({ + server, + agent: "openclaw", + adapter: "openclaw-config", + url: `https://mcp.example.test/mcp/${server}`, + env: [`${server.toUpperCase()}_TOKEN`], + allowedIps, + providerName: `nemoclaw-mcp-${server}`, + policyName: `mcp-bridge-${server}`, + source: "native", + }); + + it("applies the first server's pins instead of the second answer", { timeout: 40_000 }, () => { + const outcome = runAdd({ + siblings: { one: sibling("one", ["8.8.8.8"]) }, + dnsAnswer: "8.8.4.4", + livePolicy: { + network_policies: { + mcp_bridge_one: { + endpoints: [ + { + host: "mcp.example.test", + port: 443, + path: "/mcp/one", + protocol: "mcp", + allowed_ips: ["8.8.8.8"], + }, + ], + }, + }, + }, + }); + expect(outcome.message).toBeNull(); + expect(outcome.appliedAddresses).toEqual(["8.8.8.8"]); + }); + + it.each([ + ["another host", "https://other.example.test/mcp/one", "other.example.test", 443], + ["another port", "https://mcp.example.test:8443/mcp/one", "mcp.example.test", 8443], + ["an unknown live host", "https://other.example.test/mcp/one", "", 443], + ["an unknown live port", "https://mcp.example.test:8443/mcp/one", "mcp.example.test", 0], + ] as const)( + "adds without changing a conflicting registration on %s", + { timeout: 40_000 }, + (_label, url, host, port) => { + const outcome = runAdd({ + siblings: { one: { ...sibling("one", ["8.8.8.8"]), url } }, + dnsAnswer: "1.1.1.1", + livePolicy: { + network_policies: { + mcp_bridge_one: { + endpoints: [ + { host, port, path: "/renamed", protocol: "mcp", allowed_ips: ["8.8.8.8"] }, + ], + }, + }, + }, + }); + expect(outcome).toMatchObject({ + message: null, + appliedAddresses: ["1.1.1.1"], + }); + expect(new Set(outcome.policyMutations)).toEqual(new Set(["two"])); + }, + ); + + it( + "refuses a live sibling authority even when its registered host differs", + { timeout: 40_000 }, + () => { + const outcome = runAdd({ + siblings: { + one: { ...sibling("one", ["8.8.8.8"]), url: "https://other.example.test/mcp/one" }, + }, + dnsAnswer: "1.1.1.1", + livePolicy: { + network_policies: { + mcp_bridge_one: { + endpoints: [ + { + host: "mcp.example.test", + port: 443, + path: "/mcp/one", + protocol: "mcp", + allowed_ips: ["8.8.8.8"], + }, + ], + }, + }, + }, + }); + expect(outcome).toMatchObject({ + mutated: false, + policyMutations: [], + message: expect.stringMatching(/live policy endpoint/), + }); + }, + ); + + it.each([ + ["path", { host: "mcp.example.test", port: 443, path: "/renamed" }], + ["host", { host: "other.example.test", port: 443, path: "/mcp/one" }], + ["port", { host: "mcp.example.test", port: 8443, path: "/mcp/one" }], + ] as const)( + "refuses before mutation when the joined live sibling has %s drift", + { timeout: 40_000 }, + (_kind, endpoint) => { + const outcome = runAdd({ + siblings: { one: sibling("one", ["8.8.8.8"]) }, + dnsAnswer: "1.1.1.1", + livePolicy: { + network_policies: { + mcp_bridge_one: { + endpoints: [{ ...endpoint, protocol: "mcp", allowed_ips: ["8.8.8.8"] }], + }, + }, + }, + }); + expect(outcome, JSON.stringify(outcome)).toMatchObject({ + mutated: false, + appliedAddresses: null, + message: expect.stringMatching(/not added.*live policy endpoint.*'one'.*Resolve.*conflict/), + }); + }, + ); + + it.each([undefined, "Live policy contains invalid denied-tool selectors."])( + "fails before changing anything when existing servers disagree (policy conflict: %s)", + { timeout: 40_000 }, + (policyConflict) => { + const outcome = runAdd({ + siblings: { + one: sibling("one", ["8.8.8.8"]), + three: { + ...sibling("three", ["9.9.9.9"]), + ...(policyConflict ? { policyConflict } : {}), + }, + }, + dnsAnswer: "8.8.4.4", + }); + expect(outcome.message).toMatch(/'one': 8\.8\.8\.8; 'three': 9\.9\.9\.9/); + expect(outcome.mutated).toBe(false); + }, + ); +}); diff --git a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts new file mode 100644 index 00000000000..a5d9ef64a45 --- /dev/null +++ b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts @@ -0,0 +1,121 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { McpSourceEntry } from "../mcp-bridge-contracts"; +import { + parseMcpUrlWithValidatedTarget, + type McpBridgeTargetValidation, +} from "../mcp-bridge-url-validation"; + +export type McpSharedHostPinAlignment = + | { + ok: true; + target: McpBridgeTargetValidation; + /** Servers whose recorded public pins are reused. */ + reusedFrom: string[]; + } + | { + ok: false; + /** Operator-facing reason the operation cannot proceed; the caller reports it as a usage error. */ + message: string; + }; + +interface PinGroup { + pins: string[]; + servers: string[]; + trustedPrivate: boolean; +} + +function endpointAuthority(rawUrl: string): string | null { + try { + const parsed = new URL(rawUrl); + return `${parsed.hostname.toLowerCase()}:${parsed.port || "443"}`; + } catch { + return null; + } +} + +function sortedPins(addresses: readonly string[]): string[] { + return [...new Set(addresses.map((address) => address.toLowerCase()))].sort(); +} + +function describePins(pins: readonly string[]): string { + return pins.join(", "); +} + +function describeServers(servers: readonly string[]): string { + return servers.map((server) => `'${server}'`).join(", "); +} + +/** Align policy targets with recorded pins on the same host and port before mutation. */ +export function alignMcpTargetWithSharedHostPins(options: { + operation: "add" | "update" | "refresh"; + sandboxName: string; + server: string; + url: string; + target: McpBridgeTargetValidation; + bridges: Readonly>; +}): McpSharedHostPinAlignment { + const { operation, sandboxName, server, url, target, bridges } = options; + const action = { add: "added", update: "updated", refresh: "refreshed" }[operation]; + const authority = endpointAuthority(url); + if (!authority) return { ok: true, target, reusedFrom: [] }; + + const recovery = `Before removing registrations with \`nemoclaw ${sandboxName} mcp remove \`, follow https://docs.nvidia.com/nemoclaw/latest/user-guide/openclaw/manage-sandboxes/mcp-servers/manage-mcp-servers#rotate-a-credential to record current denied-tool selectors and re-export the affected credential variables. Removal preserves providers. Perform explicit provider cleanup only after confirming no other sandbox uses them. Re-add with the recorded selectors.`; + const groups = new Map(); + for (const entry of Object.values(bridges)) { + if (entry.server === server) continue; + if (endpointAuthority(entry.url) !== authority && entry.policyEndpointConflict !== authority) { + continue; + } + if (entry.policyEndpointConflict !== undefined) { + return { + ok: false, + message: `MCP server '${server}' was not ${action}: the live policy endpoint for managed server '${entry.server}' differs from its registered URL. Resolve that conflict before reconciling address pins on ${authority}. ${recovery}`, + }; + } + if (!entry.allowedIps?.length) continue; + const pins = sortedPins(entry.allowedIps); + const key = pins.join(","); + const group = groups.get(key) ?? { pins, servers: [], trustedPrivate: false }; + group.servers.push(entry.server); + group.trustedPrivate ||= Boolean(entry.trustedPrivateHost); + groups.set(key, group); + } + if (groups.size === 0) return { ok: true, target, reusedFrom: [] }; + + const [firstGroup, ...otherGroups] = [...groups.values()]; + if (otherGroups.length > 0) { + const recorded = [firstGroup, ...otherGroups] + .map((group) => `${describeServers(group.servers)}: ${describePins(group.pins)}`) + .join("; "); + return { + ok: false, + message: `MCP server '${server}' was not ${action}: managed servers on ${authority} already record different address pins (${recorded}). OpenShell rejects endpoints that share a host and port but list different allowed IPs. ${recovery}`, + }; + } + + const requested = sortedPins(target.addresses); + if (requested.join(",") === firstGroup.pins.join(",")) + return { ok: true, target, reusedFrom: [] }; + + if (firstGroup.trustedPrivate || target.trustedPrivateHost) { + return { + ok: false, + message: `MCP server '${server}' was not ${action}: it resolves to ${describePins(requested)} on ${authority}, but ${describeServers(firstGroup.servers)} record${firstGroup.servers.length === 1 ? "s" : ""} ${describePins(firstGroup.pins)}, and OpenShell rejects endpoints that share a host and port but list different allowed IPs. NemoClaw does not reuse or replace trusted-private pins on its own. ${recovery}`, + }; + } + + if (operation === "refresh") { + return { + ok: false, + message: `MCP server '${server}' was not refreshed: ${authority} is shared with ${describeServers(firstGroup.servers)}, which record ${describePins(firstGroup.pins)}. Refreshing only this server to ${describePins(requested)} would create conflicting address pins. ${recovery}`, + }; + } + + const reused = { addresses: [...firstGroup.pins] }; + // The recorded pins were validated when they were written; check them again + // so a tampered or hand-edited policy cannot widen a new server's egress. + parseMcpUrlWithValidatedTarget(url, reused); + return { ok: true, target: reused, reusedFrom: [...firstGroup.servers] }; +} diff --git a/src/lib/actions/sandbox/rebuild-entry-lock.test.ts b/src/lib/actions/sandbox/rebuild-entry-lock.test.ts index dd7543f882a..8692dcca8ec 100644 --- a/src/lib/actions/sandbox/rebuild-entry-lock.test.ts +++ b/src/lib/actions/sandbox/rebuild-entry-lock.test.ts @@ -1,19 +1,49 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawn, type ChildProcess } from "node:child_process"; +import { execFileSync, spawn, type ChildProcess } from "node:child_process"; import { once } from "node:events"; import fs from "node:fs"; import { fileURLToPath } from "node:url"; import path from "node:path"; +import { beforeAll } from "vitest"; import { expect, test } from "../../../../test/helpers/owned-test-resources"; +import { SOURCE_REQUIRE_HOOK } from "../../../../test/helpers/source-loader-options"; // Passing CI shards ran each case in 2.2-4.7 s, including lock-holder startup // (#14689). This deadline allows slower runners and still reports the child's // stderr before the 30 s test timeout. const REBUILD_CHILD_TIMEOUT_MS = 20_000; +beforeAll(() => { + const rootDir = fileURLToPath(new URL("../../../../", import.meta.url)); + const catalogDir = path.join(rootDir, "dist/managed-inference"); + fs.mkdirSync(catalogDir, { recursive: true }); + const stagingDir = fs.mkdtempSync(path.join(catalogDir, "rebuild-entry-lock-")); + const stagedCatalog = path.join(stagingDir, "catalog.json"); + try { + // Source-loaded inference modules need the real catalog even without a CLI build. + execFileSync( + process.execPath, + [ + "--require", + SOURCE_REQUIRE_HOOK, + "-e", + "require(process.argv[1]).generateServingCatalog({ rootDir: process.argv[2], outputPath: process.argv[3] });", + fileURLToPath(new URL("../../inference/serving/generate-catalog.ts", import.meta.url)), + rootDir, + stagedCatalog, + ], + { cwd: rootDir, timeout: REBUILD_CHILD_TIMEOUT_MS, stdio: "pipe" }, + ); + // Other test workers must only see complete catalog bytes. + fs.renameSync(stagedCatalog, path.join(catalogDir, "catalog.json")); + } finally { + fs.rmSync(stagingDir, { recursive: true, force: true }); + } +}, REBUILD_CHILD_TIMEOUT_MS); + function firstOutput(child: ChildProcess, label: string, stderr: () => string): Promise { return Promise.race([ once(child.stdout!, "data"), @@ -55,7 +85,7 @@ test.for(["registered", "missing"] as const)( process.execPath, [ "--require", - "tsx/cjs", + SOURCE_REQUIRE_HOOK, "-e", ` const session = require(process.argv[1]); @@ -72,13 +102,17 @@ test.for(["registered", "missing"] as const)( { env, stdio: ["ignore", "pipe", "pipe"] }, ), ); + let holderStderr = ""; + holder.stderr!.setEncoding("utf8").on("data", (chunk: string) => { + holderStderr += chunk; + }); // Load the rebuild entry while the holder starts, then run it once the locks are held. const rebuild = resources.ownChild( spawn( process.execPath, [ "--require", - "tsx/cjs", + SOURCE_REQUIRE_HOOK, "-e", ` const entry = require(process.argv[1]); @@ -108,7 +142,7 @@ test.for(["registered", "missing"] as const)( }); const closed = once(rebuild, "close"); await Promise.all([ - firstOutput(holder, "lock holder", () => ""), + firstOutput(holder, "lock holder", () => holderStderr), firstOutput(rebuild, "rebuild entry", () => stderr), ]); const onboardLock = path.join(stateDir, "onboard.lock"); diff --git a/test/e2e/README.md b/test/e2e/README.md index e9245618857..377ba23bc5f 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -1125,6 +1125,16 @@ except `allowed_ips`. This live step proves that OpenShell enforces the refreshe depend on an external DNS rotation happening during the test. A failed step restores the captured policy before normal sandbox cleanup. +The shared-host MCP scenario sends each provider placeholder to both configured paths for OpenClaw, Hermes, and Deep Agents Code. +The fixture gives the second add a subset of the first DNS answer set. +For status, its preload explicitly loads the fixture in the isolated resolver child and supplies the first answer set. +The resolver keeps its cleared loader environment and existing deadline. +A process regression exercises the real bounded resolver and public-pin status inspection. +Its own path must authenticate; the peer must reject it without receiving the foreign raw credential. +The probe requires HTTP 401 or 403, and the server observation rejects a credential leak even when authentication fails. +Transport, TLS, timeout, and unrelated HTTP failures cannot establish credential withholding. +Support tests validate these oracles; candidate-bound MCP jobs must establish OpenShell enforcement. + The pin-recovery proof stays within the existing assertion budget by retiring fixture-detail checks: the probe's fixed HTTP method and JSON-RPC fields, and the removed proxy's `enc:v1:` and `proxy.pid` markers. `test/mcp/mcp-bridge-servers.test.ts` owns the fake server's protocol behavior, and diff --git a/test/e2e/live/mcp-bridge-reliability.ts b/test/e2e/live/mcp-bridge-reliability.ts index 8928d05721c..cbfc976f094 100644 --- a/test/e2e/live/mcp-bridge-reliability.ts +++ b/test/e2e/live/mcp-bridge-reliability.ts @@ -56,6 +56,8 @@ export async function addBridgeAndReadStatus( serverName?: string; credentialEnvName?: string; applyHostPolicyEdit?: boolean; + addNodeOptions?: string; + statusNodeOptions?: string; }, ): Promise { await (options.applyHostPolicyEdit === false @@ -80,6 +82,7 @@ export async function addBridgeAndReadStatus( artifactName: `${options.artifactPrefix}-mcp-add-fake-server`, env: { ...buildAvailabilityProbeEnv(), + ...(options.addNodeOptions ? { NODE_OPTIONS: options.addNodeOptions } : {}), [credentialEnvName]: credential, }, redactionValues: [credential], @@ -90,6 +93,7 @@ export async function addBridgeAndReadStatus( artifactName: `${options.artifactPrefix}-mcp-status-json`, env: { ...buildAvailabilityProbeEnv(), + ...(options.statusNodeOptions ? { NODE_OPTIONS: options.statusNodeOptions } : {}), [credentialEnvName]: credential, }, redactionValues: [credential], @@ -429,17 +433,26 @@ export async function runMcpProviderRewriteProbe( sandboxName: string, targetUrl: string, method: string, - expectation: "allow" | "deny" | "deny-strict", + expectation: "allow" | "deny" | "deny-strict" | "withhold", artifactName: string, credentialKey = "FAKE_MCP_SECRET", toolName?: string, + adapter: McpAdapter = "openclaw-config", ): Promise { + // Keep the admitted Python interpreter as an ancestor of the Node probe, + // matching the runtime attribution used by the existing rebinding probe. + const runtime = + adapter === "openclaw-config" + ? "node" + : `${adapter === "hermes-config" ? "/opt/hermes/.venv/bin/python3" : "/opt/venv/bin/python3"} -c ${shellQuote("import subprocess, sys; raise SystemExit(subprocess.run(sys.argv[1:], check=False).returncode)")} node`; + // Hermes startup owns supervisor state and cannot be re-entered by an exec probe. + const launcher = adapter === "hermes-config" ? "" : "nemoclaw-start "; return sandbox.execShell( sandboxName, trustedSandboxShellScript( [ "set -eu", - `nemoclaw-start node - ${shellQuote(targetUrl)} ${shellQuote(method)} ${shellQuote(expectation)} ${shellQuote(credentialKey)}${toolName ? ` ${shellQuote(toolName)}` : ""} <<'NEMOCLAW_MCP_PROVIDER_REWRITE_PROBE'`, + `${launcher}${runtime} - ${shellQuote(targetUrl)} ${shellQuote(method)} ${shellQuote(expectation)} ${shellQuote(credentialKey)}${toolName ? ` ${shellQuote(toolName)}` : ""} <<'NEMOCLAW_MCP_PROVIDER_REWRITE_PROBE'`, MCP_PROVIDER_REWRITE_PROBE_SOURCE, "NEMOCLAW_MCP_PROVIDER_REWRITE_PROBE", ].join("\n"), diff --git a/test/e2e/live/mcp-bridge-servers.ts b/test/e2e/live/mcp-bridge-servers.ts index 12148027c2b..1462a8ba2c1 100644 --- a/test/e2e/live/mcp-bridge-servers.ts +++ b/test/e2e/live/mcp-bridge-servers.ts @@ -1072,6 +1072,7 @@ export async function startCompatibleMock(options: { export async function startFakeMcpHttpsServer(options: { secret: string; + additionalPaths?: Readonly>; challenge?: string; resultToken?: string; tls?: { cert: Buffer; key: Buffer }; @@ -1203,7 +1204,9 @@ export async function startFakeMcpHttpsServer(options: { res.writeHead(202); res.end(); }; - if (requestPath !== "/mcp") { + const requestSecret = + requestPath === "/mcp" ? expectedSecret : options.additionalPaths?.[requestPath]; + if (requestSecret === undefined) { respondJson(404, { error: { message: "not found" } }); return; } @@ -1212,7 +1215,7 @@ export async function startFakeMcpHttpsServer(options: { return; } if (req.method === "GET") { - if (auth !== `Bearer ${expectedSecret}`) { + if (auth !== `Bearer ${requestSecret}`) { respondJson(401, { error: { message: "missing rewritten bearer credential" } }); return; } @@ -1241,7 +1244,7 @@ export async function startFakeMcpHttpsServer(options: { "cache-control": "no-cache", connection: "keep-alive", }); - res.write(`event: endpoint\ndata: /mcp?legacySessionId=${eventSessionId}\n\n`); + res.write(`event: endpoint\ndata: ${requestPath}?legacySessionId=${eventSessionId}\n\n`); serverEventStreams.add(res); res.once("close", () => { eventSession.phase = "closed"; @@ -1270,7 +1273,7 @@ export async function startFakeMcpHttpsServer(options: { respondJson(405, { error: { message: "method not allowed" } }); return; } - if (auth !== `Bearer ${expectedSecret}`) { + if (auth !== `Bearer ${requestSecret}`) { respondJson(401, { error: { message: "missing rewritten bearer credential" } }); return; } diff --git a/test/e2e/live/mcp-bridge-shared-host.ts b/test/e2e/live/mcp-bridge-shared-host.ts new file mode 100644 index 00000000000..92014c73229 --- /dev/null +++ b/test/e2e/live/mcp-bridge-shared-host.ts @@ -0,0 +1,296 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import dns from "node:dns/promises"; +import fs from "node:fs"; +import path from "node:path"; +import { expect } from "vitest"; + +import type { ArtifactSink } from "../fixtures/artifacts.ts"; +import type { CleanupRegistry } from "../fixtures/cleanup.ts"; +import { assertCleanupSucceededOrAbsent } from "../fixtures/cleanup-resources.ts"; +import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; +import { assertExitZero } from "../fixtures/clients/command.ts"; +import type { HostCliClient } from "../fixtures/clients/host.ts"; +import type { SandboxClient } from "../fixtures/clients/sandbox.ts"; +import { MCP_BRIDGE_TEST_CREDENTIALS } from "../fixtures/mcp-bridge-credentials.ts"; +import type { TestProgress } from "../fixtures/progress.ts"; +import { buildMcpBridgePolicyKey } from "../../../src/lib/actions/sandbox/mcp-bridge-policy-render"; +import { cleanupMcpBridge, type McpAdapter } from "./mcp-bridge-cleanup.ts"; +import { approveOpenClawAdminScope } from "./openclaw-admin-scope.ts"; +import { addBridgeAndReadStatus, runMcpProviderRewriteProbe } from "./mcp-bridge-reliability.ts"; +import { captureManagedMcpPolicy, expectExitNonZero } from "./mcp-bridge-sandbox.ts"; +import { startFakeMcpHttpsServer, startPublicMcpHttpsTunnel } from "./mcp-bridge-servers.ts"; + +type Address = { address: string; family: number }; + +/** Control a CLI process's DNS input without replacing policy or provider operations. */ +export async function withMcpDnsAnswers( + hostname: string, + addresses: readonly Address[], + run: (nodeOptions: string) => Promise, +): Promise { + const scratch = path.resolve(".ws-tmp", "tmp"); + fs.mkdirSync(scratch, { recursive: true, mode: 0o700 }); + const directory = fs.mkdtempSync(path.join(scratch, "mcp-shared-host-dns-")); + const preload = path.join(directory, "lookup.cjs"); + const observed = path.join(directory, "observed.json"); + const callbackPreload = path.join(directory, "callback.cjs"); + try { + fs.writeFileSync( + preload, + ` +const promises = require("node:dns/promises"); +const childProcess = require("node:child_process"); +const originalPromisesLookup = promises.lookup; +const originalExecFile = childProcess.execFile; +const target = ${JSON.stringify(hostname)}; +const answers = ${JSON.stringify(addresses)}; +function selectedAnswers() { + require("node:fs").writeFileSync(${JSON.stringify(observed)}, JSON.stringify(answers)); + return answers.map(answer => ({ ...answer })); +} +promises.lookup = async (hostname, options) => { + if (hostname !== target || options?.all !== true) { + return originalPromisesLookup.call(promises, hostname, options); + } + return selectedAnswers(); +}; +// Status clears loader environment variables. Load only this fixture explicitly in its DNS child. +childProcess.execFile = function(file, args, ...rest) { + const options = rest[0]; + const boundedLookup = file === process.execPath && Array.isArray(args) && args.length === 4 && + args[0] === "-e" && args[1].includes('require("node:dns").lookup(') && + args[2] === "--" && args[3] === target && + options?.env?.NODE_OPTIONS === "" && options?.env?.NODE_PATH === ""; + return originalExecFile.call(this, file, + boundedLookup ? ["--require", ${JSON.stringify(callbackPreload)}, ...args] : args, ...rest); +}; +module.exports = selectedAnswers; +`, + { mode: 0o600 }, + ); + fs.writeFileSync( + callbackPreload, + // Only the recognized, host-bound resolver child loads this callback fixture. + `const answers = require(${JSON.stringify(preload)}); +require("node:dns").lookup = (_hostname, _options, callback) => { + queueMicrotask(() => callback(null, answers())); +}; +`, + { mode: 0o600 }, + ); + const result = await run(`--require=${JSON.stringify(preload)}`); + // An unused preload cannot establish that the CLI command saw the intended DNS input. + if (fs.readFileSync(observed, "utf8") !== JSON.stringify(addresses)) { + throw new Error("MCP command did not consume the controlled DNS answers"); + } + return result; + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } +} + +export async function assertSharedHostMcpComposition(options: { + adapter: McpAdapter; + host: HostCliClient; + sandbox: SandboxClient; + cleanup: CleanupRegistry; + artifacts: ArtifactSink; + progress: TestProgress; + sandboxName: string; +}): Promise { + const { adapter, host, sandbox, cleanup, artifacts, progress, sandboxName } = options; + if (adapter === "openclaw-config") { + await approveOpenClawAdminScope(host, sandbox, sandboxName, buildAvailabilityProbeEnv(), [ + MCP_BRIDGE_TEST_CREDENTIALS.compatibleEndpoint, + MCP_BRIDGE_TEST_CREDENTIALS.host, + ]); + } + const endpoint = await startFakeMcpHttpsServer({ + secret: MCP_BRIDGE_TEST_CREDENTIALS.host, + additionalPaths: { "/mcp-peer": MCP_BRIDGE_TEST_CREDENTIALS.rotatedHost }, + }); + cleanup.add("stop shared-host MCP endpoint", () => endpoint.close()); + const tunnel = await startPublicMcpHttpsTunnel({ + cleanup, + progress, + server: endpoint, + label: "shared-host MCP", + }); + const hostname = new URL(tunnel.origin).hostname; + const resolved = await dns.lookup(hostname, { all: true, verbatim: true }); + const answers = [ + ...new Map( + resolved.map((answer) => [ + answer.address.toLowerCase(), + { ...answer, address: answer.address.toLowerCase() }, + ]), + ).values(), + ].sort((a, b) => a.address.localeCompare(b.address)); + if (answers.length < 2) + throw new Error("Shared-host MCP fixture requires multiple public DNS answers"); + const firstPins = answers.map((answer) => answer.address).sort(); + const entries = [ + { + server: "shared-one", + pathname: "/mcp", + key: "SHARED_ONE_MCP_SECRET", + secret: MCP_BRIDGE_TEST_CREDENTIALS.host, + answers, + }, + { + server: "shared-two", + pathname: "/mcp-peer", + key: "SHARED_TWO_MCP_SECRET", + secret: MCP_BRIDGE_TEST_CREDENTIALS.rotatedHost, + answers: answers.slice(1), + }, + ]; + await artifacts.writeJson( + "mcp-shared-host-dns-answers.json", + entries.map(({ server, answers }) => ({ server, answers })), + ); + const remove = entries.map((entry) => { + let complete = false; + const provider = `${sandboxName}-mcp-${entry.server}`; + const run = async () => { + if (complete) return; + await cleanupMcpBridge(host, sandboxName, entry.server, adapter); + const deleted = await host.command( + host.openshellCommandPath, + ["provider", "delete", provider], + { + env: buildAvailabilityProbeEnv(), + artifactName: `shared-host-delete-${entry.server}`, + timeoutMs: 60_000, + }, + ); + assertCleanupSucceededOrAbsent( + deleted, + /provider[^\n]*(?:not found|does not exist)|NOT_FOUND/iu, + `remove owned shared-host provider ${provider}`, + ); + complete = true; + }; + cleanup.add(`remove shared-host MCP registration and provider ${entry.server}`, run); + return run; + }); + await withMcpDnsAnswers(hostname, answers, async (statusNodeOptions) => { + for (const entry of entries) { + await withMcpDnsAnswers(hostname, entry.answers, (addNodeOptions) => + addBridgeAndReadStatus(host, sandbox, { + sandboxName, + mcpUrl: `${tunnel.origin}${entry.pathname}`, + expectedAdapter: adapter, + artifactPrefix: entry.server, + serverName: entry.server, + credentialEnvName: entry.key, + credential: entry.secret, + applyHostPolicyEdit: false, + addNodeOptions, + statusNodeOptions, + }), + ); + } + }); + for (const entry of entries) { + const captured = await captureManagedMcpPolicy(sandbox, { + sandboxName, + url: `${tunnel.origin}${entry.pathname}`, + policyKey: buildMcpBridgePolicyKey(entry.server), + artifactName: `${entry.server}-effective-pins`, + label: "shared-host effective pins", + }); + expect(captured.policy.endpoints?.[0]?.allowed_ips).toEqual(firstPins); + const requestOffset = endpoint.requests.length; + const accepted = await runMcpProviderRewriteProbe( + sandbox, + sandboxName, + `${tunnel.origin}${entry.pathname}`, + "tools/list", + "allow", + `${entry.server}-authenticated`, + entry.key, + undefined, + adapter, + ); + assertExitZero(accepted, `${entry.server} authenticated request after both adds`); + const observed = endpoint.requests + .slice(requestOffset) + .filter((request) => request.path === entry.pathname); + expect(observed.length).toBeGreaterThan(0); + expect( + observed.every( + (request) => request.auth === `Bearer ${entry.secret}` && request.responseStatus === 200, + ), + ).toBe(true); + } + const requestOffset = endpoint.requests.length; + for (const [index, entry] of entries.entries()) { + const peer = entries[1 - index]; + const peerRequestOffset = endpoint.requests.length; + const withheld = await runMcpProviderRewriteProbe( + sandbox, + sandboxName, + `${tunnel.origin}${peer.pathname}`, + "tools/list", + "withhold", + `${entry.server}-credential-at-${peer.server}`, + entry.key, + undefined, + adapter, + ); + assertExitZero(withheld, `${entry.server} credential cannot authorize ${peer.server}`); + const peerRequests = endpoint.requests + .slice(peerRequestOffset) + .filter((request) => request.path === peer.pathname); + expect( + peerRequests.every( + (request) => !request.auth.includes(entry.secret) && request.responseStatus === 401, + ), + ).toBe(true); + const denied = await runMcpProviderRewriteProbe( + sandbox, + sandboxName, + `${tunnel.origin}/unconfigured`, + "tools/list", + "deny-strict", + `${entry.server}-outside-binding`, + entry.key, + undefined, + adapter, + ); + assertExitZero(denied, `${entry.server} credential cannot reach an unconfigured path`); + } + expect( + endpoint.requests.slice(requestOffset).filter((request) => request.path === "/unconfigured"), + ).toHaveLength(0); + for (const run of remove) await run(); + const list = await host.nemoclaw([sandboxName, "mcp", "list", "--json"], { + env: buildAvailabilityProbeEnv(), + artifactName: "shared-host-registrations-removed", + timeoutMs: 60_000, + }); + assertExitZero(list, "list registrations after shared-host cleanup"); + const names = (JSON.parse(list.stdout).bridges as Array<{ server: string }>).map( + (entry) => entry.server, + ); + expect(names.filter((name) => entries.some((entry) => entry.server === name))).toEqual([]); + for (const entry of entries) { + const absent = await host.command( + host.openshellCommandPath, + ["provider", "get", `${sandboxName}-mcp-${entry.server}`], + { + env: buildAvailabilityProbeEnv(), + artifactName: `${entry.server}-provider-absent`, + timeoutMs: 60_000, + }, + ); + expectExitNonZero( + absent, + "shared-host provider removed", + /not found|does not exist|NOT_FOUND/iu, + ); + } +} diff --git a/test/e2e/live/mcp-bridge.test.ts b/test/e2e/live/mcp-bridge.test.ts index b166e73e5b0..4e8a7ef4d21 100644 --- a/test/e2e/live/mcp-bridge.test.ts +++ b/test/e2e/live/mcp-bridge.test.ts @@ -14,9 +14,10 @@ import { shellQuote } from "../../../src/lib/core/shell-quote"; import type { McpSourceEntry } from "../../../src/lib/actions/sandbox/mcp-bridge-contracts"; import { execTimeout, testTimeout } from "../../helpers/timeouts.ts"; import type { ArtifactSink } from "../fixtures/artifacts.ts"; -import { approveOpenClawAdminScope } from "./openclaw-admin-scope.ts"; +import { loadAgent } from "../../../src/lib/agent/defs"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; import type { CleanupRegistry } from "../fixtures/cleanup.ts"; +import type { TestProgress } from "../fixtures/progress.ts"; import { assertExitZero as expectExitZero, resultText } from "../fixtures/clients/command.ts"; import type { HostCliClient } from "../fixtures/clients/host.ts"; import { type SandboxClient, trustedSandboxShellScript } from "../fixtures/clients/sandbox.ts"; @@ -58,6 +59,7 @@ import { requireMcpBridgeTlsCaCert, } from "./mcp-bridge-onboard-env.ts"; import { MCP_BRIDGE_PHASES } from "./mcp-bridge-phases.ts"; +import { assertSharedHostMcpComposition } from "./mcp-bridge-shared-host.ts"; import { DEEPAGENTS_MCP_DENIED_TOOL_PROBE, HERMES_MCP_ENV_LOAD_COMMANDS, @@ -135,6 +137,8 @@ async function onboardAgent( agent: McpAgent; sandboxName: string; artifactName: string; + artifacts: ArtifactSink; + progress: TestProgress; envOverlay?: NodeJS.ProcessEnv; }, ): Promise { @@ -173,6 +177,15 @@ async function onboardAgent( }); expectExitZero(result, `onboard ${options.agent} sandbox for MCP bridge`); assertMcpBridgeManagedRegistryReceipt(options.sandboxName, options.agent, REGISTRY_FILE); + await assertSharedHostMcpComposition({ + host, + sandbox, + cleanup, + artifacts: options.artifacts, + progress: options.progress, + sandboxName: options.sandboxName, + adapter: loadAgent(options.agent).mcpCapability.adapter!, + }); } async function assertSecretAbsentFromSandbox( sandbox: SandboxClient, @@ -611,22 +624,15 @@ async function replaceBridgeCredentialConservatively( host: HostCliClient, sandbox: SandboxClient, fakeMcp: Awaited>, - adapter: McpAdapter, - sandboxName: string, - mcpUrl: string, + options: { + agent: McpAgent; + artifactPrefix: string; + sandboxName: string; + mcpUrl: string; + }, ): Promise { - const artifactPrefix = - adapter === "openclaw-config" - ? "openclaw" - : adapter === "hermes-config" - ? "hermes" - : "deepagents"; - const agent: McpAgent = - adapter === "openclaw-config" - ? "openclaw" - : adapter === "hermes-config" - ? "hermes" - : "langchain-deepagents-code"; + const { agent, artifactPrefix, sandboxName, mcpUrl } = options; + const adapter = loadAgent(agent).mcpCapability.adapter!; const providerName = `${sandboxName}-mcp-${SERVER_NAME}`; const bridge = { sandboxName, mcpUrl, artifactPrefix }; const restart = await host.nemoclaw([sandboxName, "mcp", "restart", SERVER_NAME], { @@ -723,16 +729,11 @@ test( await onboardAgent(host, sandbox, cleanup, endpointUrl, { ...bridge, artifactName: "onboard-openclaw-mcp-bridge", + artifacts, + progress, }); - await approveOpenClawAdminScope( - host, - sandbox, - OPENCLAW_SANDBOX_NAME, - buildAvailabilityProbeEnv(), - [COMPATIBLE_KEY, HOST_SECRET], - ); - // Prove raw OpenShell allowed_ips with curl and a /** grant before MCP - // mutation. The helper restores the exact base policy before returning. + // Prove raw OpenShell allowed_ips with curl and a /** grant before ordinary + // lifecycle checks. The helper restores the exact base policy before returning. await runFullMcpBridgeE2eCoverage(mcpBridgeE2eScope, () => assertRawOpenShellAllowedIpsRebindingDenied({ artifacts, @@ -830,7 +831,7 @@ test( cleanupMcpBridge(host, OPENCLAW_SANDBOX_NAME, "distinct", "openclaw-config"), ); await addBridgeAndReadStatus(host, sandbox, { - ...bridge, + sandboxName: OPENCLAW_SANDBOX_NAME, mcpUrl: distinctTunnel.url, expectedAdapter: "openclaw-config", serverName: "distinct", @@ -1006,14 +1007,7 @@ test( expect(updateProof.lastCall).toMatchObject({ auth: `Bearer ${HOST_SECRET}`, }); - await replaceBridgeCredentialConservatively( - host, - sandbox, - fakeMcp, - "openclaw-config", - OPENCLAW_SANDBOX_NAME, - mcpUrl, - ); + await replaceBridgeCredentialConservatively(host, sandbox, fakeMcp, bridge); await assertRealAdapterToolCall(host, sandbox, fakeMcp, { ...bridge, resultToken: MCP_RESULT, @@ -1121,6 +1115,8 @@ mcpBridgeShardTest("hermes")( await onboardAgent(host, sandbox, cleanup, endpointUrl, { ...bridge, artifactName: "onboard-hermes-mcp-bridge", + artifacts, + progress, }); cleanup.add("remove Hermes MCP bridge", () => cleanupMcpBridge(host, HERMES_SANDBOX_NAME, SERVER_NAME, "hermes-config"), @@ -1218,14 +1214,7 @@ mcpBridgeShardTest("hermes")( await restartBridgeWithoutHostSecret(host, HERMES_SANDBOX_NAME, "hermes"); await assertHermesToolCall("hermes-real-mcp-tool-call-after-rediscovery-restart"); await assertAuthenticatedMcpRediscovery(survivingMcp, survivingDiscoveryOffset); - await replaceBridgeCredentialConservatively( - host, - sandbox, - fakeMcp, - "hermes-config", - HERMES_SANDBOX_NAME, - mcpUrl, - ); + await replaceBridgeCredentialConservatively(host, sandbox, fakeMcp, bridge); await assertRealAdapterToolCall(host, sandbox, fakeMcp, { ...bridge, resultToken: MCP_RESULT, @@ -1354,6 +1343,8 @@ mcpBridgeShardTest("deepagents")( await onboardAgent(host, sandbox, cleanup, endpointUrl, { ...bridge, artifactName: "onboard-deepagents-mcp-bridge", + artifacts, + progress, envOverlay: exactMainProof.envOverlay, }); await exactMainProof.afterOnboard(); @@ -1419,14 +1410,7 @@ mcpBridgeShardTest("deepagents")( deniedTool: MCP_BRIDGE_DENIED_TOOL_NAME, }); await exactMainProof.assertSnapshotResidue("after-restart-tool-call"); - await replaceBridgeCredentialConservatively( - host, - sandbox, - fakeMcp, - "deepagents-config", - sandboxName, - mcpUrl, - ); + await replaceBridgeCredentialConservatively(host, sandbox, fakeMcp, bridge); await assertRealAdapterToolCall(host, sandbox, fakeMcp, { ...bridge, resultToken: MCP_RESULT, diff --git a/test/e2e/live/mcp-provider-rewrite-probe.ts b/test/e2e/live/mcp-provider-rewrite-probe.ts index b6b4088bc34..44bb3db93b7 100644 --- a/test/e2e/live/mcp-provider-rewrite-probe.ts +++ b/test/e2e/live/mcp-provider-rewrite-probe.ts @@ -59,13 +59,13 @@ const req = https.request({ res.on("end", () => { console.log(JSON.stringify({ status: res.statusCode, body: data })); const allowed = res.statusCode === 200 && data.includes('"result"'); - const denied = res.statusCode === 403; + const denied = res.statusCode === 403 || (expectation === "withhold" && res.statusCode === 401); process.exit(expectation === "allow" ? (allowed ? 0 : 1) : (denied ? 0 : 1)); }); }); req.on("error", (error) => { console.error(error.message); - const strictDenied = expectation === "deny-strict" && /HTTP\\/1\\.[01] 403 Forbidden/.test(error.message); + const strictDenied = (expectation === "deny-strict" || expectation === "withhold") && /HTTP\\/1\\.[01] 403 Forbidden/.test(error.message); strictDenied && console.log(JSON.stringify({ status: 403, error: error.message })); process.exit(expectation === "deny" || strictDenied ? 0 : 1); }); diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 395be47ebb7..11c902d7810 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -826,6 +826,7 @@ "test/e2e/live/mcp-bridge-onboard-env.ts", "test/e2e/live/mcp-bridge-reliability.ts", "test/e2e/live/mcp-bridge-servers.ts", + "test/e2e/live/mcp-bridge-shared-host.ts", "test/e2e/fixtures/mcp-fixture-tls.ts", "test/e2e/live/mcp-bridge-hermes-lifecycle.ts", "test/e2e/live/mcp-bridge-phases.ts", @@ -859,6 +860,8 @@ "test/e2e/support/mcp-bridge-hermes-http.test.ts", "test/e2e/support/mcp-bridge-onboard-env.test.ts", "test/e2e/support/mcp-bridge-reliability.test.ts", + "test/e2e/support/mcp-bridge-shared-host.test.ts", + "test/e2e/support/mcp-bridge-status-dns.test.ts", "test/e2e/support/retry-policy.test.ts", "test/e2e/support/mcp-bridge-sandbox.test.ts", "test/e2e/support/mcp-bridge-tool-discovery.test.ts", diff --git a/test/e2e/support/mcp-bridge-shared-host.test.ts b/test/e2e/support/mcp-bridge-shared-host.test.ts new file mode 100644 index 00000000000..2682a33b42e --- /dev/null +++ b/test/e2e/support/mcp-bridge-shared-host.test.ts @@ -0,0 +1,489 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { execFileSync, spawnSync } from "node:child_process"; +import dns from "node:dns/promises"; +import fs from "node:fs"; +import https from "node:https"; +import path from "node:path"; +import os from "node:os"; +import { shellQuote } from "../../../src/lib/core/shell-quote"; +import { SOURCE_REQUIRE_HOOK } from "../../helpers/source-loader-options"; +import { MCP_PROVIDER_REWRITE_PROBE_SOURCE } from "../live/mcp-provider-rewrite-probe.ts"; +import { afterAll, afterEach, expect, it, vi } from "vitest"; +import { createMcpFixtureTls } from "../fixtures/mcp-fixture-tls.ts"; +import { + assertSharedHostMcpComposition, + withMcpDnsAnswers, +} from "../live/mcp-bridge-shared-host.ts"; +import * as bridgeCleanup from "../live/mcp-bridge-cleanup.ts"; +import * as reliability from "../live/mcp-bridge-reliability.ts"; +import * as servers from "../live/mcp-bridge-servers.ts"; +import * as adminScope from "../live/openclaw-admin-scope.ts"; +import * as sandboxProbes from "../live/mcp-bridge-sandbox.ts"; +import { MCP_BRIDGE_TEST_CREDENTIALS } from "../fixtures/mcp-bridge-credentials.ts"; +import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; +import { startFakeMcpHttpsServer } from "../live/mcp-bridge-servers.ts"; + +const { tls, close } = createMcpFixtureTls(); +afterAll(close); +afterEach(() => vi.restoreAllMocks()); + +it("controls only the selected host lookup and removes its DNS preload afterward", async () => { + const answers = [ + { address: "8.8.8.8", family: 4 }, + { address: "8.8.4.4", family: 4 }, + ]; + let directory = ""; + await withMcpDnsAnswers("shared.example.test", answers, async (nodeOptions) => { + directory = path.dirname(JSON.parse(nodeOptions.slice("--require=".length)) as string); + const script = ` +const dns = require("node:dns/promises"); +Promise.all([ + dns.lookup("shared.example.test", { all: true, verbatim: true }), + dns.lookup("127.0.0.1", { all: true, verbatim: true }), +]).then(result => process.stdout.write(JSON.stringify(result))); +`; + const output = execFileSync(process.execPath, ["-e", script], { + env: { ...process.env, NODE_OPTIONS: nodeOptions }, + encoding: "utf8", + timeout: 10_000, + }); + expect(JSON.parse(output)).toEqual([answers, [{ address: "127.0.0.1", family: 4 }]]); + }); + expect(fs.existsSync(directory)).toBe(false); +}); + +it("rejects an unused DNS preload and removes it when the add fails", async () => { + const answers = [{ address: "8.8.8.8", family: 4 }]; + let directory = ""; + await expect( + withMcpDnsAnswers("shared.example.test", answers, async (nodeOptions) => { + directory = path.dirname(JSON.parse(nodeOptions.slice("--require=".length)) as string); + }), + ).rejects.toThrow(/ENOENT/u); + expect(fs.existsSync(directory)).toBe(false); + await expect( + withMcpDnsAnswers("shared.example.test", answers, async (nodeOptions) => { + directory = path.dirname(JSON.parse(nodeOptions.slice("--require=".length)) as string); + throw new Error("add refused"); + }), + ).rejects.toThrow("add refused"); + expect(fs.existsSync(directory)).toBe(false); +}); + +function lookupSharedHostAnswers( + nodeOptions: string, + bounded = false, +): Array<{ address: string; family: number }> { + return JSON.parse( + execFileSync( + process.execPath, + [ + "--require", + SOURCE_REQUIRE_HOOK, + "-e", + bounded + ? 'require("./src/lib/adapters/dns/resolve.js").resolveHostAddressesBounded("shared.example.test", 2_000).then(answers => process.stdout.write(JSON.stringify(answers)))' + : 'require("node:dns/promises").lookup("shared.example.test", { all: true }).then(answers => process.stdout.write(JSON.stringify(answers)))', + ], + { env: { ...process.env, NODE_OPTIONS: nodeOptions }, encoding: "utf8", timeout: 10_000 }, + ), + ); +} + +it.each(["shared-one", "shared-two"])( + "holds status DNS steady when live answers change for %s", + async (driftingServer) => { + type Options = Parameters[0]; + const firstAnswers = [ + { address: "104.16.230.132", family: 4 }, + { address: "104.16.231.132", family: 4 }, + ]; + const liveAnswers = [ + ...firstAnswers, + { address: "2606:4700::6810:e684", family: 6 }, + { address: "2606:4700::6810:e784", family: 6 }, + ]; + const observations: Array<{ server: string; command: string; answers: typeof firstAnswers }> = + []; + vi.spyOn(adminScope, "approveOpenClawAdminScope").mockResolvedValue(); + vi.spyOn(servers, "startFakeMcpHttpsServer").mockResolvedValue({ + close: vi.fn(), + } as unknown as Awaited>); + vi.spyOn(servers, "startPublicMcpHttpsTunnel").mockResolvedValue({ + origin: "https://shared.example.test", + } as Awaited>); + vi.spyOn(dns, "lookup").mockResolvedValue(firstAnswers as never); + const stop = new Error("stop after controlled DNS handoff"); + vi.spyOn(sandboxProbes, "captureManagedMcpPolicy").mockRejectedValue(stop); + const host = { + nemoclaw: vi.fn(async (args: string[], options: { env: NodeJS.ProcessEnv }) => { + const [, , command, server] = args; + const nodeOptions = options.env.NODE_OPTIONS; + const answers = nodeOptions + ? lookupSharedHostAnswers(nodeOptions, command === "status") + : server === driftingServer + ? liveAnswers + : firstAnswers; + observations.push({ server, command, answers }); + const pins = answers.map((entry) => entry.address); + return { + exitCode: 0, + stderr: "", + stdout: JSON.stringify({ + server, + url: `https://shared.example.test${server === "shared-one" ? "/mcp" : "/mcp-peer"}`, + support: { adapter: "openclaw-config" }, + env: { + names: [server === "shared-one" ? "SHARED_ONE_MCP_SECRET" : "SHARED_TWO_MCP_SECRET"], + ready: true, + }, + provider: { + name: `alpha-mcp-${server}`, + present: true, + attached: true, + state: "configured", + }, + policy: { name: `mcp-bridge-${server}`, present: true, state: "configured" }, + adapter: { registered: true }, + warnings: + pins.join(",") === firstAnswers.map((entry) => entry.address).join(",") + ? [] + : [ + "Public DNS answers differ from the recorded pins. Run mcp update --refresh-public-pins to refresh the live policy.", + ], + }), + }; + }), + } as unknown as Options["host"]; + await expect( + assertSharedHostMcpComposition({ + adapter: "openclaw-config", + host, + sandbox: {} as Options["sandbox"], + cleanup: { add: vi.fn() } as unknown as Options["cleanup"], + artifacts: { writeJson: vi.fn() } as unknown as Options["artifacts"], + progress: {} as Options["progress"], + sandboxName: "alpha", + }), + ).rejects.toThrow(stop.message); + expect(observations).toEqual([ + { server: "shared-one", command: "add", answers: firstAnswers }, + { server: "shared-one", command: "status", answers: firstAnswers }, + { server: "shared-two", command: "add", answers: firstAnswers.slice(1) }, + { server: "shared-two", command: "status", answers: firstAnswers }, + ]); + }, +); + +it("authenticates each MCP path with its own credential through real HTTPS", async () => { + const server = await startFakeMcpHttpsServer({ + secret: "first", + additionalPaths: { "/mcp-peer": "second" }, + tls, + }); + async function request(pathname: string, secret: string): Promise { + return new Promise((resolve, reject) => { + const request = https.request( + `https://127.0.0.1:${server.port}${pathname}`, + { + ca: tls.cert, + method: "POST", + timeout: 5_000, + headers: { authorization: `Bearer ${secret}`, "content-type": "application/json" }, + }, + (response) => { + response.resume(); + response.once("end", () => resolve(response.statusCode ?? 0)); + }, + ); + request.once("error", reject); + request.once("timeout", () => request.destroy(new Error("MCP fixture request timed out"))); + request.end(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" })); + }); + } + try { + expect(await request("/mcp", "first")).toBe(200); + expect(await request("/mcp-peer", "second")).toBe(200); + expect(await request("/mcp", "second")).toBe(401); + expect(await request("/mcp-peer", "first")).toBe(401); + expect(await request("/unconfigured", "first")).toBe(404); + server.setSecret("replacement"); + expect(await request("/mcp", "replacement")).toBe(200); + expect(await request("/mcp-peer", "second")).toBe(200); + } finally { + await server.close(); + } +}); + +it.each(["openclaw-config", "hermes-config", "deepagents-config"] as const)( + "passes %s through shared-host registration and partial-failure cleanup", + async (adapter) => { + type Options = Parameters[0]; + vi.spyOn(adminScope, "approveOpenClawAdminScope").mockResolvedValue(); + vi.spyOn(servers, "startFakeMcpHttpsServer").mockResolvedValue({ + close: vi.fn(), + } as unknown as Awaited>); + vi.spyOn(servers, "startPublicMcpHttpsTunnel").mockResolvedValue({ + origin: "https://shared.example.test", + } as Awaited>); + vi.spyOn(dns, "lookup").mockResolvedValue([ + { address: "8.8.8.8", family: 4 }, + { address: "8.8.4.4", family: 4 }, + ] as never); + const add = vi + .spyOn(reliability, "addBridgeAndReadStatus") + .mockRejectedValue(new Error("stop after registration handoff")); + const remove = vi.spyOn(bridgeCleanup, "cleanupMcpBridge").mockResolvedValue(); + const host = { + command: vi.fn().mockResolvedValue({ exitCode: 0, stdout: "", stderr: "" }), + openshellCommandPath: "openshell", + } as unknown as Options["host"]; + const cleanup = { add: vi.fn() }; + await expect( + assertSharedHostMcpComposition({ + adapter, + host, + sandbox: {} as Options["sandbox"], + cleanup: cleanup as unknown as Options["cleanup"], + artifacts: { writeJson: vi.fn() } as unknown as Options["artifacts"], + progress: {} as Options["progress"], + sandboxName: "alpha", + }), + ).rejects.toThrow("stop after registration handoff"); + expect(add).toHaveBeenCalledWith( + host, + expect.anything(), + expect.objectContaining({ + expectedAdapter: adapter, + serverName: "shared-one", + credentialEnvName: "SHARED_ONE_MCP_SECRET", + }), + ); + const cleanupEntry = cleanup.add.mock.calls.find( + ([name]) => name === "remove shared-host MCP registration and provider shared-one", + ); + await cleanupEntry![1](); + expect(remove).toHaveBeenCalledWith(host, "alpha", "shared-one", adapter); + }, +); + +it.each([ + ["openclaw-config", "nemoclaw-start node -"], + ["hermes-config", "/opt/hermes/.venv/bin/python3 -c"], + ["deepagents-config", "nemoclaw-start /opt/venv/bin/python3 -c"], +] as const)("uses the admitted %s runtime for credential probes", async (adapter, runtime) => { + const result = { exitCode: 0, stdout: "", stderr: "" }; + const execShell = vi.fn().mockResolvedValue(result); + type Sandbox = Parameters[0]; + expect( + await reliability.runMcpProviderRewriteProbe( + { execShell } as unknown as Sandbox, + "alpha", + "https://shared.example.test/mcp", + "tools/list", + "allow", + "shared-host-probe", + "SHARED_ONE_MCP_SECRET", + undefined, + adapter, + ), + ).toBe(result); + expect(execShell.mock.calls[0][1]).toContain(`\n${runtime}`); + expect(execShell.mock.calls[0][1]).toContain("SHARED_ONE_MCP_SECRET"); +}); + +it.each([0, 23])( + "runs Hermes credential probes without restarting its supervisor (exit %s)", + async (exitCode) => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "hermes-mcp-probe-")); + try { + fs.writeFileSync( + path.join(directory, "nemoclaw-start"), + "#!/bin/sh\nprintf '%s\\n' '[SECURITY] Hermes runtime config guard refuses mutation under a foreign PID 1' >&2\nexit 23\n", + { mode: 0o700 }, + ); + const python = execFileSync("python3", ["-c", "import sys; print(sys.executable)"], { + encoding: "utf8", + }).trim(); + const target = "https://shared.example.test/mcp?label=some'quote"; + const execShell = vi.fn().mockResolvedValue({ exitCode: 0, stdout: "", stderr: "" }); + type Sandbox = Parameters[0]; + await reliability.runMcpProviderRewriteProbe( + { execShell } as unknown as Sandbox, + "alpha", + target, + "tools/list", + "allow", + "hermes-process-probe", + "SHARED_ONE_MCP_SECRET", + undefined, + "hermes-config", + ); + const script = (execShell.mock.calls[0][1] as string) + .replace(/\/opt\/hermes\/\.venv\/bin\/python3?(?= )/u, shellQuote(python)) + .replace( + MCP_PROVIDER_REWRITE_PROBE_SOURCE, + `process.stdout.write(JSON.stringify(process.argv.slice(2))); process.exit(${exitCode});`, + ); + const result = spawnSync("sh", ["-c", script], { + encoding: "utf8", + env: { ...process.env, PATH: `${directory}:${process.env.PATH}` }, + timeout: 10_000, + }); + expect(result.status).toBe(exitCode); + expect(result.stderr).toBe(""); + expect(JSON.parse(result.stdout)).toEqual([ + target, + "tools/list", + "allow", + "SHARED_ONE_MCP_SECRET", + ]); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }, +); + +it.each([ + ["withheld", "SHARED_ONE_MCP_SECRET", "success", 2], + ["gateway-rejection", "SHARED_ONE_MCP_SECRET", "success", 2], + ["foreign-credential", "SHARED_ONE_MCP_SECRET", "failure", 1], + ["foreign-credential", "SHARED_TWO_MCP_SECRET", "failure", 2], + ["peer-credential", "SHARED_ONE_MCP_SECRET", "failure", 1], + ["peer-credential", "SHARED_TWO_MCP_SECRET", "failure", 2], + ["transport-failure", "SHARED_ONE_MCP_SECRET", "failure", 1], +] as const)( + "requires configured-peer withholding for %s at %s", + async (behavior, affectedKey, expected, count) => { + type Options = Parameters[0]; + const requests: Array<{ path: string; auth: string; responseStatus: number }> = []; + const peerCalls: string[] = []; + vi.spyOn(adminScope, "approveOpenClawAdminScope").mockResolvedValue(); + vi.spyOn(servers, "startFakeMcpHttpsServer").mockResolvedValue({ + requests, + close: vi.fn(), + } as unknown as Awaited>); + vi.spyOn(servers, "startPublicMcpHttpsTunnel").mockResolvedValue({ + origin: "https://shared.example.test", + } as Awaited>); + vi.spyOn(dns, "lookup").mockResolvedValue([ + { address: "8.8.8.8", family: 4 }, + { address: "8.8.4.4", family: 4 }, + ] as never); + vi.spyOn(reliability, "addBridgeAndReadStatus").mockImplementation( + async (_host, _sandbox, options) => { + lookupSharedHostAnswers(options.addNodeOptions!); + lookupSharedHostAnswers(options.statusNodeOptions!, true); + return ""; + }, + ); + vi.spyOn(sandboxProbes, "captureManagedMcpPolicy").mockResolvedValue({ + policy: { endpoints: [{ allowed_ips: ["8.8.4.4", "8.8.8.8"] }] }, + } as unknown as Awaited>); + const result = (exitCode = 0): ShellProbeResult => ({ + command: [], + exitCode, + stdout: "", + stderr: "", + signal: null, + timedOut: false, + artifacts: { stdout: "", stderr: "", result: "" }, + }); + const entries = [ + { + key: "SHARED_ONE_MCP_SECRET", + own: "/mcp", + peer: "/mcp-peer", + secret: MCP_BRIDGE_TEST_CREDENTIALS.host, + peerSecret: MCP_BRIDGE_TEST_CREDENTIALS.rotatedHost, + }, + { + key: "SHARED_TWO_MCP_SECRET", + own: "/mcp-peer", + peer: "/mcp", + secret: MCP_BRIDGE_TEST_CREDENTIALS.rotatedHost, + peerSecret: MCP_BRIDGE_TEST_CREDENTIALS.host, + }, + ]; + type Plan = { requests: typeof requests; peer: boolean; result: ShellProbeResult }; + const plans = new Map( + entries.flatMap<[string, Plan]>((entry) => { + const selected = entry.key === affectedKey ? behavior : "withheld"; + const peerAuth = { + withheld: `Bearer openshell:resolve:env:v1_${entry.key}`, + "gateway-rejection": "", + "foreign-credential": `Bearer ${entry.secret}`, + "peer-credential": `Bearer ${entry.peerSecret}`, + "transport-failure": "", + }[selected]; + return [ + [ + `${entry.key}:${entry.own}`, + { + requests: [{ path: entry.own, auth: `Bearer ${entry.secret}`, responseStatus: 200 }], + peer: false, + result: result(), + }, + ], + [ + `${entry.key}:${entry.peer}`, + { + requests: peerAuth + ? [ + { + path: entry.peer, + auth: peerAuth, + responseStatus: selected === "peer-credential" ? 200 : 401, + }, + ] + : [], + peer: true, + result: result(selected === "transport-failure" ? 1 : 0), + }, + ], + [`${entry.key}:/unconfigured`, { requests: [], peer: false, result: result() }], + ]; + }), + ); + vi.spyOn(reliability, "runMcpProviderRewriteProbe").mockImplementation( + async (_sandbox, _name, url, _method, expectation, _artifact, key) => { + const pathname = new URL(url).pathname; + const plan = plans.get(`${key}:${pathname}`)!; + requests.push(...plan.requests); + peerCalls.push(...(plan.peer ? [`${key}:${pathname}:${expectation}`] : [])); + return plan.result; + }, + ); + vi.spyOn(bridgeCleanup, "cleanupMcpBridge").mockResolvedValue(); + const host = { + command: vi.fn(async (_command: string, args: string[]) => + args[1] === "get" ? { ...result(1), stderr: "NOT_FOUND" } : result(), + ), + nemoclaw: vi.fn(async () => ({ ...result(), stdout: '{"bridges":[]}' })), + openshellCommandPath: "openshell", + } as unknown as Options["host"]; + const run = assertSharedHostMcpComposition({ + adapter: "openclaw-config", + host, + sandbox: {} as Options["sandbox"], + cleanup: { add: vi.fn() } as unknown as Options["cleanup"], + artifacts: { writeJson: vi.fn() } as unknown as Options["artifacts"], + progress: {} as Options["progress"], + sandboxName: "alpha", + }); + await expect( + run.then( + () => "success", + () => "failure", + ), + ).resolves.toBe(expected); + expect(peerCalls).toEqual( + ["SHARED_ONE_MCP_SECRET:/mcp-peer:withhold", "SHARED_TWO_MCP_SECRET:/mcp:withhold"].slice( + 0, + count, + ), + ); + }, +); diff --git a/test/e2e/support/mcp-bridge-status-dns.test.ts b/test/e2e/support/mcp-bridge-status-dns.test.ts new file mode 100644 index 00000000000..97a327d34a8 --- /dev/null +++ b/test/e2e/support/mcp-bridge-status-dns.test.ts @@ -0,0 +1,79 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import { expect, it } from "vitest"; +import { SOURCE_REQUIRE_HOOK } from "../../helpers/source-loader-options"; +import { withMcpDnsAnswers } from "../live/mcp-bridge-shared-host"; + +it("controls public-pin status through the isolated bounded DNS resolver", async () => { + const answers = [ + { address: "104.16.230.132", family: 4 }, + { address: "104.16.231.132", family: 4 }, + ]; + let observation: unknown; + await withMcpDnsAnswers("shared.example.test", answers, async (nodeOptions) => { + const result = spawnSync( + process.execPath, + [ + "--require", + SOURCE_REQUIRE_HOOK, + "-e", + ` +const childProcess = require("node:child_process"); +const execFile = childProcess.execFile; +const launches = []; +childProcess.execFile = function(file, args, options, callback) { + const child = execFile.call(this, file, args, options, callback); + launches.push({ + hostname: args.at(-1), + fixtureLoaded: child.spawnargs[1] === "--require", + loaderEnvironmentCleared: options.env.NODE_OPTIONS === "" && options.env.NODE_PATH === "", + timeout: options.timeout, + killSignal: options.killSignal, + }); + return child; +}; +const { resolveHostAddressesBounded } = require("./src/lib/adapters/dns/resolve.js"); +const { inspectMcpRecordedPublicTargetPins } = require("./src/lib/actions/sandbox/mcp-bridge-url-validation.js"); +(async () => { + const status = await inspectMcpRecordedPublicTargetPins( + new URL("https://shared.example.test/mcp"), + ["104.16.230.132", "104.16.231.132"], + hostname => resolveHostAddressesBounded(hostname, 2_000), + ); + const unrelated = await resolveHostAddressesBounded("127.0.0.1", 2_000); + process.stdout.write(JSON.stringify({ status, unrelated, launches })); +})().catch(error => { console.error(error); process.exitCode = 1; }); +`, + ], + { + env: { ...process.env, NODE_OPTIONS: nodeOptions }, + encoding: "utf8", + timeout: 20_000, + }, + ); + expect(result.status, result.stderr).toBe(0); + observation = JSON.parse(result.stdout); + }); + expect(observation).toEqual({ + status: { state: "match", currentAddresses: answers.map(({ address }) => address) }, + unrelated: [{ address: "127.0.0.1", family: 4 }], + launches: [ + { + hostname: "shared.example.test", + fixtureLoaded: true, + loaderEnvironmentCleared: true, + timeout: 2_000, + killSignal: "SIGKILL", + }, + { + hostname: "127.0.0.1", + fixtureLoaded: false, + loaderEnvironmentCleared: true, + timeout: 2_000, + killSignal: "SIGKILL", + }, + ], + }); +}, 30_000); diff --git a/test/e2e/support/mcp-provider-rewrite-probe.test.ts b/test/e2e/support/mcp-provider-rewrite-probe.test.ts index 7f093f3883e..3f79bb6fe7d 100644 --- a/test/e2e/support/mcp-provider-rewrite-probe.test.ts +++ b/test/e2e/support/mcp-provider-rewrite-probe.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import vm from "node:vm"; +import { EventEmitter } from "node:events"; import { describe, expect, it } from "vitest"; @@ -88,3 +89,66 @@ describe("managed MCP provider rewrite probe", () => { ); }); }); + +function runRewriteProbe(expectation: string, status: number, error?: string): number { + let exitCode = -1; + const request = Object.assign(new EventEmitter(), { end: () => {} }); + const response = Object.assign(new EventEmitter(), { + statusCode: status, + setEncoding: () => {}, + }); + new vm.Script(MCP_PROVIDER_REWRITE_PROBE_SOURCE).runInNewContext({ + require: () => ({ + request: (_options: unknown, respond: (response: unknown) => void) => { + request.end = error + ? () => { + request.emit("error", new Error(error)); + } + : () => { + respond(response); + response.emit("data", '{"result":{}}'); + response.emit("end"); + }; + return request; + }, + }), + process: { + argv: [ + "node", + "-", + "https://shared.example.test/mcp-peer", + "tools/list", + expectation, + "SOURCE_TOKEN", + ], + env: { SOURCE_TOKEN: "openshell:resolve:env:v1_SOURCE_TOKEN" }, + exit: (code: number) => { + exitCode = code; + }, + }, + Buffer, + URL, + console: { log: () => {}, error: () => {} }, + }); + return exitCode; +} + +it.each([ + [401, undefined, 0], + [403, undefined, 0], + [0, "HTTP/1.1 403 Forbidden", 0], + [200, undefined, 1], + [404, undefined, 1], + [500, undefined, 1], + [0, "ECONNRESET", 1], + [0, "ETIMEDOUT", 1], + [0, "certificate has expired", 1], +])("requires explicit credential rejection for peer status %s / %s", (status, error, expected) => { + expect(runRewriteProbe("withhold", status, error)).toBe(expected); +}); + +it("keeps strict route denial separate from credential withholding", () => { + expect(runRewriteProbe("deny-strict", 401)).toBe(1); + expect(runRewriteProbe("allow", 401)).toBe(1); + expect(runRewriteProbe("deny-strict", 0, "ECONNRESET")).toBe(1); +});