Skip to content

feat(execd): propagate ingress request id into command execution - #2722

Open
yjjnls wants to merge 1 commit into
opensandbox-group:mainfrom
yjjnls:feat/execd-request-id-propagation
Open

yjjnls wants to merge 1 commit into
opensandbox-group:mainfrom
yjjnls:feat/execd-request-id-propagation

Conversation

@yjjnls

@yjjnls yjjnls commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

Summary

Implements #2721.

When /command (or PTY session creation) carries an X-Request-Id header, execd now propagates it into the launched command so process-level audit (eBPF process_exec arguments, ps, /proc/<pid>/cmdline) can correlate executions to the calling request:

  • Shell-mode commands (foreground, background, and PTY sessions) are wrapped as export SANDBOX_REQUEST_ID=<rid>; <code>: the id lands in the launched shell's argv and is inherited by descendant processes via the environment. The wrap happens inside prepareCommand, so both entry paths are covered.
  • The header value is capped at 128 chars and shell-quoted (shellQuote), so a hostile header cannot break out of the wrapper.
  • An absent/empty header leaves the command byte-for-byte unchanged; native argv execution is passed through untouched.
  • No wire-format change: the id is header-driven; the request body schema (RunCommandRequest) is unchanged.

Testing

  • go test ./pkg/runtime/... ./pkg/web/controller/... in components/execd (all pass, incl. new requestid_test.go covering wrapping/quoting/injection and PTY wrap path)
  • go build ./... and go vet on the touched packages
  • gofmt -l clean on touched packages

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-11T14:50:42.908174Z 8318a8e Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions github-actions Bot added component/execd size/L Denotes a PR that changes 100-499 lines, ignoring generated files. labels Nov 11, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Credits must be used to enable repository wide code reviews.

@yjjnls

yjjnls commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 029942df6f

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +62 to +63
if rid := requestIDFromRequest(c.basicController); rid != "" {
command = runtime.WrapCommandWithRequestID(req.Command, rid)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve interactive PTYs when propagating request IDs

When POST /pty includes X-Request-Id but omits the optional command (the normal long-lived-shell flow documented in components/execd/PTY.md), this branch converts the empty command into a nonempty export ...; string. runtime.buildPTYCommand treats every nonempty command as a -c invocation, so the shell performs the export and exits on the first WebSocket attach instead of remaining interactive; carry the ID separately so an empty command stays on the interactive launch path.

AGENTS.md reference: AGENTS.md:L46-L46

Useful? React with 👍 / 👎.

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.

Fixed in 7423ae1: the wrap now only applies when the command is non-empty (rid != "" && command != ""), so the default interactive-shell PTY flow is byte-for-byte unchanged. Interactive shells intentionally don't carry the id (documented in the PR body); non-empty PTY commands keep the argv wrap.

if requestID == "" {
return code
}
return "export " + RequestIDEnvVar + "=" + shellQuote(requestID) + "; " + code

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Use Windows-compatible request-ID propagation

When a Windows execd receives a shell-mode /command with X-Request-Id, this prepends the POSIX-only export ...; syntax, while command_windows.go:newShellCommand executes the text with cmd /C; cmd.exe has no export command and does not use ; as this command separator, so the user's command fails instead of running. This regresses the documented Windows execd command path, so the wrapper must be OS-specific (or propagate through Cmd.Env on Windows).

AGENTS.md reference: AGENTS.md:L46-L46

Useful? React with 👍 / 👎.

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.

Fixed in 7423ae1: WrapCommandWithRequestID now no-ops on Windows (wrapCommandForShell(runtime.GOOS, …), unit-tested), and prepareCommand injects SANDBOX_REQUEST_ID directly into cmd.Env on every platform and for native argv execution, so descendants still inherit the correlation id. Also adopted the charset-validation option (see command.go): ids outside [A-Za-z0-9._-] are dropped at the controller, which makes the single POSIX wrapper sound.

@Pangjiping Pangjiping left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review summary — Request changes

The overall approach is sound: header-driven, no wire-format change, POSIX quoting is correct, and native argv mode is untouched. However, two high-severity issues must be fixed before merge:

  1. [High] pty_controller.go:61-64 — default (empty-command) PTY sessions break. WrapCommandWithRequestID("", rid) returns a non-empty string, so buildPTYCommand takes the -c branch and runs a shell that exits immediately. Since the ingress RequestIdMiddleware always sets X-Request-ID (it generates a uuid4 when the client omits it), every default-shell PTY creation regresses in production.
  2. [High] command_argv.go:66 — Windows is broken by the POSIX-only wrapper. On Windows the shell is cmd /C (command_windows.go:210-212); export is not a cmd builtin, and single quotes have no cmd.exe quoting semantics, so both command execution and injection containment fail there.
  3. [Medium] command.go:43-47 — silent byte-truncation diverges from the ingress-logged id for oversized values (exactly what a hostile client would send) and can split UTF-8 runes. Prefer rejecting oversized ids over truncating.

Non-blocking notes: shellQuote escaping is correct on POSIX (covered by the new tests); no double-wrap (PTY spawns via buildPTYCommand directly); language dispatch only wraps shell languages; no wire-format change. Test coverage for wrapping/quoting/injection is good — please add a case for the empty-command PTY path.

Comment on lines +61 to +64
command := req.Command
if rid := requestIDFromRequest(c.basicController); rid != "" {
command = runtime.WrapCommandWithRequestID(req.Command, rid)
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

High: this breaks default (empty-command) PTY sessions — the session exits immediately.

CreatePTYSessionRequest.Command is omitempty, and an empty command means "launch an interactive shell": buildPTYCommand (runtime/pty_session.go:241-248) only appends -c <command> when command != "". But WrapCommandWithRequestID("", rid) returns the non-empty string export SANDBOX_REQUEST_ID='<rid>'; — so the empty-command branch is silently defeated and execd runs bash --noprofile --norc -c "export SANDBOX_REQUEST_ID='…'; ", which exits immediately. The PTY session dies on creation.

This is not an edge case: the ingress RequestIdMiddleware (server/opensandbox_server/middleware/request_id.py) always populates X-Request-ID (it generates a uuid4 when the client omits it), so every default-shell PTY creation regresses in production. The supported empty-command case is exercised by the existing test at pty_session_test.go:366 (CreatePTYSession(id, "", "")).

Please only wrap when the command is non-empty (or special-case empty as export …; exec "$SHELL" to keep both audit and interactivity):

Suggested change
command := req.Command
if rid := requestIDFromRequest(c.basicController); rid != "" {
command = runtime.WrapCommandWithRequestID(req.Command, rid)
}
command := req.Command
if rid := requestIDFromRequest(c.basicController); rid != "" && command != "" {
command = runtime.WrapCommandWithRequestID(req.Command, rid)
}

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.

Fixed in 7423ae1 — adopted the suggested form verbatim (rid != "" && command != ""). Thanks for the pointer to the ingress middleware always populating X-Request-ID; with that context the skip-empty guard is clearly load-bearing. The export …; exec "$SHELL" variant is a nice follow-up idea; kept it out of this PR to stay minimal.

// Shell-mode commands carry the ingress request id in argv (via the
// exported env) so process-level audit captures the correlation id.
// Native argv mode is passed through untouched.
cmd = newShellCommand(ctx, WrapCommandWithRequestID(request.Code, request.RequestID))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

High: the POSIX-only wrapper is injected into cmd /C on Windows — every shell-mode command fails there, and the quoting guarantee does not hold.

prepareCommand is platform-neutral (no build tag; it already handles Windows executable resolution) and is called from the Windows paths (command_windows.go:54,146). On Windows, newShellCommand runs cmd /C <code> (command_windows.go:210-212), so once ingress forwards X-Request-Id:

  1. export is not a cmd.exe builtin → every shell-mode /command fails with 'export' is not recognized… and the user's command never executes.
  2. shellQuote's POSIX single-quoting ('…') has no quoting semantics in cmd.exe, so header characters like &, ^, %VAR% are interpreted rather than contained — the injection resistance this PR claims does not hold on the Windows path.

Please pick one:

  • Add a per-OS wrapper (e.g. requestid_windows.go with a cmd-safe set "SANDBOX_REQUEST_ID=…" form) and dispatch in prepareCommand, mirroring the existing newShellCommand split; or
  • Skip wrapping when runtime.GOOS == goosWindows until a safe form exists; or
  • Validate the header against a safe charset ([A-Za-z0-9._-], reject rather than truncate), which makes a single wrapper sound on both shells.

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.

Fixed in 7423ae1 — took the 'skip wrapping on Windows' option (wrapCommandForShell no-ops for windows, unit-tested) and combined it with the charset-validation idea from the command.go thread: prepareCommand now injects SANDBOX_REQUEST_ID into cmd.Env unconditionally (all platforms, native argv included), so Windows still gets env propagation without a cmd.exe-unsafe prefix.

Comment on lines +43 to +47
rid := ctx.GetHeader("X-Request-Id")
if len(rid) > maxRequestIDLen {
rid = rid[:maxRequestIDLen]
}
return rid

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Medium: silently byte-truncating oversized ids defeats correlation and can produce invalid UTF-8.

  • The ingress middleware accepts arbitrarily long client-supplied ids (only .strip(), no cap) and logs/echoes the full value. Truncating here to 128 bytes means the audit-visible SANDBOX_REQUEST_ID silently diverges from the id ingress logged — exactly for the oversized ids a hostile client would send.
  • rid[:128] slices bytes, not runes — it can split a multi-byte UTF-8 sequence, leaving invalid UTF-8 in shell argv and the exported env var.

Prefer dropping the id when it exceeds the cap (return "" so no wrapping happens), or at minimum truncate on a rune boundary and document the divergence:

Suggested change
rid := ctx.GetHeader("X-Request-Id")
if len(rid) > maxRequestIDLen {
rid = rid[:maxRequestIDLen]
}
return rid
rid := ctx.GetHeader("X-Request-Id")
if len(rid) > maxRequestIDLen {
// Oversized ids are dropped rather than truncated: a truncated id
// would silently mismatch the id logged by ingress.
return ""
}
return rid

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.

Fixed in 7423ae1 — adopted the drop-not-truncate suggestion and extended it with your charset option: sanitizeRequestID drops oversized ids entirely and rejects anything outside [A-Za-z0-9._-] (requestIDCharset), so the propagated id always matches the ingress-logged id and is sound in both POSIX and cmd.exe shells. Unit-tested in TestSanitizeRequestID.

@Pangjiping Pangjiping self-assigned this Nov 11, 2026
@yjjnls
yjjnls force-pushed the feat/execd-request-id-propagation branch 2 times, most recently from c0d7682 to 7423ae1 Compare November 11, 2026 05:46
@yjjnls

yjjnls commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

@codex review — pushed 7423ae1 addressing the two P1 findings (PTY empty-command wrap; Windows POSIX prefix) and the truncation thread (drop-not-truncate + charset validation). PTY empty-command regression test added to the controller suite; Windows no-wrap and env injection covered by unit tests in requestid_test.go / command_argv_test.go.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7423ae1afb

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

// sanitizeRequestID validates a caller-supplied request id and returns ""
// for anything that must not be propagated (oversized, wrong charset).
func sanitizeRequestID(rid string) string {
if rid == "" || len(rid) > maxRequestIDLen || !requestIDCharset.MatchString(rid) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Document the request-ID propagation contract

When /command carries X-Request-ID, this adds or overrides a user-visible SANDBOX_REQUEST_ID environment variable and silently drops IDs that exceed 128 bytes or fail this charset check, but the /command operation in specs/execd-api.yaml declares neither the header nor these validation/reserved-environment semantics and no user documentation changed. Add this behavior to the contract and docs so clients know which IDs propagate and that this environment key is owned by execd.

AGENTS.md reference: AGENTS.md:L45-L46

Useful? React with 👍 / 👎.

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.

Fixed in 9a86d35: /command in specs/execd-api.yaml now declares the X-Request-Id header (optional, ≤128, ^[A-Za-z0-9._-]+$) with the propagation/drop semantics, and docs/architecture/data-plane/execd.md gained a 'Request id propagation' section covering the reserved SANDBOX_REQUEST_ID env, argv visibility, and the silent-drop policy.

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.

Fixed in 214e373 — took the sync path: the checked-in JS (execd.ts runCommand header typed "X-Request-Id"?: string with doc comment) and Python (run_command.py: x_request_id: str | Unset = UNSET threaded through sync_detailed/sync/asyncio_detailed/asyncio → _get_kwargs → X-Request-Id header) clients now expose the optional header, matching the declared spec. Go/Kotlin SDKs are unaffected (handwritten / no header surface change needed).

// environment and the original code still runs.
func TestWrapCommandWithRequestIDExecutesInShell(t *testing.T) {
wrapped := WrapCommandWithRequestID("printf '%s' \"$SANDBOX_REQUEST_ID\"", "req-xyz")
out, err := exec.Command("sh", "-c", wrapped).Output()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Guard POSIX shell execution tests on Windows

On a native Windows go test ./pkg/runtime, WrapCommandWithRequestID deliberately returns the original code, so this test either cannot start sh or, when an MSYS/Git shell is available, prints an empty value instead of req-xyz; the newly added package tests therefore fail on the supported Windows platform. Put these POSIX execution checks behind a !windows constraint or skip while retaining the pure Windows no-wrap test.

Useful? React with 👍 / 👎.

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.

Fixed in 9a86d35: the two POSIX sh -c execution checks moved to requestid_exec_test.go behind a //go:build !windows tag; requestid_test.go keeps only the GOOS-parametrized classification table (wrapCommandForShell), which is shell-free and Windows-safe.

cmd, err = prepareCommand(context.Background(), noID)
require.NoError(t, err)
for _, entry := range cmd.Env {
require.NotContains(t, entry, "SANDBOX_REQUEST_ID=")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Isolate the no-ID test from the parent environment

When the suite starts with SANDBOX_REQUEST_ID set—for example, when go test is itself launched as a descendant of a newly instrumented execd command—prepareCommand seeds cmd.Env from os.Environ() before handling the empty request ID, so this assertion finds the inherited entry and fails even though no value was injected by the request. Unset and restore the key around this case, or compare against the inherited baseline rather than requiring total absence.

Useful? React with 👍 / 👎.

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.

Fixed in 9a86d35: the no-ID case now does t.Setenv(SANDBOX_REQUEST_ID, "") before calling prepareCommand and asserts that any SANDBOX_REQUEST_ID=-prefixed entry carries an empty value — an inherited variable can no longer satisfy (or break) the assertion.

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.

Fixed in 214e373: the spec description and docs/architecture/data-plane/execd.md now scope the argv guarantee to POSIX shells (Windows propagates via the environment only) and explicitly exclude interactive PTY sessions (created without command) from the propagation promise.

@yjjnls
yjjnls force-pushed the feat/execd-request-id-propagation branch from 7423ae1 to 9a86d35 Compare November 11, 2026 06:46
@yjjnls
yjjnls requested a review from jwx0925 as a code owner November 11, 2026 06:46
@github-actions github-actions Bot added the documentation Improvements or additions to documentation label Nov 11, 2026
@yjjnls

yjjnls commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

@codex review — pushed 9a86d35 addressing all three P2s: API spec + docs now declare the X-Request-Id propagation contract; POSIX shell-execution tests moved behind !windows; the no-ID env assertion is isolated from the parent environment. No production code changes in this round (docs + tests only).

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9a86d35a6e

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread specs/execd-api.yaml
tags:
- Command
parameters:
- name: X-Request-Id

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Regenerate the execd clients for the new header

After adding this header, the checked-in generated clients are stale: sdks/sandbox/javascript/src/api/execd.ts:2258-2264 still types runCommand.parameters.header as never, and Python's generated run_command._get_kwargs accepts only body and emits only Content-Type at sdks/sandbox/python/src/opensandbox/api/execd/api/command/run_command.py:30-45. Consumers of these generated operations therefore cannot supply the newly documented header through their typed API; rerun the execd generators and commit the affected outputs.

AGENTS.md reference: specs/AGENTS.md:L50-L50

Useful? React with 👍 / 👎.

Comment thread specs/execd-api.yaml Outdated
Comment on lines +436 to +437
processes, and (for shell-mode commands) includes it in the launched shell's
argv so process-level audit can correlate executions to the calling request.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Limit the argv guarantee to non-Windows shells

On a Windows execd, shell mode uses cmd /C, and wrapCommandForShell returns the original command for goosWindows at components/execd/pkg/runtime/requestid.go:45-47, so the request ID is injected only into Cmd.Env and never into the launched shell's argv. This unconditional public contract promises argv correlation for every shell-mode command and will mislead Windows consumers and audit tooling; qualify the guarantee as POSIX/non-Windows.

AGENTS.md reference: AGENTS.md:L46-L46

Useful? React with 👍 / 👎.

Comment thread docs/architecture/data-plane/execd.md Outdated

### Request id propagation

`/command` and PTY session creation accept an optional `X-Request-Id` header. When it is present and well-formed (at most 128 characters from `[A-Za-z0-9._-]`), execd exports it as the `SANDBOX_REQUEST_ID` environment variable for the launched command and every descendant process, and shell-mode commands also carry it in the launched shell's argv — so process-level audit (eBPF `process_exec` arguments, `ps`) can correlate executions back to the calling request. Ids that are oversized or use other characters are dropped silently (no propagation, no error), and calls without the header are byte-for-byte unchanged.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Exclude interactive PTYs from the propagation promise

For the normal long-lived POST /pty request with no command, CreatePTYSession intentionally requires command != "" before wrapping at components/execd/pkg/web/controller/pty_controller.go:60-66, and the runtime API receives no separate request-ID field, so the interactive shell and its descendants do not get SANDBOX_REQUEST_ID. The fresh architecture text now promises propagation for PTY creation without this exception; document that only PTYs created with a nonempty one-shot command propagate the ID.

AGENTS.md reference: AGENTS.md:L46-L46

Useful? React with 👍 / 👎.

@yjjnls
yjjnls force-pushed the feat/execd-request-id-propagation branch from 9a86d35 to 214e373 Compare November 11, 2026 08:46
@yjjnls

yjjnls commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

@codex review — pushed 214e373 addressing the three P2s: JS/Python generated clients synced with the declared header; spec/docs wording scoped (POSIX-only argv guarantee; interactive PTYs excluded). Docs/spec/tests only again — no production code touched.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 214e373ec5

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

*,
client: AuthenticatedClient | Client,
body: RunCommandRequest,
x_request_id: str | Unset = UNSET,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Forward x_request_id from the async wrapper

When a caller uses the generated Python asyncio(...) helper with a non-default x_request_id, the value is never passed to asyncio_detailed, so _get_kwargs receives UNSET and omits the X-Request-Id header. The fresh evidence after the earlier generated-client report is that this newly added parameter is accepted here while the call at the bottom still invokes asyncio_detailed with only client and body; forward the parameter so the async convenience API behaves like the other three entry points.

AGENTS.md reference: sdks/AGENTS.md:L117-L117

Useful? React with 👍 / 👎.

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.

Fixed in 1444485: the asyncio() wrapper now forwards x_request_id to asyncio_detailed (parity with the sync path).

@yjjnls
yjjnls force-pushed the feat/execd-request-id-propagation branch from 214e373 to 1444485 Compare November 11, 2026 10:42
@yjjnls

yjjnls commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

@codex review — pushed 1444485 forwarding x_request_id from the asyncio() wrapper (single-line fix from the previous round).

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 14444857e0

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

await asyncio_detailed(
client=client,
body=body,
x_request_id=x_request_id,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Add async request-ID forwarding coverage

The forwarding line fixes the prior async omission, but I checked sdks/sandbox/python/tests and there is still no x_request_id/X-Request-Id coverage. Consequently, a later regeneration or wrapper edit can again accept a non-default ID while silently omitting the header without any Python check failing; add an async transport test that calls this convenience wrapper and asserts the outgoing header, ideally alongside sync parity.

AGENTS.md reference: sdks/AGENTS.md:L119-L120

Useful? React with 👍 / 👎.

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.

Fixed in 25ba596: added tests/test_run_command_request_id_header.py — four tests covering sync_detailed, the sync() wrapper, the asyncio() wrapper (the forwarding regression this thread flagged), and the unset case asserting no header is sent. Uses httpx.MockTransport with header capture; runs via pytest tests/test_run_command_request_id_header.py in sdks/sandbox/python.

@yjjnls
yjjnls force-pushed the feat/execd-request-id-propagation branch from 1444485 to 25ba596 Compare November 11, 2026 12:50
@yjjnls

yjjnls commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

@codex review — pushed 25ba596 adding the missing Python coverage for the X-Request-Id forwarding (sync + asyncio wrappers + unset case).

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 25ba596305

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".


await run_command.asyncio(client=client, body=_body(), x_request_id=UNSET)

assert "X-Request-Id" not in captured

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Check the normalized key in the unset-header test

When a regeneration accidentally sends the header for UNSET, _client_with_capture lowercases every captured key, so the emitted key is x-request-id; this mixed-case lookup can therefore never find it and the test still passes. Assert the lowercase key (or retain httpx.Headers) so the promised unset regression coverage is effective.

AGENTS.md reference: sdks/AGENTS.md:L119-L120

Useful? React with 👍 / 👎.

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.

Fixed in 8318a8e: the unset case now asserts the normalized x-request-id key (the capture lowercases header names), so a regeneration emitting the header cannot slip past a mixed-case check.

// TestWrapCommandWithRequestIDNeutralizesInjection verifies a hostile
// request id cannot break out of the export and run extra commands.
func TestWrapCommandWithRequestIDNeutralizesInjection(t *testing.T) {
wrapped := WrapCommandWithRequestID("echo ok", "'; touch /tmp/pwned; '")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Verify the injection command has no side effect

If quote escaping regresses, this payload can execute touch /tmp/pwned, but the test only inspects stdout and the final echo ok still makes Output() return success with ok\n; the injection test therefore passes even though the injected command ran. Use a marker under t.TempDir() and assert that it was not created (or otherwise make execution observable).

Useful? React with 👍 / 👎.

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.

Fixed in 8318a8e: the hostile payload now targets a marker under t.TempDir() and the test asserts the marker was never created — quote-escaping regressions fail the test even though the trailing echo ok keeps the shell exit clean.

@yjjnls
yjjnls force-pushed the feat/execd-request-id-propagation branch from 25ba596 to 8318a8e Compare November 11, 2026 14:44
@yjjnls

yjjnls commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

@codex review — pushed 8318a8e: normalized-key assertion for the unset-header test; injection test now verifies the side-effect marker under t.TempDir() is not created.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 8318a8e16b

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@Pangjiping Pangjiping left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-review after 8318a8e: the two P1s and the truncation thread are resolved, thanks. One spoofing gap in the env injection and a doc typo — details inline.

// Direct env injection guarantees descendants inherit the request id
// on every platform (including Windows, where the POSIX export prefix
// does not apply) and for native argv execution.
cmd.Env = append(cmd.Env, RequestIDEnvVar+"="+request.RequestID)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Medium] Duplicate env entry when the caller's Envs already contain SANDBOX_REQUEST_ID: request.Envs flows unfiltered through UserEnvOverlay → mergeEnvs into cmd.Env, and this append adds a second entry with the same name. Duplicate-key precedence is platform/libc-dependent (glibc and musl getenv return the first match), so the caller-supplied value wins and can spoof the audit correlation id — notably in native argv mode, where the env is the only carrier — breaking the descendants-inherit-the-request-id contract stated above and declared in the spec. UserEnvOverlay already forces OPENSANDBOX_ID on top so user envs cannot spoof sandbox attribution; please apply the same protection here (strip/override a caller-supplied SANDBOX_REQUEST_ID before appending).

return "export " + RequestIDEnvVar + "=" + shellQuote(requestID) + "; " + code
}

// shellQuote wraps s in single quotes for POSIX shell, escaping embedded

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[nit] Doc comment typo: the escape form is rendered as '\” with a typographic right double quote (looks like mojibake) instead of the actual form the code emits, '"'"'. As written the comment misstates what the quoting does.

@Pangjiping Pangjiping left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

(duplicate review entry created by a posting script error; the actual re-review comments are in the adjacent review) — please ignore.

@Pangjiping
Pangjiping self-requested a review November 18, 2026 07:34
Comment on lines +71 to +76
if request.RequestID != "" {
// Direct env injection guarantees descendants inherit the request id
// on every platform (including Windows, where the POSIX export prefix
// does not apply) and for native argv execution.
cmd.Env = append(cmd.Env, RequestIDEnvVar+"="+request.RequestID)
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Medium — security] SANDBOX_REQUEST_ID is not reserved against caller-supplied envs, so it can be spoofed or overridden via request.Envs.

request.Envs flows into cmd.Env unfiltered with respect to this name: prepareCommand builds overrides := UserEnvOverlay(request.Envs) (request envs are the top layer and win the merge) at line 52, merges them into env at line 56, and this block only appends the header-derived value — no dedup, no strip. Two consequences:

  1. Header present + caller also sets SANDBOX_REQUEST_ID in envs → cmd.Env ends up with two entries for the same name. glibc/musl getenv returns the first match — the caller-supplied entry — so in native argv mode the caller deterministically overrides the header-derived id, contradicting the contract declared in specs/execd-api.yaml ("execd exports it as the SANDBOX_REQUEST_ID environment variable"). Resolution is also consumer-dependent (Go programs dedup keeping the last entry), so the effective id is nondeterministic. Shell mode is partially shielded because the export prefix re-sets the value inside the shell; native argv mode is the exposed path.
  2. Header absent or dropped by sanitizeRequestID → a caller-supplied SANDBOX_REQUEST_ID propagates untouched into the whole process tree, letting a caller attribute its executions to an arbitrary request id in audit — exactly the spoofing this repo already guards against for OPENSANDBOX_ID (UserEnvOverlay forces it on top "so user envs cannot spoof sandbox attribution", env.go, covered by TestUserEnvOverlayForcesSandboxID).

Suggested fix — reserve the name with the existing case-insensitive helper filterEnvNames (env.go:296) before injecting, which covers both scenarios on every platform and for both argv/shell modes:

Suggested change
if request.RequestID != "" {
// Direct env injection guarantees descendants inherit the request id
// on every platform (including Windows, where the POSIX export prefix
// does not apply) and for native argv execution.
cmd.Env = append(cmd.Env, RequestIDEnvVar+"="+request.RequestID)
}
// SANDBOX_REQUEST_ID is reserved/execd-owned: drop any caller-supplied
// (or inherited) entry so the header-derived value stays authoritative
// and the variable cannot be spoofed via request envs.
cmd.Env = filterEnvNames(cmd.Env, []string{RequestIDEnvVar})
if request.RequestID != "" {
// Direct env injection guarantees descendants inherit the request id
// on every platform (including Windows, where the POSIX export prefix
// does not apply) and for native argv execution.
cmd.Env = append(cmd.Env, RequestIDEnvVar+"="+request.RequestID)
}

(Alternatively, reserve it in UserEnvOverlay the same way OPENSANDBOX_ID is.)

Could you also add a regression test for the caller-env conflict case? TestPrepareCommandInjectsRequestIDEnv covers injection presence only — a case setting SANDBOX_REQUEST_ID in request.Envs (with and without the header) and asserting the authoritative value wins / the var is absent would lock this in.

@Pangjiping

Copy link
Copy Markdown
Collaborator

Heads-up: this PR no longer merges cleanly into main (GitHub currently reports mergeable_state: dirty/unknown). The branch is based on 112694024; main has moved ahead in the meantime.

Real conflict — needs manual resolution:

  • docs/architecture/data-plane/execd.md (~line 159): main added the command_id operational-log correlation paragraph in the same spot where this PR adds the "### Request id propagation" section. The two additions are complementary (log-record correlation vs. env/argv propagation) and can coexist — just interleave both sections when resolving.

Changed on both sides (auto-merge at text level, but please re-verify after rebasing):

  • components/execd/pkg/runtime/types.go
  • components/execd/pkg/web/controller/command.go
  • components/execd/pkg/web/controller/command_test.go
  • specs/execd-api.yaml
  • sdks/sandbox/javascript/src/api/execd.ts
  • sdks/sandbox/python/src/opensandbox/api/execd/api/command/run_command.py

Note that main landed the related command_id correlation work (docs + spec + regenerated SDKs), so after rebasing please double-check the regenerated spec/SDK outputs stay consistent, and re-run go test ./pkg/runtime/... ./pkg/web/controller/... in components/execd.

Could you rebase onto the latest main and push the update? Happy to re-review once it's green. (Also see the inline comment on command_argv.go:71-76 above regarding the SANDBOX_REQUEST_ID reservation — would be great to address both in the rebase.)

@yjjnls
yjjnls force-pushed the feat/execd-request-id-propagation branch 2 times, most recently from 17bd61b to 4a05943 Compare November 26, 2026 01:18
Propagate the ingress request id (X-Request-Id header) into sandbox
command execution so process-level audit (e.g. eBPF process_exec
arguments) and shell tooling can correlate executions to the calling
request:

- ExecuteCodeRequest gains an internal RequestID field, populated by the
  command controller from the X-Request-Id header (capped at 128 chars).
- Shell-mode commands (foreground, background, and PTY sessions) are
  wrapped as 'export SANDBOX_REQUEST_ID=<rid>; <code>': the request id
  lands in the launched shell's argv and is inherited by descendant
  processes via the environment. Native argv execution is passed
  through untouched.
- shellQuote neutralizes hostile header values (injection-proof, covered
  by unit tests). No wire-format change: the id is header-driven, the
  request body schema is unchanged.
- SANDBOX_REQUEST_ID is reserved and execd-owned: prepareCommand strips any
  caller-supplied (or inherited) entry with filterEnvNames before injecting
  the header-derived value, the same protection UserEnvOverlay applies to
  OPENSANDBOX_ID. Without it a caller could plant a spoofed correlation id
  via request.Envs (no header, or a header dropped by sanitizeRequestID), or
  win the duplicate-key merge in native argv mode where the env is the only
  carrier. Covered by TestPrepareCommandReservesRequestIDEnv for both modes.

Signed-off-by: yjjnls <yjjnls@users.noreply.github.com>
@yjjnls
yjjnls force-pushed the feat/execd-request-id-propagation branch from 4a05943 to f4127ed Compare November 26, 2026 01:23
@yjjnls

yjjnls commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main (5c42221) — the only conflict was docs/architecture/data-plane/execd.md, where main's command_id log-field note (from #3033) and this PR's ### Request id propagation subsection were both appended to the Observability section; both are kept, main's paragraphs first.

Also addressed the remaining review thread from @Pangjiping in the same commit:

[Medium — security] SANDBOX_REQUEST_ID is now reserved / execd-owned. prepareCommand runs cmd.Env through filterEnvNames(env, []string{RequestIDEnvVar}) before injecting the header-derived value — the same protection UserEnvOverlay already applies to OPENSANDBOX_ID. This closes both paths you described:

  1. header present + caller also sets the var → exactly one entry, the header-derived value wins (no duplicate-key, so no libc-vs-Go precedence ambiguity in native argv mode);
  2. header absent or dropped by sanitizeRequestID → a caller-planted value no longer propagates into the process tree.

Regression test TestPrepareCommandReservesRequestIDEnv covers shell and native argv mode × {header wins, no header drops the planted value}; I verified it fails on all four subtests without the fix.

[nit] shellQuote doc comment now states the real escape form '"'"' (close-quote, escaped quote, reopen-quote); TestShellQuoteEscapesEmbeddedSingleQuote pins it so the comment can't drift again.

Also normalised the commit to the yjjnls identity with a Signed-off-by trailer (the original commit predated that convention).

Verification: go test ./pkg/runtime/ → ok (full package, 83.8s); go build ./... + go vet ./pkg/runtime/ clean; gofmt 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

component/execd documentation Improvements or additions to documentation sdk/js sdk/python size/L Denotes a PR that changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants