13. Approvals and Permission Profiles
Codex lets the operating-system sandbox carry most of the safety load and asks for approval only when a command needs more than the sandbox allows. The approval policy decides who may be asked; the permission profile decides what the sandbox allows. Every command meets execpolicy first, then hooks, then the Guardian when automatic review applies, then a person, and an escape from the sandbox always needs a fresh decision.
An agent that asks before every command is safe and useless; one that
never asks is fast and dangerous. Codex resolves the tension with two
settings. The approval policy, AskForApproval, says when
the agent may stop and ask. The permission profile,
PermissionProfile, says what a command can touch when
nobody is asked: which paths it may read or write and whether it may
reach the network.
This chapter follows one tool call from the model’s request to a decision: the policies and presets, the approval requirement, the order of the deciders, and how a person’s answer returns to the engine. It then covers what Codex remembers, what happens after a sandbox denial, and how the permission profile replaced the older sandbox policy. Chapter 14 explains how each operating system enforces the profile.
The picture
In the top lane, execpolicy rules and the approval policy reduce the tool call to one approval requirement. Forbidden goes back to the model as a rejection; Skip goes to the sandboxed first attempt. The middle lane holds the reviewers in the order the code consults them: hooks, the Guardian, a person. In the bottom lane, the first attempt runs under the platform sandbox. If it fails and the output looks like a sandbox denial, the orchestrator may retry without the sandbox, but only after a new approval that the first one does not cover.
The approval policy
Four variants
AskForApproval in
codex-rs/protocol/src/protocol.rs has four variants. Its
serialized names are the ones you write in config.toml,
except untrusted: config loading rejects it with the error
approval_policy = "untrusted" is no longer supported; remove this setting,
and Codex applies it only by default to a project marked untrusted.
| Variant | Config value | Doc comment summary |
|---|---|---|
UnlessTrusted |
untrusted (internal) |
For untrusted projects: ask unless an exec policy rule allows the command |
OnRequest |
on-request |
The model decides when to ask (the default) |
Granular(GranularApprovalConfig) |
{ granular = { ... } } |
Per-category allow or auto-reject |
Never |
never |
Never ask; failures go back to the model |
OnRequest is the #[default] variant. It
also carries #[serde(alias = "on-failure")], so an old
config that names the retired on-failure policy still
loads, as on-request.
Granular options
GranularApprovalConfig has five booleans, one per prompt
category, including Model Context Protocol (MCP) elicitations. The doc
comment states the rule: a true field lets that category
reach a reviewer, and a false field rejects the request
automatically instead of showing it.
| Field | Prompt category it controls |
|---|---|
sandbox_approval |
Sandbox escalation, including require_escalated
requests |
rules |
Prompts from execpolicy prompt rules |
skill_approval |
Skill script execution (defaults to false) |
request_permissions |
The request_permissions tool (defaults to false) |
mcp_elicitations |
MCP elicitation prompts |
A test in codex-rs/core/src/config/config_tests.rs
writes the inline form:
approval_policy = { granular = { sandbox_approval = false, rules = false, request_permissions = true, mcp_elicitations = false } }The field doc for sandbox_approval adds one exception:
dangerous commands can still request approval within the existing
permissions. Turning off sandbox approvals blocks escapes from the
sandbox, not reviews of a forced rm.
Presets
Most users pick a preset instead.
builtin_approval_presets in
codex-rs/utils/approval-presets/src/lib.rs pairs a policy
with a built-in permission profile, for the terminal user interface
(TUI) and other clients to share.
| Preset id | Label | Policy | Permission profile |
|---|---|---|---|
read-only |
Read Only | OnRequest |
:read-only |
auto |
Default | OnRequest |
:workspace |
full-access |
Full Access | Never |
:danger-full-access (Disabled) |
The preset is a pair because neither half is safe alone:
on-request with full access asks only when the model
chooses to.
Who decides, and in what order
The requirement
The shell tool handler asks ExecPolicyManager to reduce
the command, the approval policy, the permission profile, and the
requested sandbox override to one ExecApprovalRequirement,
defined in codex-rs/core/src/tools/sandboxing.rs:
pub(crate) enum ExecApprovalRequirement {
/// No approval required for this tool call.
Skip {
bypass_sandbox: bool,
proposed_execpolicy_amendment: Option<ExecPolicyAmendment>,
},
/// Approval required for this tool call.
NeedsApproval {
reason: Option<String>,
proposed_execpolicy_amendment: Option<ExecPolicyAmendment>,
},
/// A fresh human decision is required for each execution attempt.
NeedsHumanApproval { reason: Option<String> },
/// Execution forbidden for this tool call.
Forbidden { reason: String },
}The mapping from an execpolicy Decision is direct.
Forbidden becomes Forbidden.
Allow becomes Skip, and
bypass_sandbox is true only when an explicit allow rule
matches every parsed segment of the command. Prompt becomes
NeedsApproval, unless
prompt_is_rejected_by_policy turns it into
Forbidden: any prompt under never, a rule
prompt when granular rules is false, or a sandbox prompt
when granular sandbox_approval is false. A managed
prompt-user decision becomes
NeedsHumanApproval. Chapter
15 covers the rule language.
ToolOrchestrator::run in
codex-rs/core/src/tools/orchestrator.rs acts on the
requirement. Forbidden returns
ToolError::Rejected(reason) before anything runs.
Skip records a decision with source Config and
goes straight to the first attempt, unless strict automatic review is
on. Every other requirement calls
Session::request_approval.
Hooks, then the Guardian, then the user
request_approval_with_user_prompt in
codex-rs/core/src/tools/approvals.rs is a chain of
responsibility. Each link can settle the decision or pass it on, and the
code fixes the order.
check_approval_requirementruns first. ANeedsHumanApprovalcommand is rejected when the session requires automatic review, with the message “Managed command policy requires human approval, but this session requires automatic review.”run_permission_request_hooksruns thePermissionRequesthooks (see Chapter 18). A hook deny always wins. A hook allow settles the decision, except forNeedsHumanApproval, where the code ignores it.- With no hook verdict,
request_reviewer_approvalsendsNeedsHumanApprovalstraight to the user. Otherwise it callsrequest_guardian_approval. - The Guardian answers when
routes_approval_policy_to_guardianis true (the policy ison-requestor granular, andapprovals_reviewerisauto_review), or when strict automatic review or managed requirements demand it. A Guardian verdict, allow or deny, is final, and no user prompt appears. Only when it returnsNonedoes the request fall through to the user.
Automatic review is often the default. The
ApprovalsReviewer enum defaults to User, but
when approvals_reviewer is unset, config loading in
codex-rs/core/src/config/mod.rs picks
AutoReview if four conditions hold: the provider is OpenAI,
the STABLE guardian_approval flag is on (its default), the
effective profile is workspace-write, and the policy routes to the
Guardian. The Default preset with the OpenAI provider meets all four, so
its prompts go to the Guardian, not to you. The result carries an
ApprovalResolutionSource of Hook,
Guardian, or User, which matters after a
sandbox denial. Chapter 16
covers how the Guardian reviews.
A managed rule shows the chain at work. A test in
codex-rs/core/tests/suite/scenarios_managed_human_approval_tests.rs
writes this managed requirement:
allowed_approvals_reviewers = ["auto_review", "user"]
[[rules.prefix_rules]]
pattern = [{ token = "echo" }]
decision = "prompt-user"
justification = "A person must approve this command."Every echo becomes NeedsHumanApproval. A
hook allow is ignored, and the Guardian is skipped. The user prompt
carries ExecApprovalKind::HumanCommand, offers only
approve, deny, and abort, and gets a fresh approval_id on
each attempt. PendingApproval::validate in
codex-rs/core/src/state/turn.rs turns any other answer into
a denial: “Managed command policy requires a one-time human
approval.”
How the decision travels
The user path is a request and reply across a channel.
Session::request_command_approval in
codex-rs/core/src/session/mod.rs creates a
tokio::sync::oneshot channel, stores the sender in the turn
state as a PendingApproval keyed by the approval id, and
only then emits EventMsg::ExecApprovalRequest. The comment
fixes the order: “Add the tx_approve callback to the map before sending
the request.”
The app server turns the event into a server-to-client JSON-RPC
request (see Chapter 21). For a
command, the method is
item/commandExecution/requestApproval; for a patch, it is
item/fileChange/requestApproval. Trimmed, and with
illustrative ids, the request looks like this:
{"method": "item/commandExecution/requestApproval", "id": 8,
"params": {"threadId": "thr_1", "turnId": "turn_3", "itemId": "call_7",
"command": "cargo test", "cwd": "/repo",
"proposedExecpolicyAmendment": ["cargo", "test"],
"availableDecisions": ["accept",
{"acceptWithExecpolicyAmendment": {"execpolicy_amendment": ["cargo", "test"]}},
"cancel"]}}The client answers with a decision.
on_command_execution_request_approval_response in
codex-rs/app-server/src/bespoke_event_handling.rs maps it
back to a ReviewDecision and submits
Op::ExecApproval. The session’s
resolve_exec_approval removes the
PendingApproval and sends the decision through the oneshot.
If the channel closes first, the code returns
ReviewDecision::Abort, so a lost client fails closed.
ReviewDecision has eight variants. The table maps each
to its app server v2 name and its effect.
ReviewDecision |
v2 decision | Effect in the engine |
|---|---|---|
Approved |
accept |
Run once |
ApprovedForSession |
acceptForSession |
Run; cache the key for the session |
ApprovedExecpolicyAmendment |
acceptWithExecpolicyAmendment |
Run; save an allow prefix rule |
NetworkPolicyAmendment |
applyNetworkPolicyAmendment |
Persist a host allow or deny |
Denied { rejection } |
decline |
ToolError::Rejected; the turn continues |
Abort |
cancel |
CodexErr::TurnAborted; the turn stops |
TimedOut |
(shown as decline) |
Rejection with the auto-review timeout text |
ApprovedMcpPolicyAmendment |
(shown as decline) |
MCP only; elsewhere a rejection |
The default ReviewDecision is
Denied { rejection: "denied" }, so a missing decision also
fails closed. The engine also chooses what a client may offer.
default_available_decisions in
codex-rs/protocol/src/approvals.rs offers
Approved, the prefix amendment when one is proposed, and
Abort for a command. A network prompt adds
ApprovedForSession and a host amendment. The TUI renders
whatever list arrives, such as “Yes, proceed” and “No, and tell Codex
what to do differently”.
Auto-run, ask, or reject
No safe-command allowlist
At commit 081295be9d, Codex keeps no list of commands
that are safe to run without asking. The phrase “known safe” survives
only in three test names in
codex-rs/core/src/exec_policy_tests.rs. When no rule
matches a command,
render_decision_for_unmatched_command_for_platform in
codex-rs/core/src/exec_policy.rs decides, and under
on-request it leans on the sandbox:
AskForApproval::OnRequest => {
match file_system_sandbox_policy.kind {
FileSystemSandboxKind::Unrestricted | FileSystemSandboxKind::ExternalSandbox => {
Decision::Allow
}
FileSystemSandboxKind::Restricted => {
// In restricted sandboxes, do not prompt for non-escalated,
// non-dangerous commands; let the sandbox enforce
// restrictions without a user prompt.
if sandbox_permissions.requests_sandbox_override() {
Decision::Prompt
} else {
Decision::Allow
}
}
}
}An unmatched command under on-request therefore runs
inside the sandbox with no prompt. It asks only when the model requests
a sandbox override. The one exception is a dangerous command. On POSIX,
dangerous_command_match_for_platform in
codex-rs/shell-command/src/command_safety/is_dangerous_command.rs
flags exactly one pattern: rm with a force option
(-f, --force, or a combined flag such as
-rf). It looks through sudo, past
env assignments, into the action of a trap,
and into every literal command of a bash -lc script that
tree-sitter can parse. Past a wrapper depth of 8 it treats the command
as dangerous, so deep nesting fails closed. On Windows, a separate set
of PowerShell checks also applies.
The decision table
The table shows what happens to common situations under each policy,
with no execpolicy rule matching unless the row says so. It assumes a
restricted filesystem, such as the :workspace profile. The
granular column sets every field to false.
| Situation | untrusted |
on-request |
granular, all false |
never |
|---|---|---|---|---|
| Harmless unmatched command | Ask | Run sandboxed | Run sandboxed | Run sandboxed |
Forced rm |
Ask | Ask | Ask | Reject |
Execpolicy prompt rule |
Ask | Ask | Reject | Reject |
Model asks require_escalated |
Ask | Ask | Reject | Reject |
| Shell command denied by sandbox | Retry after approval | Denial to model | Denial to model | Denial to model |
| Patch denied by sandbox | Retry after approval | Retry after approval | Denial to model | Denial to model |
| Patch outside writable roots | Ask | Ask | Reject | Reject |
Three cells need a note. The forced rm under granular
asks because a dangerous command may request review without new
permissions. The require_escalated rejections under
granular and never happen earlier, in the unified exec
handler, with the message “you cannot ask for escalated permissions if
the approval policy is …”. The patch rows come from
assess_patch_safety in
codex-rs/core/src/safety.rs (see Chapter 11). It auto-approves a patch
whose every target is writable, but still runs it inside the sandbox,
because, a comment notes, its paths may be “hard links to files outside
the writable roots.”
Remembering a decision
Session-scoped approvals
ApprovalStore in
codex-rs/core/src/tools/sandboxing.rs is a
HashMap<String, ReviewDecision> keyed by the JSON
form of a cache key. with_cached_approval checks the store
before it asks. It skips the prompt only when every key is already
ApprovedForSession, and when a user answers
ApprovedForSession it stores each key separately. A patch
has one key per file, so approving a three-file patch for the session
also covers a later patch that touches only one of those files.
The exec key holds the environment id, the executable, the
canonicalized command, the working directory, the terminal flag, and the
requested sandbox permissions, paired with a fingerprint of the
requirements exec policy. canonicalize_command_for_approval
in codex-rs/core/src/command_canonicalization.rs reduces
bash -lc "cargo test" to ["cargo", "test"] for
both /bin/bash -lc and bash -lc, though the
separate executable field still keeps their keys apart; a complex script
keeps its exact text behind a __codex_shell_script__
marker. MCP calls, network access, terminal input, and permission
requests return no cache keys and always reach a reviewer.
Saved command prefixes
The stronger memory outlives the session. The model may propose a
prefix_rule such as ["cargo", "test"] when it
asks for escalation, and Codex derives one itself when its own fallback,
not a rule, asked for the prompt. If the user picks
ApprovedExecpolicyAmendment,
resolve_exec_approval calls
persist_execpolicy_amendment.
ExecPolicyManager::append_amendment_and_update takes a
semaphore and appends one line to
$CODEX_HOME/rules/default.rules on a blocking thread:
prefix_rule(pattern=["cargo", "test"], decision="allow")
It then adds the rule to the in-memory policy, and a developer
message starting “Approved command prefix saved:” tells the model.
BANNED_PREFIX_SUGGESTIONS stops Codex from proposing a bare
interpreter such as bash -lc, which would approve
everything. Note the consequence: an explicit allow rule yields
Skip { bypass_sandbox: true }, so the saved prefix also
runs later matches outside the sandbox. A comment in
exec_policy.rs states the trade: “A reusable allow rule can
bypass the sandbox on later calls.”
Escalation after a sandbox denial
The first attempt runs under the platform sandbox. When it fails, the
orchestrator checks for SandboxErr::Denied, which the exec
layer raises when is_likely_sandbox_denied sees a non-zero
exit and a telltale keyword such as “operation not permitted” (see Chapter 14). The orchestrator then
decides whether to offer an unsandboxed retry.
The shell runtime uses the default
wants_no_sandbox_approval, which returns true for
untrusted, false for on-request and
never, and the sandbox_approval field for
granular. So under on-request or never, a
shell command that the sandbox denied is never retried without the
sandbox. The model gets the denial, with its original output, and must
try another approach or ask for escalation explicitly. The one exception
is a network denial from the managed proxy under on-request
(see Chapter 16). The
apply_patch runtime overrides the method to return true for
on-request too, so a denied patch can be retried after
approval under the default preset.
When a retry is allowed, the prompt reason is the fixed string
“command failed; retry without sandbox?”, or
Network access to "<host>" is blocked by policy. for
a proxy denial. The second attempt runs with
SandboxType::None, and the code rewrites the approval
action’s sandbox_permissions to
RequireEscalated so that the reviewer, and the session
cache, see the escalation that will actually run. Whether the retry
needs a second prompt depends on who approved the first attempt:
// Human and policy approvals keep their existing retry scope. A
// Guardian verdict only covers the authority of the reviewed action.
let retry_preapproved = !human_once
&& matches!(
initial_approval_source,
Some(ApprovalResolutionSource::User | ApprovalResolutionSource::Hook)
);A user or hook approval carries over, so an untrusted
user who approved make install is not asked twice. A
Guardian approval does not: the Guardian judged a sandboxed command, so
the retry goes back through review. A NeedsHumanApproval
approval never carries over either. This is the
fresh-authority-per-escalation pattern: every widening of power needs a
decision made with that power in view.
The sandbox policy
SandboxPolicy in
codex-rs/protocol/src/protocol.rs is the older description
of what a command may touch. It survives behind the legacy
sandbox_mode setting.
| Variant | Disk | Network |
|---|---|---|
DangerFullAccess |
Full read and write | Full |
ReadOnly { network_access } |
Read only | Off unless network_access |
WorkspaceWrite { writable_roots, ... } |
Read all; write roots | Off unless network_access |
ExternalSandbox { network_access } |
Full; caller isolates | As configured |
WorkspaceWrite always adds defaults to its configured
writable_roots: the current working directory,
/tmp on Unix unless exclude_slash_tmp is set,
and $TMPDIR unless exclude_tmpdir_env_var is
set. Each root becomes a WritableRoot, and
is_path_writable refuses a path under any of its
read_only_subpaths.
default_read_only_subpaths_for_writable_root fills that
list from four protected metadata names,
PROTECTED_METADATA_PATH_NAMES in
codex-rs/protocol/src/permissions.rs: .git
(and the real gitdir when .git is a pointer file),
.agents, .codex, and .aws. The
comment on .aws gives the threat: “AWS profiles can select
credential helpers that the application executes.” For the working
directory, .codex is protected even before it exists, so
creating it still goes through approval.
Permission profiles
The type
PermissionProfile in
codex-rs/protocol/src/models.rs is the current form. Its
doc comment calls it the “canonical active runtime permissions for a
conversation, turn, or command.”
pub enum PermissionProfile {
/// Codex owns sandbox construction for this profile.
Managed {
file_system: ManagedFileSystemPermissions,
network: NetworkSandboxPolicy,
},
/// Do not apply an outer sandbox.
Disabled,
/// Filesystem isolation is enforced by an external caller.
External { network: NetworkSandboxPolicy },
}A managed filesystem is a list of entries, each a path, a special
path, or a glob with an access mode of read,
write, or deny. When two equally specific
entries name the same path, the doc comment on
FileSystemAccessMode says deny beats
write and write beats read.
Special paths such as :root, :minimal,
:workspace_roots, :tmpdir, and
:slash_tmp stand for locations that differ per machine. An
unknown special path from a newer Codex parses as
FileSystemSpecialPath::Unknown and is ignored with a
warning; the doc comment records that Codex 0.112.0 rejected such values
and broke newer configs.
Catalog, selection, and resolution
Three profiles are built in: :read-only,
:workspace, and :danger-full-access. You
define more under [permissions.<id>] and select one
with default_permissions. This example is the fixture in
config_toml_deserializes_permission_profiles, trimmed:
default_permissions = "dev"
[permissions.dev]
description = "Day-to-day workspace access."
[permissions.dev.workspace_roots]
"~/code/openai" = true
"~/code/ignored" = false
[permissions.dev.filesystem]
":minimal" = "read"
"/tmp/secret.env" = "deny"
[permissions.dev.filesystem.":workspace_roots"]
"." = "write"
"docs" = "read"
[permissions.dev.network]
enabled = true
mode = "full"
[permissions.dev.network.domains]
"openai.com" = "allow"Resolution runs in compile_permission_profile in
codex-rs/core/src/config/permissions.rs. A name that starts
with : resolves to a built-in. Any other name goes through
resolve_profile, which follows extends links
parent first, so child keys override parent keys, and reports a cycle by
name. A profile may extend :read-only or
:workspace, but not :danger-full-access. The
enabled workspace roots are resolved, deduplicated, and materialized
into the filesystem policy. When no default_permissions is
set, derive_permission_profile falls back to the legacy
sandbox_mode, which defaults to read-only. A
trusted or untrusted project raises that default to
workspace-write.
Clients see the choices through
permission_profile_catalog in
codex-rs/core/src/config/permission_profile_catalog.rs. It
lists the three built-ins first, then the user profiles, each with an
allowed flag computed against managed requirements (see Chapter 25).
PermissionProfileState then holds the selected profile for
a session inside a Constrained wrapper, so a later change
that the requirements forbid fails instead of applying.
Status at commit 081295be9d.
AskForApproval, presets, the approval chain, session
caching, and saved prefixes: IMPLEMENTED.
guardian_approval: STABLE, on by default.
write_stdin_approval: STABLE, on.
exec_permission_approvals (the
with_additional_permissions override) and
request_permissions_tool: UNDER DEVELOPMENT, off. Windows
PowerShell danger checks: PLATFORM-SPECIFIC. Read in code, not run.
What breaks
| Symptom | Cause | Check |
|---|---|---|
| A command fails with “Operation not permitted” and the model gives up | on-request never retries a shell command
unsandboxed |
Use granular sandbox_approval = true;
wants_no_sandbox_approval |
| “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 (Chapter 15) |
| “Managed command policy requires human approval, but this session requires automatic review.” | A prompt-user rule plus a required auto review |
allowed_approvals_reviewers in requirements |
Writes to .git/hooks or .codex/config.toml
fail inside the workspace |
Protected metadata names stay read-only | PROTECTED_METADATA_PATH_NAMES |
| A saved prefix now runs outside the sandbox | An explicit allow rule sets bypass_sandbox |
$CODEX_HOME/rules/default.rules |
| “Don’t ask again” never appears for a command | The prefix is banned or a rule already matched | BANNED_PREFIX_SUGGESTIONS |
| Config fails: “cannot extend unsupported built-in profile” | extends = ":danger-full-access" |
extensible_builtin_parent_profile |
Code map
| What it is | Path | Identifier |
|---|---|---|
| Approval policy and decisions | codex:codex-rs/protocol/src/protocol.rs |
AskForApproval |
| Approval requirement and session cache | codex:codex-rs/core/src/tools/sandboxing.rs |
ExecApprovalRequirement |
| Hook, Guardian, user chain | codex:codex-rs/core/src/tools/approvals.rs |
request_approval_with_user_prompt |
| First attempt and escalated retry | codex:codex-rs/core/src/tools/orchestrator.rs |
retry_preapproved |
| Unmatched-command fallback | codex:codex-rs/core/src/exec_policy.rs |
render_decision_for_unmatched_command_for_platform |
Forced rm classifier |
codex:codex-rs/shell-command/src/command_safety/is_dangerous_command.rs |
dangerous_command_match_for_platform |
| Oneshot approval request | codex:codex-rs/core/src/session/mod.rs |
request_command_approval |
| Permission profile resolution | codex:codex-rs/core/src/config/permissions.rs |
compile_permission_profile |
Recall check
Under on-request, what happens to a harmless
command that no rule matches?
It runs inside the sandbox with no prompt; Codex has no safe-command
allowlist at this commit.
In what order do the deciders run?
PermissionRequest hooks, then the Guardian (normally for
on-request or granular with auto_review; its
verdict is final), then the user.
How does a prompt-user rule change that
order?
It produces NeedsHumanApproval, which ignores a hook allow,
skips the Guardian, and accepts only approve, deny, or abort.
Why does a Guardian approval not cover the unsandboxed
retry?
The Guardian judged the sandboxed command, so
retry_preapproved counts only user and hook approvals.
What does saving a command prefix do besides skipping future
prompts?
It appends an allow rule to default.rules, and an explicit
allow rule lets matching commands bypass the sandbox.