Commit Graph

199 Commits

Author SHA1 Message Date
chess
fd875b188b Handle disabled Windows sandbox accounts during cleanup (#46333)
## Why

Cleanup needs fresh logon tokens for sandbox accounts that may already be disabled. Temporarily enabling those accounts must leave a durable obligation to disable them again if the service exits unexpectedly.

## What changed

- Persist `cleanup_logon_pending` before enabling an account, then disable it again after the logon attempt before clearing the marker.
- Recover pending account disables before owner restoration or IPC admission, validating account SIDs before restoration. Block runtime readiness and provisioning while recovery is pending, and defer retirement until cleanup logons are prepared.
- Include the blocking logon details in cleanup timeout errors and suppress repeated identical cleanup errors in the Windows event log.

## Testing

Add receipt tests covering backward-compatible defaults and pending cleanup state surviving serialization, blocking readiness and owner admission until cleared.

GitOrigin-RevId: 801bec408a27ac85ccdc3eb5ca2bdb2ccb3d5827
2026-09-18 00:36:07 +00:00
chess
2833985d88 Repair Windows sandbox access to existing runtime children (#46241)
## Why

A runtime directory can have read/execute access while existing files and subdirectories lack inherited permissions. Checking only the runtime roots leaves those children inaccessible to sandbox users.

## What changed

- Walk the Codex app runtime tree and add missing read/execute grants for the sandbox group, validating access after changes.
- Use `GRANT_ACCESS` to preserve existing grants and skip additions that could override deny entries, including inherited denials for other trustees.
- Skip reparse points and trees with reparse-point ancestors, tolerate disappearing paths, and report repair failures through setup logging and refresh errors.

## Testing

Add Windows regression tests for repairing children beneath an already-readable root, repeated repairs, preserving read/write denials and other trustees' inherited file denials, avoiding write or ACL-management grants, and leaving junction targets untouched.

GitOrigin-RevId: 93d55dd9fca2b24eac157ae9be505982d07dd9b9
2026-09-17 15:44:11 +00:00
zm-oai
32b54cffdd Prefer the provisioning service for automatic Windows sandbox setup (#46239)
## What changed

- Use the installed provisioning service regardless of the onboarding feature gate. Fall back to the elevated helper only when the service is unavailable; propagate service errors.
- Pass the effective proxy settings and filter listener ports to match them, including when preserving saved settings.
- Remove stale credentials before repairing missing, disabled, or password-expired sandbox accounts so older services cannot mistake them for completed setup.
- Select helper fallback when workload-identity environment variables are present, since service requests do not carry that environment. Continue rejecting helper fallback for registered Core.

## Testing

Extend account-repair tests to cover stale credential removal, missing and disabled accounts, and repeated setup checks. Add subprocess tests for workload-identity routing with and without registered Core.

GitOrigin-RevId: 1041ae76e9b0893ad60f30a5cdc506748be52552
2026-09-17 15:35:39 +00:00
chess
c11fdc944f Improve Windows sandbox error details and registry cleanup (#46237)
## Why

Provisioning errors omitted underlying causes, and removing a legacy installation record could leave an empty registry key behind.

## What changed

- Include error chains in provisioning responses and failure logs, retaining control-character replacement and the response byte limit.
- Attempt to delete the legacy installation registry key after removing and flushing its record, preserving any remaining values or subkeys.

## Testing

Add a regression test for nested error causes, control-character replacement, and UTF-8 truncation within the response byte limit.

GitOrigin-RevId: 8fccfb49c708be5f5d5be7180289cb74a66498a2
2026-09-17 15:28:20 +00:00
zm-oai
51c30ad800 Repair expired Windows sandbox account passwords during setup (#46043)
## Why

An ACL refresh cannot rotate expired sandbox account passwords or update stored credentials. Accounts marked with `UF_PASSWORD_EXPIRED` need full setup before logon.

## What changed

- Trigger full setup when either sandbox account has an expired password, then reload credentials and report an error if either password remains expired.
- Treat expired passwords as incomplete setup in service provisioning and reject them during registration-only refreshes.

## Testing

Add coverage for expiration on either account, a single repair attempt, credential reload, and unsuccessful repair. Add an ignored Windows test requiring administrator rights to verify that resetting an expired password preserves other account flags.

GitOrigin-RevId: cd6e86f226bea52243d37bd7c7becf7378ba8721
2026-09-16 22:26:17 +00:00
zm-oai
4cf84b7603 Test Windows sandbox bin DACL modification permissions (#46038)
## What changed

Extend the sandbox directory ACL test to verify that the real user retains
`WRITE_DAC` on `.sandbox-bin` so its DACL can be refreshed, while the sandbox
group lacks that permission. Cover both `Full` and `ProvisionOnly` setup modes.

GitOrigin-RevId: cff32956ea308803536a47d8cdfc256184346553
2026-09-16 22:06:55 +00:00
chess
872fc22f9c Complete Windows sandbox uninstall cleanup (#45799)
## Why

Packaged uninstall could leave sandbox user profiles and desktop-created data behind. Cleanup also needs to handle a service stop before package removal completes without deleting data belonging to an update or reinstall.

## What changed

- Delete sandbox profiles before their accounts, preserving accounts for retry when profile deletion fails. Defer retained runtime accounts and the sandbox group until runtime registrations are removed and profiles unload.
- Allow cleanup while the exact retiring package is still registered, while preserving desktop data when a successor package is present.
- Remove desktop-created Codex homes during registered runtime cleanup, preserve existing CLI data, and prune empty home and cache directories. Keep directory pins through retries and avoid privileged traversal after releasing the home.
- Retry cleanup up to five attempts after a service stop, while retaining shutdown cancellation behavior.
- Report cleanup outcomes in the Windows Event Log and emit final completion after registered runtime cleanup finishes. Remove the empty installation registry parent.

## Testing

Add Windows tests for profile deletion retry and account preservation, service-stop retries versus system shutdown, and PowerShell finalizer parsing and native binding compilation. Extend retained-token coverage to check account SID matching.

GitOrigin-RevId: 1aefa969e6aff9bb8e77e2c9fe9ee772230fc4fb
2026-09-15 21:33:16 +00:00
zm-oai
4e6450bbfd Resume Windows sandbox registration refresh after service restarts (#45559)
## Why

Registering the service-bearing package can restart the provisioning service once for each managed sandbox account. A restart can interrupt the response after runtime readiness has been revoked, preventing the refresh from completing.

## What changed

- Retry registered sandbox refresh requests after response pipe disconnections, allowing up to two service restarts within the original deadline. Require a different service process ID and authenticate it against the running service before resending.
- Allow refresh to resume without `ready_package` when account ownership is complete, teardown is not underway, and the existing owner, package family, live account SIDs, and settings checks pass. Runtime execution still requires readiness for the current package.
- Keep authentication failures, failed writes, explicit replies, and protocol errors outside the retry path.

## Testing

Add regression tests for disconnect classification, the two-restart budget, deadline expiry, and authentication failure before writing. Extend ownership tests to distinguish resumable registration from runtime readiness and reject incomplete accounts or retirement state.

GitOrigin-RevId: d932f179b31752fe918297b7b12e5077c17b19e5
2026-09-15 00:42:31 +00:00
zm-oai
4199fda578 Add opt-in registered package execution to the Windows sandbox (#45550)
## What changed

- Capture `CODEX_WINDOWS_REGISTERED_CORE=1` at startup and propagate the selected runtime to sandbox wrappers.
- Launch registered runners through service-recorded execution aliases, validating ownership, OS package identity, and the staged runner image before sending commands. Require service provisioning without falling back to copied helpers or `PATH` lookup.
- Preserve package context for sandboxed child processes and descendants so they can launch executables from the protected package directory.
- Refresh stale package registrations during readiness checks without blocking unrelated RPCs, and reconcile effective proxy settings through the service.
- Resolve setup ownership from the process token and avoid treating the server directory as a writable workspace when setup omits `cwd`.
- Record startup and command outcomes by runtime.

## Testing

Add coverage for runtime selection, package query validation, helper resolution, setup roots, proxy reconciliation, and command result reporting. Add an ignored integration test for environment forwarding, output, and exit status that requires an installed test MSIX and service provisioning in a Windows VM.

GitOrigin-RevId: 976d64039d611be4406c3d0e354820775f8eb6e4
2026-09-14 23:55:04 +00:00
zm-oai
6ae5e71458 Add service-managed package registration for Windows sandbox accounts (#45542)
## What changed

- Add an explicit `registered_core` provisioning mode that registers the app package for both managed sandbox accounts and records their runner aliases. Authenticate callers against the service's package family and installed version.
- Persist runtime ownership and publish readiness only after both registrations and AppData metadata grants succeed. Prevent legacy setup or another owner from replacing registered sandbox accounts, and restrict `refresh_only` requests to an existing ready setup.
- Scope service and pipe names by package identity.
- Preserve registrations across package updates and clean them up when the owner uninstalls the app. Fence provisioning during teardown and defer package removal until native cleanup succeeds and the service exits.

## Testing

Add tests for registration opt-in, ownership and readiness checks, legacy setup isolation, metadata ACL preservation, listener shutdown handling, and the cleanup finalizer's commit barrier and UTF-8 input.

GitOrigin-RevId: 69e52f7463285b51f3bef831f071245f0eca0838
2026-09-14 23:24:10 +00:00
zm-oai
d39cfa8a2d Harden and share Windows sandbox identity helpers (#45533)
## What changed

- Share process package-family queries, token user SID extraction, and account-name lookup through `codex_windows_sandbox`, and use them in the provisioning service.
- Bound token query sizes and validate SID pointers, revisions, and lengths before copying SIDs into owned storage.
- Use a drop guard to balance firewall COM initialization, and track the package lifecycle directory guard separately so cleanup releases it while keeping ancestor and home handles pinned.

## Testing

Add tests that verify copied SIDs outlive their query buffers and reject truncated token data, malformed SIDs, and invalid SID pointers.

GitOrigin-RevId: 2b893e4524d3e00cb114df05215beef7b9eebbe9
2026-09-14 22:40:01 +00:00
zm-oai
1a02867bd1 Refactor Windows sandbox setup and service helpers (#45455)
## What changed

- Extract helper copying, token-user SID queries, provisioning pipe ownership, and service runtime lifecycle into dedicated modules.
- Simplify command-runner resolution and extract setup configuration loading, payload execution, provisioning request exchange, and response handling into helpers.
- Parameterize installation-record registry access and return the saved installation record from authenticated user registration.

## Testing

Add tests for explicit setup `cwd` selection and effective workspace roots, plus valid and invalid token-user SID queries. Move existing helper-copy and freshness tests alongside the extracted copy implementation.

GitOrigin-RevId: ffb39adae7611baa95e85c89f9a31ef7a779e217
2026-09-14 16:05:40 +00:00
chess
36f0dbe796 Register Windows desktop uninstall ownership before sandbox setup (#45224)
## Why

Desktop uninstall cleanup needs an installation owner even when the user has not signed in or configured the Windows sandbox. Recording ownership only during provisioning leaves those installations unregistered.

## What changed

- Add an authenticated installation registration request and attempt it during Windows desktop stdio initialization, with a five-second timeout before the initialization response.
- Persist ownership independently of provisioning, preserve existing desktop ownership, and prevent another user or home from replacing the registered owner.
- Validate write authority and retain directory handles and guards to protect the registered home against junction conversion through privileged cleanup.
- Preserve existing CLI homes during desktop uninstall while removing their `CodexSandboxUsers` ACL entries. Report ACL revocation errors and avoid propagating unchanged ACLs.
- Grant the owner `WRITE_DAC` on `.sandbox-bin` and allow elevated-helper fallback when older permissions need repair or the service cannot establish an uninstall watcher.

## Testing

Add tests for installation registration without sandbox settings and for preserving a child's null DACL when revoking an absent SID from its parent.

GitOrigin-RevId: fb48923e9d76758d1bf5b50c7305aa60f91629db
2026-09-13 13:06:40 +00:00
zm-oai
e61f381900 Validate Windows sandbox token groups before copying SIDs (#45182)
## Why

Logon SID lookup previously walked token group entries and SID pointers without checking that they fit within the returned buffer.

## What changed

Add a shared `token_groups` helper with a caller-supplied size limit. Validate the group layout, SID bounds, revision, and length before copying SIDs into owned `TokenGroup` values, preserving group order, duplicates, and attributes. Use this helper for logon SID lookup.

## Testing

Add Windows tests for owned SID storage, preserved order and attributes, truncated layouts, malformed and out-of-buffer SIDs, query size limits, and current-token logon SID lookup.

GitOrigin-RevId: f51ff6aa5266b6c73fe07968015e462c888a95e4
2026-09-13 06:43:42 +00:00
zm-oai
a4c61afff2 Split Windows sandbox cleanup into preparation and completion phases (#45178)
## What changed

Expose `prepare_packaged_windows_sandbox_cleanup` to disable sandbox accounts and stop their processes before returning a `PreparedWindowsSandboxCleanup` guard that retains the setup lock. Its `finish` method removes resources and protections; dropping it only releases the lock, leaving accounts disabled and protections intact.

Keep `clean_up_packaged_windows_sandbox` as a wrapper around both phases, and extract the service's existing package cleanup logic into a dedicated module.

GitOrigin-RevId: a32663171bce027f771f738d71b0c46404edbedc
2026-09-13 06:15:35 +00:00
zm-oai
dfaf451426 Extract Windows sandbox setup and installation storage into the library (#45169)
## What changed

- Move the setup helper implementation and its existing tests into `codex-windows-sandbox`, with the binary delegating to `setup_helper_main`.
- Expose installation record types and storage operations from the library, preserving the registry key, size limit, and serialization format. Reuse them in the service and remove its direct `serde` dependencies.
- Extract service provisioning from IPC handling into a dedicated module, preserving authentication and machine-policy checks before provisioning and retaining directory handles through helper execution.

GitOrigin-RevId: dd1ea015aff901d5dfe39b395de1971ee0f2d33f
2026-09-13 04:59:49 +00:00
chess
4caa5d615d Keep Windows sandbox private desktops alive across helper exits (#44658)
## Why

Private desktops owned by short-lived sandbox wrappers disappear when those wrappers exit, preventing reuse across filesystem helper requests.

## What changed

- Select and cache private desktops in the calling process, keeping desktops separate for different sandbox permissions.
- Pass the desktop name through the wrapper to the restricted-token and elevated backends so helpers reuse the selected desktop.
- Separate sandbox account preparation from filesystem ACL refresh so desktop selection does not perform the wrapper's refresh.
- Propagate desktop preparation errors and require a desktop name when the wrapper's private desktop flag is set.

## Testing

Add a Windows filesystem regression test covering desktop survival and reuse across reads, writes, metadata queries, and streaming reads, plus separate read-only permissions and rejected writes. Extend wrapper argument tests to cover named desktops and rejection of a missing desktop name.

GitOrigin-RevId: 05a1cb829a902732248bfa7f4ad7470d911fa9f6
2026-09-10 22:17:03 +00:00
viyatb-oai
e25bedc166 Block non-loopback inbound traffic for the Windows offline sandbox (#44639)
## Why

The offline sandbox's non-loopback firewall block covered only outbound traffic. Add a matching inbound block for the offline sandbox user.

## What changed

- Configure an inbound firewall rule scoped to the offline user's SID, blocking all protocols and ports for non-loopback remote addresses.
- Make firewall rule direction explicit while preserving the existing outbound rules.
- Remove the new inbound rule during uninstall.

## Testing

Extend the elevated Windows sandbox integration test to inspect effective inbound and outbound rules, asserting their uniqueness, direction, block action, enabled state, profiles, address and port filters, protocol, and user scope.

GitOrigin-RevId: cbc1ca0d8d08a31fc53da5ad5be6ee5d51afa63d
2026-09-10 21:02:14 +00:00
iceweasel-oai
f11d0dd012 Prevent filesystem-root read denies in the Windows sandbox (#44327)
## Why

The elevated Windows sandbox requires effective `:root` read access and cannot safely enforce policies that deny reads at the filesystem root.

## What changed

- Validate root read access before elevated setup, service provisioning, and setup refresh, rejecting root-denying globs before expansion.
- Reject filesystem-root deny-read ACL targets after canonicalization and check the opened handle before applying an ACL, so aliases cannot bypass the root guard.
- Read and update deny ACLs through the same handle, and allow an existing deny ACE to be recognized when write access to the ACL is unavailable.

## Testing

Add regression coverage for default root denial, root-denying globs, allowed root reads with narrower deny rules, handle-based root detection, and reading existing deny ACEs without `WRITE_DAC`.

GitOrigin-RevId: b904e7cdbc09ee0147e1818c898b0382b5820c1b
2026-09-09 22:50:03 +00:00
iceweasel-oai
bb71d758cd Add telemetry for the Windows system config namespace (#44284)
## What changed

Probe the default Windows system config namespace at session start and record `codex.windows_system_config.namespace_squatting_probe` once per process when metrics are available.

When `config.toml` or `requirements.toml` exists, check the containing directories for expected ownership and broad standard-user mutation allow ACEs, including permissions inherited by child files. Report coarse results for missing files, expected directories, unexpected types or owners, mutation permissions, and check errors.

The probe is observational: it does not change configuration loading or enforce a trust decision.

GitOrigin-RevId: e1c79dca5548e16e83c7b84b44ab0de4e2643d0d
2026-09-09 19:31:12 +00:00
zm-oai
5e3f0ee94b Avoid Windows sandbox setup for irrelevant proxy port changes (#43930)
## Why

When local binding is enabled, the Windows sandbox has no port-specific loopback rules. Changing proxy listeners therefore does not require an elevated firewall setup.

## What changed

Ignore proxy port differences when both stored and requested settings enable `allow_local_binding`. Continue refreshing ACLs, and still require full setup when local binding changes or proxy ports change with local binding disabled.

## Testing

Add credential orchestration coverage using real setup markers and DPAPI credentials with injected setup and account lookup callbacks. Verify refresh versus full setup selection, returned credentials, and preservation of the setup marker.

GitOrigin-RevId: ffb0c019f3931915b3c1cf522315565df37c582b
2026-09-08 22:13:38 +00:00
Sean Huang
4fd2c460dd Extract Windows deny-read glob scan planning into protocol (#43903)
Move lexical scan-bound calculation into `codex_protocol::permissions` and
expose `windows_deny_read_glob_scan` with its `WindowsDenyReadGlobScan` result.
Have the Windows sandbox resolver use the shared helper, preserving literal
scan roots, glob suffixes, and traversal depth limits without filesystem access
in the planner.

GitOrigin-RevId: 748a12b45f89c6e045e9123c055453ec39c202b1
2026-09-08 20:23:20 +00:00
zm-oai
a482e65b86 Preserve Windows managed deny reads in the sandbox CLI (#42835)
## Why

Windows sandbox setup reconciles persistent deny ACLs against the paths supplied for a session. The `codex sandbox --permission-profile` path supplied an empty list, which could discard the profile's deny-read restrictions.

## What changed

Resolve deny-read paths from the selected permission profile and workspace roots before starting a Windows sandbox session, and pass them through to setup.

## Testing

Add a Windows CLI integration test that launches the same managed-deny profile twice and verifies that denied file reads and DLL loads remain blocked while allowed access still works.

GitOrigin-RevId: 6ec8b6a13a33b862d7b152eadbbdde3146de4b7d
2026-09-04 19:40:01 +00:00
chess
89a4eec6da Keep the Windows sandbox command runner hidden (#42801)
## What changed

- Build `codex-command-runner` as a Windows-subsystem binary outside tests.
- Launch non-TTY sandbox commands without a console window.
- Suppress the busy cursor when creating the elevated runner process.

GitOrigin-RevId: fc6b70059add7dea642805030bd508915367fe44
2026-09-04 17:08:18 +00:00
iceweasel-oai
7a7c188682 Preserve target-native paths in command approvals (#42577)
## What changed

- Pass the selected executor's `PathUri` through user command approval requests instead of converting the working directory to a host-native path.
- Make native-path permission helpers explicitly local and require executor-aware permission transforms to receive a `FileSystemSandboxPolicyContext`.
- Cover approved remote commands to verify that the approval request reports the selected remote working directory and execution resumes after approval.

GitOrigin-RevId: 0aa3042f2d7594af6c7d0abf31d7f99cf67d5556
2026-09-03 16:21:10 +00:00
chess
665e5f45ab Clean up Windows sandbox resources on app uninstall (#42375)
## What changed

- Record the authenticated sandbox owner and observe package uninstall events across service restarts and session changes.
- During uninstall, serialize setup and cleanup, disable sandbox accounts, stop their processes, and remove sandbox directories, firewall and WFP rules, hidden-user entries, accounts, and the sandbox group.
- Restrict desktop-owned directory cleanup to pinned paths and perform it while impersonating the authenticated owner.
- Detect missing or disabled sandbox accounts after interrupted cleanup and reprovision them before restoring network access.

GitOrigin-RevId: 7d63fff7ddcff3eb01d018653146df12044bd277
2026-09-02 22:19:51 +00:00
johnl-oai
7e45bdb5fd Enable authenticated Windows sandbox provisioning (#42351)
## Why

The Windows sandbox service had provisioning policy and client authentication in place, but its IPC listener was still disabled.

## What changed

- Serve framed provisioning requests over a local named pipe, authenticate packaged clients, validate requests and machine policy, and report provisioning outcomes through bounded responses and Windows event logging.
- Return `unavailable` for configuration parse failures so clients can fall back to the elevated setup helper.
- Keep validated directory handles alive in the setup helper so path protections survive an unexpected service exit.
- Make connection recovery and shutdown wakeups tolerate clients that disconnect before the listener accepts them.

## Testing

Added Windows tests for response framing, configuration-error classification, pipe security and reconnect behavior, shutdown wakeups, and retained helper handles.

GitOrigin-RevId: 68e9d546dcada88ff162ea4f98c0f4d748706b34
2026-09-02 20:27:05 +00:00
johnl-oai
add870a4bf Harden Windows sandbox provisioning file handling (#42342)
## Why

Windows sandbox provisioning performs privileged work beneath a requested Codex home. Provisioning paths and output entries must remain bound to the files and directories that were validated, without following reparse points or writing through caller-controlled hard links.

## What changed

- Add reusable no-reparse directory opens, path validation, directory guards, and handle-relative atomic file replacement.
- Use fresh or retained handles for provisioning logs, sandbox credentials, setup markers, and error reports in service provisioning mode.
- Add service-side validation for framed provisioning requests, proxy settings, fixed-drive Codex homes, and pinned sandbox directories.

## Testing

Add Windows tests covering junction and unsafe-path rejection, hard-link-safe output replacement, retained output handles, request framing and normalization, and ancestor pinning.

GitOrigin-RevId: 2ec4f0d15404c3387df1414bb0c1915cf452ecf2
2026-09-02 20:03:43 +00:00
johnl-oai
dcfcb570b2 Add an authenticated Windows sandbox provisioning client (#42337)
## What changed

- Add a client for the packaged Windows sandbox provisioning service that verifies the named-pipe server belongs to the running `CodexSandboxService` process before exchanging a versioned provisioning request.
- Treat an absent, busy, timed-out, or disconnected service as unavailable while surfacing provisioning and authentication failures.
- Send the complete `WindowsSandboxProvisioningSettings` and classify inherited HTTP and SOCKS proxy listeners separately for managed-policy validation.
- Share bounded frame-readiness handling between runner and provisioning IPC.

## Testing

- Extend proxy environment tests to cover network-enabled profiles, mixed HTTP and SOCKS listeners, explicit proxy-port overrides, case-insensitive schemes, and unclassified protocols.

GitOrigin-RevId: 6ff6741fc3ecd76314a7a045523a8d7a7e7af686
2026-09-02 19:33:34 +00:00
johnl-oai
301a7c5e01 Add a Windows sandbox provisioning protocol (#42334)
## What changed

- Define a versioned, length-prefixed JSON request/response protocol for the
  machine-wide Windows sandbox provisioning service, including its named pipe
  and network setup parameters.
- Add a readiness check that compares the recorded proxy ports and local-binding
  policy with the requested provisioning settings.
- Share framed JSON I/O, sandbox-group creation, and SID resolution between the
  existing elevated setup path and provisioning clients.

GitOrigin-RevId: d6250542d06f7646ffeb92150472e7d7fa1e5e66
2026-09-02 19:23:27 +00:00
iceweasel-oai
f59905647a Protect Windows sandbox binaries from inherited write access (#42330)
## Why

An inherited write ACE from a writable parent directory could leave sandbox
runner files in `.sandbox-bin` writable or deletable by the workspace capability
SID.

## What changed

- Mark the `.sandbox-bin` DACL as protected when applying its explicit ACL, while
  preserving inherited DACL behavior for the other persistent sandbox
  directories.
- Cover both full and provision-only setup, including runner files created before
  and after the directory is locked.

GitOrigin-RevId: fcda4df97e3f8d729438ccb3d42daa606076e0c4
2026-09-02 19:03:32 +00:00
iceweasel-oai
1bc8fb16ae Separate Windows sandbox provisioning from ACL refresh (#42309)
## What changed

- Limit elevated interactive setup to provisioning sandbox identities and proxy settings; do not include caller workspace or ACL roots in its payload.
- Always run the non-elevated setup refresh during sandbox activation so the current permission profile supplies read, write, and deny paths, including when provisioning was completed previously.
- Add an `interactive-provision` setup mode that performs provisioning without the full ACL setup path.

## Testing

- Verify elevated provisioning payloads contain no caller ACL roots and use the new mode.
- Verify the setup helper accepts `interactive-provision` payloads.

GitOrigin-RevId: 081b1b43abd2388773c230fb35da82896e7be2ea
2026-09-02 16:49:45 +00:00
Charlie Marsh
84aa75204a Format Python scripts across the repository (#42109)
## Why

The root Python formatting pass only covered `scripts/`, leaving Python utilities elsewhere in the repository outside `just fmt` and `just fmt-check`.

## What changed

- Run the scripts Ruff formatter from the repository root.
- Exclude `sdk/python`, which has its own formatter pass, and `codex-rs/vendor`.
- Apply Ruff formatting to the newly covered Python files and update the formatter coverage test.

GitOrigin-RevId: 73ac82b8bb9c713d589724f6c4f926399febb513
2026-09-01 17:47:29 +00:00
iceweasel-oai
34e74fda0e Align deny-read matching with executor path semantics (#41209)
## Why

Read-deny policies must use the target executor's path convention so URI-based
policy checks and native filesystem enumeration enforce the same rules.

## What changed

- Prepare deny roots and glob matchers from `PathUri` policy context, including
  executor-relative working directories and home-relative patterns.
- Match Windows globs case-insensitively with normalized separators, while
  preserving byte-oriented POSIX matching for non-UTF-8 paths.
- Fail closed for malformed paths, incompatible path conventions, unresolved
  home-relative patterns, and invalid globs.
- Make Windows deny-read discovery use case-insensitive ripgrep glob matching.

## Testing

Added coverage for Windows URI conventions, executor home expansion,
case-insensitive `.env` discovery, malformed paths, non-UTF-8 names, and
canonical directory-link targets.

GitOrigin-RevId: 36001219a2e9b36acfce8972dc1d3bbc304271c5
2026-08-27 21:15:37 +00:00
rka-oai
035295b46e Improve sandboxing, MCP errors, and cached approvals (#41196)
Expand Windows deny-read globs robustly across protected directories while preserving filesystem enforcement. Preserve structured MCP tool and resource errors through app-server responses. Bind cached Guardian classifications to current local and root authorization state so stale scores cannot approve actions.

Add regression coverage for the sandbox resolver, structured protocol errors, and authorization changes.

GitOrigin-RevId: 4b80ed724d869afeca79204222d8465fa99d3a24
2026-08-27 20:05:08 +00:00
iceweasel-oai
37a5149822 Record Windows world-writable scan telemetry (#40983)
## What changed

- Return the number of directories flagged by successful Windows sandbox world-writable scans.
- Record that count in the `codex.windows_sandbox.world_writable_scan_flagged_directories` histogram for startup and warning-triggered scans.
- Tag each measurement with a `success` or `error` result, using a count of zero when the scan fails.

GitOrigin-RevId: 076160f36b1d62fa737f4b2d0318774e6c44a4b1
2026-08-26 21:52:56 +00:00
zm-oai
21c58c90f2 Harden Windows sandbox helper cleanup (#40808)
## Why

Windows filesystem operations can complete while their helper process remains
alive, and elevated sandbox processes must not survive a disconnected control
pipe.

## What changed

- Read newline-delimited filesystem helper responses without imposing an
  operation deadline, then bound the time spent reaping the helper.
- Drain helper stderr concurrently, retain a bounded diagnostic on failure, and
  kill helpers that do not exit after responding.
- Terminate the elevated runner's job or process when its input pipe closes or
  fails.

## Testing

Added coverage for delayed responses, noisy stderr, stuck helpers, duplicated
file handles, and termination of elevated descendants after a control-pipe
disconnect.

GitOrigin-RevId: c0d3d5d76e13318de17638df4db71fcfb9a7397f
2026-08-26 06:02:56 +00:00
chess
7e1ee6df6c Reuse private desktops across Windows sandbox commands (#40672)
## Why

Private desktops need to remain available across command-runner exits and idle
gaps.

## What changed

- Keep parent-owned private desktops alive and reuse them only when the sandbox
  account and effective permissions match.
- Pass the selected desktop name to elevated command runners, which validate and
  open the existing desktop instead of creating their own.
- Apply the same policy-aware reuse to the legacy Windows sandbox path.

## Testing

Add Windows tests for desktop-name validation, lifetime and concurrent reuse,
and separation when effective permissions differ.

GitOrigin-RevId: 2df8b1c31ff22d72549f2ec3065cd80ea1dd0c6a
2026-08-25 18:41:03 +00:00
Adam Perry @ OpenAI
8444cf63b5 Derive sandbox contexts from turn environments (#40551)
## What changed

- Add Windows sandbox mode, private-desktop behavior, and legacy Landlock selection to each `EnvironmentConfig`.
- Centralize sandbox context construction on `TurnEnvironment`, preserving environment-owned permissions, paths, and backend settings while applying additional permission grants.
- Use the environment-derived context for project instructions, capability discovery, file uploads, and filesystem-oriented tools.

## Testing

- Verify capability discovery uses the selected environment's permission profile and sandbox backends when they differ from the thread defaults.

GitOrigin-RevId: 7ae2fed90c8ada950f2e8431e571e9b2c793c291
2026-08-25 05:16:45 +00:00
iceweasel-oai
3a211471d2 Request read control when updating Windows sandbox ACLs (#40475)
## Why

`SetSecurityInfo` can reject a directory handle opened with only `WRITE_DAC`.

## What changed

- Request `READ_CONTROL` alongside `WRITE_DAC` when opening or creating a
  no-reparse sandbox directory.
- Add a Windows regression test that provisions and locks a plain sandbox
  directory through the handle-based ACL path.

GitOrigin-RevId: bd50dc54d4cc80e9609323ddb4ecc7e4780a31fb
2026-08-24 20:34:13 +00:00
zm-oai
a12c4f4c01 Preserve Windows root reads with deny-read rules (#40441)
## What changed

- Detect readable symbolic `:root` entries separately from effective full-disk access so narrower deny-read rules do not disable the Windows sandbox's broad-read setup.
- Add explicit readable roots to that setup while omitting the filesystem root itself, and prevent read roots at or below denied paths from being granted access.

## Testing

- Extend the elevated Windows sandbox integration test to verify that an allowed bundled skill under the user profile remains readable while exact and glob-based secrets stay denied.

GitOrigin-RevId: 8f6f267b78718b9e8609a9205c489f253f478491
2026-08-24 17:29:21 +00:00
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