Skip to content

Windows sandbox: an approved request_permissions write to a file that does not exist yet is dropped (exists() filter), so the write fails and is asked again #58433

Open

Description

@hesong12

Version: rust-v0.164.0; the same code is on main today. Windows 11, [windows] sandbox = "unelevated", sandbox_mode = "workspace-write", approval_policy = "on-request".

What happens

The model calls request_permissions for file_system.write on one file that does not exist yet, outside the writable roots (for example C:\Users\person\Documents\Work\brief.docx, to save a finished document there). The user approves it. The next command, Copy-Item <built file> C:\Users\person\Documents\Work\brief.docx, fails with Access to the path ... is denied (UnauthorizedAccessException). The model then asks again with sandbox_permissions = "require_escalated", and the user has to approve the same write a second time.

The grant reaches the command (apply_granted_turn_permissions merges it and the command runs WithAdditionalPermissions / permissions_preapproved), but the Windows sandbox drops the path before granting anything, because the file does not exist yet:

  • windows-sandbox-rs/src/allow.rs, compute_allow_paths_for_permissions: add_allow_path keeps a path only if p.exists().
  • windows-sandbox-rs/src/setup.rs, canonical_existing (feeding gather_write_roots_for_permissions / effective_write_roots_for_permissions): if !p.exists() { return None; }.

So a write grant for a new file never becomes an allow ACE, and the approval the user gave does nothing. A grant for an existing file or a directory works. On macOS and Linux the same approved write succeeds.

Expected

An approved write to a file that does not exist yet lets that file be created, without a second approval.

Suggested fix

For a write grant whose path does not exist, grant creation of that one entry in its nearest existing parent (for example an allow ACE on the parent limited to FILE_ADD_FILE, then the file's own ACE once it exists), or have request_permissions refuse a file path that does not exist so the model asks for what the sandbox can grant. A test that grants write on a not-yet-existing file under a temp directory and then creates it from the sandboxed command would catch this.

Activity

  1. added
    bug
    CLI
    windows-os
    sandbox
    on Oct 30, 2026
  2. github-actions commented on Oct 30, 2026

    @github-actions
    Contributor

    Potential duplicates detected. Please review them and close your issue if it is a duplicate.

    Powered by Codex Action

  3. hesong12 commented on Nov 1, 2026

    @hesong12
    Author

    Implementation proposal (not tested on Windows; we found no way to put the grant on a name that does not exist yet, so this is the shape we think keeps it exact).

    NTFS has no ACE for "this one future child", and FILE_ADD_FILE on the parent would also allow unapproved siblings (as noted above). To keep the grant to the exact file:

    1. In compute_allow_paths_for_permissions and canonical_existing, when a write grant names a file whose parent exists and which does not exist itself, create it empty as the signed-in user, before the sandbox ACLs are applied. Refuse the grant (do not widen it) if the parent does not exist, the parent is a reparse point, or the path is a directory.
    2. Then the existing path applies the normal allow ACE to that now-existing file. Nothing is granted on the parent.

    Trade-off: an approved path that the command never writes is left as an empty file. That is visible to the person who approved it, and it is the same file they approved.

    Test (in the existing windows-sandbox-rs style): grant write on a missing brief.docx under a temp directory, then from the sandboxed command check that

    • creating/overwriting brief.docx succeeds with no second grant;
    • creating other.txt next to it, creating a new directory next to it, and replacing an existing sibling file are all denied;
    • a grant whose parent is missing is rejected.

    Refs this issue. Happy to be told a different mechanism is preferred.

  4. r266-tech commented on Nov 1, 2026

    @r266-tech

    I checked the current main implementation at 67f0994b532b8740f14b5b738af7b7b2a915b1d6 and found two filtering layers that a fix needs to keep consistent:

    Fixing only one path could make the same approved grant work in one sandbox mode and disappear in another. The regression should therefore cover both the direct allow computation and the setup/refresh payload. For the exact-file approach, the useful negative controls are: an approved missing brief.docx can be created once; an unapproved sibling, a new sibling directory, and a reparse-point/path substitution remain denied. If Windows cannot express a future-child grant without widening to the parent, rejecting that exact-file request as unsupported is safer than silently granting FILE_ADD_FILE on the parent. This is source-level analysis; I have not run Windows locally.

  5. jadibdev commented on Nov 3, 2026

    @jadibdev

    We picked up @hesong12's placeholder sketch and turned it into a tested patch. @84dnnvbdvp-debug's point about FILE_ADD_FILE and @r266-tech's trace of the two exists() filters set the constraints. The short version: it works on both Windows backends, it stays inside codex-windows-sandbox, and it has one trade-off you should decide on before anything else.

    The trade-off first

    FileSystemSandboxEntry doesn't say whether a missing path is a file or a directory, so the placeholder has to guess, and it guesses "file". For a missing grant outside every writable root that was meant as a directory (#58118, or an external writable_roots entry), mkdir goes from access denied to already exists, and an empty file stays at that path until someone deletes it. Missing paths under an already-writable root (workspace subdirectories, %TEMP%) are left alone, because the child can create those itself.

    If it were our call, we'd add an optional target kind (File | Directory) to FileSystemSandboxEntry. That settles #58118 properly, and it would line Windows up with Seatbelt, which already treats a missing root as a directory (seatbelt.rs:468-469). We also looked at scoping placeholders to request_permissions approvals, but #58118 was itself an approved grant, so that only protects static writable_roots. We kept the patch out of codex-protocol and codex-core so the choice stays yours.

    Root cause

    An approved grant for a missing file (say C:\Users\<user>\Desktop\brief.docx) survives policy resolution (writable_roots_for_cwd), and then two filters drop it: allow.rs:23 and canonical_existing in setup.rs:547. The second one applies even when write_roots_override is set. The child ends up with no ACE on the file and no FILE_ADD_FILE on Desktop, so the write fails and the prompt comes back. When the file is the only writable root (elevated backend), setup bails with "workspace-write sandbox has no writable root capability SIDs".

    What changed along the way

    The sketch held up, but review turned up four changes, and each now has a test:

    • Where the file gets created. Creating it inside compute_allow_paths_for_permissions / canonical_existing turned out to be the wrong place. Those run several times per launch (desktop hashing, deny planning) and before the sensitive-root filters (.ssh, CODEX_HOME/.sandbox*). So the patch creates the file once, in spawn_prep.rs, after filtering. That follows the existing "carveouts must exist before the command starts" pattern, and allow.rs and setup.rs stay untouched.
    • The handle we hold. Our first version kept a DELETE handle so it could roll back, and committed just before spawn. Moving the commit to after a successful spawn, so a failed launch doesn't leave a file behind, exposed a problem. DELETE takes part in sharing checks, so for that short window any writer that omits FILE_SHARE_DELETE (CRT fopen, Office) would have hit a sharing violation. Now the handle holds only FILE_READ_ATTRIBUTES | SYNCHRONIZE, and rollback gets DELETE through ReOpenFile on the same file object. It deletes only if the file is still empty, and leaves it alone if someone else has it open.
    • Which grants get a placeholder. We skip grants whose parent is already writable, since the child can create those itself, as a file or a directory. Our first version asked the policy whether the parent was writable, and that brought this exact bug back when cwd == USERPROFILE. The policy says the profile is writable, but setup filters USERPROFILE itself out of the writable roots. Now each launch passes in the roots it actually grants ACLs on, and there's a test for the USERPROFILE case.
    • Junctions anywhere in the path, not just the parent. The file is created with NtCreateFile (FILE_CREATE, OBJ_DONT_REPARSE) relative to a parent opened through no_reparse_dir, so a junction at any ancestor is rejected. Tests cover both the parent and an ancestor.

    Things that surprised us while testing

    • The elevated backend runs fine on GitHub-hosted runners. We had assumed it couldn't, because the existing elevated test failed there with CreateProcessWithLogonW failed: 2. Setup was actually working: it created the accounts and installed the WFP filters. The command runner just wasn't next to the test binary, which is where helper_materialization.rs looks for it (target\debug\deps under cargo test). Once we copied codex-command-runner.exe and codex-windows-sandbox-setup.exe there, both elevated tests pass. That may be handy for anyone testing this crate on Actions.
    • cmd.exe made our first negative tests lie. A denied > redirection leaves ERRORLEVEL at 0, so "sibling write is denied" passed even when it shouldn't have, and inline \" quoting in /c arguments isn't understood at all. The tests now run small .cmd scripts with paths in environment variables, the same pattern the existing unified_exec tests use, and check results with if exist.
    • One upstream test poisons the rest on hosted runners. legacy_capture_cancellation_terminates_descendants_without_timeout fails a timing assertion there even on unmodified main, and it poisons LEGACY_PROCESS_TEST_LOCK for every test that shares that lock.

    Results

    On GitHub-hosted windows-latest (Windows 10.0.26100, NTFS), running cargo test -p codex-windows-sandbox --no-fail-fast:

    • Unmodified main (f7167ac, run 41657662694): test result: FAILED. 267 passed; 9 failed; 5 ignored
    • With the patch (0c60964, run 41657650124): test result: FAILED. 292 passed; 10 failed; 5 ignored
    • Elevated tests on their own, with the patch: test result: ok. 2 passed; 0 failed

    None of the failures come from the patch. On both sides they're the cancellation timing test above and uninstall_windows::…::profile_cleanup_preserves_account_until_profile_can_be_deleted (registry error 1018, which looks flaky), plus the tests poisoned behind them. The tenth failure with the patch is the existing elevated test landing behind the poisoned lock: our new elevated test holds that lock for a couple of seconds. On their own, both elevated tests pass.

    Write patterns with a single-file grant, and what the tests cover
    Pattern Result
    In-place write (Set-Content, echo >, open(path, "w"), python-docx) Works
    Copy-overwrite (copy /Y, Copy-Item, CopyFileW) Works
    Temp file + rename (os.replace, sibling .tmp) Denied: needs FILE_ADD_FILE on the parent
    Delete then recreate in one command Delete works; recreate denied
    Exclusive create (CreateNew, O_EXCL, New-Item without -Force) Fails: already exists

    What the new tests cover:

    With placeholder creation switched off, the end-to-end, write-pattern, #58118, USERPROFILE, junction and wrapper tests all fail.

    Where we're least sure

    • The wrapper's elevated branch. create_windows_sandbox_command_args_for_permission_profile decides "parent already writable" with the legacy root calculation, while its ACLs come from effective_write_roots_for_permissions. The two only differ with a split write_roots_override, and the inner launch recomputes anyway, but we haven't exercised that combination.
    • Untested paths. We haven't tested ReFS, or \\?\-prefixed spellings of missing paths.

    The reference patch is one commit touching 12 files in codex-windows-sandbox: jadibdev@0c60964

    Would you want the protocol target kind as the real fix for #58118? If so, we're glad to sketch it. Or is a Windows-only placeholder like this the direction you'd take for #58433 on its own?

  6. r266-tech commented on Nov 3, 2026

    @r266-tech

    My recommendation is to model the target kind explicitly and handle these two reports through that contract. #58433 is a missing file; #58118 is a missing directory. The current public FileSystemSandboxEntry carries only path and access, while core's missing_path_behavior currently expresses Skip, not file-versus-directory intent. A Windows placeholder can make the exact-file case work, but the known directory regression follows from having to guess.

    I would add a File | Directory target kind to the permission entry and preserve it through the permission request/result, stored turn grant, and executor payload. For an existing path, the declared kind can be checked against metadata. For a missing path with no kind, return an actionable unsupported/ambiguous-target result rather than infer from existence or grant the parent.

    The tested placeholder is useful evidence for the declared-File case and its exact-file ACL approach. I would treat it as a Windows implementation detail only after the caller has declared File, not as the general missing-path behavior. Acceptance should cover both reports: a missing file can be written while an unapproved sibling/new directory stays denied, and a missing directory can be created without leaving a sentinel file. Keep the reparse/path-substitution checks on both Windows backends. I have not run these Windows tests locally.

    Sources:

    #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
    #[serde(rename_all = "camelCase")]
    #[ts(export_to = "v2/")]
    pub struct FileSystemSandboxEntry {
    pub path: FileSystemPath,
    pub access: FileSystemAccessMode,
    }
    // TODO(anp): Remove this conversion once core permission paths use PathUri.
    impl From<CoreFileSystemSandboxEntry> for FileSystemSandboxEntry {
    fn from(value: CoreFileSystemSandboxEntry) -> Self {
    Self {
    path: value.path.into(),
    access: value.access.into(),
    }
    }
    }
    impl TryFrom<FileSystemSandboxEntry> for CoreFileSystemSandboxEntry {
    type Error = io::Error;
    fn try_from(value: FileSystemSandboxEntry) -> Result<Self, Self::Error> {
    Ok(Self {
    path: value.path.try_into()?,
    access: value.access.to_core(),
    missing_path_behavior: None,
    })
    and
    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
    pub struct FileSystemSandboxEntry {
    pub path: FileSystemPath,
    pub access: FileSystemAccessMode,
    pub missing_path_behavior: Option<FileSystemSandboxEntryMissingPathBehavior>,
    }
    /// Serialized filesystem entry used at legacy string-based seams.
    #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema, TS)]
    #[schemars(rename = "FileSystemSandboxEntry")]
    #[ts(rename = "FileSystemSandboxEntry")]
    pub struct RawFileSystemSandboxEntry {
    pub path: RawFileSystemPath,
    pub access: FileSystemAccessMode,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[ts(optional)]
    pub missing_path_behavior: Option<FileSystemSandboxEntryMissingPathBehavior>,
    }
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema, TS)]
    #[serde(rename_all = "snake_case")]
    pub enum FileSystemSandboxEntryMissingPathBehavior {
    Skip,
    }
    impl FileSystemSandboxEntry {
    pub fn new(path: FileSystemPath, access: FileSystemAccessMode) -> Self {
    Self {
    path,
    access,
    missing_path_behavior: None,
    }
    }
    pub fn skip_missing_path(path: FileSystemPath, access: FileSystemAccessMode) -> Self {
    Self {
    path,
    access,
    missing_path_behavior: Some(FileSystemSandboxEntryMissingPathBehavior::Skip),
    }
    }
    pub fn skips_missing_path(&self) -> bool {
    self.missing_path_behavior == Some(FileSystemSandboxEntryMissingPathBehavior::Skip)
    }

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    CLIbugsandboxwindows-os

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions