158 Commits

Author SHA1 Message Date
zm-oai
41ab01a2ea Fix elevated Windows sandbox setup activation (#39971)
## Why

Sandbox setup runs on a Tokio worker thread without a Windows message loop, so
`ShellExecuteExW` requires synchronous activation when launching the elevated
setup helper.

## What changed

Add `SEE_MASK_NOASYNC` to the shell execution flags while retaining
`SEE_MASK_NOCLOSEPROCESS` for helper process tracking.

GitOrigin-RevId: 875cc1d49bb19f92f940633b6315711143beeae7
2026-08-21 16:56:42 +00:00
zm-oai
ab82cddd04 Resolve bundled Windows helpers through bin junctions (#39649)
## Why

Installer `bin` directories can be junctions, so looking for bundled helpers
relative to the apparent executable path can miss the package's
`codex-resources` directory.

## What changed

Retry bundled executable lookup from the canonical executable path when lookup
from the original path fails.

## Testing

Add a Windows regression test that creates a `bin` junction and verifies that
the sandbox setup helper is resolved from the package resources directory.

GitOrigin-RevId: f2f20ce1ccfa95ae65171a03a986d10e2560e696
2026-08-20 07:42:18 +00:00
chess
633bd4abf7 Add Windows sandbox diagnostics to codex doctor (#39290)
## What changed

- Report the configured Windows sandbox backend and whether denied-read restrictions are active.
- Diagnose incompatible backend policy, incomplete or failed elevated sandbox provisioning, unreadable setup failure reports, and missing, locked, disabled, or expired sandbox accounts.
- Provide issue-specific remediation and promote the sandbox check status and summary to the highest detected severity.
- Export the Windows sandbox setup data needed by the diagnostic check.

## Testing

- Cover missing Linux helpers and malformed or oversized Windows setup failure reports.
- Cover a recorded Windows sandbox refresh failure after setup completed.

GitOrigin-RevId: e965b703578a5c0597dcce9f836d2e1f510ad0c8
2026-08-18 21:56:54 +00:00
iceweasel-oai
88c39c4578 Propagate Windows sandbox ACL update failures (#39279)
## Why

Windows sandbox preflight could report success when applying a deny ACE failed,
leaving a detected world-writable path without the intended capability
restriction.

## What changed

- Return errors from `SetEntriesInAclW` and `SetNamedSecurityInfoW`, including the
  affected path in ACL API errors.
- Attempt every flagged path, aggregate deny-ACE failures, and fail preflight
  after logging them.
- Preserve cleanup of security descriptors and newly allocated ACLs on failure.

## Testing

Added tests that verify ACL API failures are returned and that preflight keeps
processing remaining paths before propagating an error.

GitOrigin-RevId: e2be1c70f72840046dc55760364de7bcf3b1bdc9
2026-08-18 20:56:10 +00:00
iceweasel-oai
2013e04354 Preserve filesystem permission path conventions (#39084)
## Why

Filesystem permission paths can use a convention that differs from the host
running Codex. Converting them immediately to native absolute paths can change
the meaning of ambiguous paths such as `/C:/secret` or Windows UNC paths.

## What changed

- Store literal filesystem permission paths as `PathUri` values through the
  runtime policy and execution protocol.
- Keep legacy string-based serialization at explicit protocol boundaries and
  reject conversions that cannot be represented losslessly.
- Encode native paths as opaque URIs when a normal file URI would imply the
  wrong path convention.

## Testing

Added coverage for cross-platform and ambiguous path round trips, UNC path
variants, permission-profile serialization, and deny-policy enforcement.

GitOrigin-RevId: 5247713796d1f2bb4e02f94eb9fc82d4698060f0
2026-08-17 21:49:30 +00:00
iceweasel-oai
a4f37a5b7f Harden Windows sandbox provisioning against reparse points (#39083)
## Why

Elevated provisioning can apply ACLs beneath a user-supplied `CODEX_HOME`.
Following a directory junction or another reparse point could apply those ACLs
to a different directory than the one provisioning intended to secure.

## What changed

- Require provisioning paths to be absolute paths on a local Windows disk.
- In provision-only mode, open or create sandbox directories with
  `OBJ_DONT_REPARSE` and keep the resulting handle open while applying ACLs
  with `SetSecurityInfo`.
- Reject reparse points in both the final directory and its ancestors while
  preserving the existing path-based behavior for full setup.

## Testing

Add Windows tests covering plain directory creation and rejection of junctions
at both the leaf and ancestor levels.

GitOrigin-RevId: d165b8b3685c89bc171e4d58c63c739fa9fb2cf9
2026-08-17 21:10:58 +00:00
Felipe Coury
d7d526b81d Prepare the telemetry shutdown worker during initialization (#39050)
## Why

Creating the telemetry shutdown thread during shutdown can fail under resource
pressure, including when the native thread guard page cannot be allocated.

## What changed

- Start and verify a dedicated shutdown worker when `OtelProvider` is created.
- Send the provider to the prepared worker for bounded shutdown, while preserving
  timeout behavior and avoiding a potentially blocking destructor if worker
  preparation failed.
- Rename the fallible provider constructor to `try_new`.

## Testing

Add Unix regression coverage that injects guard-page allocation failures, plus
coverage for worker preparation failure, successful shutdown, and timeouts.

GitOrigin-RevId: 3656298078a800a7fa392437c2ee4a68753092e3
2026-08-17 19:06:53 +00:00
johnl-oai
848cbad7f4 Enforce managed deny-read rules in the Windows sandbox (#38660)
## Why

Windows sandbox requests must preserve managed filesystem deny rules across every execution path and setup refresh. Unsupported policies should fail closed instead of allowing a command to run without the requested protection.

## What changed

- Resolve Windows filesystem overrides while constructing each sandbox execution request so both `shell_command` and `exec_command` enforce exact-path and glob deny-read entries.
- Carry resolved deny-read paths into Windows sandbox setup refreshes, including workspace-relative entries.
- Reject unelevated restricted-token requests that cannot enforce deny-read rules.
- Reject recursive globs rooted at a filesystem root unless `glob_scan_max_depth` bounds their expansion.

## Testing

Added coverage for deny-read enforcement through both command runtimes, setup refresh resolution, restricted-token failure, and bounded root-level glob scans.

GitOrigin-RevId: 33dfa4d1a45b14850cbf58f9173717e3e707d9bf
2026-08-14 22:28:33 +00:00
Adam Perry @ OpenAI
813dc5f08d Embed the Windows sandbox setup manifest in Bazel builds (#38450)
## Why

`rules_rust` drops the build script's per-binary linker directives, so Bazel
builds can omit the `asInvoker` manifest from the Windows sandbox setup helper.

## What changed

- Add per-binary compile data and Rust flags to `codex_rust_crate` so linker
  inputs remain scoped to the setup helper.
- Embed the manifest directly for MSVC builds and compile it into a resource
  with hermetic LLVM tooling for GNU/LLVM cross-builds.
- Disable the redundant build script under Bazel and avoid duplicating binary
  runfiles in integration test data.

## Testing

Add a Windows integration test that loads the setup executable's manifest
resource and verifies that it requests `asInvoker` execution with UI access
disabled.

GitOrigin-RevId: a77e7e627ee43810f5eaf7701bb4909bf855216b
2026-08-13 23:04:38 +00:00
iceweasel-oai
7c47952f7c Allow nested Git repositories in the Windows sandbox (#38080)
## Why

Git rejects repositories owned by the primary user when commands run as the
sandbox user. Trusting only the enclosing worktree leaves nested repositories
unavailable.

## What changed

Add both the worktree root and its `/*` wildcard to Git's `safe.directory`
environment configuration. Update the directory and gitfile unit tests to
expect both entries.

GitOrigin-RevId: 4b8e2bc8cc52cff580451ffbd17eb71325957404
2026-08-11 22:22:18 +00:00
zm-oai
104e25ac5a Grant Windows sandbox access to the Codex app root (#38064)
## What changed

- Apply the sandbox read/execute ACL to the local Codex application root so it
  inherits across its contents, while continuing to handle the managed runtime
  cache separately.
- Skip missing paths, non-directories, and directory reparse points before
  inspecting or updating ACLs.
- Update the runtime path test to expect the application root.

GitOrigin-RevId: 34f2946d2140f8ea2b76c449b0e5542b99cb6f70
2026-08-11 19:48:38 +00:00
iceweasel-oai
a603d7ca5c Honor the configured Windows sandbox level for managed networking (#37875)
## Why

Managed networking implicitly selected the elevated Windows sandbox backend,
even when the sandbox was configured to use a restricted token.

## What changed

- Select the Windows sandbox backend solely from `WindowsSandboxLevel`.
- Reject managed networking with a restricted-token sandbox before spawning a
  process, since managed networking requires the elevated backend.
- Cover the rejection through sandbox preparation, unified exec, and Windows
  sandbox session tests.

GitOrigin-RevId: 308858652d7b629af623d22896dafde3a23d3758
2026-08-10 19:57:40 +00:00
iceweasel-oai
6b23635a7e Terminate Windows non-TTY processes on interrupt (#35655)
## Why

Windows non-TTY exec sessions reported interrupts as unsupported, so sending
Ctrl-C through `write_stdin` did not stop the running process.

## What changed

- Route interrupt requests for Windows non-TTY processes through their existing
  termination callback, including pipe-backed processes.
- Track whether driver-backed Windows sessions use a TTY so PTY interrupts keep
  their existing behavior.
- Consume the terminator after a successful interrupt to avoid invoking it again
  when the process handle is dropped.

## Testing

Added coverage for local and remote exec-server sessions, unified exec, pipe
fallbacks, and legacy Windows sandbox processes.

GitOrigin-RevId: 34504d01f091ef57bb961e98ad5a8d9f1acee4ee
2026-07-27 18:37:11 +00:00
Adam Perry @ OpenAI
f47f28cd0d Fix Bazel test configuration for platform-specific data (#35067)
## What changed

- Include CLI snapshot files in Bazel test runfiles.
- Restrict the Windows sandbox binary test target to Windows.
- Label boolean and optional arguments in the affected CLI tests.

GitOrigin-RevId: c248396c51d881c38856739d7d9b653dcde1823e
2026-07-24 01:34:56 +00:00
iceweasel-oai
b115de97d7 Preserve Windows sandbox proxy settings in guardian sessions (#35036)
## Why

Guardian review commands can run without the proxy-port environment used to
configure the parent session. Reconciling persistent Windows sandbox settings
for those commands can discard the parent's proxy configuration.

## What changed

- Add a session-level Windows sandbox proxy-settings mode and use `Preserve`
  for guardian review sessions while keeping `Reconcile` as the default.
- Carry the mode through unified exec and the exec-server sandbox context to
  Windows process launches.
- In preserve mode, reuse the proxy settings recorded by the existing sandbox
  setup marker.

## Testing

Added coverage for guardian session configuration, exec-server transport, and
preserving an existing setup marker when proxy-port environment variables are
absent.

GitOrigin-RevId: 214655c6e6d97360906431773dc0de0fdda2db6e
2026-07-23 23:35:29 +00:00
iceweasel-oai
a26f219f67 Harden Windows elevated sandbox startup (#34629)
## What changed

- Check writable-root permissions for the sandbox group and root capability SID from a single DACL snapshot, and refresh the ACL when either SID is missing the required access or has a stale explicit delete-child grant.
- Start the command runner without loading a user profile and poll more frequently while waiting for it to become ready.
- Make the Windows sandbox binaries available to Bazel tests.

## Testing

- Add coverage that verifies ACL refresh checks every requested SID.
- Add an elevated non-TTY command test that verifies environment forwarding, stdout, and exit-code propagation.

GitOrigin-RevId: 657ed9dc906039299f9ffa4772e0926c47066a73
2026-07-21 22:36:18 +00:00
iceweasel-oai
9b33613db6 Terminate Windows process trees with job objects (#34624)
## Why

Terminating a Windows execution session must also stop child processes, while a
normal root-process exit must continue to allow background descendants to run.

## What changed

- Assign Windows pipe, ConPTY, and sandbox processes to job objects and terminate
  the job when a session is cancelled, times out, or is explicitly stopped.
- Preserve descendants when the root process exits normally.
- Attach ConPTY and sandbox processes to their jobs atomically at creation; keep
  root-process termination as a fallback where job setup is unavailable.

## Testing

Added Windows coverage for descendant termination and preservation across pipe,
ConPTY, capture, cancellation, and legacy sandbox execution paths.

GitOrigin-RevId: 8f831f2fc4caaa7b79ce842a3ed7192bd02dd3b4
2026-07-21 22:07:09 +00:00
iceweasel-oai
999a715089 Route Windows sandbox proxy traffic by restricting SID (#34613)
## Why

Elevated Windows sandboxes need stable managed-proxy ports while preserving the network policy and environment attribution of each sandboxed process.

## What changed

- Keep shared HTTP and SOCKS5 loopback ingress listeners alive across managed-proxy instances.
- Add a per-route restricting SID to elevated sandbox tokens and dispatch incoming connections to the matching proxy policy after attributing the client process.
- Reject connections without exactly one registered route, remove routes when their proxy handle is dropped, and keep unsandboxed Windows launches off the managed ingress.
- Provision the elevated sandbox with the configured proxy ports and local-binding setting, honoring the selected profile and CLI overrides.

## Testing

- Add Windows unit tests for TCP ownership attribution, route selection, restricting-token propagation, and setup settings.
- Add an end-to-end Windows test covering stable ports, isolated environment policies, HTTP and SOCKS5 routing, and route teardown.

GitOrigin-RevId: 783fac6e0f904dc9bb1955b75d4a5895e8bb9690
2026-07-21 21:06:04 +00:00
chess
dfd2d8133c Detach non-interactive subprocesses from stdin (#34612)
## What changed

Redirect stdin to null when launching:

- `codex doctor --json` for uploaded diagnostic reports
- Git commands used by `codex doctor`
- ripgrep searches over rollout files
- the Windows sandbox setup refresh helper

This keeps these non-interactive subprocesses from reading Codex's inherited
input stream.

GitOrigin-RevId: 063d191b0b1b849d74b55a7d6ff2f0b3d5212c86
2026-07-21 20:55:56 +00:00
iceweasel-oai
87f71e35b8 Skip missing paths in filesystem sandbox entries (#34598)
## Why

Default read-only protections for project metadata should apply when paths such
as `.git`, `.agents`, and `.codex` exist, without causing sandbox setup to
materialize missing paths as ACL targets.

## What changed

- Add an optional `missing_path_behavior` to filesystem sandbox entries and
  mark default project-metadata protections with `skip`.
- Preserve the behavior through permission transforms and exec/MCP protocol
  serialization while keeping existing path wire variants stable.
- Ignore skip-missing entries when projecting configuration or Windows sandbox
  overrides, while retaining explicit metadata carveouts.

## Testing

- Cover protocol round trips for path and special-path entries.
- Verify default metadata protections and Windows explicit carveout handling.

GitOrigin-RevId: 6df13dadacdd131c44aab9f15a967c81051355c1
2026-07-21 19:17:18 +00:00
Felipe Coury
bd92b056dd Ignore inherited ACEs when refreshing Windows write roots (#34392)
## Why

An inherited `FILE_DELETE_CHILD` grant can make a write root look stale, but
`SET_ACCESS` cannot replace an ACE inherited from an ancestor. Treating that
grant as explicit causes unnecessary ACL refresh attempts that cannot converge.

## What changed

- Add explicit-ACE filtering to the Windows DACL permission checks.
- Refresh a write root only when `FILE_DELETE_CHILD` is present in an explicit
  allow ACE, while retaining effective-permission checks for required rights.
- Ignore inherited stale rights when deciding whether `SET_ACCESS` must repair
  an allow ACE.

## Testing

Add a Windows regression test covering a write root that inherits
`FILE_DELETE_CHILD`, verifying that repeated refresh checks leave its explicit
write ACE unchanged.

GitOrigin-RevId: d0df9429efcf299da3ff3c1bce92942684803293
2026-07-20 18:28:02 +00:00
iceweasel-oai
4bc2c723ef Select the elevated Windows sandbox for network proxies (#33445)
## Why

Windows firewall enforcement is tied to the logon-user sandbox identities. Proxy-enforced commands therefore need the elevated backend even when the configured sandbox mode is the default restricted-token mode.

## What changed

- Select the elevated Windows sandbox backend whenever a command uses the managed network proxy.
- Remove configuration and startup checks that required users or managed requirements to select the elevated sandbox explicitly.
- Start and expose managed network proxy state consistently on Windows.

## Testing

- Verify that proxy enforcement selects the elevated backend for the restricted-token sandbox mode.

GitOrigin-RevId: e01ac052587721c468a8fbcf4e2c7c5a185a3e05
2026-07-15 23:19:00 +00:00
iceweasel-oai
3370181ec6 Coalesce concurrent Windows sandbox setup requests (#32864)
## Why

Concurrent callers can submit the same Windows sandbox setup payload while an
identical helper invocation is already running.

## What changed

- Share one in-flight helper invocation among setup and refresh requests with
  identical serialized payloads.
- Return the shared success or failure to every waiter while preserving
  structured setup error codes, then allow subsequent requests to run again.

## Testing

- Add a concurrency test that verifies identical requests execute the setup
  operation once.

GitOrigin-RevId: 18ebbcb9b36de3eb5912b8bbbe153d39328b5e48
2026-07-13 20:06:15 +00:00
iceweasel-oai
abbb8c569c Require the elevated Windows sandbox for network proxies (#32857)
## Why

Network proxy enforcement on Windows requires the elevated sandbox backend. Silently selecting that backend for an unelevated configuration makes the effective sandbox differ from the configured mode.

## What changed

- Reject enabled network proxy configurations on Windows unless managed requirements allow only the elevated sandbox and `windows.sandbox` resolves to `"elevated"`.
- Preserve the configured sandbox backend during execution and validate proxy compatibility at config loading, sandbox setup, and process launch boundaries.
- Defer this validation during cloud-config bootstrap so authoritative managed requirements can be loaded first.
- Do not start or expose disabled Windows proxies, and render transitions to disabled networking as `<network enabled="false"></network>`.

## Testing

- Cover Windows requirement and sandbox compatibility matrices, bootstrap behavior, backend selection, disabled proxy handling, and environment-context updates.

GitOrigin-RevId: bfa1dda98594e0db61883f8e7f65bd560e3453e6
2026-07-13 19:04:22 +00:00
zm-oai
87f3e39fdf Hide Windows filesystem helper console windows (#32849)
## What changed

- Add a console mode to the Windows sandbox process launcher.
- Launch `--codex-run-as-fs-helper` subprocesses with `CREATE_NO_WINDOW`.
- Preserve inherited-console behavior for regular sandboxed commands.

GitOrigin-RevId: 927be36b82903b6a5fb1a243ba7f406f9ed85f3f
2026-07-13 18:25:55 +00:00
Abhinav
c6b124bb31 [codex] Grant Windows sandbox access to primary runtime (#31574)
## Why

Codex Desktop installs its managed primary runtime under
`%USERPROFILE%\.cache\codex-runtimes`. Elevated Windows sandbox commands
run as dedicated sandbox users. The synchronous runtime ACL refresh
repairs read/execute access for the Desktop runtime directories under
`%LOCALAPPDATA%\OpenAI\Codex`, but did not include the managed primary
runtime cache.

As a result, the Desktop app could discover a bundled runtime while a
sandboxed command received `ACCESS_DENIED` when reading or executing it.

## What changed

- Include `%USERPROFILE%\.cache\codex-runtimes` in the managed runtime
paths considered by the Windows sandbox ACL refresh.
- Reuse the existing inherited read/execute ACL repair; no write
permission is added.
- Add Windows-target regression coverage for the runtime path list and
the primary-runtime-only case.

## Impact

Bundled Python, Node, and native tools remain usable from elevated
Windows sandbox sessions without broadening write access or granting
access to the rest of the user profile.

## Validation

- `just fmt`
- `just test -p codex-windows-sandbox` (10/10 host-side tests passed)
- Windows-target path tests included for CI
2026-07-08 13:22:10 -07:00
Felipe Coury
166534fc22 fix(windows-sandbox): allow deletion in writable roots (#31138)
## Why

The legacy unelevated Windows sandbox allowed tools to create and update
files in workspace-write roots, but it could not delete files that
already existed there. This breaks operations such as `apply_patch` file
deletion and replacement in the workspace, `TEMP`, and `TMP`.

The delete grant must also preserve deny-write carveouts. Granting
`FILE_DELETE_CHILD` on a writable parent would let the sandbox remove
protected children such as `.git` or an explicit read-only subpath even
when those children have direct deny ACEs.

This addresses the delete-failure variant reported in #30009 and #30712.
It does not claim to fix their separate split-root setup,
elevated-helper, or proxy-related failure modes.

## What Changed

- Give writable-root capability ACEs inheritable `DELETE` rights without
granting parent-level `FILE_DELETE_CHILD`, so descendants can be removed
while protected children remain protected.
- Replace stale write ACEs that still contain `FILE_DELETE_CHILD`, and
make elevated setup detect and refresh that unsafe legacy state.
- Keep read-only capability handling unchanged.
- Add Windows regressions covering pre-existing files in the workspace,
`TEMP`, and `TMP`, plus protected `.git` and outside-root controls.

The core ACL behavior is in
[`acl.rs`](767540eec3/codex-rs/windows-sandbox-rs/src/acl.rs (L303-L438)),
stale-ACE detection is in
[`setup_main/win.rs`](767540eec3/codex-rs/windows-sandbox-rs/src/bin/setup_main/win.rs (L163-L179)),
and the end-to-end regression is in
[`unified_exec/tests.rs`](767540eec3/codex-rs/windows-sandbox-rs/src/unified_exec/tests.rs (L458-L568)).

## How to Test

On Windows:

1. Start Codex with the legacy unelevated Windows sandbox and a
workspace-write permission profile.
2. Seed pre-existing files in the workspace, `TEMP`, and `TMP`; also
create a sibling file outside the writable roots and a protected `.git`
directory.
3. Delete the three files inside writable roots through a sandboxed
command or `apply_patch`.
4. Confirm the writable-root files are deleted, while the outside-root
file and protected `.git` directory remain intact.

Targeted tests:

- `just test -p codex-windows-sandbox`
- Windows-only
`legacy_workspace_write_delete_is_limited_to_writable_roots`
- Windows-only `write_root_refresh_replaces_stale_delete_child_grant`

The final SHA passed all 31 required checks, including the Windows Bazel
test matrix, in [run
28886245161](https://github.com/openai/codex/actions/runs/28886245161).
2026-07-08 15:05:57 -03:00
jif
3ccef20ef4 Skip credential refresh for WindowsApps launch failures (#29637)
## Summary

- keep the child error 1312 credential retry for normal executables
- return WindowsApps/AppX launch errors directly instead of rotating
sandbox credentials and retrying the same command

## Why

Windows AppX activation can return `ERROR_NO_SUCH_LOGON_SESSION` (1312)
even when the sandbox token is healthy. For executables under
`WindowsApps`, refreshing the sandbox account password cannot fix that
activation failure; it only triggers elevated setup before the same
command fails again.

This is a focused follow-up to #29624.
2026-06-24 20:59:53 +01:00
jif
4907f0c2c3 Preserve Windows sandbox identity during credential retry (#29624)
## Summary

- recognize stale Windows sandbox credentials from both runner logon and
child startup failures
- refresh credentials once without changing the original command,
permissions, file rules, desktop mode, or managed-network identity
- add a Windows regression test that forces error 1312 and inspects the
real retry arguments

## Why

Elevated unified exec starts commands in two steps:

```text
Codex -> sandbox command runner -> requested command
```

Either process start can fail when Windows invalidates the sandbox logon
session. The child-side failure was previously returned as text, so the
parent could not reliably recognize Windows error 1312.

The existing retry also refreshed credentials with `proxy_enforced =
false`, even when the original request used managed networking. That
could change the selected Windows sandbox identity from offline to
online during the retry.

## How

- carry the failure stage and numeric Windows error code through the
command-runner IPC protocol
- preserve native `CreateProcessAsUserW` error codes instead of parsing
error messages
- keep every retry-sensitive field in one request and use it for both
attempts
- retry exactly once after refreshing credentials, then return the
second failure
- share the retry rule with the elevated capture path

The Windows test injects error 1312 on both attempts and verifies:

- two spawn attempts and one credential refresh
- stale credentials are replaced by refreshed credentials
- both attempts receive the same command, environment, cwd, permissions,
roots, deny paths, TTY settings, and private-desktop mode
- credential refresh receives the original `proxy_enforced` value

## Tests

- `just test -p codex-windows-sandbox`
- the new Windows-only regression test is included in the Windows
nextest CI archive
2026-06-24 20:20:52 +01:00
iceweasel-oai
a781761eda [codex] fix Windows ConPTY input handling (#29734)
## Why

Windows unified-exec TTY input did not behave like the non-Windows PTY
path. ConPTY sessions could receive the wrong line ending or mishandle
backspace, especially when sending input to a foreground program through
PowerShell or cmd. The local, legacy restricted, and elevated paths also
handled this normalization separately.

## What changed

- share one stateful Windows TTY input normalizer across local, legacy
restricted, and elevated runner paths
- translate LF and split CRLF into one Windows terminal Enter, encode
backspace as DEL, and preserve UTF-8 and control bytes such as Ctrl-C
- add Windows integration coverage for Unicode input, backspace, Enter,
and PowerShell foreground-child Ctrl-C behavior

## Validation

- `just test -p codex-utils-pty` (13 tests passed; the Unicode
integration test retried once)
- the Unicode integration test passed five consecutive runs with retries
disabled
- integration coverage sends `cafeé 漢字` through cmd and PowerShell and
verifies that Ctrl-C interrupts a running PowerShell foreground child
2026-06-24 11:27:44 -07:00
iceweasel-oai
18fe1d9fe3 [codex] Preserve proxy state for filesystem sandbox helpers (#29671)
## Why

Filesystem helpers intentionally run with a minimal environment that
excludes proxy variables. After filesystem operations started using the
Windows sandbox wrapper, the wrapper derived an empty proxy
configuration from that helper environment and compared it with the
persistent sandbox setup marker. When the marker contained proxy ports,
every filesystem operation appeared to require a firewall update, which
could launch elevated setup, show a UAC or loader dialog, and fail
operations such as `apply_patch` with error 1223.

Filesystem helpers do not use network access, so they should preserve
the proxy/firewall state established by normal sandboxed process
launches.

## What changed

- Add an explicit Windows sandbox proxy-settings mode for reconciling or
preserving persistent proxy state.
- Use preserve mode for filesystem helpers while normal process launches
continue to reconcile proxy settings from their environment.
- Carry the selected proxy state consistently through setup validation,
elevated setup, and non-elevated ACL refreshes.
- Cover wrapper argument propagation and marker-derived proxy
preservation.

## Validation

- `cargo build -p codex-cli --bin codex`
- `just test -p codex-windows-sandbox
preserving_proxy_settings_uses_the_existing_marker`
- `just test -p codex-windows-sandbox windows_wrapper_args_round_trip`
- `just test -p codex-windows-sandbox
setup_request_prefers_explicit_proxy_settings`
- `just test -p codex-sandboxing transform_for_direct_spawn_windows`
- `just test -p codex-exec-server fs_sandbox::tests`
- Ran the same sandboxed `fs/writeFile` reproduction against published
`0.142.0-alpha.6` and the new CLI. The published CLI launched elevated
setup and failed with `ShellExecuteExW ... 1223`; the new CLI completed
without elevation.

Related to #28359.
2026-06-23 12:29:46 -07:00
iceweasel-oai
afbb69a2fb [codex] Fix Windows sandbox runtime ACL refresh (#28943)
## Why

Codex Desktop repairs sandbox-user read/execute access for binaries
copied to `%LOCALAPPDATA%\OpenAI\Codex\bin`, but Computer Use launches
its bundled Node runtime from `%LOCALAPPDATA%\OpenAI\Codex\runtimes`.

On fresh Windows installations, `CodexSandboxUsers` may therefore be
unable to execute the bundled Node binary. The command runner starts,
but `CreateProcessAsUserW` fails with error 5 (`ACCESS_DENIED`), causing
the Node REPL to exit before Computer Use can discover applications.

This is a follow-up to #21564, which added the original runtime `bin`
ACL repair.

## What changed

- Expand the Codex Desktop runtime ACL roots from only `bin` to both
`bin` and `runtimes`.
- Apply the existing inherited read/execute ACL repair to each runtime
directory when it exists.
- Rename the setup helper to reflect that it now handles multiple
runtime paths.

## Validation

- `cargo fmt -- --check`
- `just test -p codex-windows-sandbox` was run: 113 tests passed and
five environment-dependent legacy execution tests failed because
`CreateRestrictedToken` returned error 87.
2026-06-18 11:04:30 -07:00
iceweasel-oai
ef75171f18 Run fs helper through Windows sandbox wrapper (#28359)
## Why

This is the final PR in the Windows fs-helper sandbox stack and contains
the actual bug fix.

The exec-server filesystem helper is a direct-spawn path: it asks
`SandboxManager` for a `SandboxExecRequest`, then launches the returned
argv itself. That works on macOS and Linux because the transformed argv
is already a self-contained sandbox wrapper. On Windows, the transformed
request carried `WindowsRestrictedToken` metadata, but the direct-spawn
fs-helper runner still launched the helper argv directly.

That means Windows filesystem built-ins backed by the fs-helper could
run with the parent Codex process permissions instead of the configured
Windows sandbox. This PR makes the direct-spawn transform produce a
self-contained Windows wrapper argv before fs-helper launches it.

## What Changed

- Added `SandboxManager::transform_for_direct_spawn()` for callers that
launch the returned argv themselves.
- Wrapped Windows restricted-token direct-spawn requests with `codex.exe
--run-as-windows-sandbox` and then marked the outer request as
unsandboxed, matching the macOS/Linux wrapper argv shape.
- Updated `exec-server/src/fs_sandbox.rs` to use the direct-spawn
transform for fs-helper launches.
- Materialized the inner `codex.exe --codex-run-as-fs-helper` executable
into `.sandbox-bin` so the sandboxed user can run it.
- Carried runtime workspace roots through `FileSystemSandboxContext` as
`PathUri` values so `:workspace_roots` policies resolve correctly
without sending native client paths over exec-server JSON.
- Preserved wrapper setup identity environment needed by Windows sandbox
setup without changing the serialized inner helper environment.

## Verification

- `just bazel-lock-update`
- `just bazel-lock-check`
- `just test -p codex-sandboxing transform_for_direct_spawn_windows`
- `just test -p codex-exec-server fs_sandbox::tests`
- `just fix -p codex-windows-sandbox -p codex-sandboxing -p
codex-exec-server -p codex-core -p codex-file-system`

Local note: `just fmt` completed Rust formatting, but this workstation
still fails the non-Rust formatter phases because uv cannot open its
cache and the local buildifier/dotslash path is missing.
2026-06-17 10:00:42 -07:00
iceweasel-oai
fbbe7706d6 Add hidden Windows sandbox wrapper entrypoint (#28358)
## Why

This is the second PR in the Windows fs-helper sandbox stack. The
fs-helper path needs a Windows sandbox launcher that has the same
argv-shaped contract as macOS `sandbox-exec` and `codex-linux-sandbox`,
but this PR only introduces that hidden launcher. It does not route
fs-helper through it yet.

The hidden launcher still needs to be policy-complete before later
direct-spawn callers use it. In particular, it has to carry the same
Windows sandbox policy details that the existing spawn paths already
understand: proxy enforcement, read/write root overrides, and
deny-read/deny-write overrides.

## What Changed

- Added the hidden `codex.exe --run-as-windows-sandbox` arg1 dispatch
path.
- Added `windows-sandbox-rs/src/wrapper.rs`, which parses the wrapper
argv, launches the requested command through the shared Windows sandbox
session runner from PR1, and forwards stdio.
- Added `create_windows_sandbox_command_args_for_permission_profile()`
so later direct-spawn callers can build the wrapper argv consistently.
- Made the wrapper argv round-trip the full Windows sandbox policy
surface it needs later: workspace roots, environment, permission
profile, sandbox level, private desktop, proxy enforcement, read/write
root overrides, and deny-read/deny-write overrides.
- Carried `proxy_enforced` through the shared Windows session request so
proxy-managed executions continue to use the offline/elevated sandbox
identity.
- Added wrapper argument round-trip coverage for the full policy fields.

## Verification

- `just test -p codex-windows-sandbox windows_wrapper_args_round_trip`
- `just test -p codex-arg0`
- `just test -p codex-core exec::tests::windows_`
- `just fix -p codex-windows-sandbox -p codex-core -p codex-cli`

Local note: the full `just fmt` command still fails on this workstation
in non-Rust formatter setup (`uv` cache access denied and missing
`dotslash`/buildifier), but the Rust formatter phase completed.
2026-06-15 21:30:32 +00:00
iceweasel-oai
c0b36d234a recover stale Windows sandbox credentials (#27944)
## Why

The elevated Windows sandbox persists dedicated sandbox account
credentials so later commands can launch without reprovisioning. If
those persisted credentials drift from the actual Windows account
password, `CreateProcessWithLogonW` fails with `ERROR_LOGON_FAILURE` and
Codex currently surfaces that as a hard runner launch failure.

This change makes that failure self-healing. When Windows specifically
rejects the sandbox login, Codex now treats the persisted sandbox
credentials as stale, regenerates them through the existing setup path,
and retries the runner launch once.

## What Changed

- Preserve `CreateProcessWithLogonW` failures as a typed runner logon
error so callers can distinguish `ERROR_LOGON_FAILURE` from unrelated
launch failures.
- Add a sandbox credential refresh helper that deletes the persisted
`sandbox_users.json` record and reuses `require_logon_sandbox_creds()`
to reprovision credentials through the established setup flow.
- Retry elevated runner startup after stale-credential failures in both
the legacy elevated capture path and unified exec elevated backend.
- Add focused tests for stale logon failure detection and persisted
sandbox user file removal.

## Validation

- `git diff --check`
- `cargo test -p codex-windows-sandbox`
2026-06-15 13:54:24 -07:00
iceweasel-oai
c3415f76c9 Extract shared Windows sandbox session runner (#28357)
## Why

This is the first PR in a stack for the Windows fs-helper sandbox fix.
Before changing fs-helper behavior, this pulls the reusable Windows
sandbox session launch pieces out of the debug CLI path so later PRs can
call the same backend selection and stdio forwarding logic.

Keeping this as a pure refactor makes the later security fix easier to
review: `codex sandbox windows` should continue to launch the same
elevated or restricted-token backend, just through shared APIs in
`windows-sandbox-rs` instead of code local to
`cli/src/debug_sandbox.rs`.

## What Changed

- Added `WindowsSandboxSessionRequest` and
`spawn_windows_sandbox_session_for_level()` in `windows-sandbox-rs` to
share the elevated-vs-legacy session launch decision.
- Moved the Windows sandbox stdio forwarding helpers from
`cli/src/debug_sandbox.rs` into
`windows-sandbox-rs/src/stdio_bridge.rs`.
- Updated `codex sandbox windows` to call the shared session launcher
and stdio bridge.
- Added unit coverage for the moved stdio forwarding helpers.

## Verification

- `just bazel-lock-update`
- `just bazel-lock-check`
- `just test -p codex-windows-sandbox stdio_bridge::tests`
- `just fix -p codex-windows-sandbox -p codex-sandboxing -p
codex-exec-server -p codex-arg0 -p codex-core -p codex-file-system`
- The new `stdio_bridge` tests also passed as part of `just test -p
codex-windows-sandbox` on the stack tip. That full local run still fails
in pre-existing legacy session integration tests with
`CreateRestrictedToken failed: 87` on this workstation.
2026-06-15 18:30:48 +00:00
Adam Perry @ OpenAI
740c4f269d build: run buildifier from just fmt (#28125)
## Intent

Keep Bazel and Starlark files consistently formatted without requiring
contributors to install or version buildifier themselves.

## Implementation

- Add a SHA-256-pinned, cross-platform DotSlash manifest for buildifier
v8.5.1.
- Run buildifier from the shared `just fmt` and `just fmt-check` driver,
with Windows-safe explicit DotSlash invocation.
- Provision DotSlash in formatting CI and contributor devcontainers, and
document the source-build prerequisite.
- Apply the initial mechanical buildifier formatting baseline.
2026-06-13 21:43:39 -07:00
iceweasel-oai
0b2e7b5eb1 Improve Windows sandbox setup refresh diagnostics (#26471)
## Why

Users have been seeing opaque Windows sandbox setup refresh failures
such as `windows sandbox: spawn setup refresh`, including reports in
#24391 and #21208. The setup refresh path already runs the Windows
sandbox setup helper, but it was not using the same structured
`setup_error.json` reporting path that elevated setup uses. As a result,
when the helper exited non-zero, Codex only surfaced a generic refresh
status instead of the helper's `SetupFailure` code and message.

## What changed

- Clear stale `setup_error.json` before non-elevated setup refresh
launches the helper.
- When the refresh helper exits non-zero, read the helper-written report
through the existing `report_helper_failure` path.
- Keep a parent-side launch diagnostic for cases where the helper never
starts, including the helper path, cwd, sandbox log path, and spawn
error.
- Clear the setup error report after a successful refresh.
- Add regression coverage for report consumption and stale-report
avoidance.

## Verification

- `cargo test -p codex-windows-sandbox setup::tests::`
2026-06-04 16:52:10 -07:00
pakrym-oai
555f8caeff [codex] Fix Windows sandbox build script lint (#26445)
## Why

The Windows ARM64 Cargo clippy job on `main` is failing because
workspace lints deny `clippy::expect_used`, and the
`codex-windows-sandbox` build script used `expect()` while reading
`CARGO_MANIFEST_DIR`.

## What changed

`codex-rs/windows-sandbox-rs/build.rs` now returns `Result<(), String>`
from `main()` and converts a missing `CARGO_MANIFEST_DIR` into an
explicit build-script error. The non-Windows early return and Windows
linker argument behavior are unchanged.

## Verification

- `just clippy -p codex-windows-sandbox -- -D warnings`
- `just test -p codex-windows-sandbox`
2026-06-04 13:03:47 -07:00
Abhinav
0ed2735d19 Use Windows setup marker as completion signal (#26074)
# Why

When an organization requires the elevated Windows sandbox, Codex
launches an elevated helper to provision users, configure firewall and
ACL rules, and lock persistent sandbox directories.

We observed that closing the helper after setup started could leave the
machine partially initialized while the TUI still announced **Sandbox
ready**. Model-only turns continued to work, but the first shell command
retried setup and failed with Windows cancellation error `1223`.

This was not an enforcement bypass; command execution continued to fail
closed. The issue was a false readiness signal: `setup_marker.json` was
written during user provisioning, before the remaining setup stages had
completed.

# What

Treat `setup_marker.json` as the commit record for Windows sandbox
setup:

1. Before full or provisioning setup begins, remove the existing marker
and create the final marker path with a protected ACL.
2. Keep the marker empty and therefore invalid while setup is in
progress. Sandbox users cannot read, modify, or replace it.
3. Run every synchronous setup stage.
4. After setup succeeds, write the valid marker contents without
changing its ACL.
5. After the helper exits successfully, verify the existing readiness
check before enabling the sandbox.

If setup is canceled or fails, the marker remains invalid and Codex
reports setup as incomplete instead of announcing readiness.

Refresh-only and read-ACL-only helper runs continue to leave the marker
untouched. The setup version remains `5` to avoid forcing all existing
Windows users through elevated setup again.

# Verification

- Added coverage confirming sandbox users cannot read or modify the
setup marker after elevated setup.
- Added coverage confirming a successful helper exit without complete
setup artifacts is rejected.
- Ran `just test -p codex-windows-sandbox`.
2026-06-03 15:33:34 -07:00
iceweasel-oai
b2344d8fbc [codex] Restore setup helper UAC manifest (#25949)
## Why

#23764 removed Windows resource stamping from `codex-windows-sandbox`,
but it also removed the setup helper's UAC manifest. That manifest was
doing more than cosmetic version metadata: Microsoft documents
`requestedExecutionLevel level="asInvoker"` as the setting that makes an
executable run at the same permission level as the process that started
it:
https://learn.microsoft.com/en-us/windows/win32/sbscs/application-manifests#trustinfo

In the reported session, `codex-windows-sandbox-setup.exe` was launched
for a non-elevated setup refresh and `CreateProcess` failed with `os
error 740` (`The requested operation requires elevation`). Restoring an
explicit `asInvoker` manifest records the helper's intended default
launch contract: normal launches inherit the caller's token, and
elevation only happens through the code paths that request it
explicitly.

The setup helper has two launch modes:

- setup refresh uses a normal `Command::new(...)` spawn and should never
trigger UAC
- full setup explicitly uses `ShellExecuteExW` with the `runas` verb
when elevation is required

Restoring `asInvoker` keeps refresh non-elevated by default while
preserving the explicit elevated path for full setup.

## What changed

- Restored a minimal `codex-windows-sandbox-setup.manifest` containing
only `requestedExecutionLevel level="asInvoker"`.
- Added a small build script that passes setup-helper-scoped manifest
linker args for MSVC and the Windows GNU/LLVM target used by Bazel.
- Wired the manifest into Bazel build-script data.

This does not restore `winres`, `FileDescription`, `ProductName`, or
package-wide resource stamping, so other Codex binaries that link
`codex-windows-sandbox` do not inherit metadata from this package.

## Verification

- `cargo fmt -p codex-windows-sandbox`
- `cargo build -p codex-windows-sandbox --bin
codex-windows-sandbox-setup`
- `cargo build -p codex-windows-sandbox --bin codex-command-runner`
- `cargo build -p codex-windows-sandbox --lib`
- Build-script output simulation for `CARGO_CFG_TARGET_ENV=msvc` emits
`/MANIFEST:EMBED` and `/MANIFESTINPUT:<manifest>`.
- Build-script output simulation for `CARGO_CFG_TARGET_ENV=gnu` +
`CARGO_CFG_TARGET_ABI=llvm` emits `-Wl,-Xlink=/manifest:embed` and
`-Wl,-Xlink=/manifestinput:<manifest>`.
- Inspected the built binaries and confirmed:
- `codex-windows-sandbox-setup.exe` contains `requestedExecutionLevel` /
`asInvoker`
  - `codex-command-runner.exe` does not contain those manifest strings
- Windows `VersionInfo` remains blank for `FileDescription` /
`ProductName`
- `just test -p codex-windows-sandbox` ran through Nextest, with 114
passing, 2 skipped, and 1 existing Windows sandbox failure:
`unified_exec::tests::legacy_non_tty_cmd_emits_output` fails with
`CreateRestrictedToken failed: 87`.
2026-06-03 09:21:24 -07:00
iceweasel-oai
cb9178e8b3 Add Windows sandbox provisioning setup command (#24831)
## Why

Some Windows users do not have local admin access, so they cannot
complete the elevated portion of the Windows sandbox setup when Codex
first needs it. This adds an alpha provisioning path that an admin or IT
deployment script can run ahead of time for the Codex user.

The intended managed-deployment shape is:

```powershell
codex sandbox setup --elevated --user "$env:COMPUTERNAME\Alice" --codex-home "C:\Users\Alice\.codex"
```

`--elevated` is treated as the requested sandbox setup level, not as
proof that the process is elevated. The Windows sandbox setup
orchestration still checks that the caller is actually elevated before
launching the helper without a UAC prompt.

## What changed

- Added `codex sandbox setup --elevated` with explicit user selection
via either `--current-user` or `--user ... --codex-home ...`.
- Moved the CLI implementation into `cli/src/sandbox_setup.rs` instead
of growing `cli/src/main.rs`.
- Added a Windows sandbox `ProvisionOnly` helper mode that runs the
elevation-required provisioning work without requiring a workspace cwd
or runtime sandbox policy.
- Reused the existing elevated helper path for creating/updating sandbox
users, configuring firewall/WFP rules, and applying sandbox directory
ACLs.
- Persisted `windows.sandbox = "elevated"` into the target `CODEX_HOME`
so the desktop app does not show the initial sandbox setup banner after
pre-provisioning succeeds.

## Validation

- `cargo fmt -p codex-windows-sandbox -p codex-core -p codex-cli`
- `cargo test -p codex-cli sandbox_setup --target-dir
target\sandbox-setup-check`
- `cargo test -p codex-windows-sandbox
payload_accepts_provision_only_mode --target-dir
target\sandbox-setup-check`
- `git diff --check`
- Manual Windows alpha flow with a standard local user (`Mandi Lavida`):
ran the new setup command from an admin shell, verified the target
`.codex` contents, sandbox marker/secrets, ACLs, firewall rules, and
desktop startup without the sandbox setup banner once experimental
network proxy requirements were disabled.

## Notes

This intentionally does not solve later elevated update coordination for
IT-managed deployments. The setup command can still apply provisioning
updates when run again, but a broader coordination/process story is out
of scope for this alpha.
2026-05-29 11:01:44 -07:00
Michael Bolin
bcf2b55957 windows-sandbox: fix capture cancellation test roots (#24974)
## Why

The Windows Bazel job on `main` started failing after #24108 because one
Windows-only capture test still passed `cwd.as_path()` to
`run_windows_sandbox_capture`. That helper now expects the explicit
`workspace_roots` slice introduced by #24108, so the Windows test target
no longer compiled.

## What Changed

- Updates `legacy_capture_cancellation_is_not_reported_as_timeout` to
pass `workspace_roots_for(cwd.as_path()).as_slice()`, matching the
adjacent capture test and the new runner signature.

## Verification

- GitHub Actions CI is the important validation for this Windows-only
compile path.
- Created quickly to get Windows CI running while the separate Ubuntu
`compact_resume_fork` timeout is still under investigation.
2026-05-28 15:51:27 -07:00
Michael Bolin
986c60467b windows-sandbox: pass workspace roots to runner (#24108)
## Why

#23813 switches the Windows sandbox runner path to `PermissionProfile`,
but it still left one runtime anchor for resolving symbolic
`:workspace_roots` entries. That is not enough once a turn has multiple
effective workspace roots: exact entries and deny globs under
`:workspace_roots` need to be materialized for every runtime root before
the command runner chooses token mode or builds ACL plans.

## What Changed

- Replaces the Windows runner/setup `permission_profile_cwd` plumbing
with `workspace_roots: Vec<AbsolutePathBuf>`.
- Resolves Windows-local `PermissionProfile` data with
`materialize_project_roots_with_workspace_roots(...)` instead of the
single-cwd helper.
- Threads `Config::effective_workspace_roots()` through core execution,
unified exec, TUI setup/read-grant flows, app-server setup, app-server
`command/exec`, and `debug sandbox` on Windows.
- Preserves those workspace roots through the zsh-fork escalation
executor instead of rebuilding them from `sandbox_policy_cwd`.
- Makes `ExecRequest::new(...)` and the remaining
`build_exec_request(...)` helper path take
`windows_sandbox_workspace_roots` explicitly so new call sites cannot
silently fall back to `vec![cwd]`.
- Clarifies the `debug sandbox` non-Windows comment: remaining
cwd-dependent resolution still uses `sandbox_policy_cwd`, while
`:workspace_roots` entries are already materialized from config roots.
- Updates elevated runner IPC `SpawnRequest` to send `workspace_roots`
and bumps the framed IPC protocol version to `3` for the payload shape
change.
- Adds Windows-local resolver coverage for expanding exact and glob
`:workspace_roots` entries across multiple roots, plus core helper
coverage proving explicit roots are preserved.

## Verification

- `cargo check -p codex-windows-sandbox -p codex-core -p codex-tui -p
codex-cli -p codex-app-server`
- `cargo test -p codex-windows-sandbox`
- `cargo test -p codex-core windows_sandbox`
- `cargo test -p codex-core unix_escalation`
- `cargo test -p codex-app-server windows_sandbox`
- `cargo test -p codex-tui windows_sandbox`
- `cargo test -p codex-cli debug_sandbox`
- `just test -p codex-core unified_exec`
- `just test -p codex-core
build_exec_request_preserves_windows_workspace_roots`
- `env -u CODEX_NETWORK_PROXY_ACTIVE -u
CODEX_NETWORK_ALLOW_LOCAL_BINDING just test -p codex-app-server --lib
command_exec`
- `just test -p codex-windows-sandbox`
- `just test -p codex-exec sandbox`
- `just fix -p codex-core -p codex-app-server -p codex-windows-sandbox`

A local macOS cross-check with `cargo check --target
x86_64-pc-windows-msvc ...` did not reach crate Rust code because native
dependencies require Windows SDK headers (`windows.h` / `assert.h`) in
this environment; Windows CI remains the real target validation.

Two local targeted filters compile but do not run assertions on macOS:
`env -u CODEX_NETWORK_PROXY_ACTIVE -u CODEX_NETWORK_ALLOW_LOCAL_BINDING
just test -p codex-app-server --lib command_exec_processor` matched zero
tests, and `just test -p codex-linux-sandbox landlock` matched zero
tests because the landlock suite is Linux-only.
2026-05-28 15:26:55 -07:00
viyatb-oai
3cf737e4e3 fix: cancel Windows sandbox on network denial (#19880)
## Why

When Guardian or the sandbox network proxy detects and denies a network
attempt, core cancels the associated execution through `ExecExpiration`.
The Windows sandbox capture path was only forwarding the timeout
component of that expiration state. As a result, a sandboxed Windows
command whose network attempt had already been denied could keep running
until its timeout elapsed rather than terminating promptly in response
to the denial.

This change closes that cancellation-propagation gap for Windows sandbox
execution.

## What changed

- Added `WindowsSandboxCancellationToken` as the cancellation hook
exposed to Windows capture backends.
- Extracted the cancellation token from `ExecExpiration` in core and
passed it to both the direct and elevated Windows sandbox capture paths
alongside the existing timeout.
- Updated direct capture to poll for either process exit, timeout, or
cancellation and to terminate cancelled processes without reporting them
as timed out.
- Updated elevated capture to watch for cancellation and send the
existing `Terminate` IPC frame to the elevated runner. The watcher parks
for 50 ms between checks to bound response latency without a tight busy
wait.
- Added Windows regression coverage for a long-running PowerShell
command: cancellation ends capture before its timeout and does not set
`timed_out`.
- Added a visible skip diagnostic when that PowerShell-dependent
regression test cannot execute, and consolidated the duplicated
expiration-policy branch identified in review.

## Security

This improves enforcement after a denied network attempt has been
attributed to a Windows sandboxed execution: the command no longer
remains alive simply because Windows capture lost the cancellation
signal.

This PR does not claim to make Windows offline mode an airtight
no-network or no-exfiltration boundary. It does not introduce
AppContainer or change how network denial is detected; it makes an
already-detected denial promptly stop the affected sandboxed command.

## Validation

### Commands run

- `just fmt`
- `cargo test -p codex-windows-sandbox`
- `cargo test -p codex-core network_denial`
- `cargo clippy -p codex-core -p codex-windows-sandbox --tests --no-deps
-- -D warnings`
- `just argument-comment-lint -p codex-windows-sandbox -p codex-core`

The new capture regression is `cfg(target_os = "windows")`, so Windows
CI is the execution coverage for that test path. The local macOS test
runs validate the host-runnable crate and core network-denial behavior.

---------

Co-authored-by: Codex <noreply@openai.com>
2026-05-28 21:28:06 +00:00
iceweasel-oai
9826581e7b Attach Windows sandbox log to feedback reports (#24623)
## Why

Windows sandbox diagnostics are currently hard to recover from
`/feedback` even though they are often the most useful artifact when
debugging sandbox behavior. Now that sandbox logging uses daily rolling
files, feedback can safely include the current day's sandbox log without
uploading the old ever-growing legacy `sandbox.log`.

## What changed

- Add a `codex-windows-sandbox` helper that resolves the current daily
sandbox log from `codex_home`.
- When feedback is submitted with logs enabled on Windows, app-server
attaches today's sandbox log if it exists.
- Upload the attachment under the stable filename `windows-sandbox.log`,
independent of the dated on-disk filename.
- Keep existing raw `extra_log_files` behavior unchanged for rollout and
desktop log attachments.

## Verification

- `cargo fmt -p codex-app-server -p codex-windows-sandbox`
- `cargo test -p codex-windows-sandbox
current_log_file_path_for_codex_home_uses_sandbox_dir`
- `cargo test -p codex-app-server
windows_sandbox_log_attachment_uses_current_log`
- Manual CLI/TUI `/feedback` test confirmed Sentry received
`windows-sandbox.log`.
2026-05-26 15:59:25 -07:00
Michael Bolin
0a6bc4e687 windows-sandbox: remove SandboxPolicy runner plumbing (#23813)
## Why

The Windows sandbox runner still carried the old `SandboxPolicy`
compatibility path even though core now computes `PermissionProfile`.
That meant Windows command-runner execution could only see the legacy
projection, so profile-only filesystem rules such as deny globs were not
part of the runner input.

## What Changed

- Removed the Windows-local `SandboxPolicy` parser/export and deleted
`windows-sandbox-rs/src/policy.rs`.
- Changed restricted-token capture/session setup, elevated setup,
world-writable audit, read-root grant, and command-runner session APIs
to accept `PermissionProfile` plus the profile cwd.
- Bumped the elevated command-runner IPC protocol to version 2 because
`SpawnRequest` now carries `permission_profile` /
`permission_profile_cwd` instead of the legacy `policy_json_or_preset` /
`sandbox_policy_cwd` fields.
- Updated core exec, unified exec, debug-sandbox, TUI setup/grant flows,
and app-server setup to pass the actual effective `PermissionProfile`.
- Left regression coverage asserting the old IPC policy fields are
absent and the runner serializes tagged `PermissionProfile` JSON.

## Verification

- `cargo test -p codex-windows-sandbox`
- `cargo test -p codex-core windows_sandbox`
- `cargo test -p codex-app-server
request_processors::windows_sandbox_processor`
- `just fix -p codex-windows-sandbox -p codex-core -p codex-app-server
-p codex-cli -p codex-tui`
- `just fix -p codex-cli -p codex-tui`
- `just fix -p codex-windows-sandbox -p codex-tui`
- `rg "\\bSandboxPolicy\\b" codex-rs/windows-sandbox-rs` returned no
matches.

Note: `cargo test -p codex-cli` was attempted but did not reach crate
tests because local disk filled while compiling dependencies (`No space
left on device`). The targeted clippy pass compiled the affected CLI/TUI
surfaces afterward.




---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/openai/codex/pull/23813).
* #24108
* __->__ #23813
2026-05-26 14:56:27 -07:00
iceweasel-oai
5b1b6a20dd [codex] Use rolling files for Windows sandbox logs (#24117)
## Why

Windows sandbox diagnostics currently append to a single `sandbox.log`
under `CODEX_HOME/.sandbox`. That file never rolls over, which makes it
hard to safely include sandbox diagnostics in future feedback reports
without risking unbounded growth.

## What changed

- Replaced direct append-open sandbox logging with
`tracing_appender::rolling::RollingFileAppender`.
- Configured sandbox logs to rotate daily using names like
`sandbox.YYYY-MM-DD.log`.
- Added a conservative `MAX_LOG_FILES` cap of 90 retained matching log
files.
- Routed the Windows sandbox setup helper through the same rolling
writer.
- Added helpers for resolving the current daily sandbox log path so
future feedback upload work can use the same filename logic.
- Updated tests and test diagnostics to read the dated daily log file.

This intentionally does not include sandbox logs in `/feedback` yet;
scrubbing and attachment behavior can happen in a follow-up.

## Testing

- `cargo fmt -p codex-windows-sandbox`
- `cargo check -p codex-windows-sandbox`
- `cargo test -p codex-windows-sandbox`
- `cargo test -p codex-windows-sandbox logging::tests`
- `cargo clippy -p codex-windows-sandbox --all-targets -- -D warnings`
2026-05-22 11:37:01 -07:00
Michael Bolin
c9ff067e31 windows-sandbox: add profile-native elevated APIs (#23714)
## Why

This is the next step after #23167 in the Windows sandbox
`PermissionProfile` migration. The elevated Windows backend still
exposed policy-string entry points, which forced callers to pass a
compatibility `SandboxPolicy` before the command-runner IPC could
receive a profile.

Adding profile-native APIs first keeps the core switch in the next PR
small: reviewers can see that the Windows crate can prepare elevated
setup, capability SIDs, and runner IPC from a resolved
`PermissionProfile` without changing core behavior yet.

## What

- Adds `ElevatedSandboxProfileCaptureRequest` and
`run_windows_sandbox_capture_for_permission_profile_elevated` for
one-shot elevated capture.
- Adds `spawn_windows_sandbox_session_elevated_for_permission_profile`
for unified exec sessions.
- Factors elevated spawn prep through
`prepare_elevated_spawn_context_for_permissions`, so both new APIs
operate from `ResolvedWindowsSandboxPermissions` directly.
- Keeps the existing legacy policy-string APIs as adapters for callers
that have not moved yet.

## Verification

- `cargo test -p codex-windows-sandbox`












---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/openai/codex/pull/23714).
* #23715
* __->__ #23714
2026-05-21 00:25:31 +00:00
iceweasel-oai
8253ae4e5c Remove Windows sandbox resource stamping (#23764)
## Why

The `codex-windows-sandbox` crate was embedding Windows resource
metadata through a package-level `build.rs`. Because that package also
exposes the `codex_windows_sandbox` library, downstream binaries that
link the library could inherit `FileDescription` / `ProductName` values
of `codex-windows-sandbox`.

That made ordinary Codex binaries, including the long-lived `codex.exe`
app-server sidecar, appear as `codex-windows-sandbox` in Windows UI
surfaces such as Task Manager / file properties.

We do not rely on this metadata enough to justify a larger bin-only
resource split, so this removes the resource stamping entirely.

## What changed

- Removed the `windows-sandbox-rs` build script that invoked `winres`.
- Removed the setup manifest that was only consumed by that build
script.
- Removed the `winres` build dependency and corresponding `Cargo.lock` /
`MODULE.bazel.lock` entries.
- Removed the now-unused Bazel build-script data.

## Verification

- `cargo build -p codex-windows-sandbox --bins`
- `cargo build -p codex-cli --bin codex`
- `bazel mod deps --lockfile_mode=update` via Bazelisk, with local
remote-cache-disabling flags because `bazel` is not installed on PATH
here
- `bazel mod deps --lockfile_mode=error` via Bazelisk, with the same
local flags
- Verified rebuilt `codex.exe`, `codex-command-runner.exe`, and
`codex-windows-sandbox-setup.exe` now have blank `FileDescription` /
`ProductName` fields.
- `cargo test -p codex-windows-sandbox` still fails on two legacy
Windows sandbox tests with `CreateRestrictedToken failed: 87` and the
follow-on poisoned test lock; 85 passed, 2 ignored.
2026-05-20 16:15:21 -07:00