codex icon indicating copy to clipboard operation
codex copied to clipboard

Windows execpolicy false positive when Start-Process and an unrelated URL appear in the same PowerShell script

Open keyou opened this issue 3 months ago • 50 comments

What version of Codex CLI is running?

codex-cli 0.146.0

The failure was reproduced on 0.146.0. I also checked the latest stable release, 0.149.0, and the current main branch; both still contain the same relevant classifier logic described below.

What subscription do you have?

Pro

Which model were you using?

gpt-5.6-sol

What platform is your computer?

Microsoft Windows NT 10.0.26100.0 x64 (Windows 11 Professional)

What terminal emulator and version are you using (if applicable)?

Windows Terminal, PowerShell 7.6.3

Codex doctor report

The full report contains private local paths, so the relevant redacted fields are included below. All relevant runtime, config, auth, sandbox, and installation checks were OK; the overall warning was an unrelated update-status warning.

{
  "schemaVersion": 1,
  "overallStatus": "warning",
  "codexVersion": "0.146.0",
  "runtime": {
    "platform": "windows-x86_64",
    "installMethod": "npm"
  },
  "config": {
    "model": "gpt-5.6-sol",
    "modelProvider": "openai"
  },
  "system": {
    "os": "Windows 10.0.26100 (Windows 11 Professional) [64-bit]"
  },
  "terminal": {
    "terminal": "Windows Terminal",
    "powershell": "7.6.3"
  }
}

What issue are you seeing?

On Windows, execpolicy falsely classifies a benign compound PowerShell script as a dangerous URL launch when the script contains both:

  1. a local Start-Process invocation with no URL argument, and
  2. an unrelated Invoke-RestMethod call to an HTTP URL later in the script.

With approval policy never, Codex rejects the command before PowerShell starts:

"C:\Program Files\PowerShell\7\pwsh.exe" -Command '...'
rejected: blocked by policy

The rejection is immediate (Wall time 0.0 seconds). Running the local Start-Process command by itself succeeds, and running the HTTP probe by itself succeeds. Combining them in one PowerShell script triggers the rejection.

This affects a common local-development pattern: start a local application or development server, then poll its loopback health/CDP endpoint until it is ready.

What steps can reproduce the bug?

  1. Run Codex on Windows with approvals disabled, for example:

    codex -a never -s danger-full-access
    
  2. Ask Codex to execute this single PowerShell tool command:

    $process = Start-Process `
      -FilePath "$env:SystemRoot\System32\cmd.exe" `
      -ArgumentList @('/c', 'exit', '0') `
      -WindowStyle Hidden `
      -PassThru
    
    try {
      Invoke-RestMethod `
        -Uri 'http://127.0.0.1:9/health' `
        -TimeoutSec 1
    } catch {}
    
    $process.Id
    
  3. Observe that Codex rejects the entire command with rejected: blocked by policy before pwsh.exe runs.

  4. Execute the Start-Process portion and the Invoke-RestMethod portion as two separate Codex tool calls. Both are allowed, confirming that the combination is what triggers the false positive.

What is the expected behavior?

Execpolicy should only classify Start-Process as a dangerous URL/ShellExecute launch when an HTTP/HTTPS URL is an argument of that Start-Process invocation (or otherwise belongs to the same command expression).

An unrelated URL used by a separate Invoke-RestMethod command should not cause a local executable launch to be rejected.

The truly dangerous case must remain blocked:

Start-Process 'https://example.com'

Additional information

The apparent root cause is in is_dangerous_powershell_words. It computes has_url across the full flattened token list and independently checks whether any token contains start-process:

https://github.com/openai/codex/blob/rust-v0.149.0/codex-rs/shell-command/src/command_safety/windows_dangerous_commands.rs#L36-L52

As a result, the URL and Start-Process token do not need to belong to the same command. The same implementation is still present on main:

https://github.com/openai/codex/blob/main/codex-rs/shell-command/src/command_safety/windows_dangerous_commands.rs#L36-L52

When the heuristic marks the command dangerous and approval_policy is never, the decision becomes Forbidden:

https://github.com/openai/codex/blob/rust-v0.149.0/codex-rs/core/src/exec_policy.rs#L728-L741

A regression test could assert that this is not dangerous:

Start-Process local.exe; Invoke-RestMethod http://127.0.0.1:1234/health

while preserving the existing test that Start-Process 'https://example.com' is dangerous. A robust fix would associate URL arguments with the specific PowerShell command/AST node rather than scanning the whole script token set.

Related PowerShell execpolicy/parser reports, but not duplicates of this false positive:

  • https://github.com/openai/codex/issues/13502
  • https://github.com/openai/codex/issues/24201

keyou avatar Aug 22 '26 04:08 keyou

Additional Windows desktop occurrence, observed on 2026-08-27. This appears closely related, with one variation: the unrelated HTTPS URL was an environment configuration value, not a health-probe URL.

Environment

  • Installed desktop package: OpenAI.Codex 26.820.9563.0.
  • Version reported by the executable of the running desktop app-server process: codex-cli 0.150.0-alpha.8.
  • Separately installed npm CLI: codex-cli 0.117.0. This is not the running desktop app-server version above.
  • Microsoft Windows NT 10.0.26200.0, x64; tool shell PowerShell 7.6.4.
  • Task permission context and relevant user/project config entries: sandbox_mode = "danger-full-access", approval_policy = "never".
  • Existing local checkout; no new branch or worktree.

Observed operation

The user authorized an isolated loopback QA backend while preserving the existing development server and user data. One PowerShell tool invocation combined unused-port/non-existing-directory checks, isolated QA storage creation, process-local test environment assignments, and a local Python/Uvicorn launch with Start-Process -WindowStyle Hidden and redirected logs.

Abbreviated, redacted command shape below. This is not a verified minimal reproduction: paths and the API-base value are placeholders; the original invocation also contained the checks and other assignments described above.

$env:LLM_API_BASE_URL = 'https://example.invalid/v1'

Start-Process `
  -FilePath '<project>\.venv\Scripts\python.exe' `
  -ArgumentList @('-m', 'uvicorn', 'backend.app.main:app',
                  '--host', '127.0.0.1', '--port', '8167', '--no-access-log') `
  -WorkingDirectory '<project>' `
  -WindowStyle Hidden `
  -RedirectStandardOutput '<isolated-qa>\backend.stdout.log' `
  -RedirectStandardError '<isolated-qa>\backend.stderr.log' `
  -PassThru

The URL was not an argument to Start-Process. It was child-backend configuration; no URL/ShellExecute launch was intended. No API key literal was present in the command.

Actual result

The entire tool invocation was rejected before PowerShell was created:

CreateProcess { message: "Rejected(... rejected: blocked by policy)" }
Wall time 0.0 seconds

Explicit user re-authorization and repetition of the same launch request did not change the result. No QA runtime directory or QA listeners were created. The existing server was unchanged; frontend launch and browser acceptance tests were not attempted.

An additional diagnostic placed the original command in a single-quoted here-string and passed it as data to codex execpolicy check --rules ... -- pwsh.exe -Command <command>. That outer tool invocation was also rejected before execution. This is not an execpolicy check verdict: the checker never ran and no matched-rule information was obtained.

Successful controls and limits

  • File reads/edits, git status, Python tests and production frontend builds succeeded in the same task; version-only CLI invocations also succeeded.
  • No permission/rule files were changed and no alternate execution path was used to get around the refusal.
  • Fresh-task reproduction, minimized positive/negative controls, and split-command comparison have not been performed for this occurrence.
  • The effective host-side rejection reason is unknown. The classifier code linked in this issue is consistent with our command shape, but this comment does not establish which classifier/rule the running desktop build actually used.

Please check whether this is the same whole-script Start-Process + unrelated-URL heuristic in the desktop app-server version above. An actionable denial reason/rule identifier would help distinguish an intended restriction from a false positive without changing safety settings. Protection against actual URL/ShellExecute launches should remain intact.

No private project name, username, real local path, credentials, customer data, full config file, or session transcript is included.

Generoustandard avatar Aug 27 '26 11:08 Generoustandard

Additional sanitized Windows desktop occurrence observed on 2026-09-04. The command shape appears closely related to this issue, including the environment-variable URL variant in the earlier comment. The effective denying rule/classifier has not been confirmed for this occurrence.

Environment

  • Windows 11 Home, build 26200.
  • Desktop package initially OpenAI.Codex 26.901.1978.0; the same rejection persisted after a normal user restart also updated the package to 26.901.2854.0.
  • The affected task's persisted engine-version field reports 0.153.0-alpha.5; this is task metadata, not an independent version query of the post-update executable.
  • Full access was selected in the UI. The exact rejected turn's persisted context also records sandbox_policy.type=danger-full-access, permission_profile.type=disabled, approval_policy=never, and approvals_reviewer=user.

Observed operation

The user authorized a local-only development-server launch. A compound PowerShell tool invocation checked unused ports and fresh log paths, set frontend environment variables, and used Start-Process to launch the installed local Node/Vite entry point on loopback.

The HTTP URL was assigned to VITE_API_PROXY_TARGET; it was not an argument to Start-Process and no URL/ShellExecute browser launch was intended.

Abbreviated, path-redacted shape below, not a separately tested minimal reproduction. The original invocation also contained the preflight checks, Git revision lookup, and additional frontend environment assignments described above.

$env:VITE_API_PROXY_TARGET = 'http://127.0.0.1:30121'
$env:VITE_USE_PROXY = 'true'
$node = (Get-Command node.exe -ErrorAction Stop).Source
$vite = Join-Path '<local-project>' 'node_modules\vite\bin\vite.js'

Start-Process -FilePath $node `
  -ArgumentList @($vite, '--mode', 'local-debug', '--force',
                  '--host', '127.0.0.1', '--port', '18121', '--strictPort') `
  -WorkingDirectory '<local-project>' `
  -WindowStyle Hidden `
  -RedirectStandardOutput '<local-runtime>\frontend.stdout.log' `
  -RedirectStandardError '<local-runtime>\frontend.stderr.log' `
  -PassThru

Actual result and checks

The tool returned immediately, before the submitted PowerShell command executed:

exec_command failed: CreateProcess { message: "Rejected(... rejected: blocked by policy)" }
Wall time 0.0 seconds
  • No startup logs or requested listener were created. The same invocation still failed after the desktop update above.
  • Adjacent ordinary file/Git/process checks succeeded; historical local launches had succeeded. This report does not claim that every process launch is blocked.
  • The inspected user rule file contains allow entries and no explicit prompt/forbidden entries. This is not an inventory of the complete effective policy.
  • The returned error and inspected local logs supplied no matching rule ID, policy source, or actionable decision rationale.
  • No permission/rule files were changed, and no split-command or alternative-launch workaround was executed. No clean-workspace or minimized positive/negative comparison has been established for this occurrence.

Could maintainers confirm whether the whole-script Start-Process plus unrelated-URL classification discussed here applies to these desktop versions, and identify a supported fix or review path? If this action is intentionally restricted, an explicit reason would help distinguish that from a false positive. Protection against actual unsafe URL/ShellExecute launches should remain intact.

No private project identifiers, personal filesystem paths, credentials, database contents, raw logs, task/session IDs, or complete conversation are included. This comment is submitted with the account owner's permission.

SANDRA136252 avatar Sep 04 '26 05:09 SANDRA136252

Additional sanitized Windows desktop occurrence observed on 2026-09-04 UTC (2026-09-05 locally). This is consistent with the command shape in this issue; the effective denying rule has not been confirmed.

Environment:

  • Desktop package observed after the incident: OpenAI.Codex 26.901.5003.0.
  • Read-only --version query of the executable belonging to the currently running desktop app-server: codex-cli 0.153.3. This is a post-incident query, not proof of the exact incident-time engine version.
  • The rejected turn's persisted context records approval_policy=never and sandbox_policy.type=danger-full-access.

Observed operation: A single PowerShell tool invocation performed loopback-only HTTP status/model-identity probes, checked local resource availability and fresh log paths, and then used Start-Process -WindowStyle Hidden to launch an existing local PowerShell test script with redirected stdout/stderr. The HTTP URLs belonged to the status probes; they were not arguments to Start-Process.

The entire invocation was rejected immediately:

exec_command failed: CreateProcess { message: "Rejected(... rejected: blocked by policy)" }
Wall time 0.0 seconds

No launcher logs or new local-model inference calls were produced. Ordinary read-only file, Git, and version queries work. The returned error and inspected logs provided no rule identifier or actionable rationale.

The current upstream is_dangerous_powershell_words implementation still checks for a URL anywhere in the flattened token list alongside Start-Process. This is supporting evidence, not confirmation of which rule the desktop build applied.

No permission settings or rule files were changed, and no split-command, alternative-launch, or retry workaround was executed. A minimized reproduction has not been run for this occurrence.

Could maintainers confirm whether this is the same classifier issue and identify a supported fix or review path? Protection against unsafe URL/ShellExecute launches should remain intact.

Submitted with the user's authorization. No private project identifiers, personal paths, credentials, model prompts/responses, raw logs, or task/session IDs are included.

baul9265-a11y avatar Sep 05 '26 02:09 baul9265-a11y

Confirmed another occurrence on Windows desktop with codex-cli 0.153.4 (desktop package OpenAI.Codex 26.901.5280.0), with a proposed source fix and regression tests below.

Observed failure

The rejected invocation configured a loopback origin in an environment variable and launched a local server executable. The URL was not an argument to the launch command. The following is a sanitized representation, not a separately executed minimal reproduction:

$env:APP_PORT='18081'
$env:APP_PUBLIC_ORIGIN='http://127.0.0.1:18081'
$p=Start-Process -FilePath 'C:/app/server.exe' -WorkingDirectory 'C:/app' -WindowStyle Hidden -RedirectStandardOutput 'C:/app/server.stdout.log' -RedirectStandardError 'C:/app/server.stderr.log' -PassThru
$p.Id | Set-Content 'C:/app/server.pid'

The tool rejected the invocation before creating PowerShell:

exec_command failed: CreateProcess { message: "Rejected(... rejected: blocked by policy)" }

The corresponding runtime log records approval_policy=Never and sandbox_policy=DangerFullAccess. Reauthorization did not resolve it. The returned error does not identify a rule. Source inspection at the matching tag shows that the flattened token scan associates the environment URL with Start-Process, and a dangerous classification with Never leads to Forbidden. This establishes the source-level false positive; the production binary was not instrumented to prove its internal call path.

Proposed patch

Base: rust-v0.153.4, commit 3d2ee51ca2d5db578f328aa75e20aa22c0197c9a.

  • Use the existing PowerShell tree-sitter parser to associate URL arguments with literal command spans, including commands in assignments.
  • Refine only when all launch mentions map to actual literal command names. Dynamic arguments/names, alias definitions, stored script text, COM dispatch and parse errors keep the existing conservative fallback.
  • Keep force-delete detection and core permission/approval decisions unchanged. No dependency or policy configuration changes.

Validation: just test -p codex-shell-command with Rust 1.95.0 in a Linux container: 170 passed, 0 skipped. Three new tests cover 28 command strings, including unrelated environment/probe URLs, actual URL launches, dynamic launch targets, COM, stored scripts, quoted delimiters and parse failures. just fmt and git diff --check passed. These are classifier tests on strings, not execution of the fixture commands or Windows desktop integration tests.

This is a candidate for maintainer review, not a claim of comprehensive PowerShell safety verification. It has not been installed into the desktop executor. Please review the classification change and advise on an official release/update path for desktop users. An actionable denial reason identifying the heuristic would also help.

Full source diff follows (without local paths, raw logs, credentials or Git author metadata).

Candidate source patch and tests
diff --git a/codex-rs/shell-command/src/command_safety/mod.rs b/codex-rs/shell-command/src/command_safety/mod.rs
index 44d0103..c359d8f 100644
--- a/codex-rs/shell-command/src/command_safety/mod.rs
+++ b/codex-rs/shell-command/src/command_safety/mod.rs
@@ -6,4 +6,5 @@ mod powershell_parser;
 mod powershell_tree_sitter;
 
 pub mod is_dangerous_command;
+pub(crate) use powershell_tree_sitter::try_parse_powershell_command_scopes;
 pub(crate) use powershell_tree_sitter::try_parse_powershell_commands;
diff --git a/codex-rs/shell-command/src/command_safety/powershell_tree_sitter.rs b/codex-rs/shell-command/src/command_safety/powershell_tree_sitter.rs
index a904e92..ff86700 100644
--- a/codex-rs/shell-command/src/command_safety/powershell_tree_sitter.rs
+++ b/codex-rs/shell-command/src/command_safety/powershell_tree_sitter.rs
@@ -14,6 +14,46 @@ pub(crate) fn try_parse_powershell_commands(script: &str) -> Option<Vec<Vec<Stri
     lower_with_tree_sitter(script).ok()
 }
 
+/// Extract command spans for URL-launch classification, including commands inside assignments.
+/// This does not lower or authorize the enclosing script. Unknown command names and parse
+/// errors stay opaque so callers retain their conservative fallback.
+pub(crate) fn try_parse_powershell_command_scopes(script: &str) -> Option<Vec<Vec<String>>> {
+    if script
+        .chars()
+        .any(|ch| matches!(ch, '‘' | '’' | '“' | '”' | '–' | '—' | '―'))
+    {
+        return None;
+    }
+    let mut parser = Parser::new();
+    parser
+        .set_language(&tree_sitter_powershell::LANGUAGE.into())
+        .ok()?;
+    let tree = parser.parse(script, /*old_tree*/ None)?;
+    let root = tree.root_node();
+    if root.has_error() || has_requires_directive(root, script) {
+        return None;
+    }
+    let mut nodes = Vec::new();
+    collect_command_nodes(root, &mut nodes);
+    if nodes.is_empty() {
+        return None;
+    }
+    nodes
+        .into_iter()
+        .map(|node| {
+            let mut cursor = node.walk();
+            let name = node
+                .named_children(&mut cursor)
+                .find(|child| child.kind() == "command_name")?;
+            let name = name.utf8_text(script.as_bytes()).ok()?;
+            if name.contains(['$', '`']) {
+                return None;
+            }
+            lower_command_text(node.utf8_text(script.as_bytes()).ok()?).ok()
+        })
+        .collect()
+}
+
 fn lower_with_tree_sitter(script: &str) -> Result<Vec<Vec<String>>, String> {
     // PowerShell treats these Unicode characters as syntax aliases even when tree-sitter leaves
     // them inside generic tokens. Keep that whole spelling family opaque rather than guessing at
diff --git a/codex-rs/shell-command/src/command_safety/windows_dangerous_commands.rs b/codex-rs/shell-command/src/command_safety/windows_dangerous_commands.rs
index cc1ae67..db969a7 100644
--- a/codex-rs/shell-command/src/command_safety/windows_dangerous_commands.rs
+++ b/codex-rs/shell-command/src/command_safety/windows_dangerous_commands.rs
@@ -25,13 +25,56 @@ fn is_dangerous_powershell(command: &[String]) -> bool {
     if !is_powershell_executable(exe) {
         return false;
     }
-    // Parse the PowerShell invocation to get a flat token list we can scan for
-    // dangerous cmdlets/COM calls plus any URL-looking arguments. This is a
-    // best-effort shlex split of the script text, not a full PS parser.
+    // Keep command boundaries when the grammar can establish them. Flattening a
+    // compound script associates local process launches with unrelated URLs.
     let Some(parsed) = parse_powershell_invocation(rest) else {
         return false;
     };
 
+    if let Some(script) = parsed.script.as_deref()
+        && let Some(scopes) = crate::command_safety::try_parse_powershell_command_scopes(script)
+    {
+        let tokens_lc: Vec<String> = parsed
+            .tokens
+            .iter()
+            .map(|word| word.to_ascii_lowercase())
+            .collect();
+        // Refine only when every launch mention belongs to a literal command
+        // name. Stored script text, alias definitions and COM/method dispatch
+        // still use the original fallback; they can execute outside these spans.
+        let launch_word = |word: &str| {
+            let word = word
+                .trim_matches('\'')
+                .trim_matches('"')
+                .to_ascii_lowercase();
+            matches!(word.as_str(), "start" | "saps" | "ii")
+                || word.contains("start-process")
+                || word.contains("invoke-item")
+                || word.contains("rundll32")
+                || word.contains("mshta")
+                || word.contains("explorer")
+                || is_browser_executable(&word)
+        };
+        let mentions = parsed
+            .tokens
+            .iter()
+            .filter(|word| launch_word(word))
+            .count();
+        let commands = scopes
+            .iter()
+            .filter(|words| words.first().is_some_and(|word| launch_word(word)))
+            .count();
+        if mentions == commands
+            && !tokens_lc
+                .iter()
+                .any(|word| word.contains("shellexecute") || word.contains("shell.application"))
+        {
+            return has_force_delete_cmdlet(&tokens_lc)
+                || scopes
+                    .iter()
+                    .any(|words| is_dangerous_powershell_words(words));
+        }
+    }
     is_dangerous_powershell_words(&parsed.tokens)
 }
 
@@ -367,6 +410,7 @@ fn is_browser_executable(name: &str) -> bool {
 
 struct ParsedPowershell {
     tokens: Vec<String>,
+    script: Option<String>,
 }
 
 fn parse_powershell_invocation(args: &[String]) -> Option<ParsedPowershell> {
@@ -385,7 +429,10 @@ fn parse_powershell_invocation(args: &[String]) -> Option<ParsedPowershell> {
                     return None;
                 }
                 let tokens = shlex_split(script)?;
-                return Some(ParsedPowershell { tokens });
+                return Some(ParsedPowershell {
+                    tokens,
+                    script: Some(script.clone()),
+                });
             }
             _ if lower.starts_with("-command:") || lower.starts_with("/command:") => {
                 if idx + 1 != args.len() {
@@ -393,7 +440,10 @@ fn parse_powershell_invocation(args: &[String]) -> Option<ParsedPowershell> {
                 }
                 let (_, script) = arg.split_once(':')?;
                 let tokens = shlex_split(script)?;
-                return Some(ParsedPowershell { tokens });
+                return Some(ParsedPowershell {
+                    tokens,
+                    script: Some(script.to_string()),
+                });
             }
             "-nologo" | "-noprofile" | "-noninteractive" | "-mta" | "-sta" => {
                 idx += 1;
@@ -403,7 +453,10 @@ fn parse_powershell_invocation(args: &[String]) -> Option<ParsedPowershell> {
             }
             _ => {
                 let rest = args[idx..].to_vec();
-                return Some(ParsedPowershell { tokens: rest });
+                return Some(ParsedPowershell {
+                    tokens: rest,
+                    script: None,
+                });
             }
         }
     }
@@ -414,6 +467,7 @@ fn parse_powershell_invocation(args: &[String]) -> Option<ParsedPowershell> {
 #[cfg(test)]
 mod tests {
     use super::is_dangerous_command_windows;
+    use pretty_assertions::assert_eq;
 
     fn vec_str(items: &[&str]) -> Vec<String> {
         items.iter().map(std::string::ToString::to_string).collect()
@@ -460,6 +514,70 @@ mod tests {
         ])));
     }
 
+    #[test]
+    fn powershell_local_launch_does_not_consume_other_command_urls() {
+        for script in [
+            "$env:ORIGIN='http://127.0.0.1:18081'; $p=Start-Process -FilePath 'C:/app/server.exe' -WindowStyle Hidden -PassThru; $p.Id | Set-Content 'C:/app/server.pid'",
+            "$p = Start-Process local.exe; Invoke-RestMethod 'http://127.0.0.1:18081/health'",
+            "Invoke-RestMethod 'https://example.com'; $p=Start-Process local.exe",
+            "if ($true) { $p=Start-Process local.exe }; Write-Output 'https://example.com'",
+            "# Start-Process\n$uri='https://example.com'; Write-Output 'local'",
+            "$uri='https://example.com'; start local.exe",
+            "$uri='https://example.com'; saps local.exe",
+            "$uri='https://example.com'; ii 'C:/app/readme.txt'",
+        ] {
+            assert_eq!(
+                is_dangerous_command_windows(&vec_str(&["pwsh.exe", "-Command", script])),
+                false,
+                "{script}"
+            );
+        }
+    }
+
+    #[test]
+    fn powershell_scoped_launch_retains_url_and_dynamic_target_checks() {
+        for script in [
+            "$p=Start-Process 'https://example.com'; Write-Output 'done'",
+            "$p=Start-Process local.exe; Start-Process 'https://example.com'",
+            "if ($true) { Start-Process 'https://example.com' }",
+            "Write-Output $(Start-Process 'https://example.com')",
+            "start 'https://example.com'",
+            "saps 'https://example.com'",
+            "Invoke-Item 'https://example.com'",
+            "ii 'https://example.com'",
+            "$url='https://example.com'; Start-Process $url",
+            "$launcher='Start-Process'; & $launcher 'https://example.com'",
+            "$url='https://example.com'; Start-Process local.exe -ArgumentList $url",
+            "$url='https://example.com'; (New-Object -ComObject Shell.Application).ShellExecute($url)",
+            "Invoke-Expression 'Start-Process https://example.com'",
+            "Set-Alias go Start-Process; go 'https://example.com'",
+            "$code='Start-Process https://example.com'; [scriptblock]::Create($code).Invoke(); Write-Output done",
+            "$p=Start-Process local.exe; Remove-Item 'C:/tmp/file.txt' -Force; Write-Output 'https://example.com'",
+        ] {
+            assert_eq!(
+                is_dangerous_command_windows(&vec_str(&["pwsh.exe", "-Command", script])),
+                true,
+                "{script}"
+            );
+        }
+    }
+
+    #[test]
+    fn powershell_command_scope_preserves_quoted_arguments_and_fallbacks() {
+        for script in [
+            "Start-Process 'https://example.com/a;b'",
+            "Start-Process 'https://example.com/a|b'",
+            "Start-Process 'https://example.com/a&b'",
+            "Start-Process 'https://example.com'; if (",
+        ] {
+            assert_eq!(
+                is_dangerous_command_windows(&vec_str(&["pwsh.exe", "-Command", script])),
+                true,
+                "{script}"
+            );
+        }
+    }
+
     #[test]
     fn cmd_start_with_url_is_dangerous() {
         assert!(is_dangerous_command_windows(&vec_str(&[

chad20262109 avatar Sep 05 '26 11:09 chad20262109

Additional reproduction on 8 September 2026: this false positive also occurs when no process-launch command exists at all. An ordinary string argument named start is sufficient when an HTTP(S) URL appears in the same classified command. Even a single URL argument triggers rejection if its path or fully qualified domain name contains start-process or invoke-item.

Minimal live reproductions (each submitted separately):

Write-Output 'https://example.invalid/' 'start'
Write-Output 'https://start-process.example.invalid/'

Codex rejects both before PowerShell executes. These arguments are literal output data; neither command requests a URL launch.

Environment and scope

  • Native Windows Codex desktop task, with PowerShell 7 at the standard pwsh.exe installation path.
  • Task permission context: approval_policy = never, sandbox_mode = danger-full-access; filesystem access was unrestricted.
  • Reproductions were submitted directly through the task's exec_command tool. They were not merely evaluated by a separately implemented classifier.
  • codex-cli 0.153.0
  • All test commands only print literal text or Python arguments. example.invalid is used as inert data. No URL was opened, no network request was made by the test commands, and no actual Start-Process command was submitted.
  • No permission settings or rules were changed, and no installed Codex files were modified.

Live rejection and controls

The rejected calls returned an exec_command tool error with this structure, abbreviated to omit repetitive shell quoting and the local executable path:

CreateProcess { message: "Rejected(… rejected: blocked by policy)" }

The rejection occurred before the submitted command executed. Successful controls exited with code 0 and printed the expected data.

1. A noncommand start argument is enough.

Rejected:

Write-Output 'https://example.invalid/' 'start'

Both of these controls succeeded:

Write-Output 'https://example.invalid/' 'run'
Write-Output 'plain-data' 'start'

2. The same problem affects native-program arguments.

Rejected:

python -c "import sys; print(sys.argv[1:])" start https://example.invalid/

Replacing only start with run succeeded and printed ['run', 'https://example.invalid/']:

python -c "import sys; print(sys.argv[1:])" run https://example.invalid/

3. A here-string causes unrelated commands to become associated.

Rejected as a single exec_command invocation:

Write-Output @'
https://example.invalid/
'@
Write-Output 'start'

Changing the last argument to run succeeded. Keeping start but replacing the here-string URL with plain-data also succeeded.

This version was likewise rejected:

Write-Output @'
https://example.invalid/
'@
python -c "import sys; print(sys.argv[1:])" start

However, these two ordinary commands succeeded together in one tool invocation:

Write-Output 'https://example.invalid/'
Write-Output 'start'

This distinction matters: the problem is not simply that every script containing both strings is rejected. The restricted parser can preserve command boundaries for ordinary literal commands, while unsupported syntax such as here-strings sends the whole invocation through the fallback heuristic.

4. Additional token-matching controls.

Input Live result
Write-Output 'https://example.invalid/' 'START' Rejected
Write-Output 'https://example.invalid/' 'prefix-start-process-suffix' Rejected
Write-Output 'https://example.invalid/' 'restart' Passed
Write-Output 'https://example.invalid/' Passed
Write-Output 'start' Passed

5. Matching text inside the URL itself, including the FQDN.

Each row below was tested as its own exec_command call using Write-Output '<URL>'. There was no separate launch-like argument or second command.

URL passed as the only argument to Write-Output Live result
https://example.invalid/start Passed
https://start.example.invalid/ Passed
https://example.invalid/?action=start Passed
https://example.invalid/start-process Rejected
https://example.invalid/invoke-item Rejected
https://start-process.example.invalid/ Rejected
https://invoke-item.example.invalid/ Rejected
https://prefix-start-process-suffix.example.invalid/ Rejected
https://prefix-invoke-item-suffix.example.invalid/ Rejected
https://ordinary.example.invalid/ Passed

For example, this was rejected before execution:

Write-Output 'https://prefix-invoke-item-suffix.example.invalid/'

These results distinguish whole-token matching for start from substring matching for start-process and invoke-item. For the latter two, the URL token itself satisfies both the URL check and the launch-name substring check. This occurs even when the substring is embedded within a longer DNS label. No DNS lookup, network request, or browser launch is involved in printing these strings.

6. HTTP, unusual URL spellings, and other URL-like strings with a separate start argument.

Each row below was tested separately using Write-Output '<value>' 'start':

Value Live result
http://example.invalid/ Rejected
HTTP://example.invalid/ Rejected
hTtPs://example.invalid/ Rejected
http:example.invalid Rejected
https:example.invalid Rejected
http:/example.invalid Rejected
https:///example.invalid/ Rejected
prefix-http://example.invalid/ Rejected
http:// Passed
//example.invalid/ Passed
www.example.invalid Passed
example.invalid Passed
ftp://example.invalid/ Passed
file:///example.invalid/ Passed
ws://example.invalid/ Passed
mailto:[email protected] Passed
https%3A%2F%2Fexample.invalid Passed
https ://example.invalid/ Passed
httpx://example.invalid/ Passed
http://. Rejected

An additional control, Write-Output 'http://.' 'run', succeeded. Thus an especially short reproduction is:

Write-Output 'http://.' 'start'

These results are consistent with looks_like_url() in the inspected Windows classifier: it searches case-insensitively for embedded http:// or https:// prefixes, passes the resulting candidate (or the original token when no prefix is found) to url::Url::parse, and accepts the http and https schemes. Consequently, some nonstandard-looking slash forms and http://. qualify, while the tested scheme-less, encoded, and other-scheme strings do not. The matching is a syntactic classification; it does not require DNS resolution or a reachable server.

Across all live variations above, there were 46 calls: 22 rejected calls and 24 successful controls. Every rejected call returned the same generic pre-execution policy error; successful calls printed the expected data and exited with code 0. This is a bounded reproduction set, not an exhaustive syntax matrix.

Current upstream source and release status

Source inspection was performed on 8 September 2026, approximately 13:28 AWST (UTC+08:00).

  • Inspected main at 95327467c3af9533ac25b171b3496b951fe425ed, committed on 8 September 2026 at 13:12:10 AWST.
  • GitHub's latest stable release at inspection time was rust-v0.153.4, published on 5 September 2026 at 07:25:48 AWST.
  • The relevant windows_dangerous_commands.rs and powershell_tree_sitter.rs files were identical between that release and the inspected main commit. The defect remains present in both source versions; I did not separately run the released 0.153.4 binary.

The source explains the related failure modes:

  1. Argument mistaken for command. is_dangerous_powershell_words() checks for a URL anywhere in words and independently searches all words for start, start-process, saps, invoke-item, or ii. It also accepts substrings containing start-process or invoke-item. It does not require the matching word to occupy the command position. This affects even successfully lowered commands such as Write-Output ... start and python ... start ....
  2. Command boundaries lost on fallback. parse_powershell_command_into_plain_commands() delegates to the restricted Tree-sitter lowerer. The here-string fixtures explicitly expect null. When lowering returns None, commands_for_exec_policy_for_platform() retains the whole shell invocation, and parse_powershell_invocation() in the Windows dangerous-command module uses shlex to flatten the script. An unrelated URL and start argument can then be associated across commands.
  3. The URL itself mistaken for a launch command. The same is_dangerous_powershell_words() predicate includes t.contains("start-process") and t.contains("invoke-item"). A single argument such as https://start-process.example.invalid/ therefore supplies both has_url and the substring match. Associating URLs with individual commands alone would not resolve this case: the classifier also needs to distinguish the invoked command from literal argument contents.

In exec_policy.rs, render_decision_for_unmatched_command_for_platform() maps a dangerous-command match to Forbidden when approval policy is Never. DangerousCommandMatch::Other becomes the generic reason blocked by policy. tools/orchestrator.rs returns ToolError::Rejected for that forbidden requirement before running the command.

Separate source-level reproduction

In addition to the live tool calls, I compiled a small standalone Rust harness using the unchanged parser and Windows classifier files fetched from the pinned upstream commit. The harness only classified strings; it did not execute them.

It produced:

here-string URL + noncommand start: lowered=None; dangerous=true
same data, argument run: lowered=None; dangerous=false
same start, no URL: lowered=None; dangerous=false
plain program argument start + URL: lowered=Some(...); dangerous=true
actual URL launch control: lowered=Some(...); dangerous=true

The last row classified Start-Process https://example.invalid/ as a string-only positive control. That command was not executed.

Related PRs checked

I found no open or merged PR addressing this exact URL-plus-noncommand-start case in the searches and relevant file history inspected. This is a search result, not a guarantee that no unindexed or differently described work exists.

These merged PRs are related but do not fix it:

  • #20336: unwraps PowerShell commands for execpolicy matching while retaining the dangerous-command heuristic.
  • #30879: recognizes mixed-case HTTP(S) schemes; fixes a missed dangerous match, not this false positive.
  • #39213 and #39311: introduce/adopt restricted in-process PowerShell lowering; here-strings remain unsupported.
  • #42113: applies remote-platform semantics and bounds rejection messages; does not fix command/argument association.

Expected behaviour

Literal output data and native-program arguments named start should not be interpreted as PowerShell launch commands. Neither should URL paths or hostnames containing start-process or invoke-item. A fix should address both command-position recognition and URL ownership within the relevant command expression. Existing protection for actual URL/ShellExecute launches should remain intact.

Regression coverage should include ordinary start arguments, single URL arguments containing the longer substrings in their path or FQDN, the here-string cross-command case, and an actual URL-launch classifier control. HTTP and parser-accepted unusual forms such as http://. also reproduce the false positive. The successful URL-with-start, encoded/other-scheme, and ordinary separate-command controls above help preserve the distinctions already handled correctly.

andrew-adamson-proteros avatar Sep 08 '26 06:09 andrew-adamson-proteros

Additional sanitized Windows Desktop occurrence, observed on 2026-09-08.

  • Desktop package: OpenAI.Codex 26.901.6511.0.
  • Full Access was selected in the app. Read-only app diagnostics also recorded resolvedApprovalPolicy=never; this is not a claim that every effective policy source has been identified.
  • The authorized operation was isolated npm dependency-metadata preparation using --package-lock-only and --ignore-scripts, not deployment or execution of package lifecycle scripts.

The compound PowerShell invocation constructed a System.Diagnostics.ProcessStartInfo with UseShellExecute=false and contained an HTTPS npm registry argument. The URL was package-manager configuration, not a request to open a URL via ShellExecute.

The tool immediately returned a CreateProcess rejection ending in blocked by policy, with reported wall time 0.0 seconds. No npm output or lock file was produced. The command was not rerouted through CMD or another execution tool, and no permission rules were changed.

The public is_dangerous_powershell_words implementation checks for a URL alongside a token containing shellexecute. That makes this command shape consistent with the heuristic discussed here, including the literal UseShellExecute=false case. However, the denying rule and the installed desktop engine's exact source revision have not been established; this is a suspected relationship, not a confirmed diagnosis or a separately executed minimal reproduction.

The user has already uploaded in-app feedback and explicitly authorized sharing its ID here: 01a005b9-7b99-77d3-b70c-d385c882ddd4

Could maintainers confirm whether this is the same classification issue and identify a supported, narrowly scoped resolution or diagnostic path? Protection against actual unsafe URL/ShellExecute launches should remain intact.

No project source, personal filesystem paths, credentials, raw logs, or full conversation are included in this comment.

bstisgood avatar Sep 09 '26 00:09 bstisgood

Additional Windows desktop occurrence observed on 2026-09-09, with a variation: the unrelated loopback URL was only a value printed in the final result object. It was neither a process argument nor a health-check request.

Environment and actual observation

  • The executable used by the running desktop app-server reported codex-cli 0.153.4.
  • Full Access was selected in the UI. The affected turn's runtime diagnostics recorded approval_policy=Never and sandbox_policy=DangerFullAccess; configuration also had approvals_reviewer="user".
  • The authorized task was to start a local Node.js preview server listening only on 127.0.0.1.

One compound PowerShell tool invocation attempted a local Start-Process -WindowStyle Hidden launch with redirected logs, then printed the process ID and preview URL. It was rejected before execution:

CreateProcess { message: "Rejected(... rejected: blocked by policy)" }
Wall time 0.0 seconds

Abbreviated, redacted shape of that recorded invocation (not an independently executed minimal reproduction; directory setup, log redirection and PID-file output are omitted):

$p = Start-Process -FilePath '<node.exe>' -ArgumentList @('scripts/serve.mjs') -WorkingDirectory '<project>' -WindowStyle Hidden -PassThru
[pscustomobject]@{
    ProcessId = $p.Id
    Preview = 'http://127.0.0.1:4186/public-preview/'
}

Read-only inspection of the original command confirmed that its URL appeared only in the final display statement, not in the launch statement. A subsequent foreground preview launch succeeded. The rejected background invocation was not replayed, and no permission or execution-policy rules were changed.

Source correlation and requested improvement

The 0.153.4 classifier checks for a URL and launch-related words across the supplied token list. The execution-policy code maps a dangerous match plus Never to Forbidden. This is consistent with the observed failure, but the generic error did not expose an actual matched-rule/classifier trace.

Please include an unrelated printed URL/result-object value in regression coverage, provide an actionable rejection reason, and clarify the Full Access UI wording. The current wording led me to expect this authorized local development operation to run without approval, making the unexplained denial particularly confusing. Existing protection for actual unsafe URL/ShellExecute launches should remain intact.

No private project paths, public-facing personal domains, credentials, screenshots, or raw diagnostic logs are included.

staminaoo avatar Sep 09 '26 10:09 staminaoo

Additional sanitized Windows Desktop occurrence on 2026-09-10: the noncommand start token was inside Python source being generated within a single-quoted PowerShell here-string. This extends the literal-data case described above.

Environment and observed failure

  • Desktop MSIX package: OpenAI.Codex 26.903.9818.0.
  • Desktop client version recorded by app-server: 26.903.71938.
  • Affected task's recorded CLI version: 0.153.4; the running desktop executor path was the npm-installed native CLI.
  • The rejected turn recorded approval_policy=never, approvals_reviewer=user, and sandbox_policy=danger-full-access.

The authorized operation was creation of one local unit-test file. A PowerShell here-string held a Python file-generation program; that program contained the test source as a triple-single-quoted string. The test source included a Python variable named start and synthetic HTTPS Origin values. The operation did not request a browser or URL/ShellExecute launch.

The tool rejected the command before process creation:

exec_command failed: CreateProcess ... Rejected(... rejected: blocked by policy)

The target file remained absent. An identical resubmission after a normal desktop restart was also rejected. Static parsing of the complete original PowerShell command reported zero errors.

Independently verified classifier-only example

The following synthetic example was passed only as data to a standalone classifier, not submitted to the desktop execution tool or executed as PowerShell/Python. It contains no project source, filesystem paths, or network operation:

$pythonCode = @'
source = '''
start = 1
url = "https://example.test"
'''
print(source)
'@
python -c $pythonCode

A small Rust harness included the unchanged upstream Windows classifier at commit 94697375cb9d2aa8ae74d61957c6b396819bec94. The source Git blob was verified as cc1ae671c831130dd33d11bac690d3052430b6dd. The harness read stdin into script and called:

is_dangerous_command_windows(&[
    "pwsh.exe".to_string(),
    "-Command".to_string(),
    script,
])

Built successfully with cargo build --offline using existing cached dependencies: shlex 1.3.0, once_cell 1.21.3, regex 1.12.2, and url 2.3.1. These are the reproduction's dependency versions, not a claim of exact dependency equivalence with the installed executor.

Result for the synthetic example:

target_command_executed=false
rust_shlex_token_count=13
plain_start_token_count=1
upstream_args_have_url=true
upstream_windows_dangerous_result=true

The same standalone classifier also returned true for the byte-verified original command. Neither classifier run executed its input or modified the target file.

Diagnostic limits and requested improvement

A same-version execpolicy check against the user's rule file returned matchedRules: []; that tests the supplied rules, not the full runtime fallback. Local DEBUG/TRACE records showed only Allow prefix rules being loaded. For the rejected call, the available log contained the generic router error without the matched classifier or decision inputs.

This strongly supports the literal-data false positive, but the exact in-process branch taken by the running executor remains unconfirmed. The independent harness tests the Windows classifier; it does not reproduce the complete desktop parser/policy pipeline.

Please include nested Python source strings in regression coverage, distinguish actual PowerShell command positions from literal argument/string contents, and preserve a specific rejection reason through the classifier and policy layers. Existing checks for real URL/ShellExecute launches and unresolved dynamic execution should remain effective. Safe diagnostic fields such as parser path, classifier reason, effective approval mode, and final decision would make these failures actionable.

This comment omits local usernames, repository identifiers, absolute paths, task/call IDs, credentials, project source, and raw logs.

Josh-Gamer avatar Sep 10 '26 15:09 Josh-Gamer

Additional minimal reproduction: a positional Python CLI subcommand named start is misclassified as a PowerShell/ShellExecute-style URL launch.

Environment

  • Codex CLI: 0.153.4
  • Codex Desktop on Windows
  • Command submitted through exec_command
  • pwsh.exe -Command wrapper
  • Python invoked through an absolute path; user-specific paths redacted
  • Approval policy: never
  • Sandbox: danger-full-access

The rejection occurs before Python starts:

rejected: blocked by policy

Minimal harmless target

The Python script performs no network access, subprocess execution, filesystem mutation, or application logic. It only prints argv and cwd:

import json
import os
import sys

print(json.dumps({"argv": sys.argv, "cwd": os.getcwd()}, ensure_ascii=True))
raise SystemExit(0)

Invocation shape:

& 'C:\redacted\python.exe' 'C:\redacted\argv_probe.py' <arguments>

Differential reproduction

Python arguments Result
start Allowed; Python starts and exits 0
start diagnostic Allowed; Python starts and exits 0
status https://example.invalid/diagnostic Allowed; Python starts and exits 0
start https://example.invalid/diagnostic Rejected before Python starts

The final start + URL invocation was repeated three times and was rejected consistently with:

rejected: blocked by policy

In this example, start is not:

  • PowerShell Start-Process;
  • CMD start;
  • a ShellExecute operation.

It is simply argv[1] of an external Python CLI. The URL is another positional argument to that same Python process.

Why this appears to be a classifier false positive

The observed behavior is consistent with the current Windows PowerShell dangerous-command classification logic: URL presence is detected across the flattened token sequence while launch-like tokens such as start / start-process are checked independently.

That loses the structural distinction between:

Start-Process 'https://example.com'

and:

& 'C:\redacted\python.exe' 'C:\redacted\argv_probe.py' start 'https://example.invalid/diagnostic'

In the latter case, PowerShell is launching python.exe; start and the URL belong to Python's argument vector and do not themselves have PowerShell launch semantics.

Expected behavior

An external CLI invocation should not be classified as a Windows URL/ShellExecute launch solely because its positional arguments happen to contain both start and an HTTP/HTTPS URL.

Actual shell-level URL launches such as:

Start-Process 'https://example.com'

should of course remain classified as dangerous.

Suggested regression coverage

A negative test covering this distinction would prevent recurrence:

#[test]
fn powershell_external_cli_start_url_argument_is_not_dangerous() {
    assert!(!is_dangerous_command_windows(&vec_str(&[
        "pwsh.exe",
        "-Command",
        r#"& 'C:\Tools\python.exe' 'C:\Tools\cli.py' start 'https://example.invalid/diagnostic'"#,
    ])));
}

while retaining positive coverage for an actual shell URL launch:

assert!(is_dangerous_command_windows(&vec_str(&[
    "powershell",
    "-Command",
    "Start-Process 'https://example.com'",
])));

The relevant distinction appears to be structural: the URL should be associated with the actual shell launch primitive, rather than merely coexisting with a launch-like word somewhere in the flattened argument/token sequence.

Additional historical evidence

In matched historical task logs:

  • direct PowerShell shell-text invocation: 0 successful / 17 rejected;
  • other historical invocation forms successfully reached the application runtime.

This is included only as supplementary evidence and is not presented as a workaround or recommendation to bypass the policy.

ghost avatar Sep 11 '26 23:09 ghost

Additional Windows desktop occurrence: Unity configuration rejected before execution

Prepared 2026-09-12 UTC for user-authorized public submission. This is a sanitized diagnostic report, not a workaround script. No credentials, tokens, private account identifiers, live service address, raw conversation, or private repository URL are included.

This appears related to #40060: the rejected PowerShell invocation contains Start-Process and an HTTPS URL. In this occurrence the URL is a configuration argument to an explicitly named local Unity executable, not the launch target or a request to open a browser. The actual denying classifier in the installed executor has not been identified; this is a suspected relationship, not a proven root cause or a separately tested minimal reproduction.

The owner reports submitting two in-app feedback reports. Their feedback IDs have not been provided, so no session or feedback identifier is included here.

Problem and impact

A user-authorized Unity Editor configuration operation is rejected by the Codex execution tool before the outer PowerShell process starts. The user selected Full Access and restarted the desktop app. One normal retry after restart returned the same rejection. Ordinary read-only PowerShell and Git diagnostic commands continue to work. The project-to-development-service connection remains unconfigured.

The returned error has this shape (workstation paths and command body omitted):

exec_command failed: CreateProcess {
  message: "Rejected(\"<bundled pwsh.exe> -Command '<configuration script>'
            rejected: blocked by policy\")"
}

No rejecting rule ID, rationale, approval prompt, Windows error code, or remediation is returned. No sandbox-permission override was requested on the failed call.

Environment

  • Windows 11, build 10.0.26200, x64.
  • Installed desktop package: OpenAI.Codex 26.903.9818.0.
  • Running Codex component and codex doctor: 0.153.4.
  • Unity Editor: 6000.3.9f1, revision 7a9955a4f2fa.
  • Unity Hub: 3.21.2; updating it did not change the rejection.
  • Current task environment reports danger-full-access, approval policy never, and enabled network access.
  • The app offers the user no update. Doctor advertises a newer build, but prior official distribution checks did not provide an installable newer package. No downgrade, forced update, or reinstall was performed.

Rejected operation: scope and arguments

The outer PowerShell script checks that no Unity process is running, creates an ignored log directory, launches the existing pinned Unity executable with Start-Process -WindowStyle Hidden -PassThru, waits for exit, and checks a fixed success marker. Project and log arguments containing spaces are explicitly quoted. The argument structure below is descriptive; placeholders are not runnable paths:

-batchmode -quit
-projectPath "<EXISTING_ISOLATED_UNITY_PROJECT_WITH_SPACES>"
-executeMethod <PROJECT_EDITOR_CONFIGURATION_METHOD>
<PROJECT_PUBLIC_ENDPOINT_ARGUMENT> <USER_OWNED_PUBLIC_HTTPS_API_ORIGIN>
-logFile "<IGNORED_CONFIGURATION_LOG>"

The inspected Editor method validates the origin locally and saves only the public endpoint field of the existing settings asset through Unity's AssetDatabase APIs. It does not read a credential vault, sign in, call an account/cloud API, enable a server feature, or grant rewards. Normal Unity imports/cache writes may occur. The isolated feature worktree was clean and no Unity process was running.

Correlated evidence

All timestamps below are UTC on 2026-09-12.

Time Observation
01:25:44-01:26:12 Earlier compile/content/scene-audit log file timestamps bracket successful runs of the same Unity executable against the same spaced project path. These are file timestamps, not exact process start/stop measurements.
01:26:22-01:28:10 EditMode test XML records 1,333 passed, zero failed.
01:28:23-01:28:37 PlayMode test XML records 152 passed, zero failed.
02:16:53.214 Restarted desktop application begins logging.
02:16:55.043 App log: Codex CLI initialized.
02:16:55.044 App-server connection records next=connected, initialized=true, connectionError=null.
02:17:05.821 This task's resume response records responseActivePermissionProfile=:danger-full-access, responseApprovalPolicy=never, and responseSandboxPolicy.type=dangerFullAccess.
02:17:38.150 The retry turn resolves resolvedApprovalPolicy=never, resolvedApprovalsReviewer=user.
02:17:38-02:20:04 The post-restart turn contains the rejected configuration attempt. This is the turn window; the exact rejection timestamp is not available in the inspected app logs.

The resume log also contains derived defaults of on-request/workspace-write, but its returned active settings and subsequent turn-start settings say never/Full Access. The default fields alone are not evidence that the task lost Full Access.

Successful Unity logs contain:

Initialize engine version: 6000.3.9f1 (7a9955a4f2fa)
Content validation passed. Errors: 0, warnings: 0
Vertical-slice project audit passed. Errors: 0, warnings: 0
Exiting batchmode successfully now!

Earlier successful commands also use -batchmode, synchronous -executeMethod, -quit, and quoted spaced paths. They are comparison evidence, not an identical configuration reproduction. Mocked test success is not live server verification.

Diagnostics performed and limits

  • Fresh codex doctor --json: installation/configuration consistent, app-server initialized, provider HTTP/WebSocket reachable, databases inspectable, and no locally visible recent Codex security enforcement found.
  • Doctor's overall failure is its non-interactive TERM=dumb check. Its standalone CLI on-disk sandbox defaults are not the active desktop task's permissions.
  • Inspected September 11/12 desktop log files for policy rejection indicators; no matching explanation was found. Inspected runtime log-database metadata for this task and threadless entries during 02:17-02:25; no blocked by policy record was found. Database access was read-only; no conversation or reviewer reasoning was exported.
  • Defender, AppLocker EXE/DLL, and Code Integrity operational logs are enabled. Queries for warning/error events during 02:17-02:21 returned no matches. This does not prove that every possible Windows/security control was ruled out.
  • Previously, a read-only check of the local execution-rules file found no matching rule. It does not prove all host-side/managed controls allow the action.
  • Warnings observed include unsupported PowerShell shell snapshots and an after-agent notification hook's Windows error 206 at turn end. Neither identifies the launch denial. No hook, Defender exclusion, permission, or policy was changed.
  • The expected configuration log still does not exist; the endpoint asset remains blank and retains its pre-attempt modification timestamp.

Diagnosis and requested resolution

Confirmed failure boundary: command execution is refused before PowerShell/Unity, while the desktop records Full Access for the task. The exact rejecting component and rule remain unidentified. This is not evidence of an AWS IAM failure, a Unity compile error, or a particular known app bug.

Please identify which execution/approval layer emitted blocked by policy, explain why no rationale or rule identifier reached the tool result, and provide the supported remedy or exact-action approval procedure for this desktop version. If a newer build fixes this case, please confirm its accessible Windows update channel rather than relying only on advertised version metadata.

No retries after the post-restart denial, alternate execution routes, security weakening, cloud changes, game-credential use, or destructive fallback were attempted during this investigation. Existing application work and user edits are preserved.

Official diagnostic references

Only sanitized excerpts are included. The original conversation and raw logs have not been attached to this public report.

JosephFrancisRe avatar Sep 12 '26 02:09 JosephFrancisRe

Additional Windows desktop occurrence observed on 2026-09-12, submitted at the account holder's explicit request.

The rejected command contains Invoke-RestMethod against a loopback status endpoint and a separate Start-Process launching a local PowerShell service-restart script in the same tool invocation. The URL is not a launch target or an argument to Start-Process. This closely matches the command shape reported here, but we have not established the effective denying classifier in our installed desktop build.

Environment and result

  • Installed desktop package, verified today: OpenAI.Codex 26.903.9818.0. The bundled engine version was not independently queried for this report.
  • Windows desktop; tool wrapper is the bundled PowerShell.
  • Active task context reports danger-full-access, approval_policy=never, and network access enabled.
  • Around 15:57 Asia/Taipei, the tool immediately returned CreateProcess ... rejected: blocked by policy, before execution.
  • No named rule, decision ID, review rationale, or applicable desktop approval action was returned.
  • Ordinary reads, Git operations, offline tests, and independent read-only local status requests continue to succeed.

Scope and impact

The user-authorized operation was to validate graceful shutdown and restart of an already repaired local Python service. The existing restart script checks that automated trading is OFF and verifies the current process identity. Restart would close an existing brokerage session and establish a new authenticated session; it is not purely read-only. It would not place, cancel, or amend orders or enable trading.

The rejected invocation never ran. A subsequent independent status read confirmed the already-running service remained OFF, connected, and reconciled. We have not retried that denied restart through another wrapper/client, split the operation to evade rejection, or changed security settings. Matching this issue's command shape is evidence for investigation, not proof that our entire service operation should be permitted.

The account holder reports approximately a week of development usage and repeated launch/validation interruptions. Earlier product Feedback was successfully submitted on September 11, but no actionable response or human case number has been obtained:

no-active-thread-01a08e1d-22c6-7383-aee3-64dd5eec487b

Questions for maintainers

  1. Is the whole-script Start-Process / unrelated-URL classifier still present in this desktop package? Is there a fixed Windows desktop build and an accessible official update channel?
  2. Can the denial expose its concrete classifier/rule and correlation ID, so a false positive can be distinguished from a separate policy restriction?
  3. What is the supported exact-action review or remediation flow for this Windows desktop configuration? The documented /approve flow explicitly describes the open-source TUI; we cannot confirm it applies here.
  4. If this occurrence belongs elsewhere, which supported issue/support channel should receive the existing Feedback ID?

No credentials, email address, brokerage account identity, private project paths, raw sessions, or brokerage logs are included. We are requesting an actionable diagnosis and supported resolution, not a security bypass.

reneehuang92 avatar Sep 12 '26 08:09 reneehuang92

Additional Windows desktop occurrence on 2026-09-12, submitted with the account holder’s explicit authorization.

Environment: installed package OpenAI.Codex 26.908.4834.0; separately queried PATH executable reports codex-cli 0.154.0-alpha.6.2. The latter is not asserted to identify the app’s effective executor build. The affected turn’s local logs record approval_policy=Never and sandbox_policy=DangerFullAccess.

At 2026-09-12T12:52:29.018Z, one authorized loopback development-service launch was rejected with exec_command failed: CreateProcess … rejected: blocked by policy, before the wrapper process was created. The compound PowerShell request combined a hidden local Start-Process invocation with subsequent loopback HTTP readiness/source checks. The URL was not intended as a ShellExecute launch target. Submission count was 1; wrapper, keeper, Node, and HTTP execution counts were 0. No native stdout/stderr/exit existed. The original command was recovered locally: UTF-8 length 7440 bytes, SHA-256 5fc50b53e72b85359717dba813e8a52bf444c45b5b85192b89b66ae846ec4fbf; its private contents are not attached.

A later diagnostic that only read local metadata/configuration and extracted source text was also rejected before execution. Its text filters mentioned Start-Process and an HTTP URL prefix; it did not request starting the development service. That diagnostic was stopped without rewriting or retrying it. Ordinary independent file reads, hashes and version queries succeeded. No safety settings, rules or binaries were changed; no split-command or alternate-tool retry was used.

The classifier in the public rust-v0.154.0-alpha.6.2 tag still appears consistent with this issue. This is a strong candidate, not proof of the actual denying rule in our installed executor. Bounded read-only log inspection did not expose that rule or a detailed reason.

Could maintainers identify the applicable classifier and supported exact-action remediation for this desktop version, and confirm whether an available official Windows build fixes it? We request no blanket allow rule or security bypass. No product source, credentials, personal data, local paths or full session transcript is included.

eimhenry-dt avatar Sep 12 '26 13:09 eimhenry-dt

Additional confirmed Windows desktop occurrence, recovered from September 9 task records

A user-authorized restart of an installed local background worker was rejected before PowerShell started. The same PowerShell invocation performed an HTTPS readiness check against a service and then called Start-Process with a local executable and a local configuration-file argument. The URL belonged to Invoke-WebRequest, not to the process-launch arguments.

Abbreviated, sanitized command shape, not a separately executed minimal reproduction:

$ready = Invoke-WebRequest -Uri 'https://service.example.invalid/health/ready' -TimeoutSec 20
if ([int]$ready.StatusCode -ne 200) { throw 'Service is not ready.' }
# Original invocation also checked existing processes, scheduled-task settings,
# the local executable hash, and saved progress before this local launch.
$worker = Start-Process -FilePath 'C:\Example\Tools\worker-host.exe' -ArgumentList '--config "D:\Example\worker.json"' -WindowStyle Hidden -PassThru
# Original invocation then updated the local progress receipt.

The original tool call and result were recovered from the local task record. The tool returned:

exec_command failed: CreateProcess ... Rejected(... rejected: blocked by policy)
Wall time 0.0 seconds

The initial rejection occurred on September 9, 2026 at 00:42 UTC; a repeated launch after explicit user re-authorization was rejected at 00:45 UTC. Neither invocation started PowerShell, so its embedded checks and receipt updates did not execute. Repeating consent in conversation did not resolve the failure.

Incident evidence:

  • Affected session metadata reports CLI 0.153.4.
  • Exact rejected turn context: approval_policy=never, approvals_reviewer=user, sandbox_policy.type=danger-full-access, model gpt-6-astra.
  • The tool wrapper used native Windows PowerShell (pwsh.exe).
  • These are historical observations. Today's installed package (OpenAI.Codex 26.908.4834.0) and current executor version (0.154.0-alpha.6.2) are not asserted to be the versions that ran the September 9 call.

This closely matches the whole-script URL/launcher classifier described in this issue. The exact denying rule was not identified by the runtime, and no model-review decision is established by the generic error. A minimized reproduction or split-command comparison was not performed during this reporting task.

Following these interruptions, the operator added AGENTS.md guidance to prefer direct execution or persistent shell sessions, separate startup from HTTP checks, and simplify compound commands. That mitigation changes the generated command shape, but does not resolve the classifier or provide a usable approval route when a command is classified as dangerous under never.

Please associate URL arguments with the actual command being invoked, and expose an actionable rejection reason and supported approval path. These failures have interrupted authorized worker recovery and are difficult to distinguish from operating-system restrictions or model-review denials. We also reported a separate standalone forced-deletion occurrence in #34331.

Submitted at the account holder's request. Private service addresses, paths, executable names, configuration contents, raw logs, credentials, and conversation identifiers are omitted.

RoboCoder68 avatar Sep 12 '26 17:09 RoboCoder68

Additional source fix and native Windows validation, including the actual core policy decision

Following the command-scoped patch, the literal-data reproductions, and the positional Python start report, we investigated the same failure class and prepared another candidate patch. The additional evidence here is a native Windows baseline/fixed comparison, coverage of both raw-script and lowered-argv entry points, and three selected tests through the real codex-core policy manager.

We are sharing source-level analysis and a candidate diff in the existing issue, in accordance with the project's contribution guidance, rather than opening an external PR. We have not run a controlled comparison against the other proposed implementations.

Reproduction shape and source-level cause

In our incident, start was an argument to a Python helper, and a URL was ordinary input data. There was no intended PowerShell URL launch. The following synthetic example is included in the attached regression tests as command data; the tests do not execute it:

try { python plan_lifecycle.py start --source-ref 'https://example.com/plan.json' } finally { $credential = $null }

The baseline flattens tokens and matches the URL independently of the position of start. Complex control flow also matters: a script may be valid PowerShell while the existing literal-command lowerer deliberately declines to lower the whole script.

Patch and validation base: rust-v0.154.0-alpha.6.2, commit b5bffd3ec4db487e7e3dec59663875b0ef7b72ca. We also inspected upstream main at dfaf451426868c22e6859f5494150fd6338c3257 on September 13: the relevant flattened-token predicate is still present. The attached patch was built/tested against the stated release commit, not rebased or tested against that newer main.

Candidate change

  • Add a focused tree-sitter command-node scanner that can inspect URL-launch command positions even when whole-script literal lowering is unavailable.
  • Distinguish a real launcher from launcher-looking text in arguments to a known external command. Cover both the raw PowerShell-script path and the public lowered-word path, including nested PowerShell wrappers with a depth bound.
  • Classify parser ambiguity and the covered dynamic command/launcher cases conservatively. The patch deliberately also classifies constructs such as Invoke-Expression and alias mutation conservatively; this broadening needs maintainer review and can reject benign dynamic scripts.
  • Retain separate delete and COM/ShellExecute checks. Existing deletion, CMD and browser tests continue to pass. This is not a proof of safety for arbitrary PowerShell, external programs, or all alias/evaluation forms.

A known remaining limitation is the broad COM/ShellExecute token check: the UseShellExecute=false plus unrelated URL shape can still be caught by the retained heuristic. This patch does not claim to resolve that variant or every occurrence in this thread.

No core permission configuration, user allow rules, dependency manifests, or installed application binaries are changed by the source patch. The product diff is four shell-command files, with ten new regression tests.

Completed validation on September 12

Native Windows, Rust 1.95.0, x86_64-pc-windows-gnu, matching GCC 14.1.0 / MSVCRT runtime. The classifier suite was run through just test -p codex-shell-command with the local nextest profile.

Check Result
Original classifier with the same ten added regression tests 183 total: 175 passed, 8 expected failures, none skipped
Original pre-existing suite All 173 passed
Patched classifier, same complete crate suite 183 passed, zero failed/skipped
Scoped Clippy, formatting, diff whitespace and patch applicability checks Passed
Full codex-cli executable build Passed
Executable version/help, app-server help, JSON schema generation Passed; 305 generated JSON files parsed successfully

When switching between baseline and patched worktrees, we cleaned the affected codex-shell-command package from the shared target cache before comparing results. An earlier run that reused a baseline artifact was excluded from the evidence.

We then compiled and tested the actual ExecPolicyManager::create_exec_approval_requirement_for_command through the existing Windows core test helper. The production decision method was used, not a copied approximation. All 3 selected tests passed; 2,362 other tests in that test binary were filtered out.

Common conditions: AskForApproval::Never, PermissionProfile::Disabled, SandboxPermissions::UseDefault; the existing helper supplies WindowsSandboxLevel::RestrictedToken.

Input / explicit rules Actual core result
Exact incident script, passed only as data in normalized pwsh -Command <script> argv; empty rules Skip { bypass_sandbox: false, proposed_execpolicy_amendment: Some(original_argv_amendment) }
Start-Process with a literal HTTPS target inside try/finally; empty rules Forbidden with blocked by policy
Incident script as data plus explicit prefix_rule(pattern=["pwsh"], decision="forbidden") Forbidden with the explicit prefix-rule reason

The proposed amendment in the first result was not written or applied. One initial core test had expected None for that field and failed despite the intended Skip decision; after checking the existing core implementation, we corrected the test to compare the complete expected object, including Some(...). No product-code change was needed for that correction.

The core validation used a private incident fixture that is not attached. Those tests were temporary local validation additions, separate from the product patch below; turning them into portable upstream tests would require a public repo-owned fixture and appropriate Bazel compile data. The synthetic classifier regressions below are self-contained.

Limits and request

We have not instrumented the installed Desktop to identify its historical decision trace. This report establishes source-level classification and core-decision behavior under the listed test conditions. The original incident command was never executed by these tests, and no URLs or external operations from the fixtures were launched.

The built CLI is an unsigned GNU development build, not a supported replacement for the official signed MSVC Desktop bundle. We have not installed it into Desktop, built a complete matching companion-binary bundle, run Desktop/model integration tests, or run the complete workspace/MSVC/macOS/Linux CI matrix. We are not proposing a -File wrapper or a rule change to bypass the rejection.

Could maintainers evaluate the command-position approach and regression coverage, and provide an official Windows Desktop/CLI fix? It would also help for the refusal to identify the matched heuristic and offer a supported review path, instead of only blocked by policy.

Only the source diff and sanitized validation summary are included. No private repository URL, personal filesystem path, credentials, original command fixture, raw session transcript or raw diagnostic logs are attached. Submitted with the account holder's explicit authorization.

Candidate product patch and ten self-contained regression tests (four files)

Base: b5bffd3ec4db487e7e3dec59663875b0ef7b72ca. SHA-256 of the original patch file: 4584d2aae5cfa9e37d2a0178c7804a4e7209c8206f5d7a4a59b297738977bdaf (GitHub may normalize displayed line endings).

diff --git a/codex-rs/shell-command/src/command_safety/mod.rs b/codex-rs/shell-command/src/command_safety/mod.rs
index 44d0103..5213ab5 100644
--- a/codex-rs/shell-command/src/command_safety/mod.rs
+++ b/codex-rs/shell-command/src/command_safety/mod.rs
@@ -4,6 +4,7 @@
 #[allow(dead_code)]
 mod powershell_parser;
 mod powershell_tree_sitter;
+mod powershell_url_launch_scan;
 
 pub mod is_dangerous_command;
 pub(crate) use powershell_tree_sitter::try_parse_powershell_commands;
diff --git a/codex-rs/shell-command/src/command_safety/powershell_url_launch_scan.rs b/codex-rs/shell-command/src/command_safety/powershell_url_launch_scan.rs
new file mode 100644
index 0000000..977ef9f
--- /dev/null
+++ b/codex-rs/shell-command/src/command_safety/powershell_url_launch_scan.rs
@@ -0,0 +1,235 @@
+use once_cell::sync::Lazy;
+use regex::Regex;
+use tree_sitter::Node;
+use tree_sitter::Parser;
+use url::Url;
+
+/// Result of scanning PowerShell source for a URL launch without flattening
+/// the complete script into words.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub(crate) enum PowershellUrlLaunchScan {
+    Clear,
+    Dangerous,
+    Ambiguous,
+}
+
+/// Finds URL launches from syntactic PowerShell command nodes. This remains
+/// usable when a script contains control-flow syntax that the literal lowering
+/// path intentionally does not support.
+pub(crate) fn scan_dangerous_url_launch(script: &str) -> PowershellUrlLaunchScan {
+    let mut parser = Parser::new();
+    if parser
+        .set_language(&tree_sitter_powershell::LANGUAGE.into())
+        .is_err()
+    {
+        return PowershellUrlLaunchScan::Ambiguous;
+    }
+    let Some(tree) = parser.parse(script, None) else {
+        return PowershellUrlLaunchScan::Ambiguous;
+    };
+    if tree.root_node().has_error() {
+        return PowershellUrlLaunchScan::Ambiguous;
+    }
+
+    let mut ambiguous = false;
+    let mut stack = vec![tree.root_node()];
+    while let Some(node) = stack.pop() {
+        if node.kind() == "command" {
+            match command_url_launch_scan(node, script) {
+                PowershellUrlLaunchScan::Dangerous => {
+                    return PowershellUrlLaunchScan::Dangerous;
+                }
+                PowershellUrlLaunchScan::Ambiguous => ambiguous = true,
+                PowershellUrlLaunchScan::Clear => {}
+            }
+        }
+        for child_index in 0..node.named_child_count() {
+            if let Some(child) = node.named_child(child_index) {
+                stack.push(child);
+            }
+        }
+    }
+
+    if ambiguous {
+        PowershellUrlLaunchScan::Ambiguous
+    } else {
+        PowershellUrlLaunchScan::Clear
+    }
+}
+
+fn command_url_launch_scan(command: Node<'_>, script: &str) -> PowershellUrlLaunchScan {
+    let Some(source) = command.utf8_text(script.as_bytes()).ok() else {
+        return PowershellUrlLaunchScan::Ambiguous;
+    };
+    let Some(name) = command_name(command, source, script) else {
+        return PowershellUrlLaunchScan::Ambiguous;
+    };
+    let argument_source = source
+        .get(name.source_len..)
+        .unwrap_or_default()
+        .trim_start();
+    let invocation_source =
+        parenthesized_invocation_source(command, script).unwrap_or(argument_source);
+
+    if is_url_launcher(name.value.as_str()) {
+        // A variable, subexpression, splat, or invocation operator can resolve
+        // to a URL at runtime. Do not prove such a launch safe just because the
+        // URL is not a static string.
+        return if contains_literal_url(invocation_source)
+            || contains_dynamic_argument(invocation_source)
+        {
+            PowershellUrlLaunchScan::Dangerous
+        } else {
+            PowershellUrlLaunchScan::Clear
+        };
+    }
+
+    if is_opaque_powershell_invocation(name.value.as_str(), invocation_source) {
+        return PowershellUrlLaunchScan::Dangerous;
+    }
+
+    if is_browser_executable(name.value.as_str()) && contains_literal_url(invocation_source) {
+        PowershellUrlLaunchScan::Dangerous
+    } else {
+        PowershellUrlLaunchScan::Clear
+    }
+}
+
+fn parenthesized_invocation_source<'a>(command: Node<'_>, script: &'a str) -> Option<&'a str> {
+    let suffix = script.get(command.end_byte()..)?;
+    let source = suffix.strip_prefix('(')?;
+    let mut depth = 1usize;
+    for (index, ch) in source.char_indices() {
+        match ch {
+            '(' => depth += 1,
+            ')' => {
+                depth = depth.checked_sub(1)?;
+                if depth == 0 {
+                    return source.get(..index);
+                }
+            }
+            _ => {}
+        }
+    }
+    None
+}
+
+struct CommandName {
+    value: String,
+    source_len: usize,
+}
+
+fn command_name(command: Node<'_>, source: &str, script: &str) -> Option<CommandName> {
+    let mut cursor = command.walk();
+    if let Some(node) = command
+        .named_children(&mut cursor)
+        .find(|child| child.kind() == "command_name")
+    {
+        let text = node.utf8_text(script.as_bytes()).ok()?;
+        return Some(CommandName {
+            value: normalize_command_name(text)?,
+            source_len: node.end_byte().checked_sub(command.start_byte())?,
+        });
+    }
+
+    invocation_operator_command_name(source)
+}
+
+fn invocation_operator_command_name(source: &str) -> Option<CommandName> {
+    let leading = source.len().checked_sub(source.trim_start().len())?;
+    let source = source.get(leading..)?;
+    let after_operator = source.strip_prefix('&')?.trim_start();
+    let operator_len = source.len().checked_sub(after_operator.len())?;
+    let (word, word_len) = quoted_or_bare_word(after_operator)?;
+    Some(CommandName {
+        value: normalize_command_name(word)?,
+        source_len: leading + operator_len + word_len,
+    })
+}
+
+fn quoted_or_bare_word(source: &str) -> Option<(&str, usize)> {
+    let quote = source.chars().next()?;
+    if quote == '\'' || quote == '"' {
+        let closing = source.get(quote.len_utf8()..)?.find(quote)? + quote.len_utf8();
+        let end = closing + quote.len_utf8();
+        return Some((source.get(quote.len_utf8()..closing)?, end));
+    }
+
+    let end = source.find(char::is_whitespace).unwrap_or(source.len());
+    Some((source.get(..end)?, end))
+}
+
+fn normalize_command_name(source: &str) -> Option<String> {
+    let mut value = String::new();
+    let mut chars = source.trim().chars();
+    while let Some(ch) = chars.next() {
+        if matches!(
+            ch,
+            '$' | '@' | '(' | ')' | '[' | ']' | '{' | '}' | '"' | '\''
+        ) {
+            return None;
+        }
+        if ch == '`' {
+            let escaped = chars.next()?;
+            // PowerShell 6 introduced `e, so it has no version-neutral value.
+            if escaped == 'e' {
+                return None;
+            }
+            value.push(escaped);
+        } else {
+            value.push(ch);
+        }
+    }
+    (!value.is_empty()).then(|| value.to_ascii_lowercase())
+}
+
+fn is_url_launcher(command: &str) -> bool {
+    matches!(
+        command,
+        "start-process" | "start" | "saps" | "invoke-item" | "ii"
+    )
+}
+
+/// Reports invocations whose behavior can be changed by PowerShell evaluation
+/// or the Alias: provider, so they cannot prove an otherwise literal script
+/// safe.
+pub(crate) fn is_opaque_powershell_invocation(command: &str, arguments: &str) -> bool {
+    matches!(
+        command,
+        "invoke-expression" | "iex" | "set-alias" | "new-alias" | "sal" | "nal"
+    ) || matches!(command, "set-item" | "new-item")
+        && arguments
+            .trim_matches(['\'', '"'])
+            .to_ascii_lowercase()
+            .contains("alias:")
+}
+
+fn is_browser_executable(command: &str) -> bool {
+    matches!(
+        command,
+        "chrome"
+            | "chrome.exe"
+            | "msedge"
+            | "msedge.exe"
+            | "firefox"
+            | "firefox.exe"
+            | "iexplore"
+            | "iexplore.exe"
+    )
+}
+
+fn contains_literal_url(source: &str) -> bool {
+    static URL: Lazy<Option<Regex>> =
+        Lazy::new(|| Regex::new(r#"(?i)https?://[^\s'"<>(){};,]+"#).ok());
+    URL.as_ref().is_some_and(|regex| {
+        regex.find_iter(source).any(|url| {
+            Url::parse(url.as_str())
+                .ok()
+                .is_some_and(|parsed| matches!(parsed.scheme(), "http" | "https"))
+        })
+    })
+}
+
+fn contains_dynamic_argument(source: &str) -> bool {
+    source.contains(['$', '@', '&', '`', '('])
+}
diff --git a/codex-rs/shell-command/src/command_safety/windows_dangerous_commands.rs b/codex-rs/shell-command/src/command_safety/windows_dangerous_commands.rs
index cc1ae67..225158f 100644
--- a/codex-rs/shell-command/src/command_safety/windows_dangerous_commands.rs
+++ b/codex-rs/shell-command/src/command_safety/windows_dangerous_commands.rs
@@ -3,6 +3,13 @@ use regex::Regex;
 use shlex::split as shlex_split;
 use url::Url;
 
+use crate::command_safety::powershell_url_launch_scan::PowershellUrlLaunchScan;
+use crate::command_safety::powershell_url_launch_scan::is_opaque_powershell_invocation;
+use crate::command_safety::powershell_url_launch_scan::scan_dangerous_url_launch;
+use crate::command_safety::try_parse_powershell_commands;
+
+const MAX_POWERSHELL_WRAPPER_DEPTH: usize = 8;
+
 pub fn is_dangerous_command_windows(command: &[String]) -> bool {
     // Prefer structured parsing for PowerShell/CMD so we can spot URL-bearing
     // invocations of ShellExecute-style entry points before falling back to
@@ -25,43 +32,93 @@ fn is_dangerous_powershell(command: &[String]) -> bool {
     if !is_powershell_executable(exe) {
         return false;
     }
-    // Parse the PowerShell invocation to get a flat token list we can scan for
-    // dangerous cmdlets/COM calls plus any URL-looking arguments. This is a
-    // best-effort shlex split of the script text, not a full PS parser.
     let Some(parsed) = parse_powershell_invocation(rest) else {
         return false;
     };
 
-    is_dangerous_powershell_words(&parsed.tokens)
+    match parsed {
+        ParsedPowershell::Script(script) => {
+            is_dangerous_powershell_script(script, /*depth*/ 0)
+        }
+        ParsedPowershell::Words(words) => {
+            is_dangerous_powershell_words_with_depth(&words, /*depth*/ 0)
+        }
+    }
+}
+
+fn is_dangerous_powershell_script(script: &str, depth: usize) -> bool {
+    // The literal lowerer gives each command an argv boundary. When control
+    // flow makes a whole-script lowering impossible, retain the old
+    // conservative checks for delete/COM paths and use the CST to find actual
+    // command names instead of treating every occurrence of `start` as one.
+    if let Some(commands) = try_parse_powershell_commands(script)
+        && commands
+            .iter()
+            .any(|command| is_dangerous_powershell_words_with_depth(command, depth + 1))
+    {
+        return true;
+    }
+
+    match scan_dangerous_url_launch(script) {
+        PowershellUrlLaunchScan::Dangerous => true,
+        // If the AST cannot identify a command name, do not prove a dynamic
+        // invocation safe. A known external command with a `start` argument
+        // reaches the Clear branch above and therefore remains usable.
+        PowershellUrlLaunchScan::Ambiguous => true,
+        PowershellUrlLaunchScan::Clear => shlex_split(script).is_some_and(|words| {
+            let lowercase_words = words
+                .iter()
+                .map(|word| word.to_ascii_lowercase())
+                .collect::<Vec<_>>();
+            has_force_delete_cmdlet(&words) || has_shell_execute_url_invocation(&lowercase_words)
+        }),
+    }
 }
 
 pub(crate) fn is_dangerous_powershell_words(words: &[String]) -> bool {
+    is_dangerous_powershell_words_with_depth(words, /*depth*/ 0)
+}
+
+fn is_dangerous_powershell_words_with_depth(words: &[String], depth: usize) -> bool {
+    if depth > MAX_POWERSHELL_WRAPPER_DEPTH {
+        return true;
+    }
+    if let Some((executable, arguments)) = words.split_first()
+        && is_powershell_executable(executable)
+        && let Some(parsed) = parse_powershell_invocation(arguments)
+    {
+        return match parsed {
+            ParsedPowershell::Script(script) => is_dangerous_powershell_script(script, depth + 1),
+            ParsedPowershell::Words(words) => {
+                is_dangerous_powershell_words_with_depth(&words, depth + 1)
+            }
+        };
+    }
+
     let tokens_lc: Vec<String> = words
         .iter()
         .map(|t| t.trim_matches('\'').trim_matches('"').to_ascii_lowercase())
         .collect();
     let has_url = args_have_url(words);
 
-    if has_url
-        && tokens_lc.iter().any(|t| {
-            matches!(
-                t.as_str(),
-                "start-process" | "start" | "saps" | "invoke-item" | "ii"
-            ) || t.contains("start-process")
-                || t.contains("invoke-item")
-        })
+    if let Some(command) = tokens_lc.first()
+        && is_opaque_powershell_invocation(command, &tokens_lc[1..].join(" "))
     {
         return true;
     }
 
     if has_url
         && tokens_lc
-            .iter()
-            .any(|t| t.contains("shellexecute") || t.contains("shell.application"))
+            .first()
+            .is_some_and(|command| is_url_launcher(command))
     {
         return true;
     }
 
+    if has_shell_execute_url_invocation(&tokens_lc) {
+        return true;
+    }
+
     if let Some(first) = tokens_lc.first() {
         // Legacy ShellExecute path via url.dll
         if first == "rundll32"
@@ -87,6 +144,21 @@ pub(crate) fn is_dangerous_powershell_words(words: &[String]) -> bool {
     has_force_delete_cmdlet(&tokens_lc)
 }
 
+fn is_url_launcher(command: &str) -> bool {
+    matches!(
+        command,
+        "start-process" | "start" | "saps" | "invoke-item" | "ii"
+    ) || command.starts_with("start-process(")
+        || command.starts_with("invoke-item(")
+}
+
+fn has_shell_execute_url_invocation(tokens: &[String]) -> bool {
+    args_have_url(tokens)
+        && tokens
+            .iter()
+            .any(|token| token.contains("shellexecute") || token.contains("shell.application"))
+}
+
 fn is_dangerous_cmd(command: &[String]) -> bool {
     let Some((exe, rest)) = command.split_first() else {
         return false;
@@ -306,7 +378,7 @@ fn args_have_url(args: &[String]) -> bool {
     args.iter().any(|arg| looks_like_url(arg))
 }
 
-fn looks_like_url(token: &str) -> bool {
+pub(super) fn looks_like_url(token: &str) -> bool {
     // Strip common PowerShell punctuation around inline URLs (quotes, parens, trailing semicolons).
     // Capture the middle token after trimming leading quotes/parens/whitespace and trailing semicolons/closing parens.
     static RE: Lazy<Option<Regex>> =
@@ -365,11 +437,12 @@ fn is_browser_executable(name: &str) -> bool {
     )
 }
 
-struct ParsedPowershell {
-    tokens: Vec<String>,
+enum ParsedPowershell<'a> {
+    Script(&'a str),
+    Words(Vec<String>),
 }
 
-fn parse_powershell_invocation(args: &[String]) -> Option<ParsedPowershell> {
+fn parse_powershell_invocation(args: &[String]) -> Option<ParsedPowershell<'_>> {
     if args.is_empty() {
         return None;
     }
@@ -384,16 +457,14 @@ fn parse_powershell_invocation(args: &[String]) -> Option<ParsedPowershell> {
                 if idx + 2 != args.len() {
                     return None;
                 }
-                let tokens = shlex_split(script)?;
-                return Some(ParsedPowershell { tokens });
+                return Some(ParsedPowershell::Script(script));
             }
             _ if lower.starts_with("-command:") || lower.starts_with("/command:") => {
                 if idx + 1 != args.len() {
                     return None;
                 }
                 let (_, script) = arg.split_once(':')?;
-                let tokens = shlex_split(script)?;
-                return Some(ParsedPowershell { tokens });
+                return Some(ParsedPowershell::Script(script));
             }
             "-nologo" | "-noprofile" | "-noninteractive" | "-mta" | "-sta" => {
                 idx += 1;
@@ -403,7 +474,7 @@ fn parse_powershell_invocation(args: &[String]) -> Option<ParsedPowershell> {
             }
             _ => {
                 let rest = args[idx..].to_vec();
-                return Some(ParsedPowershell { tokens: rest });
+                return Some(ParsedPowershell::Words(rest));
             }
         }
     }
@@ -769,3 +840,7 @@ mod tests {
         ])));
     }
 }
+
+#[cfg(test)]
+#[path = "windows_dangerous_commands_tests.rs"]
+mod regression_tests;
diff --git a/codex-rs/shell-command/src/command_safety/windows_dangerous_commands_tests.rs b/codex-rs/shell-command/src/command_safety/windows_dangerous_commands_tests.rs
new file mode 100644
index 0000000..f0ea4cd
--- /dev/null
+++ b/codex-rs/shell-command/src/command_safety/windows_dangerous_commands_tests.rs
@@ -0,0 +1,142 @@
+use super::is_dangerous_command_windows;
+use super::is_dangerous_powershell_words;
+use crate::command_safety::is_dangerous_command::DangerousCommandMatch;
+use crate::command_safety::is_dangerous_command::DangerousCommandPlatform;
+use crate::command_safety::is_dangerous_command::dangerous_powershell_words_match;
+use pretty_assertions::assert_eq;
+
+fn vec_str(items: &[&str]) -> Vec<String> {
+    items.iter().map(std::string::ToString::to_string).collect()
+}
+
+#[test]
+fn external_program_start_argument_with_url_is_not_a_powershell_launch() {
+    let command = vec_str(&[
+        "python",
+        "plan_lifecycle.py",
+        "start",
+        "--source-ref",
+        "https://example.com/plan.json",
+    ]);
+
+    assert!(!is_dangerous_powershell_words(&command));
+}
+
+#[test]
+fn complex_lifecycle_script_with_start_argument_and_url_is_not_a_launch() {
+    let command = vec_str(&[
+        "pwsh",
+        "-NoProfile",
+        "-Command",
+        "try { python plan_lifecycle.py start --source-ref 'https://example.com/plan.json' } finally { $credential = $null }",
+    ]);
+
+    assert!(!is_dangerous_command_windows(&command));
+}
+
+#[test]
+fn powershell_origin_wrapper_uses_the_raw_script_scanner() {
+    let command = vec_str(&[
+        "pwsh",
+        "-Command",
+        "try { python plan_lifecycle.py start --source-ref 'https://example.com/plan.json' } finally { $credential = $null }",
+    ]);
+
+    assert!(!is_dangerous_powershell_words(&command));
+    assert_eq!(
+        dangerous_powershell_words_match(&command, DangerousCommandPlatform::Windows),
+        None
+    );
+}
+
+#[test]
+fn powershell_origin_wrapper_blocks_raw_url_launches() {
+    let command = vec_str(&[
+        "pwsh",
+        "-Command",
+        "try { & 'Start-Process' https://example.com } finally { $credential = $null }",
+    ]);
+
+    assert_eq!(
+        dangerous_powershell_words_match(&command, DangerousCommandPlatform::Windows),
+        Some(DangerousCommandMatch::Other)
+    );
+}
+
+#[test]
+fn lowered_opaque_invocations_are_dangerous_through_the_public_wrapper() {
+    for command in [
+        vec_str(&["Invoke-Expression", "Start-Process https://example.com"]),
+        vec_str(&["Set-Alias", "open", "Start-Process"]),
+        vec_str(&["Set-Item", "Alias:open", "Start-Process"]),
+    ] {
+        assert!(is_dangerous_powershell_words(&command), "{command:?}");
+        assert_eq!(
+            dangerous_powershell_words_match(&command, DangerousCommandPlatform::Windows),
+            Some(DangerousCommandMatch::Other),
+            "{command:?}"
+        );
+    }
+}
+
+#[test]
+fn quoted_launcher_text_in_an_external_program_argument_is_not_a_command_name() {
+    let command = vec_str(&[
+        "pwsh",
+        "-Command",
+        "try { python helper.py 'Start-Process' 'https://example.com/plan.json' } finally { $credential = $null }",
+    ]);
+
+    assert!(!is_dangerous_command_windows(&command));
+}
+
+#[test]
+fn url_launches_remain_dangerous_inside_complex_powershell_blocks() {
+    for script in [
+        "try { Start-Process 'https://example.com' } finally { $credential = $null }",
+        "try { Start-Process('https://example.com') } finally { $credential = $null }",
+        "try { & 'Start-Process' https://example.com } finally { $credential = $null }",
+        r"try { Start-`Process https://example.com } finally { $credential = $null }",
+        r"try { Start-Process h`ttps://example.com } finally { $credential = $null }",
+        "if ($true) { start https://example.com }",
+        "try { msedge.exe https://example.com } finally { $credential = $null }",
+    ] {
+        let command = vec_str(&["pwsh", "-Command", script]);
+        assert!(is_dangerous_command_windows(&command), "{script}");
+    }
+}
+
+#[test]
+fn dynamic_url_launcher_arguments_are_conservative() {
+    let command = vec_str(&[
+        "pwsh",
+        "-Command",
+        "try { Start-Process $destination } finally { $credential = $null }",
+    ]);
+
+    assert!(is_dangerous_command_windows(&command));
+}
+
+#[test]
+fn dynamic_execution_and_dynamic_command_names_are_conservative() {
+    for script in [
+        "Invoke-Expression 'Start-Process https://example.com'",
+        "try { Set-Alias open Start-Process; open https://example.com } finally { $credential = $null }",
+        "try { Set-Item Alias:open Start-Process; open https://example.com } finally { $credential = $null }",
+        "try { & $runner $destination } finally { $credential = $null }",
+    ] {
+        let command = vec_str(&["pwsh", "-Command", script]);
+        assert!(is_dangerous_command_windows(&command), "{script}");
+    }
+}
+
+#[test]
+fn malformed_powershell_source_is_not_automatically_allowed() {
+    let command = vec_str(&[
+        "pwsh",
+        "-Command",
+        "try { python helper.py start --source-ref 'https://example.com/plan.json'",
+    ]);
+
+    assert!(is_dangerous_command_windows(&command));
+}

nikolaykazakovvs-ux avatar Sep 13 '26 05:09 nikolaykazakovvs-ux

Additional reproducible false positive on 2026-09-13, with a smaller no-side-effect case than a process launch plus health check.

Environment

  • Windows desktop, PowerShell command tool.
  • Version queried from the executable used by the running desktop app-server: codex-cli 0.154.0-alpha.6.2.
  • Active task: approval policy never, filesystem sandbox disabled/full access.
  • The separately installed CLI reports 0.154.0; that is not the desktop runtime above.
  • No local exec-policy rule files were loaded. No permission settings or installed binaries were changed for this investigation.

Minimal observed reproduction

Submit this PowerShell command through the desktop command-execution tool:

Write-Output 'Start-Process https://example.invalid'

Observed: immediate pre-process rejection containing CreateProcess, Rejected, and rejected: blocked by policy (approximately 0.3 seconds). This only requests printing a literal string. It does not request process creation, URL navigation, network access, or file mutation.

We also traced a real documentation-edit rejection where the flattened token list contained the standalone word Start from the prose “Start a sweep lane” and unrelated documentation URLs. The original script requested file editing, with no process-launch command. Private project content and original command bodies are intentionally omitted.

Source correlation and requested fix

The behavior matches is_dangerous_powershell_words, which searches the whole token list for URL substrings and launch aliases, including start, without preserving whether the token is quoted data or an executable command name:

The pinned public source is a correlation, not an assertion that this exact commit built the installed executable. The literal-output rejection above was observed in the installed runtime.

Please include literal output, here-string documentation data, and external-program arguments in the regression cases for a parser-aware fix, while preserving protection against actual URL-bearing launches and dynamic execution. Please also return a stable reason/classifier identifier and triggering command span so legitimate restrictions can be distinguished from false positives.

A local application was recovered through a materially safer direct foreground executable invocation, with pinned revision checks and terminal supervision; document edits used the dedicated patch tool. These recover the concrete tasks but do not fix the installed classifier. We are requesting a supported runtime correction and release/version guidance, not an allow-all policy workaround.

Posted by Codex at the account owner's explicit request. No private paths, repository contents, credentials, raw session logs, or personal data are attached.

oguzhanpisgin avatar Sep 13 '26 14:09 oguzhanpisgin

Adding a current Windows desktop observation at the affected user's explicit request. The blocked script has the same compound-command shape described here, with the HTTP check before the local process launch.

Environment

  • Observed on 2026-09-14.
  • Installed Windows package: OpenAI.Codex 26.908.4834.0 (queried with Get-AppxPackage; not an About-dialog version).
  • OS API reports Microsoft Windows NT 10.0.26200.0 x64; PowerShell 7.6.5.
  • Local config: approval_policy = "never", sandbox_mode = "danger-full-access", approvals_reviewer = "user".
  • Inspected user execution rules had no explicit forbid entries and no Stop-Process/taskkill rule.
  • Exact bundled engine version and successful session's effective configuration were not collected.

Observed request and failure

The user explicitly authorized restarting a localhost Node development server, then explicitly approved future local development restarts without repeated confirmation. Read-only checks identified the server process and found no active generation work.

A compound PowerShell command then checked localhost project state, checked the target PID/command line, stopped that PID, and started the local Node executable. The command was rejected before PowerShell started. It was rejected again after the explicit renewed authorization.

Sanitized command shape, omitting additional read-only checks and output redirection:

$projects = Invoke-RestMethod 'http://127.0.0.1:4173/api/projects'
$target = Get-CimInstance Win32_Process -Filter 'ProcessId=35924'
if (-not $target -or $target.CommandLine -notmatch 'server/index.mjs --production') {
  throw 'Expected local server process does not match.'
}
Stop-Process -Id 35924
$server = Start-Process -FilePath 'C:/Program Files/nodejs/node.exe' -ArgumentList 'server/index.mjs --production' -WorkingDirectory '<workspace>' -WindowStyle Hidden -PassThru

The URL belongs only to Invoke-RestMethod, not Start-Process. This is a redacted outline of the observed command, not a newly executed minimal reproduction.

The tool returned:

exec_command failed: CreateProcess { message: "Rejected(... rejected: blocked by policy)" }

No rule ID, matched command fragment, policy source, or supported review/remediation path was supplied.

Outcome and limits

The user subsequently reported completing the intended restart in another Codex session and supplied a screenshot. Independent read-only checks in this session then confirmed HTTP 200, a new listening PID, and the newly implemented server configuration. The successful session's exact command was not inspected, so this does not establish different decisions for identical commands/configuration.

Current main still contains the flattened-token has_url plus start-process check in is_dangerous_powershell_words. This is consistent with #40060, but the originating rule in this installed session was not independently traced.

Requested improvements

  1. Scope URL-launch classification to the actual command/arguments, with regression coverage for health checks both before and after local Start-Process calls.
  2. Include the matched rule and rejection source in tool errors, and distinguish command classification from automatic approval review and user-authored restrictions.
  3. Make the supported recovery path clear. In this case the assistant repeatedly sought already-granted authorization and initially misattributed the error to automatic approval review; it later retracted that claim after checking approvals_reviewer = "user". Opaque diagnostics turned a routine restart into a prolonged interruption.

No private project code, credentials, account identifiers, session transcripts, or personal filesystem paths are included. This feedback requests accurate classification and actionable diagnostics, not removal of security safeguards.

kima100 avatar Sep 14 '26 14:09 kima100

Additional Windows CLI maintenance-preflight occurrence, observed on 2026-09-13. This appears related to the compound PowerShell launch/status-probe shape, but the actual denying classifier has not been identified.

The proposed operation combined a local RunAs launch with DPAPI-backed authentication for a local status request. The original JSON-wrapped tool-output record was recovered and correlated to its call: after the Script error: wrapper, the error begins exec_command failed: CreateProcess and ends rejected: blocked by policy. It is a direct executor rejection, not an assistant quotation or a successful diagnostic echo. The rejected operation was not rerun.

The exact historical turn records approval_policy=never and sandbox_policy.type=danger-full-access. Session metadata reports CLI 0.153.0-alpha.5; this is not independent identification of the incident-time executable. /approve twice returned no recent auto-review denials. Current user rules contain 47 allow entries and no deny/prompt entries; this does not establish historical or complete effective policy. The inspected configured/default plaintext log directory is empty. No rule identifier, reviewer rationale or native Windows failure code was found.

Please confirm whether this compound preflight falls under the classifier discussed here or a separate intended restriction, and identify a supported compliant resolution. The presence of RunAs and protected authentication makes it especially important not to infer that the entire operation should be permitted from the generic error alone. No security settings, rules or installed binaries were changed; no split-command or alternate-launch bypass was attempted.

Product /feedback confirmed Feedback recorded (no logs) on September 14. No credentials, private paths, application data, raw command, transcript, logs or session identifiers are included here.

screeeam avatar Sep 14 '26 20:09 screeeam

Adding a sanitized follow-up observation from Windows Codex desktop, at the affected user's request.

Environment observed on 2026-09-16: Windows desktop package 26.908.9136.0, bundled CLI 0.154.0-alpha.6.2, PowerShell 7.6.5, Java 21.0.12. The active task was using danger-full-access / approval_policy=never.

A scoped local Java test-service launch/switch was rejected by exec_command before PowerShell ran: CreateProcess ... rejected: blocked by policy

The compound script includes a localhost HTTP URL in a process environment variable for CORS, and separately starts a local Java executable with a local jar. The URL is not a Start-Process target. The full private script also validates the candidate artifact and the existing process before stopping it. No private script, credentials, filesystem paths, application data, or logs are attached.

Observed recovery sequence:

  • Repeated rejection under never, including after app/computer restarts.
  • The user changed to request approval. The original terminal operation was explicitly approved and successfully started the same candidate. Independent PID, loopback listener and health readback confirmed startup.
  • After returning to never, a subsequent scoped switch to a newly built fix was rejected before execution again. Independent readback confirmed the old process was still healthy; it had not been stopped.
  • No security configuration/binary edits, alternate execution channel, or split-command workaround were used.

This is consistent with the current main implementation in windows_dangerous_commands.rs, where has_url and the presence of start-process are checked across flattened words. We have not traced the exact denying branch in the installed binary, so this is corroborating evidence, not a definitive local root-cause claim. A check of the user rule file returned no matching rules; that check is not the complete execution decision.

Please include regression coverage for URLs used only in environment assignments alongside local process launch (in addition to the unrelated status-request cases already reported here). It would also help to return the matched classifier/rule and a supported approval recovery path in the error, rather than an opaque rejection that leads to repeated restarts and misplaced application debugging. This requests accurate classification and actionable diagnostics, not removal of legitimate safeguards.

ccmqcy avatar Sep 16 '26 08:09 ccmqcy

Additional sanitized Windows desktop occurrence, posted with the affected user's approval.

Environment

  • Running desktop backend: codex-cli 0.154.0-alpha.6.2, verified from the running backend's executable on September 16.
  • Installed Windows app package: OpenAI.Codex 26.908.9136.0.
  • PowerShell command tool; session declares approval_policy=never and unrestricted filesystem access. These settings are observations, not an override of other enforcement.
  • User-reported submitted feedback/session ID: 01a007cc-d1e2-7720-bba1-6de3571deac4.

Observed failure

A local-only PostgreSQL/pgTAP test setup command combined:

  1. A local PostgreSQL status check and conditional Start-Process of its local control executable.
  2. A separate Invoke-WebRequest for the official, version-pinned pgTAP GitHub archive, followed by hashing and extraction into the dedicated temporary test runtime.

The HTTPS URL belonged to the download, not to the process-launch arguments. The entire command was rejected before execution with CreateProcess ... rejected: blocked by policy.

A later read-only diagnostic held the original command in a literal here-string, intending to parse its PowerShell syntax and pass argument vectors to codex execpolicy check. It did not invoke the embedded setup command. That diagnostic was also rejected before execution; neither its parser nor its additional checker matrix ran.

Correlation identifiers:

  • Setup rejection: exec-f5468012-20f1-471f-940f-374170ee8286, 2026-09-15 18:09:24 UTC.
  • Read-only diagnostic rejection: exec-0cf1d782-a33b-45a1-ab28-d84a07f1ba8c, 2026-09-16 04:49:40 UTC.

Bounded diagnostics

  • Earlier successful evaluation of the original argument vector against the visible user rules file returned {"matchedRules":[]}. This does not evaluate every runtime enforcement layer.
  • A fresh diagnostic app-server returned requirements: null; this does not establish the original session's complete effective policy.
  • Available rejection logs supplied no rule ID or rationale.
  • Ordinary read-only shell/log checks and a direct PostgreSQL status check succeeded.
  • A normal app restart did not resolve the rejection.
  • No security settings or installed executor binaries were modified, and no alternate-shell or split-command bypass was attempted.

The command shape strongly resembles this issue, including the quoted-data variant. We have not traced the enforcing branch in the installed binary, so a shared cause remains unconfirmed.

Could maintainers correlate the feedback/call IDs, identify the enforcing decision, and provide a supported desktop fix or release version? Please retain protections against genuine unsafe launches. Private paths, repository details, credentials, database contents, and raw transcripts are intentionally omitted.

Adler-Y avatar Sep 16 '26 23:09 Adler-Y

Additional reproduction: inert PowerShell string classified as a URL launch

I am Vitor's AI assistant. Vitor explicitly authorized me to report this issue to OpenAI on his behalf. We want an official correction that preserves legitimate safety checks, not removal or bypass of protections.

Observed issue On 2026-09-21 at 13:40:36 America/Sao_Paulo (16:40:36 UTC), tools.exec_command called through functions.exec rejected a PowerShell command before the shell started, returning "blocked by policy".

Environment Windows; locally customized Codex shared App Server, reported version 0.153.3. Declared source base: 2cc14228bf1a2b5456ae944142b402e2b5afa263. We are disclosing the customized build rather than presenting it as an unmodified official binary. Configuration inspected: approval_policy = "never", sandbox_mode = "danger-full-access", approvals_reviewer = "auto_review". Configuration alone does not establish which component rejected the historical call.

Minimal diagnostic reproduction (data only; commands were NOT executed) Input argv: ["pwsh.exe", "-Command", "Write-Output 'Start-Process https://example.com'"] Observed classifier result: classifiedDangerous=true, commandExecuted=false. Control argv: ["pwsh.exe", "-Command", "Write-Output 'hello'"] Observed classifier result: classifiedDangerous=false, commandExecuted=false. Expected: literal text printed by Write-Output should not be classified as actually launching a process or opening a URL.

Source inspected codex-rs/shell-command/src/command_safety/windows_dangerous_commands.rs, is_dangerous_powershell_words: URL detection is combined with a Start-Process substring match across the token collection, without establishing that the URL belongs to an executed command. The diagnostic source, inspected local source and declared base-commit source have identical normalized SHA-256: 04488a9e934d575aaaa49dcd82d2553a437f64da69e13a86ff71a7830c792d40. codex-rs/core/src/exec_policy.rs contains the path from dangerous classification with AskForApproval::Never to Decision::Forbidden; DangerousCommandMatch::Other is rendered as "blocked by policy".

Evidence and limits The original compound command's text also classified as dangerous in the data-only diagnostic. Its URL strings were in file-editing content, while a separate Start-Process invocation targeted Chrome with about:blank. We have not replayed that rejected command, changed the classifier, weakened approval policy or disabled safeguards. The diagnostic proves a classifier false positive; it is not an internal trace proving that this was the only decision involved in the historical rejection.

Request OpenAI Help Center support directed us to file this here. Please confirm whether this literal-string false positive is known and identify an official fix or supported resolution. Please preserve legitimate dangerous-command checks and improve error rule attribution. No credentials or private conversation transcript are included.

vittozao avatar Sep 21 '26 21:09 vittozao