Skip to content

feat(claude-code): restrict the egress of agent-created sandboxes - #5559

Merged
gwarmstrong merged 23 commits into
NVIDIA-NeMo:mainfrom
gwarmstrong:georgea/claude-code-agent-egress
Nov 6, 2026
Merged

gwarmstrong merged 23 commits into
NVIDIA-NeMo:mainfrom
gwarmstrong:georgea/claude-code-agent-egress

Conversation

@gwarmstrong

@gwarmstrong gwarmstrong commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Follows #5554, which has merged; this PR now targets main and shows only this harness's changes.

What does this PR do?

claude_code_agent gains network_access (default inherit) for the sandboxes it creates. The value comes from #5554's restrict_sandbox_network, using the adapter's model endpoint. Claude Code takes no tool grants, so model_and_tools is rejected before a sandbox is created. A session that borrows a task sandbox rejects any value other than inherit. README: the setting.

Why. The same reason as #5554, for Claude Code: without this, a sandbox Claude Code creates has the provider's default network. The CLI is uploaded from the Gym host, so a model-only sandbox needs nothing else from the internet for setup. Stacked on #5554, whose branch this PR targets. Part of #5552.

Validation

  • gym env test +entrypoint=responses_api_agents/claude_code_agent +should_validate_data=true: 175 passed.

  • With the behavior disabled, the new tests fail: model-only egress, the model_and_tools rejection and the borrowed-sandbox rejection. The inherit control passes.

  • Review follow-up: feat(pi): restrict the egress of agent-created sandboxes #5554's review fix merged in (4642420), so this adapter's restrict_sandbox_network call refuses an unenforceable network_access with a terminal 422; test_unenforceable_network_access_is_a_terminal_seed_refusal checks the 422 and the provider close. 7cd12f8 makes model_only allow api.anthropic.com when neither a Gym model server nor anthropic_base_url is set; test_model_only_allows_the_endpoint_the_cli_calls covers that default (activation still sets no ANTHROPIC_BASE_URL), an explicit direct URL, and a Gym model server winning over a direct URL, and fails with the fallback removed. Suite in the adapter's own venv: 179 passed.

  • pre-commit run --all-files: clean. Public-API and helper tests: 860 passed.

  • Second review follow-up (7fd5999): the refusal test posts to /v1/agent_sessions for an explicit policy and for a provider without network policies; the adapter's own refusals raise AgentSeedRejectedError; the README documents the defaults and refusals. Claude Code suite: 191 passed.

  • Follow-up to the feat(pi): restrict the egress of agent-created sandboxes #5554 review: merged its latest head; the helper call passes the provider; a borrowed sandbox with a restricted value is refused with AgentSeedRejectedError; the README says a borrowed sandbox relies on its owner's policy. Its benchmark profile sets network_access: model_only; the CLI is uploaded from the Agent Server, so it needs no sandbox network. The adapter's own test_benchmark_profile.py expects model_only (removing it fails the test). Suite: Claude Code: 191 passed; profile and helper tests pass.

  • Review follow-up (Yu Yao) at a9c90f0: the README states what model_only covers on the direct-Anthropic path (untested live; pair with disallowed_tools: WebSearch,WebFetch), that only OpenSandbox enforces the policy, and the dns+nft caveat. Tests: the shipped inherit default, host extraction for uppercase, userinfo and IPv6 URLs, inherit with a loopback model endpoint, and an unknown value refused at load. Claude Code suite with the profile and helper tests: 228 passed.

Rollouts

Internal runs on the georgea/nemo-gym fork at ee833ed, which carries this change before its review updates (Nemotron 3.5 Super on vLLM, 5 text tasks each, model_only, CLI 2.1.108), with the CLI reaching the Gym Model Server through the restricted sandbox:

Earlier runs without those fixes showed the problems those PRs fix: empty turns, and one rollout that stayed open after its answer until its job was cancelled.

Compatibility and benchmark impact

Default unchanged (inherit).

The adapter's own default stays inherit. Its benchmark profile (from #5550) now sets network_access: model_only, so a run that uses the profile gets the restricted sandbox; open-network scores are not comparable.

Checklist

  • I have read the contributing guidelines.
  • The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs.
  • Tests added or updated and pass locally, or N/A for docs-only / non-code changes.
  • Documentation added or updated, or N/A with justification. The adapter README describes the new settings.
  • Pre-commit checks pass locally (pre-commit run --all-files).
  • New source files include the required Apache-2.0 SPDX header. N/A: no new source files.
  • All commits have DCO sign-off (git commit -s).

Benchmarks whose Resources server supplies no sandbox, such as HLE, have
pi_agent create one per session. pi_sandboxed_agent ran those sandboxes
with model-only egress; pi_agent could not, so a reasoning benchmark moved
to agent sessions would gain open internet.

- network_access (inherit, model_only, model_and_tools) sets an OpenSandbox
  egress policy on a sandbox the agent creates. A borrowed task sandbox
  keeps its owner's network, so a session that borrows one rejects any
  other value. The policy helper, restrict_sandbox_network, lives in
  nemo_gym.agents.utils.sandbox_network and is exported from
  nemo_gym.agents so other session agents can share it.
- sandbox_runtime_dir points setup at a runtime baked into the image and
  checks its version, since a model-only sandbox cannot download Node or Pi.

Signed-off-by: gwarmstrong <[email protected]>
network_access: model_only limits a sandbox Claude Code creates to the
model endpoint's host; the runtime is uploaded from the Gym host, so it
needs no download egress. Claude uses no tool grants, so model_and_tools
is rejected, and a session that borrows a task sandbox rejects any value
other than inherit. The policy comes from restrict_sandbox_network,
imported from nemo_gym.agents, so it cannot be combined with
sandbox_config.provider_options.network_policy.

Signed-off-by: gwarmstrong <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Nov 4, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@gwarmstrong

Copy link
Copy Markdown
Contributor Author

/ok to test 3dec36d

@svcnvidia-nemo-ci svcnvidia-nemo-ci left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SHIP WITH CARE

Two correctness RISK findings affect restricted-network setup: Claude rejects its default direct-Anthropic configuration, and Pi validates a grant it has already decided to skip. The inline comments include narrow corrections and regression checks.

RISK — Add representative Pi smoke-rollout evidence

The supplied rollout evidence covers Claude Code, not the changed Pi setup paths. The new preinstalled-runtime test mocks the version response, so it doesn't establish that the real harness runs with restricted networking. AGENTS.md requires representative real model smoke rollouts for behavior-changing agent work.

Could you add a representative Pi rollout using an agent-owned OpenSandbox, network_access: model_only, and a preinstalled runtime? Record the configuration, image, Pi version, rollout count, agent/verifier outcome, and cleanup outcome. Expected acceptance: setup downloads no runtime, model calls and grading complete, an unrelated destination is denied, and close stops the owned sandbox. Preserve the inherit and borrowed-sandbox behavior asserted by the ownership regression. This is an evidence request, not a demonstrated runtime failure.

I inspected all nine changed files and their affected endpoint, policy, runtime, and cleanup paths. Two completed child report payloads weren't available, so I covered those topics directly. This was a static review; I didn't execute tests or rollouts.

Review generated by codex. This was a full review. Request a full review with /review reset=true.

spec,
network_access=self.config.network_access,
provider_name=provider.name,
model_base_url=self._resolve_base_url(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RISK — Resolve the default direct-Anthropic endpoint for the allowlist.

With an owned OpenSandbox, network_access: model_only, an API key, and both model_server and anthropic_base_url unset, seed now fails before sandbox creation. This is the direct-Anthropic configuration shown in the quick start. _resolve_base_url returns "", which host validation rejects. The allowlist should permit the default Anthropic model endpoint rather than reject this supported configuration.

Could you apply the fallback only at this policy-construction call?

model_base_url=self._resolve_base_url() or "https://api.anthropic.com",

Don't change _resolve_base_url globally: activation uses an empty result to retain the default-provider model-name and environment behavior. Preserve configured Gym endpoint precedence, explicit direct URLs, and rejection of explicit loopback URLs. inherit must still leave the policy unchanged.

Proposed checks, not executed: seed the configuration above and assert that its policy allows only api.anthropic.com; activation should still leave ANTHROPIC_BASE_URL unset. With an explicit direct URL, allow that host instead. With a Gym model-server reference plus a competing direct URL, allow only the Gym host and retain the existing credential assertion that the direct credential never enters the payload. Retain the current inherit policy assertion. Verify this suggested replacement before adopting it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 7cd12f8: only the policy construction uses self._resolve_base_url() or "https://api.anthropic.com". _resolve_base_url is unchanged, so activation still leaves ANTHROPIC_BASE_URL unset. test_model_only_allows_the_endpoint_the_cli_calls covers three cases. The default direct-Anthropic config allows only api.anthropic.com and _resolve_call_base_url stays empty. An explicit direct URL allows its own host. A Gym model server with a competing direct URL allows only the Gym host. The inherit and borrowed-sandbox assertions are unchanged.

Comment thread responses_api_agents/pi_agent/app.py Outdated
provider_name=provider.name,
model_base_url=self.resolve_model_base_url(self.config.model_server.name, trace_context=False),
tool_urls=[
str(access.connection.url) for access in tool_accesses if isinstance(access, MCPToolAccess)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RISK — Exclude MCP grants that Pi has already decided to skip.

An owned OpenSandbox with network_access: model_and_tools, a reachable model endpoint, and an optional grant named resources.mcp at http://127.0.0.1:7000/mcp now fails the entire seed. _mcp_grant_problems marks that unsupported name for omission, and the required-only rejection lets it pass. This comprehension nevertheless forwards its URL to host validation, which raises before creation. Expected behavior is to omit the optional grant and report a mcp_server_skipped gap, as activation and the existing regression specify.

Could you build tool egress from the same usable grant set as activation? Replace the comprehension inside tool_urls with:

str(access.connection.url)
for access in tool_accesses
if isinstance(access, MCPToolAccess) and access.name not in problems

The invariant is that a grant already omitted by Pi cannot prevent seed or add an unused host to generated egress. Preserve required unsupported-grant rejection before provider creation and allow valid optional and required MCP hosts. This change leaves model_only, inherit, optional direct-HTTP omission, and borrowed-sandbox rejection unchanged.

Proposed regression, not executed: seed an owned model_and_tools session with a valid required resources grant at resources.example and the optional resources.mcp grant above. Seed and activation should succeed; the policy should allow only the model host and resources.example; close observations should contain the omitted grant's gap. Retain the existing valid optional-host assertion, optional overlapping-name cases, and required unsupported-name rejection. Verify the suggested change before adopting it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in #5554's 8a32f14 (merged into this PR in 4642420): Pi's tool egress now comes only from the grants it keeps (access.name not in problems). test_tool_egress_leaves_out_the_mcp_grants_pi_skips seeds an owned model_and_tools session with a required resources grant and the optional resources.mcp grant at 127.0.0.1. The seed succeeds, and the policy allows only the model host and resources.example. The existing test_optional_mcp_grant_that_pi_cannot_use_is_left_out still checks the mcp_server_skipped gap at close, and a required unsupported grant is still refused before the provider is created.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked: the unsupported-name case is fixed in #5554 and covered by test_tool_egress_leaves_out_the_mcp_grants_pi_skips. One related case remains: a validly named optional grant at a loopback URL under model_and_tools still fails the whole seed with a 422 (the helper refuses any unreachable tool endpoint), where inherit would skip it. That is arguably the right fail-closed call; it is worth one sentence in the README.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added to Pi's README in #5554 (1cdc63e): under model_and_tools, a grant at an address the sandbox can't reach refuses the seed even when optional, and model_only refuses a required grant.

restrict_sandbox_network raised ValueError when a restricted
network_access could not be enforced: an explicit provider network
policy as well, a provider without network policies, or an endpoint
the sandbox cannot reach. The seed route answered it with a 500, which
the Environment Server retries, though no attempt can fix the
configuration. The helper now raises AgentSeedRejectedError, still a
ValueError, so every adapter that calls it refuses the seed once with
HTTP 422, before any sandbox is created.

Pi also built its tool egress from every MCP grant, including an
optional one it leaves out at activation, so such a grant at a loopback
URL failed the seed. Egress now covers only the grants Pi keeps.

Signed-off-by: gwarmstrong <[email protected]>
With neither a Gym model server nor anthropic_base_url, the CLI calls
Anthropic's own API, but the egress policy was built from an empty
base URL and refused the documented direct-Anthropic setup before the
sandbox was created. The allowlist now falls back to
https://api.anthropic.com in that case only; activation still leaves
ANTHROPIC_BASE_URL unset, a direct URL allows its own host, and a Gym
model server still wins over a direct URL.

Signed-off-by: gwarmstrong <[email protected]>
@gwarmstrong

Copy link
Copy Markdown
Contributor Author

On the Pi smoke-evidence finding: the Pi changes in this diff are #5554's, which this PR is stacked on, and their rollout evidence is in #5554's description (the Rollouts section): #5554. It covers internal HLE runs of Pi on an agent-owned OpenSandbox with the preinstalled runtime (sandbox_runtime_dir: /opt in a baked image): model_only 5/5 completed, graded and healthy, and model_and_tools with Gym's Tavily server 5/5 healthy with the search tools called. It also covers egress probes on the same cell: the model and tool hosts were reachable, while nodejs.org, the npm registry, an inference API and GitHub's DNS name were blocked.

This PR now also has #5554's review fix merged in (4642420): restrict_sandbox_network refuses an unenforceable network_access with a terminal 422 instead of a retried 500, and Pi builds tool egress only from the MCP grants it keeps. 7cd12f8 also lets model_only allow api.anthropic.com when neither a Gym model server nor anthropic_base_url is set (see the inline thread), and adds this adapter's 422 check.

@gwarmstrong

Copy link
Copy Markdown
Contributor Author

/ok to test 7cd12f8

@lafrancef

Copy link
Copy Markdown
Contributor

A few actionable follow-ups on the claude_code_agent changes:

  1. Exercise the /v1/agent_sessions route in test_unenforceable_network_access_is_a_terminal_seed_refusal:

  2. Raise AgentSeedRejectedError instead of raw HTTPException(422, ...) in _seed_agent_session_state:

  3. Drop the redundant if self.config.network_access != "inherit": guard in _seed_agent_session_state:

  4. Document the api.anthropic.com fallback, network_policy conflict, and bash requirement under model_only, and add network_access to configs/claude_code_agent.yaml:

Both sides added public exports to nemo_gym.agents; both are kept.

Signed-off-by: gwarmstrong <[email protected]>
The model_and_tools and borrowed-sandbox refusals raise
AgentSeedRejectedError, so they go through the seed route's refusal
logging and stay ValueErrors for direct callers, still as HTTP 422. An
owned sandbox always goes through restrict_sandbox_network, which leaves
inherit unchanged, as in the other five adapters. The refusal test posts
to /v1/agent_sessions for an explicit provider policy and for a provider
without network policies, and checks that no session record is left.

The README documents the api.anthropic.com default, the conflict with an
explicit network_policy, and that model_only needs bash in the image; the
agent config lists network_access: inherit with the other sandbox settings.

Signed-off-by: gwarmstrong <[email protected]>
@gwarmstrong

Copy link
Copy Markdown
Contributor Author

@lafrancef thanks, all four are in 7fd5999 (after merging the updated #5554, which brings in main):

  1. test_unenforceable_network_access_is_a_terminal_seed_refusal now posts to /v1/agent_sessions through TestClient(instance.setup_webserver()), parametrized like Pi's: an explicit network_policy on OpenSandbox ("not both") and provider_name="docker". It checks the 422 and its reason, that no sandbox is created and the provider is closed, and that body.agent_session_id is not in _session_records.
  2. The model_and_tools and borrowed-sandbox refusals raise AgentSeedRejectedError instead of HTTPException(422); test_unusable_network_access_is_rejected_before_connecting now expects that.
  3. The network_access != "inherit" guard is gone: an owned sandbox always goes through restrict_sandbox_network, as in the other five adapters, and the mock provider has name="local".
  4. The README's network_access paragraph covers the api.anthropic.com default, the conflict with sandbox_config.provider_options.network_policy (and a provider without network policies), that each refusal is a 422, and that model_only needs bash in the image because the bootstrap runs after the sandbox starts. configs/claude_code_agent.yaml lists network_access: inherit next to the other sandbox settings.

Claude Code suite at 7fd5999: 191 passed.

@gwarmstrong

Copy link
Copy Markdown
Contributor Author

/ok to test 7fd5999

Addresses Yu Yao's review of the Pi egress change:

- restrict_sandbox_network takes the required tool grants and refuses them
  under model_only with AgentSeedRejectedError. The policy blocks their
  hosts, so a session would otherwise fail only after the sandbox and the
  runtime exist, as a retried 5xx. Pi passes its required MCP grants.
- A host written with a trailing dot no longer yields a rule the egress
  sidecar never matches, and provider_options: null is restricted like an
  empty mapping instead of raising a 500.
- Pi's tests cover both restricted values for a borrowed sandbox, a model
  URL that fails to resolve (the provider is closed), and a preinstalled
  runtime that exits nonzero or reports a version prefix.
- The profile comment says that with sandbox_runtime_dir: null the image
  must hold the runtime at the default path with its ready marker.

Signed-off-by: gwarmstrong <[email protected]>
Under model_and_tools, a grant at an unreachable address refuses the seed even when optional, and model_only refuses a required grant.

Signed-off-by: gwarmstrong <[email protected]>
…ic path

Addresses Yu Yao's review:

- The README says only OpenSandbox enforces the policy (every other
  provider refuses a restricted value), drops the unclear "uploaded
  runtime" wording, and adds the dns+nft caveat.
- On the direct-Anthropic path (no model server, no anthropic_base_url),
  model_only allows api.anthropic.com with the real key in the sandbox. The
  README now says this path has not run live behind the deny policy, that
  the host also serves Anthropic's server-side web search, and to pair it
  with disallowed_tools: WebSearch,WebFetch. The benchmark profile uses a
  Gym model server, so it is not affected.
- Tests: the shipped config's network_access default is inherit; the
  allowed host is right for an uppercase, userinfo and IPv6-literal URL;
  inherit keeps a loopback model endpoint working; an unknown
  network_access value is refused at load.

Signed-off-by: gwarmstrong <[email protected]>
Signed-off-by: gwarmstrong <[email protected]>

NVIDIA-NeMo#5554 was squash-merged, so its files conflicted with this branch's copy of them; main's versions are kept. This PR's own changes are unchanged.
@gwarmstrong
gwarmstrong requested a review from a team as a code owner November 5, 2026 22:37
@gwarmstrong
gwarmstrong changed the base branch from georgea/pi-agent-egress to main November 5, 2026 22:37
@gwarmstrong

Copy link
Copy Markdown
Contributor Author

/ok to test f7c7e23

Brings in main's latest four commits; this PR's own changes are unchanged.

Signed-off-by: gwarmstrong <[email protected]>
@gwarmstrong

Copy link
Copy Markdown
Contributor Author

/ok to test b504b88

@yaoyu-33 yaoyu-33 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed at b504b88 (the change is git diff main...head now that #5554 has merged). Everything from my earlier review is addressed, and CI is green on this head.

  • model_and_tools is rejected (Claude takes no grants), a borrowed sandbox with a restricted value is refused, and the unenforceable cases are terminal 422s with the provider closed.
  • The README now says on the direct-Anthropic path model_only allows api.anthropic.com, has not been run live behind the policy, and may not stop provider-side search, so pair it with disallowed_tools: WebSearch,WebFetch; it also says only OpenSandbox enforces the policy and adds the dns+nft caveat. The benchmark profile uses a Gym model server, so it is not affected.
  • The tests now assert the shipped network_access: inherit, host extraction for uppercase, userinfo and IPv6 URLs, inherit with a loopback model endpoint, and an unknown value refused at load.

Not run here: I did not re-run the suites locally; I read the diff and relied on the green CI at this head.

@yaoyu-33 yaoyu-33 added the ready-to-merge PR is approved, current, and waiting for final CI or merge label Nov 6, 2026
@gwarmstrong
gwarmstrong added this pull request to the merge queue Nov 6, 2026
@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/42139064385

Merged via the queue into NVIDIA-NeMo:main with commit 029746e Nov 6, 2026
61 checks passed
@gwarmstrong
gwarmstrong deleted the georgea/claude-code-agent-egress branch November 6, 2026 01:00
gwarmstrong added a commit to gwarmstrong/Gym that referenced this pull request Nov 7, 2026
The egress PRs (NVIDIA-NeMo#5555-NVIDIA-NeMo#5559) added a network-policy test next to each adapter's HLE seed test. Keep this branch's seed test, which seeds HLE as shipped and with a direct_http grant, and the new egress test from main.

Signed-off-by: gwarmstrong <[email protected]>

This branch was previously deployed

1 inactive deployment
public — b504b88d Deployed Nov 5, 2026 by copy-pr-bot[bot] via release / finalize / notify #10549
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-to-merge PR is approved, current, and waiting for final CI or merge sla:review-overdue Review response is over the one-business-day SLA

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants