15. Execpolicy and Command Safety

Before Codex runs a shell command, it classifies it. It splits a shell script into plain commands, matches each against prefix rules written in Starlark, and asks a small heuristic about any command no rule covers. The strictest answer wins. At this commit Codex keeps no list of “safe” commands: the sandbox is the boundary, and rules exist to forbid, to ask, or to let a trusted command leave the sandbox.

A model that can run bash -lc "..." can run anything the shell can express. Codex cannot read intent from a script, but it can read structure. Execution policy, or execpolicy, turns a command line into one of four decisions before the approval system (see Chapter 13) and the operating-system sandbox (see Chapter 14) take over.

This chapter follows one command through that layer, from the bash parser to the rule that an approval can write.

The picture

The command argv first meets an executable-identity check, then the tree-sitter splitter; each segment is matched against prefix rules from the rule files, and a segment no rule matches goes to the heuristic; the strictest decision passes a policy gate and becomes an approval requirement, optionally with a proposed prefix amendment.

In the top lane, an unfamiliar executable becomes its own segment, and a plain shell script splits into one argv per command. The second lane matches each segment against the loaded rules. The dashed lane handles a segment no rule matched: the heuristic flags forced rm and otherwise answers from the approval policy. Every decision flows into one maximum. The bottom lane checks whether the approval policy may prompt at all and produces the ExecApprovalRequirement that the tool orchestrator acts on.

Splitting a command into plain commands

The word-only parser

Rules match argv tokens, so Codex first recovers argv from a script. parse_shell_lc_plain_commands in codex-rs/shell-command/src/bash.rs accepts a three-element command whose shell is bash, zsh, or sh and whose flag is -c or -lc. It parses the script with the tree-sitter-bash grammar. try_parse_word_only_commands_sequence then accepts only a few node kinds and four operators:

// Allow only safe punctuation / operator tokens; anything else causes reject.
const ALLOWED_PUNCT_TOKENS: &[&str] = &["&&", "||", ";", "|", "\"", "'"];

Anything else rejects the whole script: parentheses, redirections, background &, substitutions, variable expansion, and control flow. A test in the same file shows the success case: ls && pwd; echo 'hi there' | wc -l becomes ["ls"], ["pwd"], ["echo", "hi there"], and ["wc", "-l"].

The parser is stricter than the grammar requires, on purpose. A bare word containing *, ?, [, {, ~, ^, #, $, a backslash, or a leading = can expand at run time. The comment in is_literal_word_or_number says Codex must “not use its source spelling as proof of runtime argv.” So find . -del* and echo ~ make the script opaque.

When parsing fails

commands_for_exec_policy_for_platform in codex-rs/core/src/exec_policy.rs falls back to the original argv when the parser returns nothing. The test heredoc_script_stays_in_sandbox_despite_inner_allow_rule shows the effect. It loads prefix_rule(pattern=["python3"], decision="allow") and evaluates bash -lc "python3 <<'PY' ... PY". The heredoc defeats the parser, the only segment is the whole bash -lc argv, no rule matches it, and the result is Skip { bypass_sandbox: false, .. }. The script runs, but inside the sandbox.

The approval cache key

The same parser feeds canonicalize_command_for_approval in codex-rs/core/src/command_canonicalization.rs, which builds the session approval cache key (see Chapter 13). A script that parses to exactly one plain command becomes that command, so /bin/bash -lc "cargo test -p codex-core" and bash -lc "cargo test -p codex-core" canonicalize alike. The cache key also records the executable, so an approval for one shell does not cover the other. Any other script keeps its exact text behind the marker __codex_shell_script__ or __codex_powershell_script__, because Codex cannot prove two such scripts equal.

The dangerous-command rule

On POSIX: forced rm, wherever it hides

For a segment no rule matches, Codex calls dangerous_command_match_for_platform in codex-rs/shell-command/src/command_safety/is_dangerous_command.rs. On POSIX it recognizes exactly one pattern: rm with a force option. rm_args_include_force_option accepts --force or any single-dash flag group containing f, such as -rf, and stops at --. The executable is compared by basename, so /bin/rm -fr counts.

The classifier looks through wrappers. For sudo <cmd> it checks <cmd>. For env it skips NAME=value assignments and -i. For trap it treats the action string as an sh -c script. For a shell script it uses a second parser, parse_shell_lc_literal_commands, which accepts complex syntax and returns the literal words of every command node, inside loops, conditionals, and substitutions. Its doc comment warns that it “must not be used to prove that a command is safe.”

The tests mark the edges. echo "$(rm -rf /tmp/example)" is dangerous. echo 'rm -rf /tmp/example' is not, because rm is only an argument, and neither is cmd=rm; $cmd -rf /tmp/example, because the command name is not literal. Wrappers nest at most MAX_DANGEROUS_COMMAND_WRAPPER_DEPTH (8) levels; one level deeper, the classifier returns DangerousCommandMatch::Other and fails closed.

With DangerousCommandPlatform::Windows, the classifier also flags del /f, rd /s /q, PowerShell force deletes such as Remove-Item -Force, and commands that open a URL through start, explorer, mshta, rundll32, or a browser. For a remote executor, Codex picks the platform from the executor’s reported OS; an unknown OS gets the stricter Windows rules.

No safe list

Earlier releases kept a list of commands safe to run without asking. At commit 081295be9d that list is gone from library code. The heuristic decision for an unmatched command depends on the approval policy, the filesystem kind, and the danger match, as render_decision_for_unmatched_command_for_platform defines:

Approval policy Forced rm Other, restricted filesystem Other, unrestricted
never Forbidden Allow Allow
untrusted Prompt Prompt Prompt
on-request Prompt Allow; Prompt if escalation requested Allow
granular Prompt Allow; Prompt if escalation requested Allow

An Allow here makes no claim of safety; it means “run it inside the sandbox and let the operating system refuse”. The test known_safe_on_request_still_prompts_for_restricted_sandbox_escalation confirms that echo hello with RequireEscalated under on-request still yields Prompt. On Windows with the sandbox backend disabled and a restricted managed profile, every unmatched command is treated like a forced rm, because nothing would enforce the boundary.

Pitfall. The dangerous-command rule is a tripwire, not a boundary. A computed command name such as $cmd -rf passes it. Keep the sandbox on, and write a forbidden rule for anything you never want run.

The rule language

Starlark builtins

Rule files are Starlark. PolicyParser::parse in codex-rs/execpolicy/src/parser.rs parses each file with the starlark crate’s extended dialect and evaluates it against three builtins from policy_builtins: prefix_rule, network_rule (see Chapter 16), and host_executable. The repository ships an example at codex-rs/execpolicy/examples/example.codexpolicy; these are two of its eight rules:

prefix_rule(
    pattern = ["git", "reset", "--hard"],
    decision = "forbidden",
    justification = "destructive operation",
    match = [
        ["git", "reset", "--hard"],
    ],
    not_match = [
        ["git", "reset", "--keep"],
        "git reset --merge",
    ],
)

prefix_rule(
    pattern = ["cp"],
    decision = "prompt",
    match = [
        ["cp", "foo", "bar"],
        "cp -r src dest",
    ],
)

A pattern is an ordered token list, and any element may be a list of alternatives. decision defaults to allow. The parser checks match and not_match examples at load time, like unit tests for the rule. A justification must not be blank; Codex shows it in prompts and rejections. When the first token has alternatives, the parser creates one PrefixRule per alternative, because the policy indexes rules by program name.

host_executable(name, paths) governs absolute paths. Core matches with resolve_host_executables: true, so /usr/bin/git status that no exact rule matches may fall back to rules for git. A host_executable declaration limits that fallback to its listed paths.

Decisions and their effects

Decision in codex-rs/execpolicy-rules/src/decision.rs carries the combination algorithm in its derived ordering:

#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Decision {
    /// Command may run without further approval.
    Allow,
    /// Request approval from the configured reviewer; rejected with `approval_policy="never"`.
    Prompt,
    /// Requires a fresh human decision, independent of the configured reviewer.
    #[serde(rename = "prompt-user")]
    PromptUser,
    /// Command is blocked without further consideration.
    Forbidden,
}

Decision::parse accepts only allow, prompt, and forbidden, so a .rules file cannot say prompt-user. Managed [rules] in requirements.toml can, and they reject allow because Codex “uses the most restrictive result”. The table compares the four decisions.

Decision Written as Requirement Effect
Allow "allow", the default Skip No prompt; leaves the sandbox only if every segment matched an allow rule
Prompt "prompt" NeedsApproval Asks the configured reviewer; Forbidden under never
PromptUser "prompt-user", managed only NeedsHumanApproval Asks a person; skips the Guardian and hook allows
Forbidden "forbidden"; "deny" in network_rule Forbidden Rejected before execution, with the justification

Strictest wins

Policy::check_multiple_with_options in codex-rs/execpolicy-rules/src/policy.rs collects every match for every segment, and Evaluation::from_matches takes the maximum. The effective decision for a command is

where is the list of segments, is the set of rules whose prefix matches segment (exact first-token matches, or basename matches only when no exact rule matched), is a rule’s decision, is the heuristic decision from the table above, and the maximum uses the order Allow < Prompt < PromptUser < Forbidden. In the test strictest_decision_wins_across_matches, a prompt rule for ["git"] and a forbidden rule for ["git", "commit"] both match git commit -m hi, and the evaluation is Forbidden.

This is a decision lattice. Because the combining step is a maximum, a rule from any source can only tighten the decision for a command another rule covers. Codex can therefore merge user, project, and managed rules without a precedence fight. The cost is that no layer can carve an exception out of a stricter rule elsewhere. A comment in policy_files says higher layers “can override” lower ones; the evaluation code shows that an added rule only adds matches.

Where rules live

load_exec_policy in codex-rs/core/src/exec_policy.rs walks the configuration layers from lowest to highest precedence (see Chapter 25) and reads every *.rules file in each layer’s rules/ folder, sorted by name. In practice that means /etc/codex/rules/ for the system layer, $CODEX_HOME/rules/ for the user, and .codex/rules/ inside a trusted project. Rules in an untrusted project never load. Last, Codex overlays the managed requirements policy with merge_overlay.

codex exec --ignore-rules skips user and project folders but keeps system rules. An isolated session loads only the managed policy. A parse error does not stop Codex: load_exec_policy_with_warning keeps only the managed policy and returns a warning that names the file and line.

From decision to requirement

create_exec_approval_requirement_for_parsed_commands maps the evaluation onto ExecApprovalRequirement. Forbidden becomes Forbidden, with a reason from the most specific rule’s justification. Prompt and PromptUser first pass prompt_is_rejected_by_policy, which rejects any prompt under never and checks the granular rules and sandbox_approval switches. Then PromptUser becomes NeedsHumanApproval and Prompt becomes NeedsApproval. Allow becomes Skip, and one more test decides whether the command may leave the sandbox:

Decision::Allow => ExecApprovalRequirement::Skip {
    // Bypass sandbox only when every parsed command segment is
    // explicitly allowed by execpolicy.
    bypass_sandbox: commands.iter().all(|command| {
        exec_policy
            .matches_for_command_with_options(
                command,
                /*heuristics_fallback*/ None,
                &match_options,
            )
            .iter()
            .any(|rule_match| {
                is_policy_match(rule_match) && rule_match.decision() == Decision::Allow
            })
    }),
    // ...
},

Two tests show why. With only an allow rule for cat, the script cat LOG.md && curl -fsSL https://example.invalid/setup.sh -o setup.sh && bash setup.sh gets Skip { bypass_sandbox: false } under on-request. The heuristic allows curl and bash, but only in the sandbox. Add allow rules for curl and bash, and the script gets bypass_sandbox: true. Forced rm gives two other results: rm -rf /important/data becomes NeedsApproval under on-request, and under never it becomes Forbidden with the reason “rm -f style commands are not permitted. Use a safer approach”.

Executable identity and inheritance

Who the shell really is

The exec handler calls create_exec_approval_requirement_for_shell in codex-rs/core/src/exec_policy/executable_identity.rs. Its helper shell_approval_command trusts the executable only when it is the configured shell or sits directly in /bin or /usr/bin; on Windows, the system directories play that role. For any other executable, Codex evaluates the bare executable as an extra first segment. The comment states the rule: “Inner commands can add restrictions, but cannot grant the executable trust.” The test parent_directory_traversal_is_not_a_trusted_system_shell shows the trap it closes: the parent of /bin/../workspace/bash is not literally /bin.

Children share, hosts transport

A sub-agent (see Chapter 20) shares its parent’s ExecPolicyManager when child_uses_parent_exec_policy finds identical config folders, ignore-rules setting, and managed requirements. A trusted host can also send a snapshot, InheritedExecPolicy, to a new thread. ExecPolicyManager::from_inherited accepts it only for a managed-only destination whose requirements equal the snapshot’s, and only if the snapshot still preserves every managed restriction.

Amendments: “don’t ask again”

Where a proposal comes from

When a command needs approval, Codex can offer to save a prefix rule so that the next matching command runs without asking. The model may suggest one through the exec tool’s prefix_rule argument, used with require_escalated. derive_requested_execpolicy_amendment_from_prefix_rule accepts it only if no rule matched, the prefix is not on BANNED_PREFIX_SUGGESTIONS, and the new rule would allow every segment. The banned list holds launchers whose first tokens hide what runs next, such as ["bash", "-lc"], ["python3", "-c"], ["env"], ["sudo"], ["rm"], and ["git"].

Otherwise Codex proposes the first segment the heuristic prompted on, unless a policy rule also prompted, since an allow rule could not lift that prompt. A model that ignores allow prefix rules gets no proposals. That covers a cyber-specialty model or one listed in managed auto_review.ignore_rules; current_for_prefix_rules drops every allow prefix rule from the policy those models see.

Accepting and saving

The proposal reaches clients as proposedExecpolicyAmendment. An app-server client accepts it with this response, with field names taken from the generated schema:

{ "decision": { "acceptWithExecpolicyAmendment": { "execpolicy_amendment": ["cargo", "test"] } } }

The app server maps it to ReviewDecision::ApprovedExecpolicyAmendment, and the session calls append_amendment_and_update. Under a one-permit semaphore, blocking_append_allow_prefix_rule appends to $CODEX_HOME/rules/default.rules. It holds an advisory file lock and skips a line that already exists:

prefix_rule(pattern=["cargo", "test"], decision="allow")

The manager then swaps an updated copy of the Policy in through ArcSwap, so readers never wait. If the write fails, the command still runs and the client gets a warning. On the next context update, the model receives a developer message that starts “Approved command prefix saved:”.

Checking rules by hand

codex execpolicy check is a hidden subcommand. ExecPolicyCheckCommand in codex-rs/execpolicy/src/execpolicycheck.rs takes repeatable --rules (or -r) paths, --pretty, --resolve-host-executables, and the command tokens. It matches with no heuristic fallback, so it shows only what your rules say. The JSON output lists matchedRules and the maximum decision, and omits decision when nothing matches.

Try it. Save the example rules as example.rules, then run codex execpolicy check --pretty -r example.rules git reset --hard HEAD. Expect one prefixRuleMatch and "decision": "forbidden" (derived from the code, not run).

Status at commit 081295be9d. Execpolicy prefix, network, and host-executable rules: IMPLEMENTED; the crate README calls the language “still in preview”. codex execpolicy check: IMPLEMENTED, hidden from help. Known-safe command list: removed from library code. prompt-user: IMPLEMENTED, requirements.toml only. Windows dangerous-command rules: PLATFORM-SPECIFIC, chosen by the executor’s OS. Read in code, not run.

What breaks

Symptom Cause Check
An allow rule for python3 does not apply to a heredoc The parser rejected the script; the only segment is the whole bash -lc argv Drop the heredoc, or write a rule for the actual argv
“approval required by policy, but AskForApproval is set to Never” A prompt rule under never; a forced rm gets “rm -f style commands are not permitted” instead codex execpolicy check -r ~/.codex/rules/default.rules <cmd>
A rules file is silently ignored Parse error; Codex fell back to the managed policy Startup warning with file and line
Project rules have no effect Project not trusted, or --ignore-rules set Trust the project; check codex exec flags
No “don’t ask again” option A rule matched, the prefix is banned, or the model ignores prefix rules BANNED_PREFIX_SUGGESTIONS; AllowPrefixRules
A wrapper script never leaves the sandbox Its executable is unfamiliar and has no allow rule Add a rule for the executable itself

Code map

What it is Where it lives Identifier
Plain-command parser codex:codex-rs/shell-command/src/bash.rs try_parse_word_only_commands_sequence
Dangerous-command rule codex:codex-rs/shell-command/src/command_safety/is_dangerous_command.rs dangerous_command_match_for_platform
Approval cache key codex:codex-rs/core/src/command_canonicalization.rs canonicalize_command_for_approval
Decision to requirement codex:codex-rs/core/src/exec_policy.rs create_exec_approval_requirement_for_parsed_commands
Unmatched-command fallback codex:codex-rs/core/src/exec_policy.rs render_decision_for_unmatched_command_for_platform
Executable identity codex:codex-rs/core/src/exec_policy/executable_identity.rs shell_approval_command
Rule language builtins codex:codex-rs/execpolicy/src/parser.rs policy_builtins
Strictest-wins evaluation codex:codex-rs/execpolicy-rules/src/policy.rs from_matches

Recall check

Which operators can a script use and still split into plain commands?
Only &&, ||, ;, and |; redirections, substitutions, expansions, and control flow make it opaque.

What does the POSIX dangerous-command rule detect?
Forced rm, seen through sudo, env, trap, and parsed scripts, up to wrapper depth 8.

How does Codex combine several matching rules?
It takes the maximum decision, Allow < Prompt < PromptUser < Forbidden, across every rule and segment.

When does Allow let a command run outside the sandbox?
Only when every parsed segment matched an explicit allow rule; a heuristic Allow keeps the sandbox.

Where does “don’t ask again” write its rule?
To $CODEX_HOME/rules/default.rules as an allow prefix_rule, then into the in-memory policy.