From 14effb273e3858b7c555a0a92624b6306b113138 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 8 Jul 2026 13:09:20 -0700 Subject: [PATCH 01/21] fix(dcode): route fetch_url through managed proxy Signed-off-by: Aaron Erickson --- .../dcode-launcher.sh | 5 + .../managed-dcode-runtime.py | 132 +++++++++- .../patch-managed-deepagents-code.py | 32 +++ .../policy-additions.yaml | 10 + agents/langchain-deepagents-code/start.sh | 9 + docs/reference/network-policies.mdx | 2 +- .../06-deepagents-code-python-egress.sh | 109 ++++++++ ...platform-parity-cloud-experimental.test.ts | 22 ++ .../langchain-deepagents-code-headless.ts | 3 + ...langchain-deepagents-code-patch-fixture.ts | 20 ++ ...eepagents-code-direct-module-patch.test.ts | 239 +++++++++++++++++- ...gchain-deepagents-code-fetch-proxy.test.ts | 83 ++++++ test/langchain-deepagents-code-image.test.ts | 1 - ...ain-deepagents-code-proxy-launcher.test.ts | 12 +- 14 files changed, 674 insertions(+), 5 deletions(-) create mode 100644 test/langchain-deepagents-code-fetch-proxy.test.ts diff --git a/agents/langchain-deepagents-code/dcode-launcher.sh b/agents/langchain-deepagents-code/dcode-launcher.sh index 5c1943df698..f24ffa66fde 100755 --- a/agents/langchain-deepagents-code/dcode-launcher.sh +++ b/agents/langchain-deepagents-code/dcode-launcher.sh @@ -108,6 +108,11 @@ fi _PROXY_URL="http://${PROXY_HOST}:${PROXY_PORT}" _NO_PROXY_VAL="localhost,127.0.0.1,::1,${PROXY_HOST}" +# fetch_url cannot use its direct DNS-pinning transport inside OpenShell's +# proxy-only network namespace. Opt only this managed launch into the explicit +# trusted-proxy transport, using the same root-owned values as inference and +# shell egress. The managed package patch still ignores ambient proxy values. +export DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL="$_PROXY_URL" export HTTP_PROXY="$_PROXY_URL" export HTTPS_PROXY="$_PROXY_URL" export NO_PROXY="$_NO_PROXY_VAL" diff --git a/agents/langchain-deepagents-code/managed-dcode-runtime.py b/agents/langchain-deepagents-code/managed-dcode-runtime.py index 08cd7076e95..05d3fdf0ecb 100644 --- a/agents/langchain-deepagents-code/managed-dcode-runtime.py +++ b/agents/langchain-deepagents-code/managed-dcode-runtime.py @@ -13,8 +13,10 @@ import os import re import stat +from collections.abc import Callable from pathlib import Path -from urllib.parse import urlparse, urlsplit +from typing import Any +from urllib.parse import urljoin, urlparse, urlsplit _MANAGED_STATE_DIR = Path("/sandbox/.deepagents/.state") _AUTH_FILE = _MANAGED_STATE_DIR / "auth.json" @@ -38,11 +40,15 @@ } _OPENSHELL_ENV_PLACEHOLDER_PREFIX = "openshell:resolve:env:" _UPSTREAM_PROVIDER_ENV = "NEMOCLAW_UPSTREAM_PROVIDER" +_FETCH_URL_TRUSTED_PROXY_ENV = ( + "DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL" +) _MANAGED_ADAPTER_PROVIDER = "openai" _NVIDIA_DISPLAY_PROVIDER_ALIASES = frozenset( {"nvidia", "nvidia-prod", "nvidia-nim", "nvidia-router"} ) _DISPLAY_PROVIDER_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}") +_MANAGED_PROXY_HOST = re.compile(r"[A-Za-z0-9._-]+") _MCP_SERVER_NAME = re.compile(r"[A-Za-z][A-Za-z0-9_-]{0,63}") _MCP_ENV_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]{0,127}") _MCP_DNS_NAME = re.compile( @@ -864,6 +870,129 @@ def managed_inference_base_url() -> str: return value +def managed_fetch_proxy_url() -> str | None: + """Return the explicit OpenShell proxy delegated to managed ``fetch_url``. + + The variable is absent when this helper is imported outside the managed + launcher, in which case the upstream direct DNS-pinning transport remains + authoritative. When present, every conventional HTTP(S) proxy variable + must carry the same launcher-derived value. This prevents a mutable ambient + proxy or ``NO_PROXY`` rule from silently replacing the root-owned route. + """ + value = os.environ.get(_FETCH_URL_TRUSTED_PROXY_ENV) + if value is None: + return None + if ( + not value + or len(value) > 2048 + or value != value.strip() + or any(ord(character) < 32 for character in value) + ): + raise RuntimeError("managed fetch URL proxy is invalid") + try: + parsed = urlparse(value) + port = parsed.port + except ValueError as exc: + raise RuntimeError("managed fetch URL proxy is invalid") from exc + if ( + parsed.scheme != "http" + or not parsed.hostname + or port is None + or port < 1 + or parsed.username is not None + or parsed.password is not None + or parsed.path not in {"", "/"} + or parsed.params + or parsed.query + or parsed.fragment + or _MANAGED_PROXY_HOST.fullmatch(parsed.hostname) is None + ): + raise RuntimeError("managed fetch URL proxy is invalid") + for name in ("HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"): + if os.environ.get(name) != value: + raise RuntimeError("managed fetch URL proxy does not match runtime proxy") + return value + + +def managed_fetch_with_redirects( + url: str, + *, + timeout: int, + max_redirects: int, + original_fetch: Callable[..., Any], + validation_error: type[ValueError], +) -> Any: + """Fetch through only the launcher-delegated OpenShell proxy. + + Outside the managed launcher, preserve the pinned upstream transport. In + the managed image, avoid forbidden direct DNS while keeping requests' + ambient proxy discovery and ``NO_PROXY`` disabled. OpenShell's proxy then + remains the authoritative network-policy and SSRF boundary for every hop. + """ + try: + proxy_url = managed_fetch_proxy_url() + except RuntimeError as exc: + # Keep runtime-integrity failures inside fetch_url's structured + # validation result instead of surfacing an opaque tool exception. + raise validation_error(str(exc)) from exc + if proxy_url is None: + return original_fetch(url, timeout=timeout) + + import requests + + def validate_url(candidate: str) -> None: + try: + parsed = urlparse(candidate) + hostname = parsed.hostname + # Force malformed ports through the same structured validation path + # even though requests, rather than this helper, uses the value. + _ = parsed.port + except ValueError as exc: + raise validation_error("URL is malformed") from exc + if parsed.scheme not in {"http", "https"}: + raise validation_error( + f"URL scheme not allowed: {parsed.scheme!r} (must be http or https)" + ) + if not hostname: + raise validation_error("URL is missing a hostname") + if parsed.username is not None or parsed.password is not None: + raise validation_error("URL credentials are not allowed") + try: + hostname.encode("idna").decode("ascii") + except UnicodeError as exc: + raise validation_error( + f"Could not encode hostname {hostname!r} as IDNA: {exc}" + ) from exc + + current_url = url + session = requests.Session() + session.trust_env = False + proxies = {"http": proxy_url, "https": proxy_url} + for _hop in range(max_redirects + 1): + validate_url(current_url) + response = session.get( + current_url, + timeout=timeout, + headers={"User-Agent": "Mozilla/5.0 (compatible; DeepAgents/1.0)"}, + allow_redirects=False, + proxies=proxies, + ) + if 300 <= response.status_code < 400: + location = response.headers.get("Location") + if not location: + raise validation_error( + f"Redirect response (status {response.status_code}) is missing a Location header" + ) + current_url = urljoin(current_url, location) + continue + response.raise_for_status() + return response + + raise requests.exceptions.TooManyRedirects( + f"Exceeded {max_redirects} redirects" + ) + + def managed_display_provider(adapter_provider: object) -> str: """Return the provider label to show for the managed inference adapter. @@ -890,6 +1019,7 @@ def assert_safe_runtime() -> None: """Reject unmanaged runtime credentials before dcode bootstraps settings.""" _assert_safe_environment() _assert_safe_auth_state() + managed_fetch_proxy_url() base_url = managed_inference_base_url() os.environ["OPENAI_BASE_URL"] = base_url os.environ["NEMOCLAW_INFERENCE_BASE_URL"] = base_url diff --git a/agents/langchain-deepagents-code/patch-managed-deepagents-code.py b/agents/langchain-deepagents-code/patch-managed-deepagents-code.py index f75a019af69..a1159dd86a6 100644 --- a/agents/langchain-deepagents-code/patch-managed-deepagents-code.py +++ b/agents/langchain-deepagents-code/patch-managed-deepagents-code.py @@ -419,6 +419,32 @@ def _get_provider_kwargs(provider: str, *, model_name: str | None = None) -> dic } ''' +# Source-of-truth boundary: upstream Deep Agents Code 0.1.34 resolves and pins +# destination DNS locally, then disables environment proxies. That is a sound +# standalone SSRF defense but cannot operate in OpenShell's proxy-only network +# namespace, where direct DNS and direct target connections are rejected. The +# managed launcher supplies an explicit, root-owned proxy URL; this patch keeps +# requests' ambient proxy discovery disabled and delegates every redirect hop to +# that exact proxy, whose network policy and SSRF checks remain authoritative. +TOOLS_PATCH = r''' + +# NemoClaw-managed Deep Agents Code hardening v2. +_nemoclaw_original_fetch_with_redirects = _fetch_with_redirects + + +def _fetch_with_redirects(url: str, *, timeout: int): + """Use only the launcher-delegated OpenShell proxy when configured.""" + from deepagents_code._nemoclaw_managed import managed_fetch_with_redirects + + return managed_fetch_with_redirects( + url, + timeout=timeout, + max_redirects=_MAX_FETCH_REDIRECTS, + original_fetch=_nemoclaw_original_fetch_with_redirects, + validation_error=_UrlValidationError, + ) +''' + MODEL_CONFIG_PATCH = r''' # NemoClaw-managed Deep Agents Code hardening v2. @@ -1126,6 +1152,7 @@ def main() -> None: "app": root / "app.py", "auth_store": root / "auth_store.py", "config": root / "config.py", + "tools": root / "tools.py", "model_config": root / "model_config.py", "agent": root / "agent.py", "update_check": root / "update_check.py", @@ -1189,6 +1216,7 @@ def main() -> None: for name, patch in ( ("entrypoint", ENTRYPOINT_PATCH), ("main", MAIN_PATCH), + ("tools", TOOLS_PATCH), ("agent", AGENT_PATCH), ("status", STATUS_PATCH), ("welcome", WELCOME_PATCH), @@ -1259,6 +1287,9 @@ def main() -> None: "_tracing_enabled", }, ) + _require_functions( + paths["tools"], texts["tools"], {"_fetch_with_redirects"} + ) _require_methods( paths["model_config"], texts["model_config"], @@ -1378,6 +1409,7 @@ def main() -> None: paths["auth_store"], texts["auth_store"], AUTH_STORE_PATCH ) transformed["config"] = _append_patch(paths["config"], texts["config"], CONFIG_PATCH) + transformed["tools"] = _append_patch(paths["tools"], texts["tools"], TOOLS_PATCH) transformed["model_config"] = _append_patch( paths["model_config"], texts["model_config"], MODEL_CONFIG_PATCH ) diff --git a/agents/langchain-deepagents-code/policy-additions.yaml b/agents/langchain-deepagents-code/policy-additions.yaml index 129f4501e16..4cefb8250d1 100644 --- a/agents/langchain-deepagents-code/policy-additions.yaml +++ b/agents/langchain-deepagents-code/policy-additions.yaml @@ -65,6 +65,16 @@ network_policies: - host: api.github.com port: 443 access: full + # GitHub's API and HTML pages link repository file bodies through this + # separate host. Keep the default coding-agent capability read-only even + # though the broader GitHub/API endpoints above support normal git work. + - host: raw.githubusercontent.com + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/**" } + - allow: { method: HEAD, path: "/**" } binaries: - { path: /usr/bin/git } - { path: /usr/local/bin/dcode } diff --git a/agents/langchain-deepagents-code/start.sh b/agents/langchain-deepagents-code/start.sh index 3be24805038..7ce765c280f 100755 --- a/agents/langchain-deepagents-code/start.sh +++ b/agents/langchain-deepagents-code/start.sh @@ -114,6 +114,14 @@ fi _PROXY_URL="http://${PROXY_HOST}:${PROXY_PORT}" _NO_PROXY_VAL="localhost,127.0.0.1,::1,${PROXY_HOST}" +# Deep Agents Code 0.1.34 intentionally ignores environment proxies in +# fetch_url so it can pin direct DNS results against rebinding. OpenShell's +# sandbox instead requires all ordinary egress, including DNS resolution for a +# destination, to stay behind its policy proxy. This explicit variable opts the +# managed package patch into that trusted proxy boundary without teaching the +# upstream tool to trust arbitrary ambient HTTP_PROXY values. It is derived +# only from the root-owned image files validated above. +export DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL="$_PROXY_URL" export HTTP_PROXY="$_PROXY_URL" export HTTPS_PROXY="$_PROXY_URL" export NO_PROXY="$_NO_PROXY_VAL" @@ -150,6 +158,7 @@ prepare_runtime_env() { printf '%s\n' 'export LANGCHAIN_TRACING_V2=false' printf '%s\n' 'export DEEPAGENTS_CODE_OFFLINE=1' printf '%s\n' 'export DEEPAGENTS_CODE_RIPGREP_INSTALLER=system' + write_export_if_set DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL # shellcheck disable=SC2016 printf '%s\n' 'export DEEPAGENTS_CODE_OPENAI_API_KEY="${DEEPAGENTS_CODE_OPENAI_API_KEY:-nemoclaw-managed-inference}"' # shellcheck disable=SC2016 diff --git a/docs/reference/network-policies.mdx b/docs/reference/network-policies.mdx index 6b92282125b..f9b0c08c4f9 100644 --- a/docs/reference/network-policies.mdx +++ b/docs/reference/network-policies.mdx @@ -91,7 +91,7 @@ Use `$$nemoclaw policy-list` or `openshell policy get --base | Policy | Endpoints | Binaries | Rules | | --- | --- | --- | --- | | `managed_inference` | `inference.local:443` | `/usr/local/bin/dcode`, `/opt/venv/bin/python3*`, `/opt/venv/lib/python3.13/**` | POST to OpenAI-compatible completion and embedding paths, GET to model listings | -| `github` | `github.com:443`, `api.github.com:443` | `/usr/bin/git`, `/usr/local/bin/dcode`, `/opt/venv/bin/python3*` | Full access to the listed hosts | +| `github` | `github.com:443`, `api.github.com:443`, `raw.githubusercontent.com:443` | `/usr/bin/git`, `/usr/local/bin/dcode`, `/opt/venv/bin/python3*` | Full access to `github.com` and `api.github.com`; GET and HEAD only to `raw.githubusercontent.com` | | `pypi` | `pypi.org:443`, `files.pythonhosted.org:443` | `/opt/venv/bin/python3*`, `/opt/venv/bin/pip3*` | GET and HEAD for package installation | diff --git a/test/e2e/e2e-cloud-experimental/checks/06-deepagents-code-python-egress.sh b/test/e2e/e2e-cloud-experimental/checks/06-deepagents-code-python-egress.sh index 254a516f02f..a2d759b6230 100755 --- a/test/e2e/e2e-cloud-experimental/checks/06-deepagents-code-python-egress.sh +++ b/test/e2e/e2e-cloud-experimental/checks/06-deepagents-code-python-egress.sh @@ -134,6 +134,87 @@ expect_blocked() { fi } +fetch_url_probe_source() { + cat <<'PY' +import os +import sys + +from deepagents_code.tools import fetch_url + +DENIAL_MARKERS = ( + 'access denied', + 'blocked by', + 'connection forbidden', + 'egress denied', + 'network policy', + 'operation not permitted', + 'permission denied', + 'policy denied', + 'tunnel connection failed', +) + +if not os.environ.get('DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL'): + print('FETCH_ERROR:managed fetch proxy delegation is absent') + raise SystemExit(0) + +result = fetch_url(sys.argv[1], timeout=8) +status = result.get('status_code') +content_length = result.get('content_length') +if ( + isinstance(status, int) + and 200 <= status < 300 + and isinstance(content_length, int) + and content_length > 0 +): + print(f'FETCH_SUCCESS:{status}:{content_length}') +else: + details = str(result.get('error', result)) + lowered = details.lower() + if any(marker in lowered for marker in DENIAL_MARKERS): + print(f'FETCH_BLOCKED:{details}') + else: + print(f'FETCH_ERROR:{details}') +PY +} + +fetch_url_probe() { + local url="$1" + local encoded remote_cmd + if [ -n "${NEMOCLAW_E2E_FETCH_URL_PROBE_FIXTURE+x}" ]; then + printf '%s\n' "$NEMOCLAW_E2E_FETCH_URL_PROBE_FIXTURE" + return 0 + fi + encoded="$(fetch_url_probe_source | base64 | tr -d '\n')" + remote_cmd=". /tmp/nemoclaw-proxy-env.sh && /opt/venv/bin/python3 -c \"\$(printf '%s' ${encoded@Q} | base64 -d)\" ${url@Q}" + sandbox_exec "$remote_cmd" +} + +expect_fetch_reached() { + local label="$1" + local url="$2" + local output + output="$(fetch_url_probe "$url" || true)" + if echo "$output" | grep -Eq 'FETCH_SUCCESS:2[0-9]{2}:[1-9][0-9]*'; then + pass "Deep Agents fetch_url can reach approved ${label} host through the managed proxy" + else + fail_test "Deep Agents fetch_url could not reach approved ${label} host: $output" + fi +} + +expect_fetch_blocked() { + local label="$1" + local url="$2" + local output + output="$(fetch_url_probe "$url" || true)" + if echo "$output" | grep -q "FETCH_BLOCKED:" && ! echo "$output" | grep -q "FETCH_SUCCESS:"; then + pass "Deep Agents fetch_url cannot reach ${label} without explicit policy" + elif echo "$output" | grep -q "FETCH_SUCCESS:"; then + fail_test "Deep Agents fetch_url reached ${label} unexpectedly: $output" + else + fail_test "Deep Agents fetch_url probe for ${label} lacked denial evidence: $output" + fi +} + PASSED=0 FAILED=0 @@ -161,6 +242,23 @@ if [ "${NEMOCLAW_E2E_PYTHON_EGRESS_SELF_TEST:-}" = "probe-command-shape" ]; then exit 0 fi +if [ "${NEMOCLAW_E2E_PYTHON_EGRESS_SELF_TEST:-}" = "fetch-probe-command-shape" ]; then + sandbox_exec() { + case "$1" in + *$'\n'*) + printf '%s\n' "NEWLINE_IN_COMMAND" + return 1 + ;; + *) + printf '%s\n' "NO_NEWLINE_IN_FETCH_COMMAND" + return 0 + ;; + esac + } + fetch_url_probe "https://raw.githubusercontent.com/NVIDIA/NemoClaw/main/README.md" + exit 0 +fi + cleanup_project_venv() { sandbox_exec "rm -rf ${PROJECT_VENV@Q}" >/dev/null || true } @@ -193,6 +291,17 @@ expect_blocked "arbitrary Python" "LangSmith" "https://api.smith.langchain.com/" expect_blocked "arbitrary Python" "MCP hosts" "https://modelcontextprotocol.io/" expect_blocked "arbitrary Python" "unapproved hosts" "https://example.com/" +# Exercise the actual Deep Agents fetch_url transport. Unlike urllib, upstream +# fetch_url disables ambient proxies to pin direct DNS results; the managed +# image patch must instead force the root-owned OpenShell proxy without honoring +# NO_PROXY. The raw GitHub path covers the separate read-only policy endpoint. +expect_fetch_reached \ + "raw GitHub" \ + "https://raw.githubusercontent.com/NVIDIA/NemoClaw/main/README.md" +expect_fetch_blocked "unapproved hosts" "https://example.com/" +expect_fetch_blocked "instance metadata" "http://169.254.169.254/latest/meta-data/" +expect_fetch_blocked "sandbox loopback" "http://127.0.0.1/" + # Exercise the writable-project-venv allowlist entries directly. The managed # /opt/venv Python creates the project venv, then the probes run through the # /sandbox/.../bin/python3 executable path that policy-additions.yaml allows diff --git a/test/e2e/support/platform-parity-cloud-experimental.test.ts b/test/e2e/support/platform-parity-cloud-experimental.test.ts index cd44f0633d4..2184996d60a 100644 --- a/test/e2e/support/platform-parity-cloud-experimental.test.ts +++ b/test/e2e/support/platform-parity-cloud-experimental.test.ts @@ -225,6 +225,28 @@ describe("P0-E cloud-experimental parity guardrails", () => { expect(result.stdout.trim()).toBe("NO_NEWLINE_IN_COMMAND"); }); + it("keeps Deep Agents fetch_url probe command single-line for OpenShell exec", () => { + const result = spawnSync( + "bash", + [ + path.join( + process.cwd(), + "test/e2e/e2e-cloud-experimental/checks/06-deepagents-code-python-egress.sh", + ), + ], + { + encoding: "utf8", + env: { + NEMOCLAW_E2E_PYTHON_EGRESS_SELF_TEST: "fetch-probe-command-shape", + PATH: process.env.PATH ?? "/usr/bin:/bin", + }, + }, + ); + + expect(result.status).toBe(0); + expect(result.stdout.trim()).toBe("NO_NEWLINE_IN_FETCH_COMMAND"); + }); + it("keeps Deep Agents secret-boundary probe command single-line for OpenShell exec", () => { const result = spawnSync( "bash", diff --git a/test/helpers/langchain-deepagents-code-headless.ts b/test/helpers/langchain-deepagents-code-headless.ts index 13d280dbe35..3404c05f3e9 100644 --- a/test/helpers/langchain-deepagents-code-headless.ts +++ b/test/helpers/langchain-deepagents-code-headless.ts @@ -27,6 +27,7 @@ export const PROXY_URL_ENV_NAMES = [ "https_proxy", ] as const; export const NO_PROXY_ENV_NAMES = ["NO_PROXY", "no_proxy"] as const; +export const TRUSTED_FETCH_PROXY_ENV_NAME = "DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL" as const; const CLEARED_PROXY_ENV_NAMES = ["ALL_PROXY", "all_proxy", "OPENAI_PROXY"] as const; export const TRACING_ENABLE_ENV_NAMES = [ "DEEPAGENTS_CODE_LANGSMITH_TRACING", @@ -135,6 +136,7 @@ export function runStartScriptProxyProbe( const probe = [ ...[ ...PROXY_URL_ENV_NAMES, + TRUSTED_FETCH_PROXY_ENV_NAME, ...NO_PROXY_ENV_NAMES, ...CLEARED_PROXY_ENV_NAMES, ...TRACING_ENABLE_ENV_NAMES, @@ -146,6 +148,7 @@ export function runStartScriptProxyProbe( '. "$NEMOCLAW_TEST_PROXY_ENV"', ...[ ...PROXY_URL_ENV_NAMES, + TRUSTED_FETCH_PROXY_ENV_NAME, ...NO_PROXY_ENV_NAMES, ...CLEARED_PROXY_ENV_NAMES, ...TRACING_ENABLE_ENV_NAMES, diff --git a/test/helpers/langchain-deepagents-code-patch-fixture.ts b/test/helpers/langchain-deepagents-code-patch-fixture.ts index e010b08bbe9..7e1d6a8171b 100644 --- a/test/helpers/langchain-deepagents-code-patch-fixture.ts +++ b/test/helpers/langchain-deepagents-code-patch-fixture.ts @@ -190,6 +190,26 @@ def _parse_interpreter_ptc(raw): def _get_provider_kwargs(provider, *, model_name=None): del provider, model_name return {"api_key": "unsafe", "base_url": "https://unsafe.example"} +`, + ); + writeFixtureFile( + packageDir, + "tools.py", + ` +from __future__ import annotations + +from urllib.parse import urljoin, urlparse + +_ALLOWED_URL_SCHEMES = frozenset({"http", "https"}) +_MAX_FETCH_REDIRECTS = 5 + + +class _UrlValidationError(ValueError): + pass + + +def _fetch_with_redirects(url, *, timeout): + return {"transport": "direct", "url": url, "timeout": timeout} `, ); writeFixtureFile( diff --git a/test/langchain-deepagents-code-direct-module-patch.test.ts b/test/langchain-deepagents-code-direct-module-patch.test.ts index 9f2f53faa92..47e22170f60 100644 --- a/test/langchain-deepagents-code-direct-module-patch.test.ts +++ b/test/langchain-deepagents-code-direct-module-patch.test.ts @@ -41,6 +41,7 @@ describe("LangChain Deep Agents Code managed package patch", () => { "app.py", "auth_store.py", "config.py", + "tools.py", "model_config.py", "agent.py", "update_check.py", @@ -84,6 +85,7 @@ describe("LangChain Deep Agents Code managed package patch", () => { it.each([ ["entrypoint", "__main__.py", 'os.environ["LANGGRAPH_CLI_NO_ANALYTICS"] = "1"'], ["main", "main.py", 'os.environ["LANGGRAPH_CLI_NO_ANALYTICS"] = "1"'], + ["tools", "tools.py", "_nemoclaw_original_fetch_with_redirects = _fetch_with_redirects"], [ "agent", "agent.py", @@ -228,6 +230,218 @@ else: } }); + it("routes fetch_url through only the explicit managed proxy without direct DNS", () => { + const tempDir = createPackageFixture(); + patchFixture(tempDir); + const proxyUrl = "http://managed-proxy.internal:3128"; + const result = spawnSync( + "python3", + [ + "-c", + ` +import os +import sys +import types + +calls = [] +responses = [] + +class Response: + def __init__(self, status_code=200, location=None): + self.status_code = status_code + self.headers = {} if location is None else {"Location": location} + + def raise_for_status(self): + return None + +class Session: + def __init__(self): + self.trust_env = True + + def get(self, url, **kwargs): + calls.append((self.trust_env, url, kwargs)) + return responses.pop(0) if responses else Response() + +requests = types.ModuleType("requests") +requests.Session = Session +requests.exceptions = types.SimpleNamespace(TooManyRedirects=RuntimeError) +sys.modules["requests"] = requests + +from deepagents_code import tools +from deepagents_code._nemoclaw_managed import managed_fetch_proxy_url + +def forbidden_direct_dns(*_args, **_kwargs): + raise AssertionError("managed fetch attempted direct DNS validation") + +tools._validate_url = forbidden_direct_dns +response = tools._fetch_with_redirects("https://raw.githubusercontent.com/example/repo/main/README.md", timeout=8) +assert response.status_code == 200 +assert calls == [( + False, + "https://raw.githubusercontent.com/example/repo/main/README.md", + { + "timeout": 8, + "headers": {"User-Agent": "Mozilla/5.0 (compatible; DeepAgents/1.0)"}, + "allow_redirects": False, + "proxies": {"http": ${JSON.stringify(proxyUrl)}, "https": ${JSON.stringify(proxyUrl)}}, + }, +)] + +calls.clear() +responses.extend([ + Response(302, "../main/README.md"), + Response(), +]) +response = tools._fetch_with_redirects( + "https://raw.githubusercontent.com/example/repo/start", + timeout=8, +) +assert response.status_code == 200 +assert [url for _, url, _ in calls] == [ + "https://raw.githubusercontent.com/example/repo/start", + "https://raw.githubusercontent.com/example/main/README.md", +] +assert all( + kwargs["proxies"] + == {"http": ${JSON.stringify(proxyUrl)}, "https": ${JSON.stringify(proxyUrl)}} + for _, _, kwargs in calls +) + +calls.clear() +responses.append(Response(302)) +try: + tools._fetch_with_redirects("https://raw.githubusercontent.com/missing-location", timeout=8) +except tools._UrlValidationError as exc: + assert "missing a Location header" in str(exc) +else: + raise AssertionError("redirect without Location escaped validation") + +calls.clear() +responses.append(Response(302, "https://user:redirect-secret@raw.githubusercontent.com/private")) +try: + tools._fetch_with_redirects("https://raw.githubusercontent.com/credential-redirect", timeout=8) +except tools._UrlValidationError as exc: + assert str(exc) == "URL credentials are not allowed" + assert "redirect-secret" not in str(exc) +else: + raise AssertionError("credentialed redirect escaped validation") +assert len(calls) == 1 + +calls.clear() +responses.append(Response(302, "https://raw.githubusercontent.com/next")) +tools._MAX_FETCH_REDIRECTS = 0 +try: + tools._fetch_with_redirects("https://raw.githubusercontent.com/start", timeout=8) +except RuntimeError as exc: + assert "Exceeded 0 redirects" in str(exc) +else: + raise AssertionError("managed fetch ignored the reviewed upstream redirect cap") +assert len(calls) == 1 + +tools._MAX_FETCH_REDIRECTS = 5 +for malformed in ("https://[broken", "https://example.com:not-a-port"): + try: + tools._fetch_with_redirects(malformed, timeout=8) + except tools._UrlValidationError as exc: + assert str(exc) == "URL is malformed" + else: + raise AssertionError(f"malformed URL escaped validation: {malformed}") + +os.environ["HTTP_PROXY"] = "http://attacker.internal:4444" +try: + tools._fetch_with_redirects("https://raw.githubusercontent.com/example", timeout=8) +except tools._UrlValidationError as exc: + assert str(exc) == "managed fetch URL proxy does not match runtime proxy" + assert "attacker.internal" not in str(exc) +else: + raise AssertionError("proxy-integrity error escaped fetch_url validation") + +for invalid_proxy in ( + "http://user:proxy-secret@proxy.internal:3128", + "http://proxy.internal", + "http://proxy.internal:0", + "http://proxy.internal:70000", + "http://proxy.internal:3128/unexpected", + "http://proxy.internal:3128?route=unsafe", + "http://proxy.internal:3128#fragment", + " http://proxy.internal:3128", + "http://proxy.internal:3128\\n", +): + os.environ["DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL"] = invalid_proxy + for proxy_name in ("HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"): + os.environ[proxy_name] = invalid_proxy + try: + managed_fetch_proxy_url() + except RuntimeError as exc: + assert str(exc) == "managed fetch URL proxy is invalid" + assert "proxy-secret" not in str(exc) + else: + raise AssertionError(f"invalid managed proxy was accepted: {invalid_proxy!r}") +print("managed-fetch-proxy-ok") +`, + ], + { + env: { + PATH: process.env.PATH, + PYTHONPATH: tempDir, + DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL: proxyUrl, + HTTP_PROXY: proxyUrl, + HTTPS_PROXY: proxyUrl, + http_proxy: proxyUrl, + https_proxy: proxyUrl, + NO_PROXY: "raw.githubusercontent.com", + no_proxy: "raw.githubusercontent.com", + }, + encoding: "utf8", + }, + ); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toContain("managed-fetch-proxy-ok"); + + const withoutDelegation = spawnSync( + "python3", + [ + "-c", + [ + "from deepagents_code import tools", + 'result = tools._fetch_with_redirects("https://example.com", timeout=3)', + 'assert result == {"transport": "direct", "url": "https://example.com", "timeout": 3}', + ].join("; "), + ], + { + env: { PATH: process.env.PATH, PYTHONPATH: tempDir }, + encoding: "utf8", + }, + ); + expect(withoutDelegation.status, withoutDelegation.stderr).toBe(0); + + const mismatchedProxy = spawnSync( + "python3", + [ + "-c", + "from deepagents_code._nemoclaw_managed import managed_fetch_proxy_url; managed_fetch_proxy_url()", + ], + { + env: { + PATH: process.env.PATH, + PYTHONPATH: tempDir, + DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL: proxyUrl, + HTTP_PROXY: "http://attacker.internal:4444", + HTTPS_PROXY: proxyUrl, + http_proxy: proxyUrl, + https_proxy: proxyUrl, + }, + encoding: "utf8", + }, + ); + expect(mismatchedProxy.status).not.toBe(0); + expect(mismatchedProxy.stderr).toContain( + "managed fetch URL proxy does not match runtime proxy", + ); + expect(mismatchedProxy.stderr).not.toContain("attacker.internal"); + }); + it("rejects direct-module runtime credentials before settings bootstrap", () => { const tempDir = createPackageFixture(); patchFixture(tempDir); @@ -969,11 +1183,18 @@ async def validate(): project = Path(${JSON.stringify(tempDir)}) / "project" project.mkdir() - (project / ".env").write_text("PROJECT_API_KEY=should-not-load\\n", encoding="utf-8") + (project / ".env").write_text( + "PROJECT_API_KEY=should-not-load\\n" + "DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL=http://attacker.internal:4444\\n", + encoding="utf-8", + ) os.chdir(project) assert config._load_dotenv() is False assert "PROJECT_API_KEY" not in os.environ + assert "DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL" not in os.environ assert "PROJECT_API_KEY" not in config._preview_dotenv_environ() + assert "DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL" not in config._preview_dotenv_environ() + assert _nemoclaw_managed.managed_fetch_proxy_url() is None for name in ( "LANGSMITH_TRACING", "LANGSMITH_TRACING_V2", @@ -1042,5 +1263,21 @@ print("managed-boundaries-ok") }); expect(shapeResult.status).not.toBe(0); expect(shapeResult.stderr).toContain("_prompt_launch_tavily"); + + const missingFetch = createPackageFixture(); + const toolsPath = path.join(missingFetch, "deepagents_code", "tools.py"); + fs.writeFileSync( + toolsPath, + fs + .readFileSync(toolsPath, "utf8") + .replace("def _fetch_with_redirects(", "def _renamed_fetch_with_redirects("), + "utf8", + ); + const fetchShapeResult = spawnSync("python3", [patcher], { + env: { PATH: process.env.PATH, PYTHONPATH: missingFetch }, + encoding: "utf8", + }); + expect(fetchShapeResult.status).not.toBe(0); + expect(fetchShapeResult.stderr).toContain("_fetch_with_redirects"); }); }); diff --git a/test/langchain-deepagents-code-fetch-proxy.test.ts b/test/langchain-deepagents-code-fetch-proxy.test.ts new file mode 100644 index 00000000000..dfd2ac72707 --- /dev/null +++ b/test/langchain-deepagents-code-fetch-proxy.test.ts @@ -0,0 +1,83 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; +import YAML from "yaml"; + +import { + makeStartScriptFixture, + runStartScriptProxyProbe, + TRUSTED_FETCH_PROXY_ENV_NAME, +} from "./helpers/langchain-deepagents-code-headless.ts"; + +const repoRoot = path.resolve(import.meta.dirname, ".."); +const agentDir = path.join(repoRoot, "agents", "langchain-deepagents-code"); + +function readAgentFile(name: string): string { + return fs.readFileSync(path.join(agentDir, name), "utf8"); +} + +describe("LangChain Deep Agents Code managed fetch proxy", () => { + it("persists the root-owned proxy as the explicit fetch_url delegation", () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-dcode-fetch-proxy-")); + try { + const { envFile, scriptPath } = makeStartScriptFixture(tempDir, readAgentFile("start.sh")); + const { envFileText, output } = runStartScriptProxyProbe(scriptPath, envFile, {}); + const managedProxy = "http://10.200.0.1:3128"; + const outputLines = output.trimEnd().split("\n"); + + expect(outputLines).toContain(`RUNTIME_${TRUSTED_FETCH_PROXY_ENV_NAME}=${managedProxy}`); + expect(outputLines).toContain(`SOURCED_${TRUSTED_FETCH_PROXY_ENV_NAME}=${managedProxy}`); + expect(envFileText.trimEnd().split("\n")).toContain( + `export ${TRUSTED_FETCH_PROXY_ENV_NAME}=${managedProxy}`, + ); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }); + + it("allows raw GitHub content only through GET and HEAD", () => { + const policy = YAML.parse(readAgentFile("policy-additions.yaml")) as { + network_policies?: Record> }>; + }; + const rawGitHub = policy.network_policies?.github?.endpoints?.find( + (endpoint) => endpoint.host === "raw.githubusercontent.com", + ); + + expect(rawGitHub).toEqual({ + host: "raw.githubusercontent.com", + port: 443, + protocol: "rest", + enforcement: "enforce", + rules: [ + { allow: { method: "GET", path: "/**" } }, + { allow: { method: "HEAD", path: "/**" } }, + ], + }); + }); + + it("exercises actual fetch_url success and denied-host paths in cloud E2E", () => { + const check = fs.readFileSync( + path.join( + repoRoot, + "test/e2e/e2e-cloud-experimental/checks/06-deepagents-code-python-egress.sh", + ), + "utf8", + ); + + expect(check).toContain("fetch_url_probe_source"); + expect(check).toContain("from deepagents_code.tools import fetch_url"); + expect(check).toContain(TRUSTED_FETCH_PROXY_ENV_NAME); + expect(check).toContain("expect_fetch_reached"); + expect(check).toContain("FETCH_SUCCESS:2[0-9]{2}:[1-9][0-9]*"); + expect(check).toContain("https://raw.githubusercontent.com/NVIDIA/NemoClaw/main/README.md"); + expect(check).toContain('expect_fetch_blocked "unapproved hosts" "https://example.com/"'); + expect(check).toContain( + 'expect_fetch_blocked "instance metadata" "http://169.254.169.254/latest/meta-data/"', + ); + expect(check).toContain('expect_fetch_blocked "sandbox loopback" "http://127.0.0.1/"'); + }); +}); diff --git a/test/langchain-deepagents-code-image.test.ts b/test/langchain-deepagents-code-image.test.ts index 44112c4cb52..ffcd8396b2c 100644 --- a/test/langchain-deepagents-code-image.test.ts +++ b/test/langchain-deepagents-code-image.test.ts @@ -454,7 +454,6 @@ describe("LangChain Deep Agents Code image contracts", () => { it("keeps optional service egress out of the default policy and requires Landlock", () => { const policy = readAgentFile("policy-additions.yaml"); - expect(policy).not.toContain("api.tavily.com"); expect(policy).not.toContain("api.smith.langchain.com"); expect(policy).not.toContain("supabase.co"); diff --git a/test/langchain-deepagents-code-proxy-launcher.test.ts b/test/langchain-deepagents-code-proxy-launcher.test.ts index b38c806ad0d..9d6dcec023b 100644 --- a/test/langchain-deepagents-code-proxy-launcher.test.ts +++ b/test/langchain-deepagents-code-proxy-launcher.test.ts @@ -21,6 +21,7 @@ const headlessCheckPath = path.join( const PROXY_URL_ENV_NAMES = ["HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"] as const; const NO_PROXY_ENV_NAMES = ["NO_PROXY", "no_proxy"] as const; const CLEARED_PROXY_ENV_NAMES = ["ALL_PROXY", "all_proxy", "OPENAI_PROXY"] as const; +const TRUSTED_FETCH_PROXY_ENV_NAME = "DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL"; const DEFAULT_MANAGED_PROXY = { host: "10.200.0.1", port: "3128" } as const; const TEST_OWNER_UID = process.getuid?.() ?? 0; @@ -66,7 +67,7 @@ function makeLauncherProxyProbeFixture( const probePath = path.join(tempDir, "managed-dcode-probe.sh"); const probe = [ "#!/bin/bash -p", - "for name in HTTP_PROXY HTTPS_PROXY NO_PROXY http_proxy https_proxy no_proxy ALL_PROXY all_proxy OPENAI_PROXY NEMOCLAW_PROXY_HOST NEMOCLAW_PROXY_PORT NEMOCLAW_OBSERVABILITY; do", + `for name in HTTP_PROXY HTTPS_PROXY NO_PROXY http_proxy https_proxy no_proxy ALL_PROXY all_proxy OPENAI_PROXY ${TRUSTED_FETCH_PROXY_ENV_NAME} NEMOCLAW_PROXY_HOST NEMOCLAW_PROXY_PORT NEMOCLAW_OBSERVABILITY; do`, ' printf \'LAUNCHER_%s=%s\\n\' "$name" "${!name-__unset__}"', "done", "", @@ -222,6 +223,7 @@ describe("Deep Agents Code direct-exec proxy launcher", () => { for (const name of PROXY_URL_ENV_NAMES) { expect(lines).toContain(`LAUNCHER_${name}=${managedProxy}`); } + expect(lines).toContain(`LAUNCHER_${TRUSTED_FETCH_PROXY_ENV_NAME}=${managedProxy}`); for (const name of NO_PROXY_ENV_NAMES) { expect(lines).toContain(`LAUNCHER_${name}=${managedNoProxy}`); } @@ -312,6 +314,7 @@ describe("Deep Agents Code direct-exec proxy launcher", () => { 'export PATH="/usr/local/bin:/opt/venv/bin:/usr/local/sbin:/usr/sbin:/usr/bin:/sbin:/bin"', ); expect(launcher).toContain('export HTTPS_PROXY="$_PROXY_URL"'); + expect(launcher).toContain('export DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL="$_PROXY_URL"'); expect(launcher).toContain('export no_proxy="$_NO_PROXY_VAL"'); expect(launcher).toContain("unset ALL_PROXY all_proxy OPENAI_PROXY"); }); @@ -327,6 +330,7 @@ describe("Deep Agents Code direct-exec proxy launcher", () => { ALL_PROXY: "socks5://all-user:all-password@all-proxy.example:1080", all_proxy: "socks5://lower-all-user:lower-all-password@lower-all-proxy.example:1080", OPENAI_PROXY: "http://openai-user:openai-password@attacker.example:8080", + DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL: "http://attacker-proxy.internal:4444", NEMOCLAW_PROXY_HOST: "attacker-proxy.internal", NEMOCLAW_PROXY_PORT: "4444", }; @@ -355,6 +359,12 @@ describe("Deep Agents Code direct-exec proxy launcher", () => { "START_PROXY=http://trusted-proxy.internal:3129|localhost,127.0.0.1,::1,trusted-proxy.internal|__unset__|__unset__|__unset__|__unset__", ); expect(envFileText).toContain("export HTTPS_PROXY=http://trusted-proxy.internal:3129"); + expect(envFileText).toContain( + "export DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL=http://trusted-proxy.internal:3129", + ); + expect(launcherResult.stdout).toContain( + "LAUNCHER_DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL=http://trusted-proxy.internal:3129", + ); expect(envFileText).toContain( "export NO_PROXY=localhost\\,127.0.0.1\\,::1\\,trusted-proxy.internal", ); From 9a1745b1224dc593ada804d3a62c57b8f08c187a Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 8 Jul 2026 13:21:44 -0700 Subject: [PATCH 02/21] fix(dcode): verify managed fetch proxy source Signed-off-by: Aaron Erickson --- .../dependency-review.md | 26 +++++++ .../managed-dcode-runtime.py | 53 +++++++++++++ docs/reference/network-policies.mdx | 6 ++ ...eepagents-code-direct-module-patch.test.ts | 38 +++------- ...gchain-deepagents-code-fetch-proxy.test.ts | 75 +++++++++++++++++++ 5 files changed, 172 insertions(+), 26 deletions(-) diff --git a/agents/langchain-deepagents-code/dependency-review.md b/agents/langchain-deepagents-code/dependency-review.md index e74f6574565..71d4665837a 100644 --- a/agents/langchain-deepagents-code/dependency-review.md +++ b/agents/langchain-deepagents-code/dependency-review.md @@ -14,6 +14,32 @@ Update it whenever `requirements.lock` changes. The Dockerfile installs this lockfile with `pip3 install --require-hashes`, so this review covers the exact package versions selected for the managed image install. +## Managed `fetch_url` Proxy Adapter + +Deep Agents Code `0.1.34` deliberately disables ambient proxies and resolves +destination DNS locally before pinning the address used by `fetch_url`. That is +the wrong transport inside a NemoClaw-managed sandbox: ordinary egress and +destination resolution must pass through the policy proxy, so the direct path +fails even when the same approved URL works through the managed route. + +NemoClaw owns the managed image, launchers, and policy boundary, but not the +hash-locked third-party `fetch_url` implementation. The exact-version build +patch therefore delegates only managed launches to a proxy URL independently +derived from the image's root-owned host and port files. The runtime rejects a +missing, unsafe, or mismatched file/environment contract, disables Requests' +ambient proxy and `NO_PROXY` discovery, and supplies the verified proxy +explicitly on every redirect hop. Imports outside the managed launcher retain +the upstream direct DNS-pinning behavior. + +Focused tests patch the released wheel, exercise managed and unmanaged paths, +reject forged proxy environments and malformed redirects, and prove that +credential-bearing URLs are not reflected. The live Deep Agents Code egress +check requires a nonempty 2xx response from an approved raw GitHub URL and +denial for an unapproved host, cloud metadata, and loopback. Remove this adapter +rather than refreshing it when a pinned Deep Agents Code release exposes a +supported policy-proxy transport with equivalent redirect and fail-closed +behavior. + ## Released Nemotron 3 Ultra Profile Deep Agents Code `0.1.34` pins `deepagents==0.7.0a6`, whose official wheel diff --git a/agents/langchain-deepagents-code/managed-dcode-runtime.py b/agents/langchain-deepagents-code/managed-dcode-runtime.py index 05d3fdf0ecb..3e570323050 100644 --- a/agents/langchain-deepagents-code/managed-dcode-runtime.py +++ b/agents/langchain-deepagents-code/managed-dcode-runtime.py @@ -25,6 +25,12 @@ _INFERENCE_BASE_URL_FILE = Path( "/usr/local/share/nemoclaw/dcode-inference-base-url" ) +_MANAGED_PROXY_HOST_FILE = Path( + "/usr/local/share/nemoclaw/dcode-proxy-host" +) +_MANAGED_PROXY_PORT_FILE = Path( + "/usr/local/share/nemoclaw/dcode-proxy-port" +) _MANAGED_FILE_OWNER_UID = 0 _CREDENTIAL_NAME = re.compile( r"(?:^|_)(?:API_KEY|KEY|TOKEN|SECRET|PASSWORD|PASS|CREDENTIAL)$", @@ -882,6 +888,7 @@ def managed_fetch_proxy_url() -> str | None: value = os.environ.get(_FETCH_URL_TRUSTED_PROXY_ENV) if value is None: return None + expected_proxy_url = _managed_fetch_proxy_url_from_files() if ( not value or len(value) > 2048 @@ -908,12 +915,58 @@ def managed_fetch_proxy_url() -> str | None: or _MANAGED_PROXY_HOST.fullmatch(parsed.hostname) is None ): raise RuntimeError("managed fetch URL proxy is invalid") + if value != expected_proxy_url: + raise RuntimeError( + "managed fetch URL proxy does not match root-owned proxy" + ) for name in ("HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"): if os.environ.get(name) != value: raise RuntimeError("managed fetch URL proxy does not match runtime proxy") return value +def _read_managed_proxy_value(path: Path, label: str) -> str: + """Read one immutable proxy component from the managed image.""" + if not path.is_file() or path.is_symlink(): + raise RuntimeError(f"managed proxy {label} file is missing or unsafe") + try: + metadata = path.stat() + raw = path.read_text(encoding="utf-8") + except OSError as exc: + raise RuntimeError(f"managed proxy {label} file is unreadable") from exc + if ( + metadata.st_uid != _MANAGED_FILE_OWNER_UID + or stat.S_IMODE(metadata.st_mode) != 0o444 + ): + raise RuntimeError( + f"managed proxy {label} file has unsafe ownership or mode" + ) + value = raw.rstrip("\n") + if ( + not value + or len(value) > 2048 + or raw not in {value, f"{value}\n"} + or value != value.strip() + or any(ord(character) < 32 for character in value) + ): + raise RuntimeError(f"managed proxy {label} file has invalid contents") + return value + + +def _managed_fetch_proxy_url_from_files() -> str: + """Derive the trusted proxy URL independently from root-owned files.""" + host = _read_managed_proxy_value(_MANAGED_PROXY_HOST_FILE, "host") + port = _read_managed_proxy_value(_MANAGED_PROXY_PORT_FILE, "port") + if _MANAGED_PROXY_HOST.fullmatch(host) is None: + raise RuntimeError("managed proxy host file has invalid contents") + if ( + re.fullmatch(r"[0-9]{1,5}", port) is None + or not 1 <= int(port, 10) <= 65535 + ): + raise RuntimeError("managed proxy port file has invalid contents") + return f"http://{host}:{port}" + + def managed_fetch_with_redirects( url: str, *, diff --git a/docs/reference/network-policies.mdx b/docs/reference/network-policies.mdx index f9b0c08c4f9..b860c66aee8 100644 --- a/docs/reference/network-policies.mdx +++ b/docs/reference/network-policies.mdx @@ -94,6 +94,12 @@ Use `$$nemoclaw policy-list` or `openshell policy get --base | `github` | `github.com:443`, `api.github.com:443`, `raw.githubusercontent.com:443` | `/usr/bin/git`, `/usr/local/bin/dcode`, `/opt/venv/bin/python3*` | Full access to `github.com` and `api.github.com`; GET and HEAD only to `raw.githubusercontent.com` | | `pypi` | `pypi.org:443`, `files.pythonhosted.org:443` | `/opt/venv/bin/python3*`, `/opt/venv/bin/pip3*` | GET and HEAD for package installation | +The separate `raw.githubusercontent.com` route lets Deep Agents Code follow +GitHub file links and read repository source through its managed `fetch_url` +tool. Repository, ref, and file path segments vary by task, so the route covers +the host while limiting requests to read-only GET and HEAD methods and the +listed managed binaries. + All endpoints use TLS termination and are enforced at port 443. diff --git a/test/langchain-deepagents-code-direct-module-patch.test.ts b/test/langchain-deepagents-code-direct-module-patch.test.ts index 47e22170f60..87ad4345281 100644 --- a/test/langchain-deepagents-code-direct-module-patch.test.ts +++ b/test/langchain-deepagents-code-direct-module-patch.test.ts @@ -242,6 +242,7 @@ else: import os import sys import types +from pathlib import Path calls = [] responses = [] @@ -267,9 +268,19 @@ requests.Session = Session requests.exceptions = types.SimpleNamespace(TooManyRedirects=RuntimeError) sys.modules["requests"] = requests -from deepagents_code import tools +from deepagents_code import _nemoclaw_managed, tools from deepagents_code._nemoclaw_managed import managed_fetch_proxy_url +proxy_host_file = Path(${JSON.stringify(tempDir)}) / "managed-proxy-host" +proxy_port_file = Path(${JSON.stringify(tempDir)}) / "managed-proxy-port" +proxy_host_file.write_text("managed-proxy.internal\\n", encoding="utf-8") +proxy_port_file.write_text("3128\\n", encoding="utf-8") +proxy_host_file.chmod(0o444) +proxy_port_file.chmod(0o444) +_nemoclaw_managed._MANAGED_PROXY_HOST_FILE = proxy_host_file +_nemoclaw_managed._MANAGED_PROXY_PORT_FILE = proxy_port_file +_nemoclaw_managed._MANAGED_FILE_OWNER_UID = os.getuid() + def forbidden_direct_dns(*_args, **_kwargs): raise AssertionError("managed fetch attempted direct DNS validation") @@ -415,31 +426,6 @@ print("managed-fetch-proxy-ok") }, ); expect(withoutDelegation.status, withoutDelegation.stderr).toBe(0); - - const mismatchedProxy = spawnSync( - "python3", - [ - "-c", - "from deepagents_code._nemoclaw_managed import managed_fetch_proxy_url; managed_fetch_proxy_url()", - ], - { - env: { - PATH: process.env.PATH, - PYTHONPATH: tempDir, - DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL: proxyUrl, - HTTP_PROXY: "http://attacker.internal:4444", - HTTPS_PROXY: proxyUrl, - http_proxy: proxyUrl, - https_proxy: proxyUrl, - }, - encoding: "utf8", - }, - ); - expect(mismatchedProxy.status).not.toBe(0); - expect(mismatchedProxy.stderr).toContain( - "managed fetch URL proxy does not match runtime proxy", - ); - expect(mismatchedProxy.stderr).not.toContain("attacker.internal"); }); it("rejects direct-module runtime credentials before settings bootstrap", () => { diff --git a/test/langchain-deepagents-code-fetch-proxy.test.ts b/test/langchain-deepagents-code-fetch-proxy.test.ts index dfd2ac72707..1ea19e991d8 100644 --- a/test/langchain-deepagents-code-fetch-proxy.test.ts +++ b/test/langchain-deepagents-code-fetch-proxy.test.ts @@ -1,12 +1,14 @@ // 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 YAML from "yaml"; +import { addDarwinFcntlSealConstants } from "./helpers/darwin-fcntl-seal-fixture.ts"; import { makeStartScriptFixture, runStartScriptProxyProbe, @@ -39,6 +41,79 @@ describe("LangChain Deep Agents Code managed fetch proxy", () => { } }); + it("rejects consistently forged proxy env that differs from root-owned files", () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-dcode-proxy-root-")); + try { + const hostFile = path.join(tempDir, "dcode-proxy-host"); + const portFile = path.join(tempDir, "dcode-proxy-port"); + const runtimeFile = path.join(tempDir, "managed-dcode-runtime.py"); + fs.writeFileSync(hostFile, "trusted-proxy.internal\n", { mode: 0o444 }); + fs.writeFileSync(portFile, "3129\n", { mode: 0o444 }); + fs.writeFileSync( + runtimeFile, + addDarwinFcntlSealConstants(readAgentFile("managed-dcode-runtime.py")), + "utf8", + ); + const result = spawnSync( + "python3", + [ + "-c", + ` +import importlib.util +import os +from pathlib import Path + +spec = importlib.util.spec_from_file_location( + "nemoclaw_managed_proxy_test", + ${JSON.stringify(runtimeFile)}, +) +runtime = importlib.util.module_from_spec(spec) +spec.loader.exec_module(runtime) +runtime._MANAGED_PROXY_HOST_FILE = Path(${JSON.stringify(hostFile)}) +runtime._MANAGED_PROXY_PORT_FILE = Path(${JSON.stringify(portFile)}) +runtime._MANAGED_FILE_OWNER_UID = os.getuid() + +for name in ( + "DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL", + "HTTP_PROXY", + "HTTPS_PROXY", + "http_proxy", + "https_proxy", +): + os.environ[name] = "http://attacker.internal:4444" + +try: + runtime.managed_fetch_proxy_url() +except RuntimeError as exc: + assert str(exc) == "managed fetch URL proxy does not match root-owned proxy" + assert "attacker.internal" not in str(exc) +else: + raise AssertionError("consistently forged proxy environment was accepted") + +trusted = "http://trusted-proxy.internal:3129" +for name in ( + "DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL", + "HTTP_PROXY", + "HTTPS_PROXY", + "http_proxy", + "https_proxy", +): + os.environ[name] = trusted +os.environ["NO_PROXY"] = "raw.githubusercontent.com" +assert runtime.managed_fetch_proxy_url() == trusted +print("root-owned-proxy-verification-ok") +`, + ], + { encoding: "utf8", env: { PATH: process.env.PATH } }, + ); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toContain("root-owned-proxy-verification-ok"); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }); + it("allows raw GitHub content only through GET and HEAD", () => { const policy = YAML.parse(readAgentFile("policy-additions.yaml")) as { network_policies?: Record> }>; From 799b184456dfd74d9daef9be9048af170ffeb362 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 8 Jul 2026 13:43:59 -0700 Subject: [PATCH 03/21] fix(dcode): preserve managed proxy TLS trust Signed-off-by: Aaron Erickson --- .../dependency-review.md | 9 ++- .../managed-dcode-runtime.py | 56 +++++++++++++- .../patch-managed-deepagents-code.py | 2 +- .../06-deepagents-code-python-egress.sh | 4 +- ...platform-parity-cloud-experimental.test.ts | 16 ++++ ...eepagents-code-direct-module-patch.test.ts | 77 +++++++++++++++++++ ...gchain-deepagents-code-fetch-proxy.test.ts | 5 +- ...s-code-progressive-tool-disclosure.test.ts | 9 +++ 8 files changed, 169 insertions(+), 9 deletions(-) diff --git a/agents/langchain-deepagents-code/dependency-review.md b/agents/langchain-deepagents-code/dependency-review.md index 71d4665837a..a6b0559ee0c 100644 --- a/agents/langchain-deepagents-code/dependency-review.md +++ b/agents/langchain-deepagents-code/dependency-review.md @@ -27,9 +27,12 @@ hash-locked third-party `fetch_url` implementation. The exact-version build patch therefore delegates only managed launches to a proxy URL independently derived from the image's root-owned host and port files. The runtime rejects a missing, unsafe, or mismatched file/environment contract, disables Requests' -ambient proxy and `NO_PROXY` discovery, and supplies the verified proxy -explicitly on every redirect hop. Imports outside the managed launcher retain -the upstream direct DNS-pinning behavior. +ambient proxy, `NO_PROXY`, netrc, and CA discovery, and supplies the verified +proxy explicitly on every redirect hop. It separately validates the fixed, +root-owned CA-bundle mount injected into the sandbox and passes it as explicit +TLS transport trust; that bundle cannot select a proxy or authorize a +destination. Imports outside the managed launcher retain the upstream direct +DNS-pinning behavior. Focused tests patch the released wheel, exercise managed and unmanaged paths, reject forged proxy environments and malformed redirects, and prove that diff --git a/agents/langchain-deepagents-code/managed-dcode-runtime.py b/agents/langchain-deepagents-code/managed-dcode-runtime.py index 3e570323050..aa3d2ac6694 100644 --- a/agents/langchain-deepagents-code/managed-dcode-runtime.py +++ b/agents/langchain-deepagents-code/managed-dcode-runtime.py @@ -49,11 +49,16 @@ _FETCH_URL_TRUSTED_PROXY_ENV = ( "DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL" ) +_MANAGED_FETCH_CA_BUNDLE_FILE = Path( + "/etc/openshell-tls/ca-bundle.pem" +) _MANAGED_ADAPTER_PROVIDER = "openai" _NVIDIA_DISPLAY_PROVIDER_ALIASES = frozenset( {"nvidia", "nvidia-prod", "nvidia-nim", "nvidia-router"} ) _DISPLAY_PROVIDER_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}") +# Match the launchers' image-baked proxy validator: underscores are accepted +# intentionally for controlled internal/container aliases, not public DNS. _MANAGED_PROXY_HOST = re.compile(r"[A-Za-z0-9._-]+") _MCP_SERVER_NAME = re.compile(r"[A-Za-z][A-Za-z0-9_-]{0,63}") _MCP_ENV_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]{0,127}") @@ -967,6 +972,34 @@ def _managed_fetch_proxy_url_from_files() -> str: return f"http://{host}:{port}" +def _managed_fetch_ca_bundle() -> str: + """Validate fixed OpenShell TLS trust without granting network authority.""" + path = _MANAGED_FETCH_CA_BUNDLE_FILE + try: + link_metadata = path.lstat() + except FileNotFoundError: + raise RuntimeError("managed fetch CA bundle is unavailable") from None + except OSError: + raise RuntimeError("managed fetch CA bundle is invalid") from None + if stat.S_ISLNK(link_metadata.st_mode): + raise RuntimeError("managed fetch CA bundle is invalid") + try: + metadata = path.stat() + except FileNotFoundError: + raise RuntimeError("managed fetch CA bundle is unavailable") from None + except OSError: + raise RuntimeError("managed fetch CA bundle is invalid") from None + if ( + not stat.S_ISREG(metadata.st_mode) + or metadata.st_uid != _MANAGED_FILE_OWNER_UID + or stat.S_IMODE(metadata.st_mode) & 0o022 + or metadata.st_size <= 0 + or not os.access(path, os.R_OK) + ): + raise RuntimeError("managed fetch CA bundle is invalid") + return str(path) + + def managed_fetch_with_redirects( url: str, *, @@ -991,7 +1024,18 @@ def managed_fetch_with_redirects( if proxy_url is None: return original_fetch(url, timeout=timeout) - import requests + try: + import requests + except ImportError: + # Keep an optional dependency failure inside fetch_url's structured + # validation result without exposing import paths or stack details. + raise validation_error( + "managed fetch transport dependency is unavailable" + ) from None + try: + ca_bundle = _managed_fetch_ca_bundle() + except RuntimeError as exc: + raise validation_error(str(exc)) from None def validate_url(candidate: str) -> None: try: @@ -1008,6 +1052,10 @@ def validate_url(candidate: str) -> None: ) if not hostname: raise validation_error("URL is missing a hostname") + # username/password describe only authority userinfo. An `@` or `:` in + # parsed.path is ordinary path data and must not be misclassified as a + # credential. These validation errors never echo the candidate URL; + # the explicit OpenShell proxy remains the policy and SSRF authority. if parsed.username is not None or parsed.password is not None: raise validation_error("URL credentials are not allowed") try: @@ -1019,6 +1067,11 @@ def validate_url(candidate: str) -> None: current_url = url session = requests.Session() + # Disable every requests environment-derived session setting, including + # proxy/NO_PROXY, netrc, and CA-bundle discovery. Each request receives the + # sole root-verified proxy mapping explicitly below. The separately + # selected CA bundle establishes TLS transport trust only; it cannot choose + # a proxy or authorize a destination under OpenShell policy. session.trust_env = False proxies = {"http": proxy_url, "https": proxy_url} for _hop in range(max_redirects + 1): @@ -1029,6 +1082,7 @@ def validate_url(candidate: str) -> None: headers={"User-Agent": "Mozilla/5.0 (compatible; DeepAgents/1.0)"}, allow_redirects=False, proxies=proxies, + verify=ca_bundle, ) if 300 <= response.status_code < 400: location = response.headers.get("Location") diff --git a/agents/langchain-deepagents-code/patch-managed-deepagents-code.py b/agents/langchain-deepagents-code/patch-managed-deepagents-code.py index a1159dd86a6..56b354ee03f 100644 --- a/agents/langchain-deepagents-code/patch-managed-deepagents-code.py +++ b/agents/langchain-deepagents-code/patch-managed-deepagents-code.py @@ -381,7 +381,7 @@ def _preview_dotenv_environ(*, start_path=None) -> dict[str, str]: def _load_dotenv(*, start_path=None, refresh_loaded=False) -> bool: - """Disable project and global dotenv loading in the managed image.""" + """Disable dotenv, including DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL.""" del start_path, refresh_loaded _dotenv_loaded_values.clear() return False diff --git a/test/e2e/e2e-cloud-experimental/checks/06-deepagents-code-python-egress.sh b/test/e2e/e2e-cloud-experimental/checks/06-deepagents-code-python-egress.sh index a2d759b6230..8eb03c08f48 100755 --- a/test/e2e/e2e-cloud-experimental/checks/06-deepagents-code-python-egress.sh +++ b/test/e2e/e2e-cloud-experimental/checks/06-deepagents-code-python-egress.sh @@ -299,8 +299,8 @@ expect_fetch_reached \ "raw GitHub" \ "https://raw.githubusercontent.com/NVIDIA/NemoClaw/main/README.md" expect_fetch_blocked "unapproved hosts" "https://example.com/" -expect_fetch_blocked "instance metadata" "http://169.254.169.254/latest/meta-data/" -expect_fetch_blocked "sandbox loopback" "http://127.0.0.1/" +expect_fetch_blocked "instance metadata" "https://169.254.169.254/latest/meta-data/" +expect_fetch_blocked "sandbox loopback" "https://127.0.0.1/" # Exercise the writable-project-venv allowlist entries directly. The managed # /opt/venv Python creates the project venv, then the probes run through the diff --git a/test/e2e/support/platform-parity-cloud-experimental.test.ts b/test/e2e/support/platform-parity-cloud-experimental.test.ts index 2184996d60a..be5de6c7eb4 100644 --- a/test/e2e/support/platform-parity-cloud-experimental.test.ts +++ b/test/e2e/support/platform-parity-cloud-experimental.test.ts @@ -247,6 +247,22 @@ describe("P0-E cloud-experimental parity guardrails", () => { expect(result.stdout.trim()).toBe("NO_NEWLINE_IN_FETCH_COMMAND"); }); + it("keeps sensitive fetch_url denials on HTTPS CONNECT classification", () => { + const script = fs.readFileSync( + path.join( + process.cwd(), + "test/e2e/e2e-cloud-experimental/checks/06-deepagents-code-python-egress.sh", + ), + "utf8", + ); + + expect(script).toContain( + 'expect_fetch_blocked "instance metadata" "https://169.254.169.254/latest/meta-data/"', + ); + expect(script).toContain('expect_fetch_blocked "sandbox loopback" "https://127.0.0.1/"'); + expect(script).not.toContain("'403 client error: forbidden'"); + }); + it("keeps Deep Agents secret-boundary probe command single-line for OpenShell exec", () => { const result = spawnSync( "bash", diff --git a/test/langchain-deepagents-code-direct-module-patch.test.ts b/test/langchain-deepagents-code-direct-module-patch.test.ts index 87ad4345281..20006ecd6dd 100644 --- a/test/langchain-deepagents-code-direct-module-patch.test.ts +++ b/test/langchain-deepagents-code-direct-module-patch.test.ts @@ -239,6 +239,7 @@ else: [ "-c", ` +import builtins import os import sys import types @@ -273,13 +274,24 @@ from deepagents_code._nemoclaw_managed import managed_fetch_proxy_url proxy_host_file = Path(${JSON.stringify(tempDir)}) / "managed-proxy-host" proxy_port_file = Path(${JSON.stringify(tempDir)}) / "managed-proxy-port" +managed_ca_file = Path(${JSON.stringify(tempDir)}) / "managed-ca.pem" +writable_ca_file = Path(${JSON.stringify(tempDir)}) / "writable-sensitive-ca.pem" +symlink_ca_file = Path(${JSON.stringify(tempDir)}) / "symlink-sensitive-ca.pem" proxy_host_file.write_text("managed-proxy.internal\\n", encoding="utf-8") proxy_port_file.write_text("3128\\n", encoding="utf-8") +managed_ca_file.write_text("test CA bundle\\n", encoding="utf-8") +writable_ca_file.write_text("unsafe CA bundle\\n", encoding="utf-8") +writable_ca_file.chmod(0o666) +symlink_ca_file.symlink_to(managed_ca_file) proxy_host_file.chmod(0o444) proxy_port_file.chmod(0o444) _nemoclaw_managed._MANAGED_PROXY_HOST_FILE = proxy_host_file _nemoclaw_managed._MANAGED_PROXY_PORT_FILE = proxy_port_file +_nemoclaw_managed._MANAGED_FETCH_CA_BUNDLE_FILE = managed_ca_file _nemoclaw_managed._MANAGED_FILE_OWNER_UID = os.getuid() +os.environ["REQUESTS_CA_BUNDLE"] = "relative/../hostile-requests-ca.pem" +os.environ["CURL_CA_BUNDLE"] = "/missing/hostile-curl-ca.pem" +os.environ["SSL_CERT_FILE"] = "/missing/hostile-ssl-ca.pem" def forbidden_direct_dns(*_args, **_kwargs): raise AssertionError("managed fetch attempted direct DNS validation") @@ -295,9 +307,16 @@ assert calls == [( "headers": {"User-Agent": "Mozilla/5.0 (compatible; DeepAgents/1.0)"}, "allow_redirects": False, "proxies": {"http": ${JSON.stringify(proxyUrl)}, "https": ${JSON.stringify(proxyUrl)}}, + "verify": str(managed_ca_file), }, )] +calls.clear() +path_data_url = "https://raw.githubusercontent.com/example/path@segment:ordinary-data" +response = tools._fetch_with_redirects(path_data_url, timeout=8) +assert response.status_code == 200 +assert calls[0][1] == path_data_url + calls.clear() responses.extend([ Response(302, "../main/README.md"), @@ -317,6 +336,7 @@ assert all( == {"http": ${JSON.stringify(proxyUrl)}, "https": ${JSON.stringify(proxyUrl)}} for _, _, kwargs in calls ) +assert all(kwargs["verify"] == str(managed_ca_file) for _, _, kwargs in calls) calls.clear() responses.append(Response(302)) @@ -388,6 +408,63 @@ for invalid_proxy in ( assert "proxy-secret" not in str(exc) else: raise AssertionError(f"invalid managed proxy was accepted: {invalid_proxy!r}") + +for proxy_name in ( + "DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL", + "HTTP_PROXY", + "HTTPS_PROXY", + "http_proxy", + "https_proxy", +): + os.environ[proxy_name] = ${JSON.stringify(proxyUrl)} + +original_import = builtins.__import__ +def block_requests_import(name, *args, **kwargs): + if name == "requests": + raise ImportError("private import detail from /sensitive/runtime/path") + return original_import(name, *args, **kwargs) + +builtins.__import__ = block_requests_import +try: + tools._fetch_with_redirects("https://raw.githubusercontent.com/example", timeout=8) +except tools._UrlValidationError as exc: + assert str(exc) == "managed fetch transport dependency is unavailable" + assert "ImportError" not in str(exc) + assert "sensitive" not in str(exc) + assert exc.__cause__ is None + assert exc.__suppress_context__ is True +else: + raise AssertionError("requests ImportError escaped the structured validation path") +finally: + builtins.__import__ = original_import + +for invalid_ca_bundle, expected_error in ( + ( + Path(${JSON.stringify(tempDir)}) / "missing-sensitive-ca.pem", + "managed fetch CA bundle is unavailable", + ), + (symlink_ca_file, "managed fetch CA bundle is invalid"), + (writable_ca_file, "managed fetch CA bundle is invalid"), +): + _nemoclaw_managed._MANAGED_FETCH_CA_BUNDLE_FILE = invalid_ca_bundle + try: + tools._fetch_with_redirects("https://raw.githubusercontent.com/example", timeout=8) + except tools._UrlValidationError as exc: + assert str(exc) == expected_error + assert "sensitive" not in str(exc) + assert exc.__cause__ is None + else: + raise AssertionError(f"invalid CA bundle was accepted: {invalid_ca_bundle!r}") + +_nemoclaw_managed._MANAGED_FETCH_CA_BUNDLE_FILE = managed_ca_file +_nemoclaw_managed._MANAGED_FILE_OWNER_UID = os.getuid() + 1 +try: + _nemoclaw_managed._managed_fetch_ca_bundle() +except RuntimeError as exc: + assert str(exc) == "managed fetch CA bundle is invalid" +else: + raise AssertionError("wrong-owner CA bundle was accepted") +_nemoclaw_managed._MANAGED_FILE_OWNER_UID = os.getuid() print("managed-fetch-proxy-ok") `, ], diff --git a/test/langchain-deepagents-code-fetch-proxy.test.ts b/test/langchain-deepagents-code-fetch-proxy.test.ts index 1ea19e991d8..5bce1416ff1 100644 --- a/test/langchain-deepagents-code-fetch-proxy.test.ts +++ b/test/langchain-deepagents-code-fetch-proxy.test.ts @@ -151,8 +151,9 @@ print("root-owned-proxy-verification-ok") expect(check).toContain("https://raw.githubusercontent.com/NVIDIA/NemoClaw/main/README.md"); expect(check).toContain('expect_fetch_blocked "unapproved hosts" "https://example.com/"'); expect(check).toContain( - 'expect_fetch_blocked "instance metadata" "http://169.254.169.254/latest/meta-data/"', + 'expect_fetch_blocked "instance metadata" "https://169.254.169.254/latest/meta-data/"', ); - expect(check).toContain('expect_fetch_blocked "sandbox loopback" "http://127.0.0.1/"'); + expect(check).toContain('expect_fetch_blocked "sandbox loopback" "https://127.0.0.1/"'); + expect(check).not.toContain("'403 client error: forbidden'"); }); }); diff --git a/test/langchain-deepagents-code-progressive-tool-disclosure.test.ts b/test/langchain-deepagents-code-progressive-tool-disclosure.test.ts index ef403638a01..e7d4052990b 100644 --- a/test/langchain-deepagents-code-progressive-tool-disclosure.test.ts +++ b/test/langchain-deepagents-code-progressive-tool-disclosure.test.ts @@ -78,6 +78,15 @@ def _load_dotenv(*, start_path=None, refresh_loaded=False): return False def _parse_interpreter_ptc(raw): return raw def _preview_dotenv_environ(*, start_path=None): return {} def _tracing_enabled(): return False +`, + "tools.py": `from __future__ import annotations + +_MAX_FETCH_REDIRECTS = 5 + +class _UrlValidationError(ValueError): pass + +def _fetch_with_redirects(url, *, timeout): + return url, timeout `, "model_config.py": `from __future__ import annotations From 8a3fcb0ffb2800898e5b8a2cae1212b32832b0e5 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 8 Jul 2026 13:49:54 -0700 Subject: [PATCH 04/21] fix(dcode): clarify fetch URL trust boundaries Signed-off-by: Aaron Erickson --- .../dependency-review.md | 7 +++++++ .../managed-dcode-runtime.py | 16 ++++++++++------ .../patch-managed-deepagents-code.py | 10 ++++++---- .../policy-additions.yaml | 5 +++-- ...n-deepagents-code-direct-module-patch.test.ts | 13 +++++++++++++ 5 files changed, 39 insertions(+), 12 deletions(-) diff --git a/agents/langchain-deepagents-code/dependency-review.md b/agents/langchain-deepagents-code/dependency-review.md index a6b0559ee0c..6c46a621504 100644 --- a/agents/langchain-deepagents-code/dependency-review.md +++ b/agents/langchain-deepagents-code/dependency-review.md @@ -34,6 +34,13 @@ TLS transport trust; that bundle cannot select a proxy or authorize a destination. Imports outside the managed launcher retain the upstream direct DNS-pinning behavior. +Redirect validation rejects authority userinfo (`user:password@host`). It does +not treat `@` or `:` in a path segment as credentials: RFC 3986 defines those +characters as ordinary path data, and coding tasks can legitimately encounter +them in repository refs or filenames. Focused redirect coverage pins that +distinction, while validation errors avoid echoing candidate URLs and the +policy proxy remains authoritative for every destination. + Focused tests patch the released wheel, exercise managed and unmanaged paths, reject forged proxy environments and malformed redirects, and prove that credential-bearing URLs are not reflected. The live Deep Agents Code egress diff --git a/agents/langchain-deepagents-code/managed-dcode-runtime.py b/agents/langchain-deepagents-code/managed-dcode-runtime.py index aa3d2ac6694..60741a3e500 100644 --- a/agents/langchain-deepagents-code/managed-dcode-runtime.py +++ b/agents/langchain-deepagents-code/managed-dcode-runtime.py @@ -57,8 +57,10 @@ {"nvidia", "nvidia-prod", "nvidia-nim", "nvidia-router"} ) _DISPLAY_PROVIDER_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}") -# Match the launchers' image-baked proxy validator: underscores are accepted -# intentionally for controlled internal/container aliases, not public DNS. +# Match the launchers' root-owned, image-baked proxy validator. Its deliberate +# RFC 1123 deviation permits underscores only for controlled internal/container +# aliases such as `proxy_name`; the cross-boundary cases in +# test/langchain-deepagents-code-proxy-launcher.test.ts prevent validator drift. _MANAGED_PROXY_HOST = re.compile(r"[A-Za-z0-9._-]+") _MCP_SERVER_NAME = re.compile(r"[A-Za-z][A-Za-z0-9_-]{0,63}") _MCP_ENV_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]{0,127}") @@ -1052,10 +1054,12 @@ def validate_url(candidate: str) -> None: ) if not hostname: raise validation_error("URL is missing a hostname") - # username/password describe only authority userinfo. An `@` or `:` in - # parsed.path is ordinary path data and must not be misclassified as a - # credential. These validation errors never echo the candidate URL; - # the explicit OpenShell proxy remains the policy and SSRF authority. + # RFC 3986 credentials are authority userinfo, exposed by username and + # password. An `@` or `:` after the authority is ordinary path data + # (including valid repository refs/files), never authentication; + # rejecting that shape would create false positives. These validation + # errors never echo the candidate URL, and the explicit OpenShell proxy + # remains the destination-policy and SSRF authority for every hop. if parsed.username is not None or parsed.password is not None: raise validation_error("URL credentials are not allowed") try: diff --git a/agents/langchain-deepagents-code/patch-managed-deepagents-code.py b/agents/langchain-deepagents-code/patch-managed-deepagents-code.py index 56b354ee03f..373a20e2c51 100644 --- a/agents/langchain-deepagents-code/patch-managed-deepagents-code.py +++ b/agents/langchain-deepagents-code/patch-managed-deepagents-code.py @@ -381,7 +381,7 @@ def _preview_dotenv_environ(*, start_path=None) -> dict[str, str]: def _load_dotenv(*, start_path=None, refresh_loaded=False) -> bool: - """Disable dotenv, including DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL.""" + """Disable all dotenv loading so it cannot supply the trusted fetch proxy.""" del start_path, refresh_loaded _dotenv_loaded_values.clear() return False @@ -423,9 +423,11 @@ def _get_provider_kwargs(provider: str, *, model_name: str | None = None) -> dic # destination DNS locally, then disables environment proxies. That is a sound # standalone SSRF defense but cannot operate in OpenShell's proxy-only network # namespace, where direct DNS and direct target connections are rejected. The -# managed launcher supplies an explicit, root-owned proxy URL; this patch keeps -# requests' ambient proxy discovery disabled and delegates every redirect hop to -# that exact proxy, whose network policy and SSRF checks remain authoritative. +# managed launcher supplies an explicit, root-owned proxy URL. `trust_env=False` +# disables every Requests environment-derived session setting (proxy/NO_PROXY, +# netrc, and CA discovery); each hop receives only the explicit proxy mapping +# and separately validated fixed CA bundle. The proxy's network policy and SSRF +# checks remain authoritative. TOOLS_PATCH = r''' # NemoClaw-managed Deep Agents Code hardening v2. diff --git a/agents/langchain-deepagents-code/policy-additions.yaml b/agents/langchain-deepagents-code/policy-additions.yaml index 4cefb8250d1..a0a739f47cd 100644 --- a/agents/langchain-deepagents-code/policy-additions.yaml +++ b/agents/langchain-deepagents-code/policy-additions.yaml @@ -66,8 +66,9 @@ network_policies: port: 443 access: full # GitHub's API and HTML pages link repository file bodies through this - # separate host. Keep the default coding-agent capability read-only even - # though the broader GitHub/API endpoints above support normal git work. + # separate host. A general coding agent must follow repository, ref, and + # file paths that vary by task, so the host-wide path is intentional while + # methods remain read-only. The broader endpoints above support git work. - host: raw.githubusercontent.com port: 443 protocol: rest diff --git a/test/langchain-deepagents-code-direct-module-patch.test.ts b/test/langchain-deepagents-code-direct-module-patch.test.ts index 20006ecd6dd..31b08b673fb 100644 --- a/test/langchain-deepagents-code-direct-module-patch.test.ts +++ b/test/langchain-deepagents-code-direct-module-patch.test.ts @@ -317,6 +317,19 @@ response = tools._fetch_with_redirects(path_data_url, timeout=8) assert response.status_code == 200 assert calls[0][1] == path_data_url +calls.clear() +redirect_path_data_url = "https://raw.githubusercontent.com/example/@user:pass/source.py" +responses.extend([Response(302, redirect_path_data_url), Response(200)]) +response = tools._fetch_with_redirects( + "https://raw.githubusercontent.com/path-data-redirect", + timeout=8, +) +assert response.status_code == 200 +assert [url for _, url, _ in calls] == [ + "https://raw.githubusercontent.com/path-data-redirect", + redirect_path_data_url, +] + calls.clear() responses.extend([ Response(302, "../main/README.md"), From ab9b708a64db983e9cf896a5dc9f78c698bfcdca Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 8 Jul 2026 14:14:54 -0700 Subject: [PATCH 05/21] fix(sandbox): classify interleaved policy denials Signed-off-by: Aaron Erickson --- .../exec-policy-hint-detection.test.ts | 3 ++ .../sandbox/exec-policy-hint-detection.ts | 43 ++++++++++++++++--- .../deepagents-observability-contract.test.ts | 9 ++++ 3 files changed, 50 insertions(+), 5 deletions(-) diff --git a/src/lib/actions/sandbox/exec-policy-hint-detection.test.ts b/src/lib/actions/sandbox/exec-policy-hint-detection.test.ts index c76742caaa3..a4a69a51245 100644 --- a/src/lib/actions/sandbox/exec-policy-hint-detection.test.ts +++ b/src/lib/actions/sandbox/exec-policy-hint-detection.test.ts @@ -20,6 +20,8 @@ const SSH_RELAY_INFO_LINE = // fixture strict: speculative wording variants would widen false positives. const PROXY_JSON_LINE = '{"detail":"CONNECT example.com:443 not permitted by policy","error":"policy_denied"}'; +const INTERLEAVED_CURL_PROXY_JSON_LINE = + 'curl: (22) The reque{"detail":"POST host.openshell.internal:4318/v1/traces not permitted by policy","error":"policy_denied"}sted URL returned error: 403'; // A denial timestamp of 1783046573.602s parses to 1783046573602ms. Anchor the // command-start stamps around it to exercise the recency window. @@ -40,6 +42,7 @@ describe("isPolicyDenialLine (#5978)", () => { true, ], ["proxy JSON policy_denied body", PROXY_JSON_LINE, true], + ["proxy JSON interleaved with curl stderr", INTERLEAVED_CURL_PROXY_JSON_LINE, true], [ "forward proxy host denial body", '{"error":"policy_denied","detail":"POST example.com:4318/v1/traces not permitted by policy"}', diff --git a/src/lib/actions/sandbox/exec-policy-hint-detection.ts b/src/lib/actions/sandbox/exec-policy-hint-detection.ts index 3a84cbba205..1826d67c19a 100644 --- a/src/lib/actions/sandbox/exec-policy-hint-detection.ts +++ b/src/lib/actions/sandbox/exec-policy-hint-detection.ts @@ -86,19 +86,52 @@ function isStructuredProxyPolicyDenialDetail(detail: string): boolean { // CONNECT or forward-HTTP 403 JSON while the child tool receives opaque text. // - Source boundary/fix constraint: the payload is emitted by the external // OpenShell proxy, so NemoClaw can only translate it after exec returns. -// - Regression coverage: prefixed, unprefixed, malformed, and near-miss JSON -// payloads live in exec-policy-hint-detection.test.ts. +// curl may interleave that response body with its own stderr text, so extract +// one complete JSON object without trusting surrounding output. +// - Regression coverage: prefixed, suffixed, unprefixed, malformed, and +// near-miss JSON payloads live in exec-policy-hint-detection.test.ts. // - Removal condition: delete this fallback when OpenShell provides a typed // exec-denial result. Until then, require both the exact error code and the // complete safely bounded CONNECT or forward-HTTP detail so unrelated JSON // cannot match. The forward forms mirror OpenShell v0.0.72's endpoint, path, // and L7 policy denial messages. +function firstJsonObject(line: string): string | null { + const start = line.indexOf("{"); + if (start === -1) return null; + + let depth = 0; + let escaped = false; + let inString = false; + for (let index = start; index < line.length; index += 1) { + const character = line[index]; + if (inString) { + if (escaped) { + escaped = false; + } else if (character === "\\") { + escaped = true; + } else if (character === '"') { + inString = false; + } + continue; + } + if (character === '"') { + inString = true; + } else if (character === "{") { + depth += 1; + } else if (character === "}") { + depth -= 1; + if (depth === 0) return line.slice(start, index + 1); + } + } + return null; +} + function isStructuredJsonPolicyDenial(line: string): boolean { if (line.length > MAX_STRUCTURED_PROXY_LINE_LENGTH) return false; - const jsonStart = line.indexOf("{"); - if (jsonStart === -1) return false; + const jsonObject = firstJsonObject(line); + if (jsonObject === null) return false; try { - const parsed: unknown = JSON.parse(line.slice(jsonStart)); + const parsed: unknown = JSON.parse(jsonObject); if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return false; const payload = parsed as Record; const keys = Object.keys(payload); diff --git a/test/e2e/support/deepagents-observability-contract.test.ts b/test/e2e/support/deepagents-observability-contract.test.ts index 64b7a20aa64..7cceecb2175 100644 --- a/test/e2e/support/deepagents-observability-contract.test.ts +++ b/test/e2e/support/deepagents-observability-contract.test.ts @@ -281,6 +281,15 @@ describe("Deep Agents observability policy proof", () => { }); expect(proxyDenial.status, proxyDenial.stderr).toBe(0); expect(proxyDenial.stdout.trim()).toBe("policy-denied"); + + const interleavedCurlDenial = spawnSync(tsx, [helper, "denial-state"], { + encoding: "utf8", + env: { PATH: process.env.PATH }, + input: + 'curl: (22) The reque{"detail":"POST host.openshell.internal:4318/v1/traces not permitted by policy","error":"policy_denied"}sted URL returned error: 403\n', + }); + expect(interleavedCurlDenial.status, interleavedCurlDenial.stderr).toBe(0); + expect(interleavedCurlDenial.stdout.trim()).toBe("policy-denied"); }); }); From f41b435f6ab5110ccff7a6fdf0453092af420710 Mon Sep 17 00:00:00 2001 From: cjagwani Date: Wed, 8 Jul 2026 21:32:09 +0000 Subject: [PATCH 06/21] fix(dcode): close managed fetch proxy review gaps Signed-off-by: cjagwani --- .../managed-dcode-runtime.py | 54 ++++++------ .../patch-managed-deepagents-code.py | 25 +++++- docs/reference/network-policies.mdx | 9 +- .../06-deepagents-code-python-egress.sh | 7 ++ ...platform-parity-cloud-experimental.test.ts | 34 +++++--- ...eepagents-code-direct-module-patch.test.ts | 84 ++++++++++++++++++- ...gchain-deepagents-code-fetch-proxy.test.ts | 4 +- ...ain-deepagents-code-proxy-launcher.test.ts | 2 +- 8 files changed, 170 insertions(+), 49 deletions(-) diff --git a/agents/langchain-deepagents-code/managed-dcode-runtime.py b/agents/langchain-deepagents-code/managed-dcode-runtime.py index 782621edcba..7b77cf30b43 100644 --- a/agents/langchain-deepagents-code/managed-dcode-runtime.py +++ b/agents/langchain-deepagents-code/managed-dcode-runtime.py @@ -1070,34 +1070,34 @@ def validate_url(candidate: str) -> None: ) from exc current_url = url - session = requests.Session() - # Disable every requests environment-derived session setting, including - # proxy/NO_PROXY, netrc, and CA-bundle discovery. Each request receives the - # sole root-verified proxy mapping explicitly below. The separately - # selected CA bundle establishes TLS transport trust only; it cannot choose - # a proxy or authorize a destination under OpenShell policy. - session.trust_env = False proxies = {"http": proxy_url, "https": proxy_url} - for _hop in range(max_redirects + 1): - validate_url(current_url) - response = session.get( - current_url, - timeout=timeout, - headers={"User-Agent": "Mozilla/5.0 (compatible; DeepAgents/1.0)"}, - allow_redirects=False, - proxies=proxies, - verify=ca_bundle, - ) - if 300 <= response.status_code < 400: - location = response.headers.get("Location") - if not location: - raise validation_error( - f"Redirect response (status {response.status_code}) is missing a Location header" - ) - current_url = urljoin(current_url, location) - continue - response.raise_for_status() - return response + with requests.Session() as session: + # Disable every requests environment-derived session setting, including + # proxy/NO_PROXY, netrc, and CA-bundle discovery. Each request receives + # the sole root-verified proxy mapping explicitly below. The separately + # selected CA bundle establishes TLS transport trust only; it cannot + # choose a proxy or authorize a destination under OpenShell policy. + session.trust_env = False + for _hop in range(max_redirects + 1): + validate_url(current_url) + response = session.get( + current_url, + timeout=timeout, + headers={"User-Agent": "Mozilla/5.0 (compatible; DeepAgents/1.0)"}, + allow_redirects=False, + proxies=proxies, + verify=ca_bundle, + ) + if 300 <= response.status_code < 400: + location = response.headers.get("Location") + if not location: + raise validation_error( + f"Redirect response (status {response.status_code}) is missing a Location header" + ) + current_url = urljoin(current_url, location) + continue + response.raise_for_status() + return response raise requests.exceptions.TooManyRedirects( f"Exceeded {max_redirects} redirects" diff --git a/agents/langchain-deepagents-code/patch-managed-deepagents-code.py b/agents/langchain-deepagents-code/patch-managed-deepagents-code.py index 373a20e2c51..cca7dda244a 100644 --- a/agents/langchain-deepagents-code/patch-managed-deepagents-code.py +++ b/agents/langchain-deepagents-code/patch-managed-deepagents-code.py @@ -1051,6 +1051,20 @@ def _top_level_functions(tree: ast.Module) -> set[str]: } +def _top_level_symbols(tree: ast.Module) -> set[str]: + symbols = _top_level_functions(tree) + for node in tree.body: + if isinstance(node, ast.ClassDef): + symbols.add(node.name) + elif isinstance(node, ast.Assign): + symbols.update( + target.id for target in node.targets if isinstance(target, ast.Name) + ) + elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + symbols.add(node.target.id) + return symbols + + def _class_methods(tree: ast.Module, class_name: str) -> set[str]: for node in tree.body: if isinstance(node, ast.ClassDef) and node.name == class_name: @@ -1070,6 +1084,12 @@ def _require_functions(path: Path, text: str, names: set[str]) -> ast.Module: return tree +def _require_symbols(path: Path, tree: ast.Module, names: set[str]) -> None: + missing = names - _top_level_symbols(tree) + if missing: + raise RuntimeError(f"Required upstream symbols missing in {path}: {sorted(missing)}") + + def _require_methods( path: Path, text: str, class_name: str, names: set[str] ) -> ast.Module: @@ -1289,9 +1309,12 @@ def main() -> None: "_tracing_enabled", }, ) - _require_functions( + tools_tree = _require_functions( paths["tools"], texts["tools"], {"_fetch_with_redirects"} ) + _require_symbols( + paths["tools"], tools_tree, {"_MAX_FETCH_REDIRECTS", "_UrlValidationError"} + ) _require_methods( paths["model_config"], texts["model_config"], diff --git a/docs/reference/network-policies.mdx b/docs/reference/network-policies.mdx index b860c66aee8..950f8a1bdab 100644 --- a/docs/reference/network-policies.mdx +++ b/docs/reference/network-policies.mdx @@ -92,13 +92,10 @@ Use `$$nemoclaw policy-list` or `openshell policy get --base | --- | --- | --- | --- | | `managed_inference` | `inference.local:443` | `/usr/local/bin/dcode`, `/opt/venv/bin/python3*`, `/opt/venv/lib/python3.13/**` | POST to OpenAI-compatible completion and embedding paths, GET to model listings | | `github` | `github.com:443`, `api.github.com:443`, `raw.githubusercontent.com:443` | `/usr/bin/git`, `/usr/local/bin/dcode`, `/opt/venv/bin/python3*` | Full access to `github.com` and `api.github.com`; GET and HEAD only to `raw.githubusercontent.com` | -| `pypi` | `pypi.org:443`, `files.pythonhosted.org:443` | `/opt/venv/bin/python3*`, `/opt/venv/bin/pip3*` | GET and HEAD for package installation | +| `pypi` | `pypi.org:443`, `files.pythonhosted.org:443` | `/opt/venv/bin/python3*`, `/opt/venv/bin/pip3*` | GET for package installation | -The separate `raw.githubusercontent.com` route lets Deep Agents Code follow -GitHub file links and read repository source through its managed `fetch_url` -tool. Repository, ref, and file path segments vary by task, so the route covers -the host while limiting requests to read-only GET and HEAD methods and the -listed managed binaries. +The separate `raw.githubusercontent.com` route lets Deep Agents Code follow GitHub file links and read repository source through its managed `fetch_url` tool. +Repository, ref, and file path segments vary by task, so the route covers the host while limiting requests to read-only GET and HEAD methods and the listed managed binaries. diff --git a/test/e2e/e2e-cloud-experimental/checks/06-deepagents-code-python-egress.sh b/test/e2e/e2e-cloud-experimental/checks/06-deepagents-code-python-egress.sh index 8eb03c08f48..13542e72348 100755 --- a/test/e2e/e2e-cloud-experimental/checks/06-deepagents-code-python-egress.sh +++ b/test/e2e/e2e-cloud-experimental/checks/06-deepagents-code-python-egress.sh @@ -259,6 +259,13 @@ if [ "${NEMOCLAW_E2E_PYTHON_EGRESS_SELF_TEST:-}" = "fetch-probe-command-shape" ] exit 0 fi +if [ "${NEMOCLAW_E2E_PYTHON_EGRESS_SELF_TEST:-}" = "fetch-blocked-classification" ]; then + expect_fetch_blocked "fixture host" "https://blocked.example/" + printf '%s\n' "${PREFIX}: $PASSED passed, $FAILED failed" + [ "$FAILED" -eq 0 ] || exit 1 + exit 0 +fi + cleanup_project_venv() { sandbox_exec "rm -rf ${PROJECT_VENV@Q}" >/dev/null || true } diff --git a/test/e2e/support/platform-parity-cloud-experimental.test.ts b/test/e2e/support/platform-parity-cloud-experimental.test.ts index a97fc242bf0..980ed477803 100644 --- a/test/e2e/support/platform-parity-cloud-experimental.test.ts +++ b/test/e2e/support/platform-parity-cloud-experimental.test.ts @@ -277,20 +277,30 @@ describe("P0-E cloud-experimental parity guardrails", () => { expect(result.stdout.trim()).toBe("NO_NEWLINE_IN_FETCH_COMMAND"); }); - it("keeps sensitive fetch_url denials on HTTPS CONNECT classification", () => { - const script = fs.readFileSync( - path.join( - process.cwd(), - "test/e2e/e2e-cloud-experimental/checks/06-deepagents-code-python-egress.sh", - ), - "utf8", + it.each([ + ["accepts explicit denial evidence", "FETCH_BLOCKED:network policy denied", 0, "1 passed"], + ["rejects an unclassified fetch error", "FETCH_ERROR:opaque 403", 1, "lacked denial evidence"], + ] as const)("%s from the fetch_url probe", (_label, fixture, status, expected) => { + const result = spawnSync( + "bash", + [ + path.join( + process.cwd(), + "test/e2e/e2e-cloud-experimental/checks/06-deepagents-code-python-egress.sh", + ), + ], + { + encoding: "utf8", + env: { + NEMOCLAW_E2E_PYTHON_EGRESS_SELF_TEST: "fetch-blocked-classification", + NEMOCLAW_E2E_FETCH_URL_PROBE_FIXTURE: fixture, + PATH: process.env.PATH ?? "/usr/bin:/bin", + }, + }, ); - expect(script).toContain( - 'expect_fetch_blocked "instance metadata" "https://169.254.169.254/latest/meta-data/"', - ); - expect(script).toContain('expect_fetch_blocked "sandbox loopback" "https://127.0.0.1/"'); - expect(script).not.toContain("'403 client error: forbidden'"); + expect(result.status).toBe(status); + expect(`${result.stdout}\n${result.stderr}`).toContain(expected); }); it("keeps Deep Agents secret-boundary probe command single-line for OpenShell exec", () => { diff --git a/test/langchain-deepagents-code-direct-module-patch.test.ts b/test/langchain-deepagents-code-direct-module-patch.test.ts index 31b08b673fb..ac3cd4ce271 100644 --- a/test/langchain-deepagents-code-direct-module-patch.test.ts +++ b/test/langchain-deepagents-code-direct-module-patch.test.ts @@ -247,18 +247,33 @@ from pathlib import Path calls = [] responses = [] +sessions = [] + +class ProxyPolicyDenied(RuntimeError): + pass class Response: - def __init__(self, status_code=200, location=None): + def __init__(self, status_code=200, location=None, error=None): self.status_code = status_code self.headers = {} if location is None else {"Location": location} + self.error = error def raise_for_status(self): + if self.error is not None: + raise self.error return None class Session: def __init__(self): self.trust_env = True + self.closed = False + sessions.append(self) + + def __enter__(self): + return self + + def __exit__(self, *_args): + self.closed = True def get(self, url, **kwargs): calls.append((self.trust_env, url, kwargs)) @@ -299,6 +314,7 @@ def forbidden_direct_dns(*_args, **_kwargs): tools._validate_url = forbidden_direct_dns response = tools._fetch_with_redirects("https://raw.githubusercontent.com/example/repo/main/README.md", timeout=8) assert response.status_code == 200 +assert len(sessions) == 1 and sessions[0].closed assert calls == [( False, "https://raw.githubusercontent.com/example/repo/main/README.md", @@ -371,6 +387,34 @@ else: raise AssertionError("credentialed redirect escaped validation") assert len(calls) == 1 +for label, redirect_url in ( + ("cross-host metadata", "http://169.254.169.254/latest/meta-data/"), + ("DNS-rebinding hostname", "https://rebind.internal/private"), +): + calls.clear() + responses.extend([ + Response(302, redirect_url), + Response(403, error=ProxyPolicyDenied(f"network policy denied {label}")), + ]) + try: + tools._fetch_with_redirects( + "https://raw.githubusercontent.com/allowed/start", + timeout=8, + ) + except ProxyPolicyDenied as exc: + assert str(exc) == f"network policy denied {label}" + else: + raise AssertionError(f"{label} redirect escaped proxy policy denial") + assert [url for _, url, _ in calls] == [ + "https://raw.githubusercontent.com/allowed/start", + redirect_url, + ] + assert all( + kwargs["proxies"] + == {"http": ${JSON.stringify(proxyUrl)}, "https": ${JSON.stringify(proxyUrl)}} + for _, _, kwargs in calls + ) + calls.clear() responses.append(Response(302, "https://raw.githubusercontent.com/next")) tools._MAX_FETCH_REDIRECTS = 0 @@ -478,6 +522,8 @@ except RuntimeError as exc: else: raise AssertionError("wrong-owner CA bundle was accepted") _nemoclaw_managed._MANAGED_FILE_OWNER_UID = os.getuid() +assert sessions and all(session.closed for session in sessions) +assert len({id(session) for session in sessions}) == len(sessions) print("managed-fetch-proxy-ok") `, ], @@ -1355,5 +1401,41 @@ print("managed-boundaries-ok") }); expect(fetchShapeResult.status).not.toBe(0); expect(fetchShapeResult.stderr).toContain("_fetch_with_redirects"); + + const missingRedirectLimit = createPackageFixture(); + const missingRedirectLimitPath = path.join(missingRedirectLimit, "deepagents_code", "tools.py"); + fs.writeFileSync( + missingRedirectLimitPath, + fs + .readFileSync(missingRedirectLimitPath, "utf8") + .replace("_MAX_FETCH_REDIRECTS = 5", "_RENAMED_MAX_FETCH_REDIRECTS = 5"), + "utf8", + ); + const redirectLimitResult = spawnSync("python3", [patcher], { + env: { PATH: process.env.PATH, PYTHONPATH: missingRedirectLimit }, + encoding: "utf8", + }); + expect(redirectLimitResult.status).not.toBe(0); + expect(redirectLimitResult.stderr).toContain("_MAX_FETCH_REDIRECTS"); + + const missingValidationError = createPackageFixture(); + const missingValidationErrorPath = path.join( + missingValidationError, + "deepagents_code", + "tools.py", + ); + fs.writeFileSync( + missingValidationErrorPath, + fs + .readFileSync(missingValidationErrorPath, "utf8") + .replace("class _UrlValidationError", "class _RenamedUrlValidationError"), + "utf8", + ); + const validationErrorResult = spawnSync("python3", [patcher], { + env: { PATH: process.env.PATH, PYTHONPATH: missingValidationError }, + encoding: "utf8", + }); + expect(validationErrorResult.status).not.toBe(0); + expect(validationErrorResult.stderr).toContain("_UrlValidationError"); }); }); diff --git a/test/langchain-deepagents-code-fetch-proxy.test.ts b/test/langchain-deepagents-code-fetch-proxy.test.ts index 5bce1416ff1..7b74ddcc0ce 100644 --- a/test/langchain-deepagents-code-fetch-proxy.test.ts +++ b/test/langchain-deepagents-code-fetch-proxy.test.ts @@ -49,6 +49,8 @@ describe("LangChain Deep Agents Code managed fetch proxy", () => { const runtimeFile = path.join(tempDir, "managed-dcode-runtime.py"); fs.writeFileSync(hostFile, "trusted-proxy.internal\n", { mode: 0o444 }); fs.writeFileSync(portFile, "3129\n", { mode: 0o444 }); + fs.chmodSync(hostFile, 0o444); + fs.chmodSync(portFile, 0o444); fs.writeFileSync( runtimeFile, addDarwinFcntlSealConstants(readAgentFile("managed-dcode-runtime.py")), @@ -134,7 +136,7 @@ print("root-owned-proxy-verification-ok") }); }); - it("exercises actual fetch_url success and denied-host paths in cloud E2E", () => { + it("pins the cloud E2E wiring for fetch_url success and denied-host paths", () => { const check = fs.readFileSync( path.join( repoRoot, diff --git a/test/langchain-deepagents-code-proxy-launcher.test.ts b/test/langchain-deepagents-code-proxy-launcher.test.ts index 9d6dcec023b..54fdf5f5805 100644 --- a/test/langchain-deepagents-code-proxy-launcher.test.ts +++ b/test/langchain-deepagents-code-proxy-launcher.test.ts @@ -8,6 +8,7 @@ import path from "node:path"; import { describe, expect, it } from "vitest"; import { isValidProxyHost, isValidProxyPort } from "../src/lib/onboard/dockerfile-patch.ts"; +import { TRUSTED_FETCH_PROXY_ENV_NAME } from "./helpers/langchain-deepagents-code-headless.ts"; const agentDir = path.join(process.cwd(), "agents", "langchain-deepagents-code"); const headlessCheckPath = path.join( @@ -21,7 +22,6 @@ const headlessCheckPath = path.join( const PROXY_URL_ENV_NAMES = ["HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"] as const; const NO_PROXY_ENV_NAMES = ["NO_PROXY", "no_proxy"] as const; const CLEARED_PROXY_ENV_NAMES = ["ALL_PROXY", "all_proxy", "OPENAI_PROXY"] as const; -const TRUSTED_FETCH_PROXY_ENV_NAME = "DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL"; const DEFAULT_MANAGED_PROXY = { host: "10.200.0.1", port: "3128" } as const; const TEST_OWNER_UID = process.getuid?.() ?? 0; From c26f25996d085b3ff885c09c942078115f3eee58 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 8 Jul 2026 14:38:33 -0700 Subject: [PATCH 07/21] test(dcode): cover managed fetch redirect boundaries Signed-off-by: Aaron Erickson --- ...eepagents-code-direct-module-patch.test.ts | 114 ++++++++++++++++-- 1 file changed, 102 insertions(+), 12 deletions(-) diff --git a/test/langchain-deepagents-code-direct-module-patch.test.ts b/test/langchain-deepagents-code-direct-module-patch.test.ts index 31b08b673fb..f7dd85e94e4 100644 --- a/test/langchain-deepagents-code-direct-module-patch.test.ts +++ b/test/langchain-deepagents-code-direct-module-patch.test.ts @@ -230,7 +230,7 @@ else: } }); - it("routes fetch_url through only the explicit managed proxy without direct DNS", () => { + it("keeps redirects and concurrent fetches behind the explicit proxy without direct DNS", () => { const tempDir = createPackageFixture(); patchFixture(tempDir); const proxyUrl = "http://managed-proxy.internal:3128"; @@ -241,32 +241,48 @@ else: ` import builtins import os +import socket import sys import types +from concurrent.futures import ThreadPoolExecutor from pathlib import Path calls = [] responses = [] +sessions = [] + +class ProxyPolicyDenied(RuntimeError): + pass class Response: - def __init__(self, status_code=200, location=None): + def __init__(self, status_code=200, location=None, error=None): self.status_code = status_code self.headers = {} if location is None else {"Location": location} + self.error = error def raise_for_status(self): + if self.error is not None: + raise self.error return None class Session: def __init__(self): self.trust_env = True + self.calls = [] + sessions.append(self) def get(self, url, **kwargs): - calls.append((self.trust_env, url, kwargs)) + call = (self.trust_env, url, kwargs) + self.calls.append(call) + calls.append(call) return responses.pop(0) if responses else Response() requests = types.ModuleType("requests") requests.Session = Session -requests.exceptions = types.SimpleNamespace(TooManyRedirects=RuntimeError) +requests.exceptions = types.SimpleNamespace( + HTTPError=ProxyPolicyDenied, + TooManyRedirects=RuntimeError, +) sys.modules["requests"] = requests from deepagents_code import _nemoclaw_managed, tools @@ -297,6 +313,29 @@ def forbidden_direct_dns(*_args, **_kwargs): raise AssertionError("managed fetch attempted direct DNS validation") tools._validate_url = forbidden_direct_dns +expected_proxies = { + "http": ${JSON.stringify(proxyUrl)}, + "https": ${JSON.stringify(proxyUrl)}, +} + +def assert_managed_hops(expected_urls): + assert [url for _, url, _ in calls] == expected_urls + assert all(trust_env is False for trust_env, _, _ in calls) + assert all(kwargs["proxies"] == expected_proxies for _, _, kwargs in calls) + assert all(kwargs["verify"] == str(managed_ca_file) for _, _, kwargs in calls) + +def expect_redirect_policy_denial(initial_url, redirect_url): + calls.clear() + denial = ProxyPolicyDenied("403 policy_denied") + responses.extend([Response(302, redirect_url), Response(403, error=denial)]) + try: + tools._fetch_with_redirects(initial_url, timeout=8) + except ProxyPolicyDenied as exc: + assert exc is denial + else: + raise AssertionError("redirect escaped proxy policy denial") + assert_managed_hops([initial_url, redirect_url]) + response = tools._fetch_with_redirects("https://raw.githubusercontent.com/example/repo/main/README.md", timeout=8) assert response.status_code == 200 assert calls == [( @@ -340,16 +379,35 @@ response = tools._fetch_with_redirects( timeout=8, ) assert response.status_code == 200 -assert [url for _, url, _ in calls] == [ +assert_managed_hops([ "https://raw.githubusercontent.com/example/repo/start", "https://raw.githubusercontent.com/example/main/README.md", -] -assert all( - kwargs["proxies"] - == {"http": ${JSON.stringify(proxyUrl)}, "https": ${JSON.stringify(proxyUrl)}} - for _, _, kwargs in calls +]) + +# Cross-host redirects remain behind the same explicit proxy. The adapter does +# not locally authorize IMDS; it propagates the policy proxy's denial. The live +# egress check separately proves that OpenShell denies the IMDS destination. +metadata_url = "https://169.254.169.254/latest/meta-data/" +expect_redirect_policy_denial( + "https://raw.githubusercontent.com/example/redirect-to-imds", + metadata_url, ) -assert all(kwargs["verify"] == str(managed_ca_file) for _, _, kwargs in calls) + +# DNS and resolved-IP policy belong to OpenShell. A rebinding candidate must be +# passed by hostname through the explicit proxy without local DNS, and the +# proxy's denial must propagate rather than triggering a direct retry. +rebind_url = "https://rebind.attacker.invalid/private" +original_getaddrinfo = socket.getaddrinfo +def forbidden_local_dns(*_args, **_kwargs): + raise AssertionError("managed redirect attempted local DNS") +socket.getaddrinfo = forbidden_local_dns +try: + expect_redirect_policy_denial( + "https://raw.githubusercontent.com/example/redirect-to-rebind", + rebind_url, + ) +finally: + socket.getaddrinfo = original_getaddrinfo calls.clear() responses.append(Response(302)) @@ -361,7 +419,7 @@ else: raise AssertionError("redirect without Location escaped validation") calls.clear() -responses.append(Response(302, "https://user:redirect-secret@raw.githubusercontent.com/private")) +responses.append(Response(302, "http://user:redirect-secret@proxy.internal:3128/private")) try: tools._fetch_with_redirects("https://raw.githubusercontent.com/credential-redirect", timeout=8) except tools._UrlValidationError as exc: @@ -478,6 +536,38 @@ except RuntimeError as exc: else: raise AssertionError("wrong-owner CA bundle was accepted") _nemoclaw_managed._MANAGED_FILE_OWNER_UID = os.getuid() + +# The proxy and CA are immutable process-wide image inputs. Per-call isolation +# therefore means a fresh Session and explicit proxy mapping for each fetch, +# including concurrent calls, rather than unsupported mutable configurations. +calls.clear() +session_start = len(sessions) +concurrent_urls = [ + f"https://raw.githubusercontent.com/example/concurrent-{index}" + for index in range(4) +] +with ThreadPoolExecutor(max_workers=len(concurrent_urls)) as executor: + concurrent_responses = list(executor.map( + lambda candidate: tools._fetch_with_redirects(candidate, timeout=8), + concurrent_urls, + )) +concurrent_sessions = sessions[session_start:] +assert all(response.status_code == 200 for response in concurrent_responses) +assert len(concurrent_sessions) == len(concurrent_urls) +assert all(session.trust_env is False for session in concurrent_sessions) +assert all(len(session.calls) == 1 for session in concurrent_sessions) +assert {session.calls[0][1] for session in concurrent_sessions} == set(concurrent_urls) +assert all( + session.calls[0][2]["proxies"] == expected_proxies + for session in concurrent_sessions +) +assert all( + session.calls[0][2]["verify"] == str(managed_ca_file) + for session in concurrent_sessions +) +assert len({id(session.calls[0][2]["proxies"]) for session in concurrent_sessions}) == len( + concurrent_sessions +) print("managed-fetch-proxy-ok") `, ], From 06fc27664fb04fbf71dec867a4d638eac0c4d3ac Mon Sep 17 00:00:00 2001 From: cjagwani Date: Wed, 8 Jul 2026 22:10:16 +0000 Subject: [PATCH 08/21] test(e2e): restore Tavily policy after opt-in Signed-off-by: cjagwani --- .../09-deepagents-code-tavily-opt-in.sh | 24 +++++++++++++++++++ ...platform-parity-cloud-experimental.test.ts | 15 ++++++++++++ 2 files changed, 39 insertions(+) diff --git a/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh b/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh index 3f093dd621f..429daa38f80 100755 --- a/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh +++ b/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh @@ -200,5 +200,29 @@ else fail_test "project venv under /sandbox did not expose a usable python3 executable: $PROJECT_OUT" fi +# Restore the deny-by-default posture for later checks in this ordered live +# suite. Rebuild validation intentionally preserves active policy presets, so +# leaving Tavily enabled here would make a later baseline egress check claim +# that thread auto-approval widened network access when it only retained this +# explicit opt-in. +REMOVE_OUTPUT="$(nemoclaw_cli "$SANDBOX_NAME" policy-remove tavily --yes 2>&1)" || { + fail_test "policy-remove tavily failed: $REMOVE_OUTPUT" + printf '%s\n' "${PREFIX}: $PASSED passed, $FAILED failed" + exit 1 +} +pass "tavily policy preset removes after the opt-in proof" + +sleep "${NEMOCLAW_E2E_POLICY_SETTLE_SECONDS:-5}" + +REMOVED_PROBE_OUTPUT="$(python_probe "https://api.tavily.com/search" || true)" +if echo "$REMOVED_PROBE_OUTPUT" | grep -q "BLOCKED:" \ + && ! echo "$REMOVED_PROBE_OUTPUT" | grep -q "REACHED:"; then + pass "managed Deep Agents Code python is blocked again after policy-remove" +elif echo "$REMOVED_PROBE_OUTPUT" | grep -q "REACHED:"; then + fail_test "managed Deep Agents Code python still reached Tavily after policy-remove: $REMOVED_PROBE_OUTPUT" +else + fail_test "post-remove Tavily probe lacked denial evidence: $REMOVED_PROBE_OUTPUT" +fi + printf '%s\n' "${PREFIX}: $PASSED passed, $FAILED failed" [ "$FAILED" -eq 0 ] || exit 1 diff --git a/test/e2e/support/platform-parity-cloud-experimental.test.ts b/test/e2e/support/platform-parity-cloud-experimental.test.ts index 1ca85e61b2d..abb3026144c 100644 --- a/test/e2e/support/platform-parity-cloud-experimental.test.ts +++ b/test/e2e/support/platform-parity-cloud-experimental.test.ts @@ -347,6 +347,21 @@ describe("P0-E cloud-experimental parity guardrails", () => { expect(result.stdout).toContain("NO_NEWLINE_IN_COMMAND"); }); + it("restores Tavily denial after the opt-in proof for later ordered checks", () => { + const script = fs.readFileSync( + path.join( + process.cwd(), + "test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh", + ), + "utf8", + ); + + expect(script).toContain("policy-remove tavily --yes"); + expect(script).toContain( + "managed Deep Agents Code python is blocked again after policy-remove", + ); + }); + it("keeps the managed DCode thread-auto-approval live check valid Bash (#6478)", () => { const scriptPath = path.join( process.cwd(), From 62d34d132a87125aeb4949937943b1439e3800dd Mon Sep 17 00:00:00 2001 From: cjagwani Date: Wed, 8 Jul 2026 22:24:28 +0000 Subject: [PATCH 09/21] test(e2e): restore observability after policy cleanup Signed-off-by: cjagwani --- .../09-deepagents-code-tavily-opt-in.sh | 28 +++++++++++++++++++ ...platform-parity-cloud-experimental.test.ts | 13 ++++++++- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh b/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh index 429daa38f80..c39efac2050 100755 --- a/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh +++ b/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh @@ -28,6 +28,12 @@ sandbox_exec() { openshell sandbox exec --name "$SANDBOX_NAME" -- bash -c "$1" 2>&1 } +observability_marker_value() { + openshell sandbox exec --name "$SANDBOX_NAME" -- \ + sh -c 'if test -f /tmp/nemoclaw-observability-enabled; then cat /tmp/nemoclaw-observability-enabled; else printf "absent"; fi' \ + 2>/dev/null +} + nemoclaw_cli() { if [ -f "$CLI" ]; then node "$CLI" "$@" @@ -138,6 +144,8 @@ if ! sandbox_exec "test -d /sandbox/.deepagents && command -v dcode >/dev/null 2 exit 0 fi +OBSERVABILITY_MARKER_BEFORE="$(observability_marker_value || true)" + info "Running Deep Agents Code Tavily opt-in check in sandbox: $SANDBOX_NAME" # shellcheck disable=SC2016 # command substitution must run inside the sandbox. @@ -224,5 +232,25 @@ else fail_test "post-remove Tavily probe lacked denial evidence: $REMOVED_PROBE_OUTPUT" fi +# The temporary Tavily policy belongs only to this check. OpenShell can clear +# /tmp while applying the narrower replacement policy, so restore an +# observability marker that existed before the check through the canonical +# startup helper instead of manufacturing the marker in the test. +if [ "$OBSERVABILITY_MARKER_BEFORE" = "1" ]; then + OBSERVABILITY_MARKER_AFTER="$(observability_marker_value || true)" + if [ "$OBSERVABILITY_MARKER_AFTER" != "1" ]; then + RESTORE_OUTPUT="$(openshell sandbox exec --name "$SANDBOX_NAME" -- \ + /usr/bin/env NEMOCLAW_OBSERVABILITY=1 \ + /usr/local/bin/nemoclaw-start /usr/bin/true 2>&1)" || \ + fail_test "could not restore managed observability after policy-remove: $RESTORE_OUTPUT" + fi + OBSERVABILITY_MARKER_AFTER="$(observability_marker_value || true)" + if [ "$OBSERVABILITY_MARKER_AFTER" = "1" ]; then + pass "managed observability state restores after policy-remove" + else + fail_test "managed observability marker was not restored after policy-remove" + fi +fi + printf '%s\n' "${PREFIX}: $PASSED passed, $FAILED failed" [ "$FAILED" -eq 0 ] || exit 1 diff --git a/test/e2e/support/platform-parity-cloud-experimental.test.ts b/test/e2e/support/platform-parity-cloud-experimental.test.ts index abb3026144c..8ace94ff562 100644 --- a/test/e2e/support/platform-parity-cloud-experimental.test.ts +++ b/test/e2e/support/platform-parity-cloud-experimental.test.ts @@ -347,7 +347,7 @@ describe("P0-E cloud-experimental parity guardrails", () => { expect(result.stdout).toContain("NO_NEWLINE_IN_COMMAND"); }); - it("restores Tavily denial after the opt-in proof for later ordered checks", () => { + it("restores Tavily denial and the prior runtime marker for later ordered checks", () => { const script = fs.readFileSync( path.join( process.cwd(), @@ -360,6 +360,17 @@ describe("P0-E cloud-experimental parity guardrails", () => { expect(script).toContain( "managed Deep Agents Code python is blocked again after policy-remove", ); + expect(script).toContain("/usr/bin/env NEMOCLAW_OBSERVABILITY=1"); + expect(script).toContain("/usr/local/bin/nemoclaw-start /usr/bin/true"); + + const markerSnapshot = script.indexOf("OBSERVABILITY_MARKER_BEFORE="); + const policyRemove = script.indexOf("policy-remove tavily --yes"); + const denialProof = script.indexOf("REMOVED_PROBE_OUTPUT="); + const markerRestore = script.indexOf("/usr/bin/env NEMOCLAW_OBSERVABILITY=1"); + expect(markerSnapshot).toBeGreaterThanOrEqual(0); + expect(markerSnapshot).toBeLessThan(policyRemove); + expect(policyRemove).toBeLessThan(denialProof); + expect(denialProof).toBeLessThan(markerRestore); }); it("keeps the managed DCode thread-auto-approval live check valid Bash (#6478)", () => { From dddc00051694a84a55a97c421296603f13694c5a Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 8 Jul 2026 15:27:29 -0700 Subject: [PATCH 10/21] fix(dcode): harden managed fetch validation Signed-off-by: Aaron Erickson --- .../managed-dcode-runtime.py | 141 +++++++++++------- .../09-deepagents-code-tavily-opt-in.sh | 4 +- ...gchain-deepagents-code-fetch-proxy.test.ts | 106 +++++++++++-- 3 files changed, 183 insertions(+), 68 deletions(-) diff --git a/agents/langchain-deepagents-code/managed-dcode-runtime.py b/agents/langchain-deepagents-code/managed-dcode-runtime.py index a43b60a7b60..724213c51ae 100644 --- a/agents/langchain-deepagents-code/managed-dcode-runtime.py +++ b/agents/langchain-deepagents-code/managed-dcode-runtime.py @@ -1013,32 +1013,62 @@ def _managed_fetch_proxy_url_from_files() -> str: return f"http://{host}:{port}" -def _managed_fetch_ca_bundle() -> str: - """Validate fixed OpenShell TLS trust without granting network authority.""" +def _managed_fetch_ca_bundle() -> tuple[int, str]: + """Open and validate fixed OpenShell TLS trust without a pathname race.""" path = _MANAGED_FETCH_CA_BUNDLE_FILE + no_follow = getattr(os, "O_NOFOLLOW", None) + if no_follow is None: + raise RuntimeError("managed fetch CA bundle is invalid") + flags = os.O_RDONLY | no_follow | getattr(os, "O_CLOEXEC", 0) try: - link_metadata = path.lstat() + descriptor = os.open(path, flags) except FileNotFoundError: raise RuntimeError("managed fetch CA bundle is unavailable") from None except OSError: raise RuntimeError("managed fetch CA bundle is invalid") from None - if stat.S_ISLNK(link_metadata.st_mode): - raise RuntimeError("managed fetch CA bundle is invalid") + try: - metadata = path.stat() - except FileNotFoundError: - raise RuntimeError("managed fetch CA bundle is unavailable") from None + metadata = os.fstat(descriptor) + if ( + not stat.S_ISREG(metadata.st_mode) + or metadata.st_uid != _MANAGED_FILE_OWNER_UID + or stat.S_IMODE(metadata.st_mode) & 0o022 + or metadata.st_size <= 0 + ): + raise RuntimeError("managed fetch CA bundle is invalid") + descriptor_path = next( + ( + candidate + for root in ("/proc/self/fd", "/dev/fd") + if os.path.exists(candidate := f"{root}/{descriptor}") + ), + None, + ) + if descriptor_path is None: + raise RuntimeError("managed fetch CA bundle is invalid") + return descriptor, descriptor_path + except OSError: + os.close(descriptor) + raise RuntimeError("managed fetch CA bundle is invalid") from None + except RuntimeError: + os.close(descriptor) + raise + + +def _close_managed_fetch_ca_bundle(descriptor: int) -> None: + try: + os.close(descriptor) + except OSError: + # Closing the read-only trust snapshot cannot expand authority. + pass + + +def _rewind_managed_fetch_ca_bundle(descriptor: int) -> None: + """Reset fd-backed trust before each synchronous transport read.""" + try: + os.lseek(descriptor, 0, os.SEEK_SET) except OSError: raise RuntimeError("managed fetch CA bundle is invalid") from None - if ( - not stat.S_ISREG(metadata.st_mode) - or metadata.st_uid != _MANAGED_FILE_OWNER_UID - or stat.S_IMODE(metadata.st_mode) & 0o022 - or metadata.st_size <= 0 - or not os.access(path, os.R_OK) - ): - raise RuntimeError("managed fetch CA bundle is invalid") - return str(path) def managed_fetch_with_redirects( @@ -1074,7 +1104,7 @@ def managed_fetch_with_redirects( "managed fetch transport dependency is unavailable" ) from None try: - ca_bundle = _managed_fetch_ca_bundle() + ca_descriptor, ca_bundle = _managed_fetch_ca_bundle() except RuntimeError as exc: raise validation_error(str(exc)) from None @@ -1103,44 +1133,49 @@ def validate_url(candidate: str) -> None: raise validation_error("URL credentials are not allowed") try: hostname.encode("idna").decode("ascii") - except UnicodeError as exc: - raise validation_error( - f"Could not encode hostname {hostname!r} as IDNA: {exc}" - ) from exc + except UnicodeError: + raise validation_error("URL hostname is not valid IDNA") from None current_url = url proxies = {"http": proxy_url, "https": proxy_url} - with requests.Session() as session: - # Disable every requests environment-derived session setting, including - # proxy/NO_PROXY, netrc, and CA-bundle discovery. Each request receives - # the sole root-verified proxy mapping explicitly below. The separately - # selected CA bundle establishes TLS transport trust only; it cannot - # choose a proxy or authorize a destination under OpenShell policy. - session.trust_env = False - for _hop in range(max_redirects + 1): - validate_url(current_url) - response = session.get( - current_url, - timeout=timeout, - headers={"User-Agent": "Mozilla/5.0 (compatible; DeepAgents/1.0)"}, - allow_redirects=False, - proxies=proxies, - verify=ca_bundle, - ) - if 300 <= response.status_code < 400: - location = response.headers.get("Location") - if not location: - raise validation_error( - f"Redirect response (status {response.status_code}) is missing a Location header" - ) - current_url = urljoin(current_url, location) - continue - response.raise_for_status() - return response - - raise requests.exceptions.TooManyRedirects( - f"Exceeded {max_redirects} redirects" - ) + try: + with requests.Session() as session: + # Disable every requests environment-derived session setting, including + # proxy/NO_PROXY, netrc, and CA-bundle discovery. Each request receives + # the sole root-verified proxy mapping explicitly below. The separately + # selected CA bundle establishes TLS transport trust only; it cannot + # choose a proxy or authorize a destination under OpenShell policy. + session.trust_env = False + for _hop in range(max_redirects + 1): + validate_url(current_url) + try: + _rewind_managed_fetch_ca_bundle(ca_descriptor) + except RuntimeError as exc: + raise validation_error(str(exc)) from None + response = session.get( + current_url, + timeout=timeout, + headers={"User-Agent": "Mozilla/5.0 (compatible; DeepAgents/1.0)"}, + allow_redirects=False, + proxies=proxies, + verify=ca_bundle, + ) + if 300 <= response.status_code < 400: + location = response.headers.get("Location") + if not location: + raise validation_error( + f"Redirect response (status {response.status_code}) is missing a Location header" + ) + current_url = urljoin(current_url, location) + continue + response.raise_for_status() + return response + + raise requests.exceptions.TooManyRedirects( + f"Exceeded {max_redirects} redirects" + ) + finally: + _close_managed_fetch_ca_bundle(ca_descriptor) def _disabled_auto_approval(reason: str) -> str: diff --git a/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh b/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh index c39efac2050..7bc6756bc50 100755 --- a/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh +++ b/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh @@ -241,8 +241,8 @@ if [ "$OBSERVABILITY_MARKER_BEFORE" = "1" ]; then if [ "$OBSERVABILITY_MARKER_AFTER" != "1" ]; then RESTORE_OUTPUT="$(openshell sandbox exec --name "$SANDBOX_NAME" -- \ /usr/bin/env NEMOCLAW_OBSERVABILITY=1 \ - /usr/local/bin/nemoclaw-start /usr/bin/true 2>&1)" || \ - fail_test "could not restore managed observability after policy-remove: $RESTORE_OUTPUT" + /usr/local/bin/nemoclaw-start /usr/bin/true 2>&1)" \ + || fail_test "could not restore managed observability after policy-remove: $RESTORE_OUTPUT" fi OBSERVABILITY_MARKER_AFTER="$(observability_marker_value || true)" if [ "$OBSERVABILITY_MARKER_AFTER" = "1" ]; then diff --git a/test/langchain-deepagents-code-fetch-proxy.test.ts b/test/langchain-deepagents-code-fetch-proxy.test.ts index bfa84177fec..0b613983fbf 100644 --- a/test/langchain-deepagents-code-fetch-proxy.test.ts +++ b/test/langchain-deepagents-code-fetch-proxy.test.ts @@ -184,10 +184,12 @@ import sys import types from concurrent.futures import ThreadPoolExecutor from pathlib import Path +from threading import Thread calls = [] responses = [] sessions = [] +ca_swap_thread = None class ProxyPolicyDenied(RuntimeError): pass @@ -207,6 +209,7 @@ class Session: def __init__(self): self.trust_env = True self.calls = [] + self.ca_contents = [] self.closed = False sessions.append(self) @@ -217,6 +220,14 @@ class Session: self.closed = True def get(self, url, **kwargs): + global ca_swap_thread + if ca_swap_thread is not None: + thread = ca_swap_thread + ca_swap_thread = None + thread.start() + thread.join() + assert not thread.is_alive() + self.ca_contents.append(Path(kwargs["verify"]).read_text(encoding="utf-8")) call = (self.trust_env, url, kwargs) self.calls.append(call) calls.append(call) @@ -233,11 +244,13 @@ from deepagents_code._nemoclaw_managed import managed_fetch_proxy_url proxy_host_file = Path(${JSON.stringify(tempDir)}) / "managed-proxy-host" proxy_port_file = Path(${JSON.stringify(tempDir)}) / "managed-proxy-port" managed_ca_file = Path(${JSON.stringify(tempDir)}) / "managed-ca.pem" +attacker_ca_file = Path(${JSON.stringify(tempDir)}) / "attacker-ca.pem" writable_ca_file = Path(${JSON.stringify(tempDir)}) / "writable-sensitive-ca.pem" symlink_ca_file = Path(${JSON.stringify(tempDir)}) / "symlink-sensitive-ca.pem" proxy_host_file.write_text("managed-proxy.internal\\n", encoding="utf-8") proxy_port_file.write_text("3128\\n", encoding="utf-8") managed_ca_file.write_text("test CA bundle\\n", encoding="utf-8") +attacker_ca_file.write_text("attacker CA bundle\\n", encoding="utf-8") writable_ca_file.write_text("unsafe CA bundle\\n", encoding="utf-8") writable_ca_file.chmod(0o666) symlink_ca_file.symlink_to(managed_ca_file) @@ -257,11 +270,18 @@ def forbidden_direct_dns(*_args, **_kwargs): tools._validate_url = forbidden_direct_dns expected_proxies = {"http": ${JSON.stringify(proxyUrl)}, "https": ${JSON.stringify(proxyUrl)}} +def assert_fd_ca_path(candidate): + assert candidate.startswith(("/proc/self/fd/", "/dev/fd/")) + def assert_managed_hops(expected_urls): assert [url for _, url, _ in calls] == expected_urls assert all(trust_env is False for trust_env, _, _ in calls) assert all(kwargs["proxies"] == expected_proxies for _, _, kwargs in calls) - assert all(kwargs["verify"] == str(managed_ca_file) for _, _, kwargs in calls) + assert all( + kwargs["verify"].startswith(("/proc/self/fd/", "/dev/fd/")) + for _, _, kwargs in calls + ) + assert sessions[-1].ca_contents == ["test CA bundle\\n"] * len(expected_urls) def expect_redirect_policy_denial(initial_url, redirect_url, label): calls.clear() @@ -279,17 +299,20 @@ def expect_redirect_policy_denial(initial_url, redirect_url, label): response = tools._fetch_with_redirects("https://raw.githubusercontent.com/example/repo/main/README.md", timeout=8) assert response.status_code == 200 assert len(sessions) == 1 and sessions[0].closed -assert calls == [( - False, - "https://raw.githubusercontent.com/example/repo/main/README.md", - { - "timeout": 8, - "headers": {"User-Agent": "Mozilla/5.0 (compatible; DeepAgents/1.0)"}, - "allow_redirects": False, - "proxies": {"http": ${JSON.stringify(proxyUrl)}, "https": ${JSON.stringify(proxyUrl)}}, - "verify": str(managed_ca_file), - }, -)] +assert len(calls) == 1 +trust_env, called_url, call_kwargs = calls[0] +assert trust_env is False +assert called_url == "https://raw.githubusercontent.com/example/repo/main/README.md" +assert { + key: value for key, value in call_kwargs.items() if key != "verify" +} == { + "timeout": 8, + "headers": {"User-Agent": "Mozilla/5.0 (compatible; DeepAgents/1.0)"}, + "allow_redirects": False, + "proxies": {"http": ${JSON.stringify(proxyUrl)}, "https": ${JSON.stringify(proxyUrl)}}, +} +assert_fd_ca_path(call_kwargs["verify"]) +assert sessions[0].ca_contents == ["test CA bundle\\n"] calls.clear() path_data_url = "https://raw.githubusercontent.com/example/path@segment:ordinary-data" @@ -372,6 +395,35 @@ else: raise AssertionError("credentialed redirect escaped validation") assert len(calls) == 1 +sensitive_idna_label = "sk-EXAMPLE-DO-NOT-REFLECT" +invalid_idna_url = f"https://{sensitive_idna_label}{chr(0xD800)}.invalid/private" +calls.clear() +try: + tools._fetch_with_redirects(invalid_idna_url, timeout=8) +except tools._UrlValidationError as exc: + assert str(exc) == "URL hostname is not valid IDNA" + assert sensitive_idna_label not in str(exc) + assert "Unicode" not in str(exc) + assert exc.__cause__ is None + assert exc.__suppress_context__ is True +else: + raise AssertionError("invalid initial IDNA hostname escaped validation") +assert calls == [] + +calls.clear() +responses.append(Response(302, invalid_idna_url)) +try: + tools._fetch_with_redirects("https://raw.githubusercontent.com/idna-redirect", timeout=8) +except tools._UrlValidationError as exc: + assert str(exc) == "URL hostname is not valid IDNA" + assert sensitive_idna_label not in str(exc) + assert "Unicode" not in str(exc) + assert exc.__cause__ is None + assert exc.__suppress_context__ is True +else: + raise AssertionError("invalid redirect IDNA hostname escaped validation") +assert len(calls) == 1 + calls.clear() responses.append(Response(302, "https://raw.githubusercontent.com/next")) tools._MAX_FETCH_REDIRECTS = 0 @@ -452,6 +504,30 @@ else: finally: builtins.__import__ = original_import +# Atomically replace the validated pathname after the managed helper opens it, +# but before the transport consumes the CA input. The fd-backed verify path +# must remain pinned to the original root-owned trust bytes. +def replace_managed_ca_path(): + replacement = managed_ca_file.with_name("managed-ca-replacement") + if replacement.exists() or replacement.is_symlink(): + replacement.unlink() + replacement.symlink_to(attacker_ca_file) + os.replace(replacement, managed_ca_file) + +calls.clear() +ca_swap_thread = Thread(target=replace_managed_ca_path) +response = tools._fetch_with_redirects( + "https://raw.githubusercontent.com/example/ca-swap", + timeout=8, +) +assert response.status_code == 200 +assert managed_ca_file.is_symlink() +assert managed_ca_file.read_text(encoding="utf-8") == "attacker CA bundle\\n" +assert sessions[-1].ca_contents == ["test CA bundle\\n"] +assert_fd_ca_path(calls[0][2]["verify"]) +managed_ca_file.unlink() +managed_ca_file.write_text("test CA bundle\\n", encoding="utf-8") + for invalid_ca_bundle, expected_error in ( ( Path(${JSON.stringify(tempDir)}) / "missing-sensitive-ca.pem", @@ -505,7 +581,11 @@ assert all( for session in concurrent_sessions ) assert all( - session.calls[0][2]["verify"] == str(managed_ca_file) + session.calls[0][2]["verify"].startswith(("/proc/self/fd/", "/dev/fd/")) + for session in concurrent_sessions +) +assert all( + session.ca_contents == ["test CA bundle\\n"] for session in concurrent_sessions ) assert len({id(session.calls[0][2]["proxies"]) for session in concurrent_sessions}) == len( From d0b1871bcf37156b989c93572cc30e9210938a27 Mon Sep 17 00:00:00 2001 From: cjagwani Date: Wed, 8 Jul 2026 22:33:25 +0000 Subject: [PATCH 11/21] test(e2e): exercise policy cleanup boundary Signed-off-by: cjagwani --- .../09-deepagents-code-tavily-opt-in.sh | 81 ++++++++++++++++++- ...platform-parity-cloud-experimental.test.ts | 43 +++++----- 2 files changed, 104 insertions(+), 20 deletions(-) diff --git a/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh b/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh index 7bc6756bc50..ab8d1f4f8f2 100755 --- a/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh +++ b/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh @@ -30,7 +30,7 @@ sandbox_exec() { observability_marker_value() { openshell sandbox exec --name "$SANDBOX_NAME" -- \ - sh -c 'if test -f /tmp/nemoclaw-observability-enabled; then cat /tmp/nemoclaw-observability-enabled; else printf "absent"; fi' \ + sh -c 'marker=/tmp/nemoclaw-observability-enabled; if test -f "$marker" && ! test -L "$marker"; then cat "$marker"; else printf "absent"; fi' \ 2>/dev/null } @@ -139,6 +139,82 @@ if [ "${NEMOCLAW_E2E_TAVILY_SELF_TEST:-}" = "probe-command-shape" ]; then exit 0 fi +POLICY_CLEANUP_TRACE="" +POLICY_CLEANUP_FIXTURE_DIR="" +if [ "${NEMOCLAW_E2E_TAVILY_SELF_TEST:-}" = "policy-cleanup-order" ]; then + POLICY_CLEANUP_FIXTURE_DIR="$(mktemp -d)" + POLICY_CLEANUP_TRACE="${POLICY_CLEANUP_FIXTURE_DIR}/trace" + POLICY_CLEANUP_STATE="${POLICY_CLEANUP_FIXTURE_DIR}/policy-state" + POLICY_CLEANUP_MARKER="${POLICY_CLEANUP_FIXTURE_DIR}/observability-marker" + printf '%s\n' "baseline" >"$POLICY_CLEANUP_STATE" + printf '%s\n' "1" >"$POLICY_CLEANUP_MARKER" + trap 'rm -rf "$POLICY_CLEANUP_FIXTURE_DIR"' EXIT + + sandbox_exec() { + case "$1" in + *"test -d /sandbox/.deepagents"*) return 0 ;; + *'readlink -f "$(command -v python3)"'*) printf '%s\n' "/opt/venv/bin/python3" ;; + *"/sandbox/.nemoclaw-e2e-project-venv"*) printf '%s\n' "$PROJECT_PYTHON" ;; + *) + printf '%s\n' "unexpected sandbox command in Tavily cleanup self-test" >&2 + return 91 + ;; + esac + } + observability_marker_value() { + cat "$POLICY_CLEANUP_MARKER" + } + nemoclaw_cli() { + local action="${2:-}:${3:-}:${4:-}" + case "$action" in + policy-add:tavily:--dry-run) printf '%s\n' "api.tavily.com" ;; + policy-add:tavily:--yes) + printf '%s\n' "added" >"$POLICY_CLEANUP_STATE" + printf '%s\n' "TRACE:opt-in-proof" >>"$POLICY_CLEANUP_TRACE" + ;; + policy-remove:tavily:--yes) + printf '%s\n' "removed" >"$POLICY_CLEANUP_STATE" + printf '%s\n' "absent" >"$POLICY_CLEANUP_MARKER" + printf '%s\n' "TRACE:policy-remove" >>"$POLICY_CLEANUP_TRACE" + ;; + *) + printf '%s\n' "unexpected CLI action in Tavily cleanup self-test: $action" >&2 + return 92 + ;; + esac + } + python_probe() { + local python_bin="${2:-python3}" + local state + state="$(cat "$POLICY_CLEANUP_STATE")" + if [ "$python_bin" != "python3" ]; then + printf '%s\n' "BLOCKED:fixture non-managed Python" + elif [ "$state" = "added" ]; then + printf '%s\n' "REACHED:403" + elif [ "$state" = "removed" ]; then + printf '%s\n' "TRACE:post-remove-blocked" >>"$POLICY_CLEANUP_TRACE" + printf '%s\n' "BLOCKED:fixture restored denial" + else + printf '%s\n' "ERROR:unexpected fixture policy state" + fi + } + openshell() { + case "$*" in + *"NEMOCLAW_OBSERVABILITY=1"*"/usr/local/bin/nemoclaw-start /usr/bin/true"*) + printf '%s\n' "1" >"$POLICY_CLEANUP_MARKER" + printf '%s\n' "TRACE:observability-restore" >>"$POLICY_CLEANUP_TRACE" + ;; + *) + printf '%s\n' "unexpected OpenShell action in Tavily cleanup self-test" >&2 + return 93 + ;; + esac + } + sleep() { + : + } +fi + if ! sandbox_exec "test -d /sandbox/.deepagents && command -v dcode >/dev/null 2>&1" >/dev/null; then info "SKIP: sandbox '${SANDBOX_NAME}' is not a Deep Agents Code sandbox" exit 0 @@ -252,5 +328,8 @@ if [ "$OBSERVABILITY_MARKER_BEFORE" = "1" ]; then fi fi +if [ -n "$POLICY_CLEANUP_TRACE" ]; then + cat "$POLICY_CLEANUP_TRACE" +fi printf '%s\n' "${PREFIX}: $PASSED passed, $FAILED failed" [ "$FAILED" -eq 0 ] || exit 1 diff --git a/test/e2e/support/platform-parity-cloud-experimental.test.ts b/test/e2e/support/platform-parity-cloud-experimental.test.ts index 8ace94ff562..8c492b53f0c 100644 --- a/test/e2e/support/platform-parity-cloud-experimental.test.ts +++ b/test/e2e/support/platform-parity-cloud-experimental.test.ts @@ -348,29 +348,34 @@ describe("P0-E cloud-experimental parity guardrails", () => { }); it("restores Tavily denial and the prior runtime marker for later ordered checks", () => { - const script = fs.readFileSync( - path.join( - process.cwd(), - "test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh", - ), - "utf8", + const result = spawnSync( + "bash", + [ + path.join( + process.cwd(), + "test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh", + ), + ], + { + encoding: "utf8", + env: { + NEMOCLAW_E2E_TAVILY_SELF_TEST: "policy-cleanup-order", + PATH: process.env.PATH ?? "/usr/bin:/bin", + }, + }, ); - expect(script).toContain("policy-remove tavily --yes"); - expect(script).toContain( + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toContain( "managed Deep Agents Code python is blocked again after policy-remove", ); - expect(script).toContain("/usr/bin/env NEMOCLAW_OBSERVABILITY=1"); - expect(script).toContain("/usr/local/bin/nemoclaw-start /usr/bin/true"); - - const markerSnapshot = script.indexOf("OBSERVABILITY_MARKER_BEFORE="); - const policyRemove = script.indexOf("policy-remove tavily --yes"); - const denialProof = script.indexOf("REMOVED_PROBE_OUTPUT="); - const markerRestore = script.indexOf("/usr/bin/env NEMOCLAW_OBSERVABILITY=1"); - expect(markerSnapshot).toBeGreaterThanOrEqual(0); - expect(markerSnapshot).toBeLessThan(policyRemove); - expect(policyRemove).toBeLessThan(denialProof); - expect(denialProof).toBeLessThan(markerRestore); + expect(result.stdout).toContain("managed observability state restores after policy-remove"); + expect(result.stdout.split("\n").filter((line) => line.startsWith("TRACE:"))).toEqual([ + "TRACE:opt-in-proof", + "TRACE:policy-remove", + "TRACE:post-remove-blocked", + "TRACE:observability-restore", + ]); }); it("keeps the managed DCode thread-auto-approval live check valid Bash (#6478)", () => { From 5b35c3b1a3ea88c5341e00583831ee643abb7abb Mon Sep 17 00:00:00 2001 From: cjagwani Date: Wed, 8 Jul 2026 22:38:07 +0000 Subject: [PATCH 12/21] test(e2e): document deferred shell expansion Signed-off-by: cjagwani --- .../checks/09-deepagents-code-tavily-opt-in.sh | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh b/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh index ab8d1f4f8f2..899016c0bdb 100755 --- a/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh +++ b/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh @@ -29,6 +29,8 @@ sandbox_exec() { } observability_marker_value() { + # Expansion is intentionally deferred to the sandbox shell. + # shellcheck disable=SC2016 openshell sandbox exec --name "$SANDBOX_NAME" -- \ sh -c 'marker=/tmp/nemoclaw-observability-enabled; if test -f "$marker" && ! test -L "$marker"; then cat "$marker"; else printf "absent"; fi' \ 2>/dev/null @@ -151,6 +153,8 @@ if [ "${NEMOCLAW_E2E_TAVILY_SELF_TEST:-}" = "policy-cleanup-order" ]; then trap 'rm -rf "$POLICY_CLEANUP_FIXTURE_DIR"' EXIT sandbox_exec() { + # Match the literal command substitution sent to the sandbox. + # shellcheck disable=SC2016 case "$1" in *"test -d /sandbox/.deepagents"*) return 0 ;; *'readlink -f "$(command -v python3)"'*) printf '%s\n' "/opt/venv/bin/python3" ;; From 65933be3f3474bb0b9cd1cef5f0d5b37be7a360b Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 8 Jul 2026 15:47:39 -0700 Subject: [PATCH 13/21] fix(e2e): clean up Tavily after early exit Signed-off-by: Aaron Erickson --- .../09-deepagents-code-tavily-opt-in.sh | 43 ++++++++++++++++--- ...platform-parity-cloud-experimental.test.ts | 26 +++++++++++ 2 files changed, 64 insertions(+), 5 deletions(-) diff --git a/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh b/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh index 899016c0bdb..76c8bb9b23b 100755 --- a/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh +++ b/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh @@ -44,6 +44,31 @@ nemoclaw_cli() { fi } +TAVILY_POLICY_CLEANUP_REQUIRED=0 +POLICY_CLEANUP_TRACE="" +POLICY_CLEANUP_FIXTURE_DIR="" +POLICY_CLEANUP_EMIT_TRACE_ON_EXIT=0 + +cleanup_tavily_policy() { + if [ "$TAVILY_POLICY_CLEANUP_REQUIRED" != "1" ]; then + return 0 + fi + TAVILY_POLICY_CLEANUP_REQUIRED=0 + nemoclaw_cli "$SANDBOX_NAME" policy-remove tavily --yes >/dev/null 2>&1 || true +} + +cleanup_tavily_check() { + local exit_status=$? + cleanup_tavily_policy + if [ "$POLICY_CLEANUP_EMIT_TRACE_ON_EXIT" = "1" ] && [ -f "$POLICY_CLEANUP_TRACE" ]; then + cat "$POLICY_CLEANUP_TRACE" || true + fi + if [ -n "$POLICY_CLEANUP_FIXTURE_DIR" ]; then + rm -rf "$POLICY_CLEANUP_FIXTURE_DIR" + fi + return "$exit_status" +} + python_probe_source() { cat <<'PY' import json @@ -141,16 +166,17 @@ if [ "${NEMOCLAW_E2E_TAVILY_SELF_TEST:-}" = "probe-command-shape" ]; then exit 0 fi -POLICY_CLEANUP_TRACE="" -POLICY_CLEANUP_FIXTURE_DIR="" -if [ "${NEMOCLAW_E2E_TAVILY_SELF_TEST:-}" = "policy-cleanup-order" ]; then +if [[ "${NEMOCLAW_E2E_TAVILY_SELF_TEST:-}" =~ ^policy-cleanup-(order|on-probe-failure)$ ]]; then POLICY_CLEANUP_FIXTURE_DIR="$(mktemp -d)" POLICY_CLEANUP_TRACE="${POLICY_CLEANUP_FIXTURE_DIR}/trace" POLICY_CLEANUP_STATE="${POLICY_CLEANUP_FIXTURE_DIR}/policy-state" POLICY_CLEANUP_MARKER="${POLICY_CLEANUP_FIXTURE_DIR}/observability-marker" + if [ "$NEMOCLAW_E2E_TAVILY_SELF_TEST" = "policy-cleanup-on-probe-failure" ]; then + POLICY_CLEANUP_EMIT_TRACE_ON_EXIT=1 + fi printf '%s\n' "baseline" >"$POLICY_CLEANUP_STATE" printf '%s\n' "1" >"$POLICY_CLEANUP_MARKER" - trap 'rm -rf "$POLICY_CLEANUP_FIXTURE_DIR"' EXIT + trap cleanup_tavily_check EXIT sandbox_exec() { # Match the literal command substitution sent to the sandbox. @@ -191,7 +217,11 @@ if [ "${NEMOCLAW_E2E_TAVILY_SELF_TEST:-}" = "policy-cleanup-order" ]; then local python_bin="${2:-python3}" local state state="$(cat "$POLICY_CLEANUP_STATE")" - if [ "$python_bin" != "python3" ]; then + if [ "$NEMOCLAW_E2E_TAVILY_SELF_TEST" = "policy-cleanup-on-probe-failure" ] \ + && [ "$python_bin" = "python3" ] && [ "$state" = "added" ]; then + printf '%s\n' "TRACE:probe-failure" >>"$POLICY_CLEANUP_TRACE" + return 23 + elif [ "$python_bin" != "python3" ]; then printf '%s\n' "BLOCKED:fixture non-managed Python" elif [ "$state" = "added" ]; then printf '%s\n' "REACHED:403" @@ -252,6 +282,8 @@ APPLY_OUTPUT="$(nemoclaw_cli "$SANDBOX_NAME" policy-add tavily --yes 2>&1)" || { printf '%s\n' "${PREFIX}: $PASSED passed, $FAILED failed" exit 1 } +TAVILY_POLICY_CLEANUP_REQUIRED=1 +trap cleanup_tavily_check EXIT pass "tavily policy preset applies" sleep "${NEMOCLAW_E2E_POLICY_SETTLE_SECONDS:-5}" @@ -298,6 +330,7 @@ REMOVE_OUTPUT="$(nemoclaw_cli "$SANDBOX_NAME" policy-remove tavily --yes 2>&1)" printf '%s\n' "${PREFIX}: $PASSED passed, $FAILED failed" exit 1 } +TAVILY_POLICY_CLEANUP_REQUIRED=0 pass "tavily policy preset removes after the opt-in proof" sleep "${NEMOCLAW_E2E_POLICY_SETTLE_SECONDS:-5}" diff --git a/test/e2e/support/platform-parity-cloud-experimental.test.ts b/test/e2e/support/platform-parity-cloud-experimental.test.ts index 8c492b53f0c..b96e68ff040 100644 --- a/test/e2e/support/platform-parity-cloud-experimental.test.ts +++ b/test/e2e/support/platform-parity-cloud-experimental.test.ts @@ -378,6 +378,32 @@ describe("P0-E cloud-experimental parity guardrails", () => { ]); }); + it("removes Tavily when the first post-add probe exits early", () => { + const result = spawnSync( + "bash", + [ + path.join( + process.cwd(), + "test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh", + ), + ], + { + encoding: "utf8", + env: { + NEMOCLAW_E2E_TAVILY_SELF_TEST: "policy-cleanup-on-probe-failure", + PATH: process.env.PATH ?? "/usr/bin:/bin", + }, + }, + ); + + expect(result.status, result.stderr).toBe(23); + expect(result.stdout.split("\n").filter((line) => line.startsWith("TRACE:"))).toEqual([ + "TRACE:opt-in-proof", + "TRACE:probe-failure", + "TRACE:policy-remove", + ]); + }); + it("keeps the managed DCode thread-auto-approval live check valid Bash (#6478)", () => { const scriptPath = path.join( process.cwd(), From 7c0c911fe5c8704d4f1f27b35024d8a585d60d7f Mon Sep 17 00:00:00 2001 From: cjagwani Date: Wed, 8 Jul 2026 22:50:22 +0000 Subject: [PATCH 14/21] test(e2e): snapshot observability after policy add Signed-off-by: cjagwani --- .../checks/09-deepagents-code-tavily-opt-in.sh | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh b/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh index 899016c0bdb..5cd119a034f 100755 --- a/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh +++ b/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh @@ -149,7 +149,7 @@ if [ "${NEMOCLAW_E2E_TAVILY_SELF_TEST:-}" = "policy-cleanup-order" ]; then POLICY_CLEANUP_STATE="${POLICY_CLEANUP_FIXTURE_DIR}/policy-state" POLICY_CLEANUP_MARKER="${POLICY_CLEANUP_FIXTURE_DIR}/observability-marker" printf '%s\n' "baseline" >"$POLICY_CLEANUP_STATE" - printf '%s\n' "1" >"$POLICY_CLEANUP_MARKER" + printf '%s\n' "absent" >"$POLICY_CLEANUP_MARKER" trap 'rm -rf "$POLICY_CLEANUP_FIXTURE_DIR"' EXIT sandbox_exec() { @@ -174,6 +174,7 @@ if [ "${NEMOCLAW_E2E_TAVILY_SELF_TEST:-}" = "policy-cleanup-order" ]; then policy-add:tavily:--dry-run) printf '%s\n' "api.tavily.com" ;; policy-add:tavily:--yes) printf '%s\n' "added" >"$POLICY_CLEANUP_STATE" + printf '%s\n' "1" >"$POLICY_CLEANUP_MARKER" printf '%s\n' "TRACE:opt-in-proof" >>"$POLICY_CLEANUP_TRACE" ;; policy-remove:tavily:--yes) @@ -224,8 +225,6 @@ if ! sandbox_exec "test -d /sandbox/.deepagents && command -v dcode >/dev/null 2 exit 0 fi -OBSERVABILITY_MARKER_BEFORE="$(observability_marker_value || true)" - info "Running Deep Agents Code Tavily opt-in check in sandbox: $SANDBOX_NAME" # shellcheck disable=SC2016 # command substitution must run inside the sandbox. @@ -288,6 +287,10 @@ else fail_test "project venv under /sandbox did not expose a usable python3 executable: $PROJECT_OUT" fi +# The Tavily policy-add rebuild materializes the configured observability +# marker, so preserve the state immediately before removing that policy. +OBSERVABILITY_MARKER_BEFORE="$(observability_marker_value || true)" + # Restore the deny-by-default posture for later checks in this ordered live # suite. Rebuild validation intentionally preserves active policy presets, so # leaving Tavily enabled here would make a later baseline egress check claim @@ -314,7 +317,7 @@ fi # The temporary Tavily policy belongs only to this check. OpenShell can clear # /tmp while applying the narrower replacement policy, so restore an -# observability marker that existed before the check through the canonical +# observability marker that existed before policy removal through the canonical # startup helper instead of manufacturing the marker in the test. if [ "$OBSERVABILITY_MARKER_BEFORE" = "1" ]; then OBSERVABILITY_MARKER_AFTER="$(observability_marker_value || true)" From 4bbe769cb31c7d3ecd359befc5ec2451d26573f9 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 8 Jul 2026 15:53:48 -0700 Subject: [PATCH 15/21] test(dcode): cover concurrent CA bundle mutation Signed-off-by: Aaron Erickson --- agents/langchain-deepagents-code/start.sh | 2 + ...gchain-deepagents-code-fetch-proxy.test.ts | 173 ++++++++++++++++++ 2 files changed, 175 insertions(+) diff --git a/agents/langchain-deepagents-code/start.sh b/agents/langchain-deepagents-code/start.sh index 45a13999a0a..8e237530e3a 100755 --- a/agents/langchain-deepagents-code/start.sh +++ b/agents/langchain-deepagents-code/start.sh @@ -162,6 +162,8 @@ prepare_runtime_env() { printf '%s\n' 'export LANGCHAIN_TRACING_V2=false' printf '%s\n' 'export DEEPAGENTS_CODE_OFFLINE=1' printf '%s\n' 'export DEEPAGENTS_CODE_RIPGREP_INSTALLER=system' + # Intentionally omit the trusted proxy when unset: its absence signals + # unmanaged mode, where the upstream fetch transport remains authoritative. write_export_if_set DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL # shellcheck disable=SC2016 printf '%s\n' 'export DEEPAGENTS_CODE_OPENAI_API_KEY="${DEEPAGENTS_CODE_OPENAI_API_KEY:-nemoclaw-managed-inference}"' diff --git a/test/langchain-deepagents-code-fetch-proxy.test.ts b/test/langchain-deepagents-code-fetch-proxy.test.ts index 0b613983fbf..e2b6ea3c2f0 100644 --- a/test/langchain-deepagents-code-fetch-proxy.test.ts +++ b/test/langchain-deepagents-code-fetch-proxy.test.ts @@ -168,6 +168,173 @@ print("root-owned-proxy-verification-ok") expect(check).not.toContain("'403 client error: forbidden'"); }); + it("pins concurrent CA bundle mutation fetches to original trust bytes or generic failure", () => { + const tempDir = createPackageFixture(); + patchFixture(tempDir); + const proxyUrl = "http://managed-proxy.internal:3128"; + const result = spawnSync( + "python3", + [ + "-c", + ` +import os +import sys +import types +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from threading import Event, Lock, Thread + +PINNED_FETCH_COUNT = 4 +INVALID_FETCH_COUNT = 2 +pinned_ready = Event() +swap_complete = Event() +invalid_attempts_complete = Event() +release_pinned = Event() +state_lock = Lock() +pinned_transport_count = 0 +successful_ca_contents = [] +sessions = [] +mutation_errors = [] + +class Response: + status_code = 200 + headers = {} + + def raise_for_status(self): + return None + +class Session: + def __init__(self): + self.trust_env = True + self.closed = False + sessions.append(self) + + def __enter__(self): + return self + + def __exit__(self, *_args): + self.closed = True + + def get(self, _url, **kwargs): + global pinned_transport_count + with state_lock: + pinned_transport_count += 1 + if pinned_transport_count == PINNED_FETCH_COUNT: + pinned_ready.set() + assert release_pinned.wait(10), "timed out waiting for concurrent CA bundle mutation" + ca_contents = Path(kwargs["verify"]).read_text(encoding="utf-8") + with state_lock: + successful_ca_contents.append(ca_contents) + return Response() + +requests = types.ModuleType("requests") +requests.Session = Session +requests.exceptions = types.SimpleNamespace(TooManyRedirects=RuntimeError) +sys.modules["requests"] = requests + +from deepagents_code import _nemoclaw_managed, tools + +root = Path(${JSON.stringify(tempDir)}) +proxy_host_file = root / "managed-proxy-host" +proxy_port_file = root / "managed-proxy-port" +managed_ca_file = root / "managed-ca.pem" +attacker_ca_file = root / "attacker-ca.pem" +proxy_host_file.write_text("managed-proxy.internal\\n", encoding="utf-8") +proxy_port_file.write_text("3128\\n", encoding="utf-8") +managed_ca_file.write_text("trusted CA bundle\\n", encoding="utf-8") +attacker_ca_file.write_text("attacker CA bundle\\n", encoding="utf-8") +for trusted_file in (proxy_host_file, proxy_port_file, managed_ca_file, attacker_ca_file): + trusted_file.chmod(0o444) + +_nemoclaw_managed._MANAGED_PROXY_HOST_FILE = proxy_host_file +_nemoclaw_managed._MANAGED_PROXY_PORT_FILE = proxy_port_file +_nemoclaw_managed._MANAGED_FETCH_CA_BUNDLE_FILE = managed_ca_file +_nemoclaw_managed._MANAGED_FILE_OWNER_UID = os.getuid() + +for name in ( + "DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL", + "HTTP_PROXY", + "HTTPS_PROXY", + "http_proxy", + "https_proxy", +): + os.environ[name] = ${JSON.stringify(proxyUrl)} + +def fetch_outcome(index): + try: + response = tools._fetch_with_redirects( + f"https://raw.githubusercontent.com/example/concurrent-ca-bundle-{index}", + timeout=8, + ) + except tools._UrlValidationError as exc: + return ("error", str(exc)) + return ("success", response.status_code) + +def atomically_symlink_swap_ca_bundle(): + try: + assert pinned_ready.wait(10), "managed fetches did not reach the pinned transport" + replacement = root / "managed-ca-symlink-replacement" + replacement.symlink_to(attacker_ca_file) + os.replace(replacement, managed_ca_file) + swap_complete.set() + assert invalid_attempts_complete.wait(10), "invalid fetches did not observe CA mutation" + except BaseException as exc: + mutation_errors.append(repr(exc)) + swap_complete.set() + finally: + release_pinned.set() + +mutator = Thread(target=atomically_symlink_swap_ca_bundle, name="ca-bundle-mutator") +mutator.start() +with ThreadPoolExecutor(max_workers=PINNED_FETCH_COUNT + INVALID_FETCH_COUNT) as executor: + try: + pinned_futures = [executor.submit(fetch_outcome, index) for index in range(PINNED_FETCH_COUNT)] + assert swap_complete.wait(10), "atomic CA bundle swap did not complete" + invalid_futures = [ + executor.submit(fetch_outcome, PINNED_FETCH_COUNT + index) + for index in range(INVALID_FETCH_COUNT) + ] + invalid_results = [future.result(timeout=10) for future in invalid_futures] + invalid_attempts_complete.set() + pinned_results = [future.result(timeout=10) for future in pinned_futures] + finally: + invalid_attempts_complete.set() + release_pinned.set() + +mutator.join(timeout=10) +assert not mutator.is_alive() +assert mutation_errors == [] +assert pinned_results == [("success", 200)] * PINNED_FETCH_COUNT +assert invalid_results == [ + ("error", "managed fetch CA bundle is invalid") +] * INVALID_FETCH_COUNT +assert successful_ca_contents == ["trusted CA bundle\\n"] * PINNED_FETCH_COUNT +assert all("attacker" not in contents for contents in successful_ca_contents) +assert managed_ca_file.is_symlink() +assert managed_ca_file.read_text(encoding="utf-8") == "attacker CA bundle\\n" +assert len(sessions) == PINNED_FETCH_COUNT +assert all(session.closed for session in sessions) +print("concurrent-ca-bundle-mutation-ok") +`, + ], + { + env: { + PATH: process.env.PATH, + PYTHONPATH: tempDir, + DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL: proxyUrl, + HTTP_PROXY: proxyUrl, + HTTPS_PROXY: proxyUrl, + http_proxy: proxyUrl, + https_proxy: proxyUrl, + }, + encoding: "utf8", + }, + ); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toContain("concurrent-ca-bundle-mutation-ok"); + }); + it("keeps redirects and concurrent fetches behind the explicit proxy without direct DNS", () => { const tempDir = createPackageFixture(); patchFixture(tempDir); @@ -615,6 +782,11 @@ print("managed-fetch-proxy-ok") expect(result.status, result.stderr).toBe(0); expect(result.stdout).toContain("managed-fetch-proxy-ok"); + }); + + it("preserves unmanaged fallback when proxy env is absent", () => { + const tempDir = createPackageFixture(); + patchFixture(tempDir); const withoutDelegation = spawnSync( "python3", @@ -631,6 +803,7 @@ print("managed-fetch-proxy-ok") encoding: "utf8", }, ); + expect(withoutDelegation.status, withoutDelegation.stderr).toBe(0); }); }); From 4b07586eb7349d15a8e7fc11af05cfec8fdf580d Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 8 Jul 2026 15:50:36 -0700 Subject: [PATCH 16/21] fix(dcode): persist observability marker Signed-off-by: Aaron Erickson --- .../dcode-launcher.sh | 2 +- agents/langchain-deepagents-code/start.sh | 26 ++++++- .../09-deepagents-code-tavily-opt-in.sh | 12 ++-- .../11-deepagents-code-observability.sh | 4 +- ...platform-parity-cloud-experimental.test.ts | 4 +- ...ain-deepagents-code-proxy-launcher.test.ts | 69 ++++++++++++++----- 6 files changed, 89 insertions(+), 28 deletions(-) diff --git a/agents/langchain-deepagents-code/dcode-launcher.sh b/agents/langchain-deepagents-code/dcode-launcher.sh index c5de1244aed..0f02fe5d5ba 100755 --- a/agents/langchain-deepagents-code/dcode-launcher.sh +++ b/agents/langchain-deepagents-code/dcode-launcher.sh @@ -12,7 +12,7 @@ done < <(compgen -A variable NEMOCLAW_DCODE_AUTO_APPROVAL || true) unset _nemoclaw_auto_approval_env readonly MANAGED_DCODE_WRAPPER="/usr/local/lib/nemoclaw/dcode-wrapper.sh" -readonly MANAGED_OBSERVABILITY_MARKER="/tmp/nemoclaw-observability-enabled" +readonly MANAGED_OBSERVABILITY_MARKER="/sandbox/.deepagents/.nemoclaw-observability-enabled" export HOME=/sandbox export PATH="/usr/local/bin:/opt/venv/bin:/usr/local/sbin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/agents/langchain-deepagents-code/start.sh b/agents/langchain-deepagents-code/start.sh index 8e237530e3a..88ceac1a414 100755 --- a/agents/langchain-deepagents-code/start.sh +++ b/agents/langchain-deepagents-code/start.sh @@ -194,13 +194,35 @@ prepare_runtime_env() { } prepare_observability_marker() { - local target=/tmp/nemoclaw-observability-enabled + local marker_dir=/sandbox/.deepagents + local target="${marker_dir}/.nemoclaw-observability-enabled" local tmp + + # OpenShell policy replacement can reset the sandbox's ephemeral /tmp while + # preserving its /sandbox workspace. Keep this credential-free convenience + # bit with the managed DCode state so independent exec/login shells retain + # the host-selected observability setting across policy updates. Reject a + # symlinked state directory before creating a same-directory temporary file; + # the marker remains non-authoritative and the network policy controls OTLP. + if [ -L "$marker_dir" ] || { [ -e "$marker_dir" ] && [ ! -d "$marker_dir" ]; }; then + printf '%s\n' 'Unsafe managed Deep Agents Code state directory.' >&2 + return 1 + fi + mkdir -p "$marker_dir" + if [ -L "$marker_dir" ] || [ ! -d "$marker_dir" ]; then + printf '%s\n' 'Unsafe managed Deep Agents Code state directory.' >&2 + return 1 + fi + if [ -L "$target" ] || { [ -e "$target" ] && [ ! -f "$target" ]; }; then + printf '%s\n' 'Unsafe managed observability marker target.' >&2 + return 1 + fi + if [ "${NEMOCLAW_OBSERVABILITY:-}" != "1" ]; then rm -f "$target" return 0 fi - tmp="$(mktemp /tmp/nemoclaw-observability-enabled.XXXXXX)" + tmp="$(mktemp "${target}.XXXXXX")" printf '%s\n' '1' >"$tmp" chmod 444 "$tmp" mv -f "$tmp" "$target" diff --git a/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh b/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh index 97060be9df0..dc88e0b0882 100755 --- a/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh +++ b/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh @@ -32,7 +32,7 @@ observability_marker_value() { # Expansion is intentionally deferred to the sandbox shell. # shellcheck disable=SC2016 openshell sandbox exec --name "$SANDBOX_NAME" -- \ - sh -c 'marker=/tmp/nemoclaw-observability-enabled; if test -f "$marker" && ! test -L "$marker"; then cat "$marker"; else printf "absent"; fi' \ + sh -c 'marker=/sandbox/.deepagents/.nemoclaw-observability-enabled; if test -f "$marker" && ! test -L "$marker"; then cat "$marker"; else printf "absent"; fi' \ 2>/dev/null } @@ -348,10 +348,10 @@ else fail_test "post-remove Tavily probe lacked denial evidence: $REMOVED_PROBE_OUTPUT" fi -# The temporary Tavily policy belongs only to this check. OpenShell can clear -# /tmp while applying the narrower replacement policy, so restore an -# observability marker that existed before policy removal through the canonical -# startup helper instead of manufacturing the marker in the test. +# The temporary Tavily policy belongs only to this check. Policy replacement +# can reset ephemeral /tmp state, while the managed observability bit lives in +# the persistent /sandbox workspace. If an older runtime loses that bit, repair +# it through the canonical startup helper instead of manufacturing it here. if [ "$OBSERVABILITY_MARKER_BEFORE" = "1" ]; then OBSERVABILITY_MARKER_AFTER="$(observability_marker_value || true)" if [ "$OBSERVABILITY_MARKER_AFTER" != "1" ]; then @@ -362,7 +362,7 @@ if [ "$OBSERVABILITY_MARKER_BEFORE" = "1" ]; then fi OBSERVABILITY_MARKER_AFTER="$(observability_marker_value || true)" if [ "$OBSERVABILITY_MARKER_AFTER" = "1" ]; then - pass "managed observability state restores after policy-remove" + pass "managed observability state remains enabled after policy-remove" else fail_test "managed observability marker was not restored after policy-remove" fi diff --git a/test/e2e/e2e-cloud-experimental/checks/11-deepagents-code-observability.sh b/test/e2e/e2e-cloud-experimental/checks/11-deepagents-code-observability.sh index 4160a80f3db..a927f0634f9 100755 --- a/test/e2e/e2e-cloud-experimental/checks/11-deepagents-code-observability.sh +++ b/test/e2e/e2e-cloud-experimental/checks/11-deepagents-code-observability.sh @@ -201,8 +201,10 @@ NODE )" [ "$registry_output" = "enabled" ] || fail "host registry does not record observability enabled" +# Expansion is intentionally deferred to the sandbox shell. +# shellcheck disable=SC2016 marker_output="$(openshell sandbox exec --name "$SANDBOX_NAME" -- \ - sh -c 'test -f /tmp/nemoclaw-observability-enabled && cat /tmp/nemoclaw-observability-enabled' \ + sh -c 'marker=/sandbox/.deepagents/.nemoclaw-observability-enabled; test -f "$marker" && ! test -L "$marker" && cat "$marker"' \ 2>&1)" || fail "managed observability marker is absent" [ "$marker_output" = "1" ] || fail "managed observability marker has an unexpected value" pass "host registry, live policy, and sandbox marker agree on enabled observability" diff --git a/test/e2e/support/platform-parity-cloud-experimental.test.ts b/test/e2e/support/platform-parity-cloud-experimental.test.ts index b96e68ff040..3c0881453ab 100644 --- a/test/e2e/support/platform-parity-cloud-experimental.test.ts +++ b/test/e2e/support/platform-parity-cloud-experimental.test.ts @@ -369,7 +369,9 @@ describe("P0-E cloud-experimental parity guardrails", () => { expect(result.stdout).toContain( "managed Deep Agents Code python is blocked again after policy-remove", ); - expect(result.stdout).toContain("managed observability state restores after policy-remove"); + expect(result.stdout).toContain( + "managed observability state remains enabled after policy-remove", + ); expect(result.stdout.split("\n").filter((line) => line.startsWith("TRACE:"))).toEqual([ "TRACE:opt-in-proof", "TRACE:policy-remove", diff --git a/test/langchain-deepagents-code-proxy-launcher.test.ts b/test/langchain-deepagents-code-proxy-launcher.test.ts index 54fdf5f5805..f0832b8471b 100644 --- a/test/langchain-deepagents-code-proxy-launcher.test.ts +++ b/test/langchain-deepagents-code-proxy-launcher.test.ts @@ -23,8 +23,13 @@ const PROXY_URL_ENV_NAMES = ["HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_p const NO_PROXY_ENV_NAMES = ["NO_PROXY", "no_proxy"] as const; const CLEARED_PROXY_ENV_NAMES = ["ALL_PROXY", "all_proxy", "OPENAI_PROXY"] as const; const DEFAULT_MANAGED_PROXY = { host: "10.200.0.1", port: "3128" } as const; +const OBSERVABILITY_MARKER_NAME = ".nemoclaw-observability-enabled"; const TEST_OWNER_UID = process.getuid?.() ?? 0; +function observabilityMarkerPath(tempDir: string): string { + return path.join(tempDir, "persistent-dcode-state", OBSERVABILITY_MARKER_NAME); +} + function readAgentFile(name: string): string { return fs.readFileSync(path.join(agentDir, name), "utf8"); } @@ -79,8 +84,8 @@ function makeLauncherProxyProbeFixture( `readonly MANAGED_DCODE_WRAPPER="${probePath}"`, ) .replace( - 'readonly MANAGED_OBSERVABILITY_MARKER="/tmp/nemoclaw-observability-enabled"', - `readonly MANAGED_OBSERVABILITY_MARKER="${path.join(tempDir, "observability-enabled")}"`, + 'readonly MANAGED_OBSERVABILITY_MARKER="/sandbox/.deepagents/.nemoclaw-observability-enabled"', + `readonly MANAGED_OBSERVABILITY_MARKER="${observabilityMarkerPath(tempDir)}"`, ), tempDir, ); @@ -95,25 +100,24 @@ function makeLauncherProxyProbeFixture( function makeStartProxyProbeFixture( tempDir: string, managedProxy: { host: string; port: string } = DEFAULT_MANAGED_PROXY, -): { envFile: string; markerFile: string; scriptPath: string } { - const envFile = path.join(tempDir, "proxy-env.sh"); - const markerFile = path.join(tempDir, "observability-enabled"); +): { envFile: string; ephemeralDir: string; markerFile: string; scriptPath: string } { + const ephemeralDir = path.join(tempDir, "ephemeral-tmp"); + const envFile = path.join(ephemeralDir, "proxy-env.sh"); + const markerFile = observabilityMarkerPath(tempDir); + const markerDir = path.dirname(markerFile); const scriptPath = path.join(tempDir, "start.sh"); + fs.mkdirSync(ephemeralDir); const fixture = replaceManagedProxyFileConstants(readAgentFile("start.sh"), tempDir) .replace("local target=/tmp/nemoclaw-proxy-env.sh", `local target="${envFile}"`) .replace( 'tmp="$(mktemp /tmp/nemoclaw-proxy-env.XXXXXX)"', - `tmp="$(mktemp "${tempDir}/nemoclaw-proxy-env.XXXXXX")"`, + `tmp="$(mktemp "${ephemeralDir}/nemoclaw-proxy-env.XXXXXX")"`, ) - .replace("local target=/tmp/nemoclaw-observability-enabled", `local target="${markerFile}"`) - .replace( - 'tmp="$(mktemp /tmp/nemoclaw-observability-enabled.XXXXXX)"', - `tmp="$(mktemp "${tempDir}/nemoclaw-observability-enabled.XXXXXX")"`, - ); + .replace("local marker_dir=/sandbox/.deepagents", `local marker_dir="${markerDir}"`); fs.writeFileSync(scriptPath, fixture, "utf8"); writeManagedProxyFiles(tempDir, managedProxy); fs.chmodSync(scriptPath, 0o755); - return { envFile, markerFile, scriptPath }; + return { envFile, ephemeralDir, markerFile, scriptPath }; } function runLauncher( @@ -239,10 +243,10 @@ describe("Deep Agents Code direct-exec proxy launcher", () => { expect(output).not.toContain("all-password"); }); - it("recovers only the exact entrypoint observability bit for raw dcode exec", () => { + it("recovers the exact observability bit after ephemeral runtime state resets", () => { const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-dcode-observability-")); const launcherPath = makeLauncherProxyProbeFixture(tempDir); - const { markerFile, scriptPath } = makeStartProxyProbeFixture(tempDir); + const { ephemeralDir, markerFile, scriptPath } = makeStartProxyProbeFixture(tempDir); const noncanonicalStart = spawnSync("bash", [scriptPath, "/usr/bin/true"], { env: { @@ -266,18 +270,23 @@ describe("Deep Agents Code direct-exec proxy launcher", () => { }, encoding: "utf8", }); - const enabledLaunch = runLauncher(launcherPath, [], {}); expect(enabledStart.status, enabledStart.stderr).toBe(0); expect(fs.readFileSync(markerFile, "utf8")).toBe("1\n"); expect(fs.statSync(markerFile).mode & 0o777).toBe(0o444); + + fs.rmSync(ephemeralDir, { recursive: true, force: true }); + expect(fs.existsSync(markerFile)).toBe(true); + const enabledLaunch = runLauncher(launcherPath, [], {}); expect(enabledLaunch.status, enabledLaunch.stderr).toBe(0); expect(enabledLaunch.stdout).toContain("LAUNCHER_NEMOCLAW_OBSERVABILITY=1"); }); - it("ignores tampered and non-regular observability markers", () => { + it("ignores tampered, symlinked, and non-regular observability markers", () => { const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-dcode-observability-")); const launcherPath = makeLauncherProxyProbeFixture(tempDir); - const markerFile = path.join(tempDir, "observability-enabled"); + const { scriptPath } = makeStartProxyProbeFixture(tempDir); + const markerFile = observabilityMarkerPath(tempDir); + fs.mkdirSync(path.dirname(markerFile), { recursive: true }); fs.writeFileSync(markerFile, "true\n", { encoding: "utf8", mode: 0o644 }); const tamperedLaunch = runLauncher(launcherPath, [], { @@ -291,8 +300,34 @@ describe("Deep Agents Code direct-exec proxy launcher", () => { const nonRegularLaunch = runLauncher(launcherPath, [], { NEMOCLAW_OBSERVABILITY: "1", }); + const nonRegularStart = spawnSync("bash", [scriptPath, "/usr/bin/true"], { + env: { + PATH: process.env.PATH ?? "/usr/bin:/bin", + NEMOCLAW_OBSERVABILITY: "1", + }, + encoding: "utf8", + }); expect(nonRegularLaunch.status, nonRegularLaunch.stderr).toBe(0); expect(nonRegularLaunch.stdout).toContain("LAUNCHER_NEMOCLAW_OBSERVABILITY=__unset__"); + expect(nonRegularStart.status).not.toBe(0); + expect(nonRegularStart.stderr).toContain("Unsafe managed observability marker target"); + + fs.rmSync(markerFile, { recursive: true }); + const symlinkTarget = path.join(tempDir, "observability-symlink-target"); + fs.writeFileSync(symlinkTarget, "1\n", "utf8"); + fs.symlinkSync(symlinkTarget, markerFile); + const symlinkedLaunch = runLauncher(launcherPath, [], {}); + const symlinkedStart = spawnSync("bash", [scriptPath, "/usr/bin/true"], { + env: { + PATH: process.env.PATH ?? "/usr/bin:/bin", + NEMOCLAW_OBSERVABILITY: "1", + }, + encoding: "utf8", + }); + expect(symlinkedLaunch.status, symlinkedLaunch.stderr).toBe(0); + expect(symlinkedLaunch.stdout).toContain("LAUNCHER_NEMOCLAW_OBSERVABILITY=__unset__"); + expect(symlinkedStart.status).not.toBe(0); + expect(symlinkedStart.stderr).toContain("Unsafe managed observability marker target"); }); it("pins validated proxy overrides into direct dcode execution paths (#6191)", () => { From 714c9814df2ec84c0d5b9eb813a5c3c29421a709 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 8 Jul 2026 16:07:39 -0700 Subject: [PATCH 17/21] docs(dcode): record lifecycle repair boundaries Signed-off-by: Aaron Erickson --- .../dependency-review.md | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/agents/langchain-deepagents-code/dependency-review.md b/agents/langchain-deepagents-code/dependency-review.md index 76dac186a43..b4677f8bc8a 100644 --- a/agents/langchain-deepagents-code/dependency-review.md +++ b/agents/langchain-deepagents-code/dependency-review.md @@ -151,3 +151,35 @@ this review to revalidate the managed adapter. Remove it instead of refreshing its hashes only if a future reviewed dependency already provides both exact mappings; no external contribution is required. Issue #6424 records the NemoClaw-owned replacement of the previous installed-bootstrap mutation. + +## Managed observability and ordered policy cleanup + +The managed observability marker closes a sandbox lifecycle gap rather than an +authorization gap. OpenShell policy replacement can clear ephemeral `/tmp`, and +independent sandbox exec/login processes do not inherit the entrypoint's +environment, while the host registry and the active OTLP network policy remain +enabled. OpenShell owns those lifecycle semantics; NemoClaw owns the DCode +startup and launcher boundary but does not modify OpenShell here. The startup +script therefore writes only the credential-free enable bit to the persistent +`/sandbox/.deepagents/.nemoclaw-observability-enabled` workspace path. The +launcher accepts only a non-symlink regular marker containing exactly `1`, and +the network policy remains the authority for OTLP access. + +Focused launcher fixtures delete unrelated ephemeral state and prove the marker +survives, reject unsafe directory and marker types, and cover enabled and +disabled values. The ordered live checks prove Tavily removal restores the +deny-by-default policy while check 11 independently requires the host registry, +live policy, and durable sandbox marker to agree. Remove this marker and its +launcher recovery only when OpenShell propagates the selected observability bit +to every exec/login process across policy replacement, or when DCode no longer +needs the bit. + +Tavily cleanup persists across sandbox rebuilds because `policy-remove` first +applies the narrowed live policy and then removes the preset from the sandbox's +registry-backed policy list, which is the source used by rebuild. The +`policy-add-remove-session-sync` tests cover successful persisted removal, and +the snapshot regression `does not resurrect an earlier removed preset` guards +restore behavior. The E2E EXIT trap is still required for early probe failures +so the ordered suite cannot leave the current sandbox broader than the registry. +Remove that trap only when each check receives an isolated sandbox or no longer +mutates policy. From b041b37029a78f523a2b72d256e280b722f095d9 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 8 Jul 2026 16:10:13 -0700 Subject: [PATCH 18/21] test(dcode): isolate durable marker fixture Signed-off-by: Aaron Erickson --- test/helpers/langchain-deepagents-code-headless.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/test/helpers/langchain-deepagents-code-headless.ts b/test/helpers/langchain-deepagents-code-headless.ts index 3404c05f3e9..c40d01fa2fc 100644 --- a/test/helpers/langchain-deepagents-code-headless.ts +++ b/test/helpers/langchain-deepagents-code-headless.ts @@ -52,8 +52,10 @@ export function makeStartScriptFixture( const scriptPath = path.join(tempDir, "start.sh"); const hostFile = path.join(tempDir, "trusted-proxy-host"); const portFile = path.join(tempDir, "trusted-proxy-port"); + const markerDir = path.join(tempDir, "persistent-dcode-state"); expect(original).toContain("local target=/tmp/nemoclaw-proxy-env.sh"); expect(original).toContain('tmp="$(mktemp /tmp/nemoclaw-proxy-env.XXXXXX)"'); + expect(original).toContain("local marker_dir=/sandbox/.deepagents"); const fixture = original .replace( 'readonly MANAGED_PROXY_HOST_FILE="/usr/local/share/nemoclaw/dcode-proxy-host"', @@ -71,11 +73,14 @@ export function makeStartScriptFixture( .replace( 'tmp="$(mktemp /tmp/nemoclaw-proxy-env.XXXXXX)"', `tmp="$(mktemp "${tempDir}/nemoclaw-proxy-env.XXXXXX")"`, - ); + ) + .replace("local marker_dir=/sandbox/.deepagents", `local marker_dir="${markerDir}"`); expect(fixture).toContain(`local target="${envFile}"`); expect(fixture).toContain(`tmp="$(mktemp "${tempDir}/nemoclaw-proxy-env.XXXXXX")"`); expect(fixture).not.toContain("local target=/tmp/nemoclaw-proxy-env.sh"); expect(fixture).not.toContain('tmp="$(mktemp /tmp/nemoclaw-proxy-env.XXXXXX)"'); + expect(fixture).toContain(`local marker_dir="${markerDir}"`); + expect(fixture).not.toContain("local marker_dir=/sandbox/.deepagents"); fs.writeFileSync(hostFile, "10.200.0.1\n", "utf8"); fs.writeFileSync(portFile, "3128\n", "utf8"); fs.chmodSync(hostFile, 0o444); From 4680ea24d66b331ce379f26a669499b6f800c8fc Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 8 Jul 2026 16:24:12 -0700 Subject: [PATCH 19/21] fix(dcode): preserve observability across policy restarts Signed-off-by: Aaron Erickson --- .../dependency-review.md | 12 ++--- agents/langchain-deepagents-code/start.sh | 21 +++++++-- src/lib/actions/sandbox/snapshot.test.ts | 8 ++-- src/lib/actions/sandbox/snapshot.ts | 8 ++-- ...andbox-create-launch-observability.test.ts | 7 +-- src/lib/onboard/sandbox-create-launch.ts | 9 ++-- .../09-deepagents-code-tavily-opt-in.sh | 44 +++++-------------- ...platform-parity-cloud-experimental.test.ts | 3 +- ...ain-deepagents-code-proxy-launcher.test.ts | 23 ++++++++-- 9 files changed, 75 insertions(+), 60 deletions(-) diff --git a/agents/langchain-deepagents-code/dependency-review.md b/agents/langchain-deepagents-code/dependency-review.md index b4677f8bc8a..cd3f2821049 100644 --- a/agents/langchain-deepagents-code/dependency-review.md +++ b/agents/langchain-deepagents-code/dependency-review.md @@ -159,11 +159,13 @@ authorization gap. OpenShell policy replacement can clear ephemeral `/tmp`, and independent sandbox exec/login processes do not inherit the entrypoint's environment, while the host registry and the active OTLP network policy remain enabled. OpenShell owns those lifecycle semantics; NemoClaw owns the DCode -startup and launcher boundary but does not modify OpenShell here. The startup -script therefore writes only the credential-free enable bit to the persistent -`/sandbox/.deepagents/.nemoclaw-observability-enabled` workspace path. The -launcher accepts only a non-symlink regular marker containing exactly `1`, and -the network policy remains the authority for OTLP access. +startup and launcher boundary but does not modify OpenShell here. Create, +rebuild, and snapshot-clone paths pass an explicit `1` or `0`; an environment- +less policy restart preserves the validated durable state. The startup script +writes only the credential-free enable bit to persistent +`/sandbox/.deepagents/.nemoclaw-observability-enabled`. The launcher accepts +only a non-symlink regular marker containing exactly `1`, and the network policy +remains the authority for OTLP access. Focused launcher fixtures delete unrelated ephemeral state and prove the marker survives, reject unsafe directory and marker types, and cover enabled and diff --git a/agents/langchain-deepagents-code/start.sh b/agents/langchain-deepagents-code/start.sh index 88ceac1a414..0516b6b3d8b 100755 --- a/agents/langchain-deepagents-code/start.sh +++ b/agents/langchain-deepagents-code/start.sh @@ -208,6 +208,23 @@ prepare_observability_marker() { printf '%s\n' 'Unsafe managed Deep Agents Code state directory.' >&2 return 1 fi + if [ -d "$marker_dir" ] \ + && { [ -L "$target" ] || { [ -e "$target" ] && [ ! -f "$target" ]; }; }; then + printf '%s\n' 'Unsafe managed observability marker target.' >&2 + return 1 + fi + + # Policy replacement restarts the entrypoint without the sandbox-create + # environment. Absent therefore preserves the validated durable state; + # NemoClaw create/rebuild paths pass an explicit authoritative 1 or 0. + if [ -z "${NEMOCLAW_OBSERVABILITY+x}" ]; then + return 0 + fi + if [ "$NEMOCLAW_OBSERVABILITY" != "1" ]; then + [ -d "$marker_dir" ] || return 0 + rm -f "$target" + return 0 + fi mkdir -p "$marker_dir" if [ -L "$marker_dir" ] || [ ! -d "$marker_dir" ]; then printf '%s\n' 'Unsafe managed Deep Agents Code state directory.' >&2 @@ -218,10 +235,6 @@ prepare_observability_marker() { return 1 fi - if [ "${NEMOCLAW_OBSERVABILITY:-}" != "1" ]; then - rm -f "$target" - return 0 - fi tmp="$(mktemp "${target}.XXXXXX")" printf '%s\n' '1' >"$tmp" chmod 444 "$tmp" diff --git a/src/lib/actions/sandbox/snapshot.test.ts b/src/lib/actions/sandbox/snapshot.test.ts index aa2d0a14994..f77c00ad72f 100644 --- a/src/lib/actions/sandbox/snapshot.test.ts +++ b/src/lib/actions/sandbox/snapshot.test.ts @@ -952,11 +952,11 @@ describe("runSandboxSnapshot", () => { }); it.each([ - { enabled: true, assignmentPresent: true }, - { enabled: false, assignmentPresent: false }, + { enabled: true, expectedValue: "1" }, + { enabled: false, expectedValue: "0" }, ])("starts a snapshot clone with the authoritative source observability state when enabled=$enabled", async ({ enabled, - assignmentPresent, + expectedValue, }) => { let registeredClone: SandboxRecord | null = null; registerSandboxMock.mockImplementation((entry) => (registeredClone = entry as SandboxRecord)); @@ -986,7 +986,7 @@ describe("runSandboxSnapshot", () => { await runSandboxSnapshot("alpha", { kind: "restore", to: "beta" }); const [createCommandValue, createEnv] = streamSandboxCreateMock.mock.calls[0] ?? []; const createCommand = String(createCommandValue ?? ""); - expect(createCommand.includes("'NEMOCLAW_OBSERVABILITY=1'")).toBe(assignmentPresent); + expect(createCommand).toContain(`'NEMOCLAW_OBSERVABILITY=${expectedValue}'`); expect(createEnv?.NEMOCLAW_OBSERVABILITY).toBeUndefined(); expect(registerSandboxMock).toHaveBeenCalledWith( expect.objectContaining({ diff --git a/src/lib/actions/sandbox/snapshot.ts b/src/lib/actions/sandbox/snapshot.ts index 6e79e4c38e6..ba525d55e31 100644 --- a/src/lib/actions/sandbox/snapshot.ts +++ b/src/lib/actions/sandbox/snapshot.ts @@ -232,9 +232,11 @@ async function autoCreateSandboxFromSource( const openshellBin = getOpenshellBinary(); const sourceObservabilityEnabled = (srcEntry as { observabilityEnabled?: boolean }).observabilityEnabled === true; - const startupCommand = sourceObservabilityEnabled - ? ["env", "NEMOCLAW_OBSERVABILITY=1", "nemoclaw-start"] - : ["nemoclaw-start"]; + const startupCommand = [ + "env", + `NEMOCLAW_OBSERVABILITY=${sourceObservabilityEnabled ? "1" : "0"}`, + "nemoclaw-start", + ]; const createEnv = { ...process.env }; delete createEnv.NEMOCLAW_OBSERVABILITY; diff --git a/src/lib/onboard/sandbox-create-launch-observability.test.ts b/src/lib/onboard/sandbox-create-launch-observability.test.ts index 6f237c5782b..ec0c51c9091 100644 --- a/src/lib/onboard/sandbox-create-launch-observability.test.ts +++ b/src/lib/onboard/sandbox-create-launch-observability.test.ts @@ -36,7 +36,7 @@ describe("prepareSandboxCreateLaunch observability", () => { expect(serialized).not.toContain("secret"); }); - it("does not forward observability for another agent or when disabled", () => { + it("forwards an explicit disabled state only to Deep Agents Code", () => { const render = (name: string, observabilityEnabled: boolean) => prepareSandboxCreateLaunch({ agent: { name } as any, @@ -52,10 +52,11 @@ describe("prepareSandboxCreateLaunch observability", () => { buildEnv: () => ({}), }); - expect(render("langchain-deepagents-code", false).envArgs).not.toContain( - "NEMOCLAW_OBSERVABILITY=1", + expect(render("langchain-deepagents-code", false).envArgs).toContain( + "NEMOCLAW_OBSERVABILITY=0", ); expect(render("hermes", true).envArgs).not.toContain("NEMOCLAW_OBSERVABILITY=1"); + expect(render("hermes", false).envArgs).not.toContain("NEMOCLAW_OBSERVABILITY=0"); }); it("never trusts ambient DCode auto-approval as sandbox runtime input (#6478)", () => { diff --git a/src/lib/onboard/sandbox-create-launch.ts b/src/lib/onboard/sandbox-create-launch.ts index f809c757349..7b904c24c97 100644 --- a/src/lib/onboard/sandbox-create-launch.ts +++ b/src/lib/onboard/sandbox-create-launch.ts @@ -118,9 +118,12 @@ export function prepareSandboxCreateLaunch(input: SandboxCreateLaunchInput): San if (sandboxName) { envArgs.push(formatEnvAssignment("NEMOCLAW_SANDBOX_NAME", sandboxName)); } - if (input.observabilityEnabled === true) { - envArgs.push(formatEnvAssignment("NEMOCLAW_OBSERVABILITY", "1")); - } + envArgs.push( + formatEnvAssignment( + "NEMOCLAW_OBSERVABILITY", + input.observabilityEnabled === true ? "1" : "0", + ), + ); } appendExtraPlaceholderKeysEnvArg(envArgs, input.extraPlaceholderKeys, formatEnvAssignment); diff --git a/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh b/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh index dc88e0b0882..0f985e4c6b3 100755 --- a/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh +++ b/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh @@ -205,7 +205,6 @@ if [[ "${NEMOCLAW_E2E_TAVILY_SELF_TEST:-}" =~ ^policy-cleanup-(order|on-probe-fa ;; policy-remove:tavily:--yes) printf '%s\n' "removed" >"$POLICY_CLEANUP_STATE" - printf '%s\n' "absent" >"$POLICY_CLEANUP_MARKER" printf '%s\n' "TRACE:policy-remove" >>"$POLICY_CLEANUP_TRACE" ;; *) @@ -233,18 +232,6 @@ if [[ "${NEMOCLAW_E2E_TAVILY_SELF_TEST:-}" =~ ^policy-cleanup-(order|on-probe-fa printf '%s\n' "ERROR:unexpected fixture policy state" fi } - openshell() { - case "$*" in - *"NEMOCLAW_OBSERVABILITY=1"*"/usr/local/bin/nemoclaw-start /usr/bin/true"*) - printf '%s\n' "1" >"$POLICY_CLEANUP_MARKER" - printf '%s\n' "TRACE:observability-restore" >>"$POLICY_CLEANUP_TRACE" - ;; - *) - printf '%s\n' "unexpected OpenShell action in Tavily cleanup self-test" >&2 - return 93 - ;; - esac - } sleep() { : } @@ -319,9 +306,13 @@ else fail_test "project venv under /sandbox did not expose a usable python3 executable: $PROJECT_OUT" fi -# The Tavily policy-add rebuild materializes the configured observability -# marker, so preserve the state immediately before removing that policy. +# Policy replacement must retain the configured observability marker. Require +# that invariant here so an absent marker cannot silently skip the end-state +# proof below. OBSERVABILITY_MARKER_BEFORE="$(observability_marker_value || true)" +if [ "$OBSERVABILITY_MARKER_BEFORE" != "1" ]; then + fail_test "managed observability marker is absent after policy-add" +fi # Restore the deny-by-default posture for later checks in this ordered live # suite. Rebuild validation intentionally preserves active policy presets, so @@ -349,23 +340,12 @@ else fi # The temporary Tavily policy belongs only to this check. Policy replacement -# can reset ephemeral /tmp state, while the managed observability bit lives in -# the persistent /sandbox workspace. If an older runtime loses that bit, repair -# it through the canonical startup helper instead of manufacturing it here. -if [ "$OBSERVABILITY_MARKER_BEFORE" = "1" ]; then - OBSERVABILITY_MARKER_AFTER="$(observability_marker_value || true)" - if [ "$OBSERVABILITY_MARKER_AFTER" != "1" ]; then - RESTORE_OUTPUT="$(openshell sandbox exec --name "$SANDBOX_NAME" -- \ - /usr/bin/env NEMOCLAW_OBSERVABILITY=1 \ - /usr/local/bin/nemoclaw-start /usr/bin/true 2>&1)" \ - || fail_test "could not restore managed observability after policy-remove: $RESTORE_OUTPUT" - fi - OBSERVABILITY_MARKER_AFTER="$(observability_marker_value || true)" - if [ "$OBSERVABILITY_MARKER_AFTER" = "1" ]; then - pass "managed observability state remains enabled after policy-remove" - else - fail_test "managed observability marker was not restored after policy-remove" - fi +# may reset ephemeral /tmp, but it must preserve the managed bit in /sandbox. +OBSERVABILITY_MARKER_AFTER="$(observability_marker_value || true)" +if [ "$OBSERVABILITY_MARKER_AFTER" = "1" ]; then + pass "managed observability state remains enabled after policy-remove" +else + fail_test "managed observability marker was lost after policy-remove" fi if [ -n "$POLICY_CLEANUP_TRACE" ]; then diff --git a/test/e2e/support/platform-parity-cloud-experimental.test.ts b/test/e2e/support/platform-parity-cloud-experimental.test.ts index 3c0881453ab..f6a1d2af350 100644 --- a/test/e2e/support/platform-parity-cloud-experimental.test.ts +++ b/test/e2e/support/platform-parity-cloud-experimental.test.ts @@ -347,7 +347,7 @@ describe("P0-E cloud-experimental parity guardrails", () => { expect(result.stdout).toContain("NO_NEWLINE_IN_COMMAND"); }); - it("restores Tavily denial and the prior runtime marker for later ordered checks", () => { + it("restores Tavily denial while preserving the runtime marker for later ordered checks", () => { const result = spawnSync( "bash", [ @@ -376,7 +376,6 @@ describe("P0-E cloud-experimental parity guardrails", () => { "TRACE:opt-in-proof", "TRACE:policy-remove", "TRACE:post-remove-blocked", - "TRACE:observability-restore", ]); }); diff --git a/test/langchain-deepagents-code-proxy-launcher.test.ts b/test/langchain-deepagents-code-proxy-launcher.test.ts index f0832b8471b..f6cd13db3ea 100644 --- a/test/langchain-deepagents-code-proxy-launcher.test.ts +++ b/test/langchain-deepagents-code-proxy-launcher.test.ts @@ -274,11 +274,29 @@ describe("Deep Agents Code direct-exec proxy launcher", () => { expect(fs.readFileSync(markerFile, "utf8")).toBe("1\n"); expect(fs.statSync(markerFile).mode & 0o777).toBe(0o444); + const policyRestart = spawnSync("bash", [scriptPath, "/usr/bin/true"], { + env: { PATH: process.env.PATH ?? "/usr/bin:/bin" }, + encoding: "utf8", + }); + expect(policyRestart.status, policyRestart.stderr).toBe(0); + expect(fs.readFileSync(markerFile, "utf8")).toBe("1\n"); + fs.rmSync(ephemeralDir, { recursive: true, force: true }); expect(fs.existsSync(markerFile)).toBe(true); const enabledLaunch = runLauncher(launcherPath, [], {}); expect(enabledLaunch.status, enabledLaunch.stderr).toBe(0); expect(enabledLaunch.stdout).toContain("LAUNCHER_NEMOCLAW_OBSERVABILITY=1"); + + fs.mkdirSync(ephemeralDir, { recursive: true }); + const disabledStart = spawnSync("bash", [scriptPath, "/usr/bin/true"], { + env: { + PATH: process.env.PATH ?? "/usr/bin:/bin", + NEMOCLAW_OBSERVABILITY: "0", + }, + encoding: "utf8", + }); + expect(disabledStart.status, disabledStart.stderr).toBe(0); + expect(fs.existsSync(markerFile)).toBe(false); }); it("ignores tampered, symlinked, and non-regular observability markers", () => { @@ -318,10 +336,7 @@ describe("Deep Agents Code direct-exec proxy launcher", () => { fs.symlinkSync(symlinkTarget, markerFile); const symlinkedLaunch = runLauncher(launcherPath, [], {}); const symlinkedStart = spawnSync("bash", [scriptPath, "/usr/bin/true"], { - env: { - PATH: process.env.PATH ?? "/usr/bin:/bin", - NEMOCLAW_OBSERVABILITY: "1", - }, + env: { PATH: process.env.PATH ?? "/usr/bin:/bin" }, encoding: "utf8", }); expect(symlinkedLaunch.status, symlinkedLaunch.stderr).toBe(0); From 9f3f817da1245ef49dddf2cd81974aa1a82042a8 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 8 Jul 2026 16:50:32 -0700 Subject: [PATCH 20/21] test(dcode): close fetch and observability review gaps Signed-off-by: Aaron Erickson --- src/lib/onboard/sandbox-create-launch.test.ts | 8 ++++-- .../06-deepagents-code-python-egress.sh | 7 +++++ ...platform-parity-cloud-experimental.test.ts | 27 ++++++++++++++++--- ...ain-deepagents-code-proxy-launcher.test.ts | 4 ++- 4 files changed, 39 insertions(+), 7 deletions(-) diff --git a/src/lib/onboard/sandbox-create-launch.test.ts b/src/lib/onboard/sandbox-create-launch.test.ts index f8c68952a5e..b61ec661046 100644 --- a/src/lib/onboard/sandbox-create-launch.test.ts +++ b/src/lib/onboard/sandbox-create-launch.test.ts @@ -169,8 +169,12 @@ describe("prepareSandboxCreateLaunch", () => { }); expect(result.effectiveDashboardPort).toBe("0"); - expect(result.envArgs).toEqual([]); - expect(result.sandboxStartupCommand).toEqual(["env", "nemoclaw-start"]); + expect(result.envArgs).toEqual(["NEMOCLAW_OBSERVABILITY=0"]); + expect(result.sandboxStartupCommand).toEqual([ + "env", + "NEMOCLAW_OBSERVABILITY=0", + "nemoclaw-start", + ]); }); it("drops credential-bearing proxy URLs from Deep Agents Code sandbox create env", () => { diff --git a/test/e2e/e2e-cloud-experimental/checks/06-deepagents-code-python-egress.sh b/test/e2e/e2e-cloud-experimental/checks/06-deepagents-code-python-egress.sh index 4016e9c3dcb..0adc0ed16d7 100755 --- a/test/e2e/e2e-cloud-experimental/checks/06-deepagents-code-python-egress.sh +++ b/test/e2e/e2e-cloud-experimental/checks/06-deepagents-code-python-egress.sh @@ -264,6 +264,13 @@ if [ "${NEMOCLAW_E2E_PYTHON_EGRESS_SELF_TEST:-}" = "fetch-probe-command-shape" ] exit 0 fi +if [ "${NEMOCLAW_E2E_PYTHON_EGRESS_SELF_TEST:-}" = "fetch-success-classification" ]; then + expect_fetch_reached "fixture host" "https://approved.example/" + printf '%s\n' "${PREFIX}: $PASSED passed, $FAILED failed" + [ "$FAILED" -eq 0 ] || exit 1 + exit 0 +fi + if [ "${NEMOCLAW_E2E_PYTHON_EGRESS_SELF_TEST:-}" = "fetch-blocked-classification" ]; then expect_fetch_blocked "fixture host" "https://blocked.example/" printf '%s\n' "${PREFIX}: $PASSED passed, $FAILED failed" diff --git a/test/e2e/support/platform-parity-cloud-experimental.test.ts b/test/e2e/support/platform-parity-cloud-experimental.test.ts index a089595c779..2fa5405e8e3 100644 --- a/test/e2e/support/platform-parity-cloud-experimental.test.ts +++ b/test/e2e/support/platform-parity-cloud-experimental.test.ts @@ -288,9 +288,28 @@ describe("P0-E cloud-experimental parity guardrails", () => { }); it.each([ - ["accepts explicit denial evidence", "FETCH_BLOCKED:network policy denied", 0, "1 passed"], - ["rejects an unclassified fetch error", "FETCH_ERROR:opaque 403", 1, "lacked denial evidence"], - ] as const)("%s from the fetch_url probe", (_label, fixture, status, expected) => { + [ + "accepts an explicit non-empty success response", + "fetch-success-classification", + "FETCH_SUCCESS:200:1234", + 0, + "1 passed", + ], + [ + "accepts explicit denial evidence", + "fetch-blocked-classification", + "FETCH_BLOCKED:network policy denied", + 0, + "1 passed", + ], + [ + "rejects an unclassified fetch error", + "fetch-blocked-classification", + "FETCH_ERROR:opaque 403", + 1, + "lacked denial evidence", + ], + ] as const)("%s from the fetch_url probe", (_label, selfTest, fixture, status, expected) => { const result = spawnSync( "bash", [ @@ -302,7 +321,7 @@ describe("P0-E cloud-experimental parity guardrails", () => { { encoding: "utf8", env: { - NEMOCLAW_E2E_PYTHON_EGRESS_SELF_TEST: "fetch-blocked-classification", + NEMOCLAW_E2E_PYTHON_EGRESS_SELF_TEST: selfTest, NEMOCLAW_E2E_FETCH_URL_PROBE_FIXTURE: fixture, PATH: process.env.PATH ?? "/usr/bin:/bin", }, diff --git a/test/langchain-deepagents-code-proxy-launcher.test.ts b/test/langchain-deepagents-code-proxy-launcher.test.ts index f6cd13db3ea..099739f1ca9 100644 --- a/test/langchain-deepagents-code-proxy-launcher.test.ts +++ b/test/langchain-deepagents-code-proxy-launcher.test.ts @@ -279,7 +279,9 @@ describe("Deep Agents Code direct-exec proxy launcher", () => { encoding: "utf8", }); expect(policyRestart.status, policyRestart.stderr).toBe(0); - expect(fs.readFileSync(markerFile, "utf8")).toBe("1\n"); + const restartedLaunch = runLauncher(launcherPath, [], {}); + expect(restartedLaunch.status, restartedLaunch.stderr).toBe(0); + expect(restartedLaunch.stdout).toContain("LAUNCHER_NEMOCLAW_OBSERVABILITY=1"); fs.rmSync(ephemeralDir, { recursive: true, force: true }); expect(fs.existsSync(markerFile)).toBe(true); From 13489a76b0dafe139595e6702f50be9e3d84a60c Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 8 Jul 2026 17:27:40 -0700 Subject: [PATCH 21/21] ci: align CodeQL action versions Signed-off-by: Aaron Erickson --- .github/workflows/code-scanning.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/code-scanning.yaml b/.github/workflows/code-scanning.yaml index 223539bc03a..b598490561d 100644 --- a/.github/workflows/code-scanning.yaml +++ b/.github/workflows/code-scanning.yaml @@ -41,7 +41,7 @@ jobs: queries: security-and-quality - name: Perform CodeQL analysis - uses: github/codeql-action/analyze@8aad20d150bbac5944a9f9d289da16a4b0d87c1e # v4 + uses: github/codeql-action/analyze@99df26d4f13ea111d4ec1a7dddef6063f76b97e9 # v4 shellcheck: name: ShellCheck SARIF