Skip to content

feat(server_runtime): run-secret follow-ups, a per-run token for orchestration routes, and an MCP token age limit - #6746

Open
d-molinari wants to merge 8 commits into
mainfrom
dmolinari/session-secret-followups
Open

d-molinari wants to merge 8 commits into
mainfrom
dmolinari/session-secret-followups

Conversation

@d-molinari

@d-molinari d-molinari commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

The server-runtime follow-ups promised in the reviews of #6161 and #5010, in one PR: #6746's two commits, then #6796's and #6782's, rebased onto main.

Run secret (#6161's review):

  • A server that signs with the run's secret (signs_sessions_with_run_secret, or mcp_bearer_token) takes part in partial-rollout checkpoints as restart_only, with one warning. A restart replaces the secret, so its episodes start over after a crash instead of verifying on an empty session.
  • The Apptainer and local providers leave NEMO_GYM_RUN_SESSION_SECRET_* out of sandboxed code's environment (nemo_gym.core.run_session_secrets). The limit is documented: code that shares the server's user and process table can still read a multi-worker server's initial environment.
  • The docs on harnesses' MCP tool naming are corrected, and the bearer-token test checks serverInfo.name.

A per-run token (#5010's review of host_relay):

  • The launcher makes one random token per run (NEMO_GYM_RUN_TOKEN), and ServerClient sends it in X-NeMo-Gym-Run-Token. A client the launcher did not start reads it from a user-only file named after the head server's address.
  • With require_run_token: true, or requires_run_token on a server class, these routes answer only callers that send the token, and 401 otherwise:
    • agents: /run, /aggregate_metrics, agent sessions, /rollouts/{rollout_id}/stop;
    • resources servers: /seed_session, /close_session, /verify, /aggregate_metrics, /reverify_mode;
    • environment servers: /run, /aggregate_metrics.
  • Routes that sandboxed code calls with credentials of its own stay open: tool routes, /mcp, Environment Server tools, model inference.
  • Off by default. The local and Apptainer providers drop the variable too.

MCP token age (#6161's review):

  • Tokens are signed with their time. mcp_token_max_age_seconds refuses an older token at /mcp with 401 invalid_token, before the MCP SDK reads it.
  • With bearer tokens, the refusal carries WWW-Authenticate. A token from a clock that stepped back is not refused.

Validation

At this head, on main 64d738eca2, Linux:

  • tests/unit_tests with 24 workers: 27,653 passed, 287 skipped. The 38 tests that failed and the 2 that errored have the same outcome on main, run one at a time; this venv lacks optional packages (mlflow, PIL, cloudpickle, wandb, jinja2) and a few tests depend on the host. Eight more files did not import for the same missing packages, so CI's run covers them.
  • environment_servers/single_agent_turn: 336 passed.
  • tests/e2e/session_routing with NEMO_GYM_MULTIWORKER_E2E=1: 10 passed, 9 skipped.
  • Pre-commit passes on the 34 changed files.

Each part was first validated at its own head: its new tests failed without the change, mutants of the guarded lines failed their tests (15 for the token, 6 for the token age), and the server suites of the components that expose MCP or send the token passed. When the drafts were combined, the only conflicts were tests that both sides added to two test files, and both are kept.

Rollouts

N/A. Nothing changes unless a config sets require_run_token or mcp_token_max_age_seconds, and none here does. A server that signs with the run's secret now restarts its episodes after a crash instead of resuming them.

Compatibility and benchmark impact

None by default.

  • A server class declared exported or stateless that sets mcp_bearer_token now reports restart_only, with a warning.
  • With require_run_token: true, an HTTP client of the protected routes other than ServerClient must send the header.

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 (so CI unit/server checks pass when applicable).
  • Documentation added or updated, or N/A with justification.
  • Pre-commit checks pass locally (run on the changed files).
  • New source files include the required Apache-2.0 SPDX header.
  • All commits have DCO sign-off (git commit -s) (so the DCO check passes).

🤖 Generated with Claude Code

@copy-pr-bot

copy-pr-bot Bot commented Nov 24, 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.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added risk:high Autobot PR risk: high bug Something isn't working area:core Shared APIs, servers, telemetry, health, and registries labels Nov 24, 2026
@d-molinari

Copy link
Copy Markdown
Contributor Author

/ok to test 0d1efce

@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

@d-molinari
d-molinari force-pushed the dmolinari/session-secret-followups branch from 0d1efce to 0d4b381 Compare November 30, 2026 21:22
@d-molinari d-molinari changed the title fix(server_runtime): checkpoint run-secret servers as restart_only, keep the secret from sandboxes feat(server_runtime): run-secret follow-ups, a per-run token for orchestration routes, and an MCP token age limit Nov 30, 2026
@d-molinari

Copy link
Copy Markdown
Contributor Author

/ok to test 0d4b381

@d-molinari
d-molinari force-pushed the dmolinari/session-secret-followups branch from 0d4b381 to 405b8e0 Compare December 2, 2026 22:17
@d-molinari
d-molinari marked this pull request as ready for review December 2, 2026 22:18
@d-molinari

Copy link
Copy Markdown
Contributor Author

/ok to test 405b8e0

@nemo-pr-automation
nemo-pr-automation Bot requested review from a team December 2, 2026 22:25
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the needs-review PR is ready for code review and waiting on a reviewer label Dec 2, 2026

@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.

HOLD

I found two BLOCKERs in the run-token boundary and two RISKs in credential discovery. The inline findings include reproductions and acceptance checks.

I reviewed all 34 changed files with three delegated reviews and verified the findings against the source.

Validation

  • CI on 405b8e03c534cabc13290bfb63f0d8960d725073 reports success for Nemo_CICD_Test, all four core shards, all eight server-suite shards, session-routing end-to-end, sandbox tests, combined core coverage and lint. Changed server tests is skipped.
  • Non-blocking harness conformance fails for miniswe_sandboxed, opencode and openclaw. I have not attributed those failures to this change.
  • CPU probes ran in gym:a4bf4964cd81600018ada0c0397157c78b4b1021, the default branch’s CI image. They reproduced unauthorized orchestration through Simple Agent, credential leakage in failure diagnostics, cross-client credential contamination and discovery-file loss after a bind collision.
  • MCP expiry, checkpoint downgrade and inherited-secret filtering probes passed. I used CI for existing suites rather than rerunning them locally. The probes use synthetic services and a fake model; the ToolSandbox failure probe executes its unchanged response method in isolation. I did not run a live-model rollout or full sandbox-provider integration.

Note: formal approval is not available for this request, so this review is posted as a comment only.


Inline comments (escaped v1):

  • responses_api_agents/simple_agent/app.py line 1091: BLOCKER: Model-selected tool calls borrow the run’s orchestration credential.

    Could you separate this dispatch from trusted orchestration calls? The new header injection makes this unchanged path attach the run token to any function name the model returns. /v1/responses stays open, and its caller supplies the function-tool definitions. With Simple Agent’s configured resources_server path, a caller without the token can therefore request verify or seed_session through the agent.

    I exercised the public agent route with a fake model selecting the supplied function. Direct /verify returned 401, but unauthenticated /v1/responses returned 200 and executed the guarded verifier. A second probe obtained MCP bearer metadata through guarded /seed_session.

    Please restrict model-controlled dispatch to server-owned tool routes after path normalization, or forward only scoped tool credentials instead of the run token. Checking the caller-supplied tools list alone cannot enforce this boundary. Keep legitimate sandbox inference and authorized episode orchestration working.

    Acceptance: with token enforcement enabled, unauthenticated response requests selecting verify or seed_session must execute neither handler and return no MCP credential. Normal tools and an authorized episode must still work.

  • responses_api_agents/toolsandbox_agent/app.py line 150: BLOCKER: Native status checks leak the newly attached run token.

    Could you route these checks through Gym’s redacting await raise_for_status(...) helper? This native aiohttp call bypasses the new redaction. An ordinary model HTTP error includes X-NeMo-Gym-Run-Token in repr(e), which this handler logs and copies into failure_reason.

    My HTTP-500 probe executed this response method and confirmed the token appears in the warning, persisted failure report and exported failure header. These existing calls become credential leaks because this PR adds the token to every ServerClient request. Aviary’s model status check has the same issue.

    Please replace the native status checks on ServerClient responses in both harnesses, including their seed and step paths, with the redacting helper. Preserve the client’s non-raising response contract and existing error attribution.

    Acceptance: make the model return HTTP 500 with a synthetic run token set. Captured logs, persisted failure events and exported failure headers must contain no token while keeping the useful status, body and failure classification.

  • nemo_gym/client/server_client.py line 202: RISK: File discovery contaminates clients for other runs.

    Could you keep an automatically discovered token on the client instance instead of placing it in os.environ? After one client loads run A, run_token() treats A’s discovered credential as an explicit process-wide override. A second client for run B skips B’s token file and sends A’s token. Reconstructing a client after A restarts also keeps the stale credential.

    A probe with two head addresses and real HTTP requests produced client 1: status=200 and client 2: status=401; the second request carried A’s token. This also conflicts with the TaskRunner contract that constructing a new runner refreshes the deployment after its servers change.

    Please bind file-discovered credentials to the requested head address and client lifetime. Preserve precedence for a token explicitly supplied through the environment.

    Acceptance: two clients for distinct authenticated runs must both succeed in one process; rebuilding a client after token-file rotation must load the replacement; an explicitly configured environment token must retain its documented priority.

  • nemo_gym/server_runtime/supervisor/server_supervisor.py line 747: RISK: A failed second launcher removes a live run’s discovery credential.

    Could you defer publishing this file until the launcher confirms ownership of the head address? _RunToken.start() runs before the head server starts, so a second launcher targeting an occupied address replaces the first run’s token file. Its failed-start cleanup then removes that replacement. The first run stays live, but fresh local clients can no longer discover its token.

    I reproduced this with a real occupied socket and a separate process running the token start/end lifecycle: the second bind failed with EADDRINUSE, the first socket stayed open, and its token file was gone. The supervisor already checks that its own head server has bound, so publication can follow that confirmation.

    Please keep token minting before server creation, but publish the address-keyed file only after _wait_for_head_server() succeeds. Preserve failed-start cleanup and fresh-port recovery.

    Acceptance: leave authenticated run A active, start B on A’s head address and drive B through bind failure and retry. A’s file and a newly constructed A client must still work; B must publish its token only under the address it successfully owns.

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

d-molinari and others added 2 commits December 3, 2026 23:17
…eep the secret from sandboxes

A restart replaces the run's secret, so the cookies and MCP tokens a server signed before it no
longer decode. A resources server or agent that signs with it (signs_sessions_with_run_secret, or
mcp_bearer_token) now takes part in partial-rollout checkpoints as restart_only whatever it
declares, with one warning: a restored session could not be reached, so its episodes start over
after a crash instead of verifying on an empty session. The mcp_bearer_token description,
get_session_secret, checkpoint_mode_in_effect and participant_workers.py say so.

The secret lives in the server's environment, which every process it starts inherits. The
Apptainer and local providers now leave the run-secret variables out of the environment they pass
to sandboxed code (nemo_gym.core.run_session_secrets, which both packages may import). The
get_session_secret docstring and the MCP tutorial state the guarantee's limit: code that shares
the server's user and the host's process table (the local provider's, or Apptainer's without
--containall) can still read a multi-worker server's secret from its workers' environment.

Addresses the review notes on #6161 about the run secret and checkpoint restore, and about its
inheritance in Apptainer and local sandboxes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
…ialize reports

Pi shows the model <name>_<tool>, as OpenCode does (gym_mcp.mjs); mcp__<name>__<tool> is what Gym
records for Pi's calls, and what mini-SWE uses. The single_agent_turn README, the
_check_mcp_server_names docstring and the mcp_server_name comment now say so, and the README names
only the agents that refuse names that collide in their own naming (OpenCode and Pi). The MCP
tutorial no longer says the deprecated sandboxed agents' tool_servers entries carry
mcp_server_name: since 19ab60f they keep the server's reference name.

test_bearer_token_and_advertised_name_present_an_ordinary_endpoint now checks that initialize
introduces the endpoint under mcp_server_name, so reverting mcp_auto_exposure to the config name
fails it.

Addresses the review notes on #6161 about the naming docs and the serverInfo.name test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
d-molinari and others added 6 commits December 3, 2026 23:17
…ir orchestration routes

Code in a sandbox can often reach a run's servers over the network, and a
caller's address does not tell it apart from the run's own servers: a
provider's port forwarder can make sandbox traffic arrive from loopback.

The launcher (ServerSupervisor) now makes one random token per run, unless
NEMO_GYM_RUN_TOKEN is already set, and every server it starts inherits it
through that variable. ServerClient sends it in X-NeMo-Gym-Run-Token with
every call to another server. A client that the launcher did not start
reads it from a file that only the launcher's user can read on its host
(in ~/.cache/nemo-gym/run-tokens/, or NEMO_GYM_RUN_TOKEN_DIR). The token
never enters the config, the local and Apptainer sandbox providers drop
the variable, and an HTTP error that Gym raises keeps no copy of it.

A server requires it with `require_run_token: true` in the global config,
or with requires_run_token on its class. It then answers its orchestration
routes (SimpleServer.run_token_routes) only for callers that send it, and
HTTP 401 otherwise:
- agents: /run, /aggregate_metrics, /v1/agent_sessions (/close,
  /capabilities), /rollouts/{rollout_id}/stop;
- resources servers: /seed_session, /prepare_sandbox, /close_session,
  /verify, /aggregate_metrics, /reverify_mode;
- environment servers: /run, /aggregate_metrics.
Routes that code in a sandbox calls with a credential of its own (tool
routes, /mcp, model inference, an agent's own routes) stay open. With
require_run_token, a server without a token fails at startup, and the
launcher refuses a reused venv whose Gym does not send the token.

The default is off: the token is made and sent, and nothing checks it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
…max_age_seconds

MCP session tokens were signed with URLSafeSerializer, which carries no
timestamp, so a token stayed valid as long as the server accepted its
session. Code in a sandbox that reads a token could use it after its
episode.

Tokens are now signed with URLSafeTimedSerializer. A resources server that
sets mcp_token_max_age_seconds answers a request to /mcp whose token is
older with HTTP 401 and the OAuth invalid_token error, before the MCP SDK
reads it; with mcp_bearer_token the reply also carries the RFC 6750
WWW-Authenticate challenge. The checkpoint middleware, which runs first,
reads such a token as one that does not verify and leaves it to the
endpoint. Session routing still sends it to its session's worker, whose
endpoint refuses it.

The option is off by default, and a token is then accepted at any age, as
before. A token signed after now, which a step back of the host clock
makes, is not refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
ServerClient sent the run's token with every call, so an agent sent it with
the tool calls it makes for a model as well, to whatever path the model
named. A caller of the agent's /v1/responses, which stays open for harnesses
in sandboxes, chooses the request's tools, so it could have the agent call
/verify or /seed_session with the token even in a run that requires it.

ServerClient.request now takes send_run_token, and False leaves the token
out. The agents that send a model's tool call to their resources server
through ServerClient pass it: Simple Agent, Simple Agent with compaction,
BrowseComp, CVDP, Finance, the remote agent and Haystack's HTTP tools. Tool
routes do not require the token, so these calls answer as before, while a
route that requires it refuses them. Calls through a tool grant never
carried it. The configuration reference and nemo_gym.core.run_token say so.

Addresses the review finding on #6746 that model-selected tool calls borrow
the run's orchestration credential.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
…re reports

Both harnesses checked the replies ServerClient returned with aiohttp's own
raise_for_status, whose error keeps the request's headers: now that every
ServerClient call carries the run's token, so does the error. Its repr
reached their warnings and, in ToolSandbox, the failure reason of the run's
scored-despite-failure event, which the persisted failure report and the
reply's failure header carry.

Their seed, model and step checks now use nemo_gym.client.raise_for_status,
which leaves the token out of the error's request headers and keeps its
type, status and response body, so the same failures are recorded as before
without the token.

Addresses the review finding on #6746 that native status checks leak the run
token.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
… its client

ServerClient.load_from_global_config put a token it read from the launcher's
file into NEMO_GYM_RUN_TOKEN, where it then counted as a token set for the
whole process: a client of another run in the same process skipped its own
file and sent the first run's token, and a client built after that run
restarted kept the old one.

The client now keeps the token it read and sends it with its own calls, and
the process's environment is left as it was. A client built again reads the
file again. A token set in NEMO_GYM_RUN_TOKEN still takes precedence, and a
process the launcher started still reads no file.

Addresses the review finding on #6746 that file discovery contaminates
clients for other runs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
…holds its address

The launcher wrote the token's file, named after the head server's address,
before its head server started. When another run held that address, the
second launcher's head server could not bind it, but its file had already
replaced the first run's, and the cleanup of its failed start then removed
it: the first run went on, and a client started after that could no longer
find its token.

The launcher still makes the token before any server starts, so every server
inherits it, and now writes the file once _wait_for_head_server has seen its
own head server bind the address. A start that fails before then leaves the
files as they were, and its retry on a fresh port writes the file for that
port only. Shutdown removes the file as before.

Addresses the review finding on #6746 that a failed second launcher removes
a live run's discovery credential.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
@d-molinari
d-molinari force-pushed the dmolinari/session-secret-followups branch from 405b8e0 to 3dcbcbd Compare December 4, 2026 07:17
@d-molinari

Copy link
Copy Markdown
Contributor Author

/ok to test 3dcbcbd

@d-molinari

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Addressed in 3dcbcbd28f (rebased on main 98458af5c9):

  1. A tool call the model selects no longer carries the run token (7cbaa40dce): ServerClient.request takes a keyword-only send_run_token (default True), and every agent that sends a model-selected tool path through ServerClient passes False. That is Simple Agent and the six others with the same dispatch: simple_agent_with_compaction, finance_agent, remote_agent, browsecomp_agent, cvdp_agent and haystack_agent. /verify and /seed_session refuse such calls with 401, while tool routes answer as before. test_a_tool_call_the_model_selects_reaches_no_route_that_requires_the_token reproduces your probe end to end through a real Simple Agent. As the docs now say, a server can't require the token on a tool route that agents reach this way; such a route needs MCP or another credential.
  2. Status checks no longer leak the token (904fd9b4ff): ToolSandbox's seed, model and step checks and Aviary's seed and model checks use the redacting nemo_gym.client.raise_for_status, which keeps the error type, status and body. New tests return a real HTTP 500 to a call carrying a synthetic token, and check that logs, failure reasons and the failure header keep the status and classification but not the token.
  3. A token read from a file stays with its client (6ae9647a82): it lives on the client built for that head server, and os.environ is never written, so the clients of two runs in one process each send their own token, and a rebuilt client re-reads the file. NEMO_GYM_RUN_TOKEN still takes precedence.
  4. A failed second launcher leaves the live run's file (3dcbcbd28f): the launcher still mints the token before any server starts, but writes the address-keyed file only after _wait_for_head_server() confirms its own bind. A test drives the real supervisor through EADDRINUSE and the fresh-port retry: run A's file and client survive, and B publishes only under its own port.

Rebase note: main added /prepare_sandbox after this branch's base. It is now one of the resources server's token-guarded orchestration routes, with docs and a test.

Tests: the core unit tree with 24 workers fails only tests that fail the same way on main (failing IDs rerun one at a time at both). Agent and server suites: simple_agent 222, toolsandbox_agent 18, aviary_agent 14, simple_agent_with_compaction 39, finance_agent 135, remote_agent 72, single_agent_turn 399, browsecomp_agent 187 and haystack_agent 76 passed; cvdp_agent 71 passed, plus 2 file-mode failures that depend on the host's umask and fail the same way on main. Session-routing e2e: 10 passed, 9 skipped. Pre-commit is clean.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core Shared APIs, servers, telemetry, health, and registries bug Something isn't working needs-review PR is ready for code review and waiting on a reviewer risk:high Autobot PR risk: high 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.

2 participants