A coding agent runs commands on your computer, and before you hand it the keyboard you need to know two things: what it can touch on its own, and when it stops to ask for your permission. In Codex these are two distinct controls, and the distinction is what avoids most misunderstandings. The sandbox (sandbox_mode) is the technical boundary: it says where the agent can write and whether commands can use the network. The approval (approval_policy) decides when the agent must stop and ask before crossing that boundary. According to the documentation read on November 13, 2026, locally the low-friction combination is workspace-write plus on-request: it writes in the working folder, keeps the network off, and asks you when it has to leave the boundary. The criterion for widening permissions is a single question: what do I lose if the agent gets it wrong, and can I recover it?
Method and limits. I am not affiliated with OpenAI. I did not run Codex nor try to get around the sandbox, and I cannot guarantee that no flaws exist: a sandbox reduces the damage, it does not zero it. The tables and the evaluators on this page are my own models of the rules the documentation describes, written to see the two knobs separately; I ran them twice with the same output (Python 3.14, Linux), and they are not the Codex engine.
The two knobs, with the exact names
The sandbox page lists the values of sandbox_mode that you can put in config.toml:
read-only: the agent inspects files but does not modify them nor run commands without approval.workspace-write: it reads, edits in the workspace and runs routine local commands inside that boundary; the page indicates it as the low-friction mode for local work.danger-full-access: no sandbox restriction, so the boundaries on the filesystem and on the network fall. The name says what it does.
The boundary that matters is the workspace, and it has to be read carefully: it includes the current folder and temporary folders such as /tmp, and inside writable workspaces the folders .git, .agents, .codex and .aws still remain read-only, recursively, when they exist. The /status command shows which folders are part of the workspace of your session, and it is the way not to guess.
For approvals the same documentation describes on-request (it works in the sandbox and asks when it has to go beyond) and never (it never stops to ask). There is also a table form, approval_policy = { granular = { ... } }, with five boolean keys (sandbox_approval, rules, mcp_elicitations, request_permissions, skill_approval) to keep some categories of requests interactive and automatically reject the others. Two values have left the stage: untrusted is no longer selectable and a configuration file that contains it can prevent the client from starting, while on-failure is deprecated. If you inherit an old config.toml, check first of all that it does not contain approval_policy = "untrusted".
The most common combinations are listed by the "Agent approvals & security" page; I report them with what they produce.
| Purpose | Command-line or configuration options | Effect according to the page |
|---|---|---|
| Auto (default) | --sandbox workspace-write --ask-for-approval on-request | Reads, edits and runs in the workspace; asks to write outside the workspace or to use the network |
| Safe exploration | --sandbox read-only --ask-for-approval on-request | Reads and can run commands inside the read-only sandbox; outside it may ask |
| Read-only in CI | --sandbox read-only --ask-for-approval never | As above, but never asks |
| Automatic review | -c approvals_reviewer=auto_review with Auto | Same boundary, but eligible requests are evaluated by another agent |
| Full access | --dangerously-bypass-approvals-and-sandbox (alias --yolo) | No sandbox, no requests: the page flags it as not recommended |
In the desktop app and in the IDE extension the same profiles have readable labels: "Ask for approval", "Approve for me" (automatic review) and "Full access". You will notice that in an organization an administrator can forbid the broader values with a requirements.toml file: if you work in a company, check before writing an internal guide that recommends full access.
What happens underneath: the operating system
The sandbox is not a promise of the model, it is an operating-system mechanism applied to every command the agent launches, including git, package managers and test runners, which inherit the same limits. The "Agent approvals & security" page distinguishes the platforms: on macOS Seatbelt, on Linux bwrap plus seccomp, on Windows the native sandbox, and in WSL2 the Linux one. It concerns you in two ways. If bwrap is missing or user namespaces are not enabled, the sandbox does not start; the right choice is to fix the environment, not to switch to danger-full-access to silence the error. In a container the same page warns that the sandbox may not work, and suggests in that case letting the container provide the isolation and starting Codex with --sandbox danger-full-access inside it, adding that a dev container does not prevent every attack: a malicious project can take out whatever is available in the container, including the Codex credentials.
The network: off, unless you turn it on
The documentation declares the default value of the network: in the desktop app, in the CLI and in the IDE extension, the workspace-write mode keeps network access off until you enable it. It is enabled with a single key, and the effect is broad.
- Network off and
network_proxyon: the network stays off, the feature does nothing. - Network on and
network_proxyoff: the network stays on, with direct unrestricted outbound access. - Network on and
network_proxyon: outbound traffic is limited by the domain policy you configure, withallowanddenyrules (denyalways prevails).
The three lines say that turning on the network and declaring the permitted domains are two different gestures, and the second alone protects nothing: if you write a list of domains without enabling network_proxy, your list does not limit the destinations. You also have to keep in mind what the proxy does not filter: the page specifies that it does not cover web search, calls to app and connector tools, connections to MCP servers, browser activity, cloud tasks or the client's requests to the model. Web search has a separate control: web_search is cached by default, that is, results from an index maintained by OpenAI instead of pages downloaded live, which reduces exposure to prompt injection; with a full-access profile it switches to live.
Why does the network matter more than the filesystem? Because it is the exit channel. An agent that reads a page or a file with hidden instructions and has the network open can, in theory, send outside what it finds in the environment. The defense is in layers: network off by default, no secrets in the session environment, and your attention when the agent reads external content.
The two knobs in an executable table
To see that sandbox and approval are independent I wrote a model of the documentation's rules. The inside_boundary function answers only the technical question: does the action stay inside the sandbox boundary? The outcome function adds the second knob: if the action is outside the boundary, with on-request the result is "ASKS", with never no request is possible and the action is not executed. The latter is my own reading: the page says that never never stops to ask and that Codex does its best within the constraints set, it does not literally say that the action fails. There are six actions: a read, a write in the workspace, a write in .git, one in /tmp, one in /etc, and a network access. The identifiers in the listing are English and so are the printed words: executed and not executed stand for the two outcomes, ASKS for the request to you, and the prefixes read:, write: and network: name the type of action.
"""Sandbox and approval as two independent knobs: a table, not an opinion.
MY model of the rules written in the Codex documentation (Sandbox and
"Agent approvals & security" pages, consulted on 2026-11-13; the workspace includes the current
folder and temporary folders such as /tmp). It is not Codex: it is a
way to see the two knobs separately. No assistant involved.
"""
PROTECTED = (".git", ".agents", ".codex", ".aws") # read-only even inside the workspace
def inside_boundary(sandbox, action, network_on=False):
"""True if the action stays inside the boundary imposed by the sandbox."""
kind, _, path = action.partition(":")
if sandbox == "danger-full-access":
return True
if kind == "read":
return True
if kind == "network":
return sandbox == "workspace-write" and network_on
if kind == "write":
if sandbox == "read-only":
return False
if path.startswith("/tmp/"): # the workspace includes /tmp
return True
if path.startswith("/"): # any other absolute path: outside
return False
return path.split("/")[0] not in PROTECTED
raise ValueError(action)
def outcome(sandbox, approval, action, network_on=False):
if inside_boundary(sandbox, action, network_on):
return "executed"
return "ASKS" if approval == "on-request" else "not executed"
ACTIONS = ("read:src/app.js", "write:src/app.js", "write:.git/config",
"write:/tmp/build", "write:/etc/hosts", "network:registry")
COMBINATIONS = (("read-only", "on-request"), ("read-only", "never"),
("workspace-write", "on-request"), ("workspace-write", "never"),
("danger-full-access", "never"))
if __name__ == "__main__":
width = max(len(a) for a in ACTIONS)
for sandbox, appr in COMBINATIONS:
print(f"{sandbox} + {appr}")
for action in ACTIONS:
print(f" {action:<{width}} {outcome(sandbox, appr, action)}")
print("workspace-write + on-request, with network_access = true")
print(f" {'network:registry':<{width}} "
f"{outcome('workspace-write', 'on-request', 'network:registry', network_on=True)}")
# Command: python3 -I politica.py
# Output:
# read-only + on-request
# read:src/app.js executed
# write:src/app.js ASKS
# write:.git/config ASKS
# write:/tmp/build ASKS
# write:/etc/hosts ASKS
# network:registry ASKS
# read-only + never
# read:src/app.js executed
# write:src/app.js not executed
# write:.git/config not executed
# write:/tmp/build not executed
# write:/etc/hosts not executed
# network:registry not executed
# workspace-write + on-request
# read:src/app.js executed
# write:src/app.js executed
# write:.git/config ASKS
# write:/tmp/build executed
# write:/etc/hosts ASKS
# network:registry ASKS
# workspace-write + never
# read:src/app.js executed
# write:src/app.js executed
# write:.git/config not executed
# write:/tmp/build executed
# write:/etc/hosts not executed
# network:registry not executed
# danger-full-access + never
# read:src/app.js executed
# write:src/app.js executed
# write:.git/config executed
# write:/tmp/build executed
# write:/etc/hosts executed
# network:registry executed
# workspace-write + on-request, with network_access = true
# network:registry executed
Look at the workspace-write + on-request lines: the write to src/app.js and to /tmp/build goes through without asking, while .git/config and /etc/hosts ask, because the first is a protected path and the second is outside the workspace. In the lines with never the same actions are not executed, and it is the behavior you need in CI: nobody is there to answer. With danger-full-access everything goes through, and never on that line is what the page calls full access. In the last line, with network_access = true, the network no longer asks. Declared limits: the model does not know the command rules, the automatic review, the permission profiles or the individual paths added with writable_roots; do not use it to predict the behavior of a real configuration, but to explain to a colleague what each knob does.
The targeted exceptions: command rules
The documentation says that, when a workflow needs a precise exception, command rules are often better than widening access wholesale. The rules are declared experimental and may change. They are written in a .rules file under a rules/ folder next to a configuration layer (for example ~/.codex/rules/default.rules), in the Starlark language, which has a syntax close to Python's. Each prefix_rule has a pattern (the exact prefix of the command; one element can be a list of alternatives), a decision (allow, which is the default, prompt or forbidden), an optional justification and two lists of examples, match and not_match, which Codex checks at load time, like small tests. If several rules match, the most restrictive decision wins: forbidden, then prompt, then allow. The following file is a scheme to adapt, written by me on the documented format; I did not give it to Codex.
# Test rules for a sample repository (scheme to adapt).
prefix_rule(
pattern = ["git", ["status", "diff", "log"]],
decision = "allow",
justification = "Read-only.",
match = ["git status", "git diff --stat"],
not_match = ["git commit -m x"],
)
prefix_rule(
pattern = ["gh", "pr", "view"],
decision = "prompt",
justification = "Reading a PR leaves the sandbox: I decide.",
match = ["gh pr view 7888", "gh pr view --repo owner/repo"],
not_match = ["gh pr --repo owner/repo view 7888"],
)
prefix_rule(
pattern = ["git", "push"],
decision = "forbidden",
justification = "I do the push myself, by hand.",
match = ["git push origin main"],
not_match = ["git pull"],
)
A rule applies only to commands that coincide by prefix: gh pr --repo owner/repo view 7888 does not match ["gh", "pr", "view"], and that is the reason for its not_match. Where the documentation provides for it, Codex splits shell scripts before applying the rules, but only when they are a linear chain of simple words joined by &&, ||, ; or |; with redirections, substitutions, variables or wildcards it treats the whole script as a single command. The following evaluator implements those rules on a .rules file: it runs the file as Python with only the prefix_rule function (it is not Starlark and it is not the Codex engine), checks the inline examples and evaluates a few commands. For the real check the documentation points to codex execpolicy check --pretty --rules <file> -- <command>, which I did not run.
"""A prefix_rule evaluator to try rules out before you trust them.
It follows the rules written on the Rules page of the Codex documentation
(consulted on 2026-11-13): exact prefix, most restrictive decision
(forbidden > prompt > allow), shell script split only if made of simple words
joined by && || ; |. It is NOT the Codex engine: the .rules file is Starlark,
here I run it as Python with only the prefix_rule function (the syntax used is common).
For the real engine there is `codex execpolicy check`, which I did not run here.
"""
import re, shlex, sys
SEVERITY = {"allow": 0, "prompt": 1, "forbidden": 2}
RULES = []
def prefix_rule(pattern, decision="allow", justification=None, match=(), not_match=()):
assert pattern and decision in SEVERITY, "non-empty pattern, valid decision"
RULES.append(dict(pattern=pattern, decision=decision, justification=justification,
match=list(match), not_match=list(not_match)))
def matches(pattern, argv):
if len(argv) < len(pattern):
return False
return all((arg in elem) if isinstance(elem, list) else arg == elem
for elem, arg in zip(pattern, argv))
def evaluate_argv(argv):
found = [r for r in RULES if matches(r["pattern"], argv)]
if not found:
return None, None
worst = max(found, key=lambda r: SEVERITY[r["decision"]])
return worst["decision"], worst["justification"]
NOT_SPLITTABLE = re.compile(r"[<>`$*?(){}]|(^|[\s;&|])\w+=|\b(if|for|while|case)\b")
def commands(line):
argv = shlex.split(line)
if len(argv) >= 3 and argv[0] in ("bash", "zsh", "sh") and argv[1] in ("-c", "-lc"):
script = argv[2]
if NOT_SPLITTABLE.search(script):
return [argv] # a single opaque command
return [shlex.split(p) for p in re.split(r"&&|\|\||;|\|", script) if p.strip()]
return [argv]
def evaluate(line):
verdicts = [evaluate_argv(a) + (a,) for a in commands(line)]
known = [v for v in verdicts if v[0]]
if not known:
return "no rule", None
d, why, _ = max(known, key=lambda v: SEVERITY[v[0]])
return d, why
def check_examples():
errors = 0
for r in RULES:
for line in r["match"]:
if not matches(r["pattern"], shlex.split(line)):
print("ERROR match does not match:", line); errors += 1
for line in r["not_match"]:
if matches(r["pattern"], shlex.split(line)):
print("ERROR not_match matches:", line); errors += 1
return errors
if __name__ == "__main__":
exec(open(sys.argv[1]).read(), {"prefix_rule": prefix_rule})
print("rules loaded:", len(RULES), "- inline examples in error:", check_examples())
for line in ("git status", "git push origin main", "gh pr view 7888",
"bash -lc 'git add . && git push'", "bash -lc 'git status && git push'",
"bash -lc 'git status > out.txt; git push'", "npm test"):
decision, why = evaluate(line)
print(f"{line:<44} -> {decision}" + (f" ({why})" if why else ""))
# Command: python3 -I regole.py esempio.rules
# Output:
# rules loaded: 3 - inline examples in error: 0
# git status -> allow (Read-only.)
# git push origin main -> forbidden (I do the push myself, by hand.)
# gh pr view 7888 -> prompt (Reading a PR leaves the sandbox: I decide.)
# bash -lc 'git add . && git push' -> forbidden (I do the push myself, by hand.)
# bash -lc 'git status && git push' -> forbidden (I do the push myself, by hand.)
# bash -lc 'git status > out.txt; git push' -> no rule
# npm test -> no rule
The line that matters is the second to last. bash -lc 'git status && git push' is a linear chain: it is split and the git push finds the forbidden rule. But bash -lc 'git status > out.txt; git push' contains a redirection, so the whole script remains a single command, no rule matches, and the verdict is "no rule": your forbidden rule does not fire. It does not mean the push is allowed, because the sandbox (network off) and the approvals remain; it means a command rule is not a barrier on its own. It is one more reason to keep the network off and not to trust a list of prohibitions as the only defense.
Environment and secrets
The configuration has a [shell_environment_policy] table that decides which environment variables reach the commands launched by the agent. A surprising detail: ignore_default_excludes is true by default, so Codex does not automatically remove the variables whose name contains KEY, SECRET or TOKEN. To activate that automatic exclusion you have to set it to false. The rest is adjusted with inherit (none starts from an empty environment, core from a reduced one) and with filters by name, which accept * and ?. The order of application is: automatic exclusions, custom exclusions, set values, and finally the list of inclusions; since set comes after the exclusions, it can restore an excluded variable. The following scheme takes up the example from the documentation; I verified only that it is valid TOML, not that Codex accepts it.
# scheme to adapt: which environment variables reach the agent's commands
[shell_environment_policy]
inherit = "core"
ignore_default_excludes = false
[shell_environment_policy.filters]
"AWS_*" = "exclude"
"AZURE_*" = "exclude"
The cost of this discipline is a few errors of the "variable not found" type, to be solved once; the advantage is that a wrong command cannot read a secret that is not there. The principle of passing the minimum necessary is mine, not the documentation's. A concrete example: a session fixing unit tests has no reason to see the AWS_* variables of your shell.
A decision matrix
My recommendation, derived from the question "what do I lose and can I recover it?", is in the following table. The rows are mine; the options cited exist in the documentation.
| Situation | Sandbox + approval | Why |
|---|---|---|
| Reading an unknown repository | read-only + on-request | Zero writes; exploration does not require more |
| Daily work on a repository of yours, clean Git tree | workspace-write + on-request | The changes are in the diff and can be undone; exits ask |
| Many repetitive tasks, network off | as above with approvals_reviewer = "auto_review" | Fewer interruptions; the automatic review makes other calls to the model and may affect usage |
| Non-interactive execution in CI | codex exec, read-only sandbox by default; --sandbox workspace-write to allow changes | The documentation of the non-interactive mode indicates it; --full-auto is no longer supported |
| Disposable machine or container without secrets | danger-full-access may be acceptable | You set the boundary, outside Codex |
| Your laptop with SSH keys and credentials | Never danger-full-access + never | A wrong command has access to everything |
The trade-off of the row with automatic review is real: the page says that the reviewer evaluates only the actions that already require approval, that failures in building the prompt or in parsing close safely (the action does not start) and that critical-risk actions are denied. It remains another model judging a request, and for commands that touch production it is better that you read them yourself. A last configuration note: the named permission profiles (:read-only, :workspace, :danger-full-access) are in beta and, according to their page, do not combine with sandbox_mode: you configure one or the other.
A minimal practice, in the order in which it is needed
- Clean Git tree and commit made before every session.
/statusat the start: check profile, approval and writable folders.- Start from
workspace-writewithon-requestand the network off; widen one thing at a time, only for the task. - Read every approval request: command, path, network destination, and choose the narrowest scope that allows you to proceed.
- Review the diff and run the tests again yourself before trusting.
The order makes sense: the first two steps are free and protect all the following ones; the third fixes the perimeter before a request exists; the fourth is the only one that requires attention every time; the last closes the loop and is not skipped. If an approval request seems repetitive to you, the remedy is a targeted rule, not a broader permission.
Frequently asked questions
What is the difference between sandbox_mode and approval_policy?
The first is the technical boundary: where the agent can write and whether it can use the network. The second is the moment when the agent must stop and ask your permission before crossing it. They are independent: never with read-only is an agent that does not ask and cannot write; never with danger-full-access is an agent that does not ask and can do everything.
Why does Codex ask me for permission even inside my repository?
The most likely causes are three: the action touches a protected path such as .git or .codex, it requires the network (off by default in workspace-write), or it leaves the workspace. Open /status to see the writable folders and read the requested command before approving.
Is it safe to use approval_policy = never?
It depends on the sandbox that accompanies it. With a read-only sandbox or workspace-write the agent cannot leave the boundary, so in CI it is a reasonable choice; with danger-full-access there is no boundary left. The same page warns to use the combination with caution.
What you can do now
You can read the security configuration of Codex as two separate decisions, you know that the network is off by default in workspace-write and that the paths .git, .agents, .codex and .aws remain read-only, and you can write a command rule knowing that it does not cover scripts with redirections. In part 4 you put these choices in a config.toml and in the project instructions; if you arrive here without having read the installation, part 2 shows how to launch the first task, and part 1 the product map.
What I did not verify
I did not run Codex, so I tested neither the start of the sandbox nor the behavior of the approvals: what I describe is what the documentation says on 2026-11-13. I did not verify what happens to a command outside the sandbox with never (my reading is declared as such), nor the operation of codex execpolicy check, nor the exact text of the messages. The permissions page is in beta and may change.
The same series also includes choosing the model and the reasoning level (part 5), codex exec and the SDK in CI (part 6), cloud, subagents, skills and MCP (part 7) and the comparison with Claude Code, Copilot and Cursor (part 8).
Sources
- Sandbox - the three values of
sandbox_mode,on-requestandnever,untrustedno longer selectable,approvals_reviewer; consulted on 2026-11-13 - Agent approvals & security - network off by default,
network_proxy, protected paths, table of combinations, sandbox by operating system, containers; consulted on 2026-11-13 - Rules -
prefix_rule, most restrictive decision, splitting of shell scripts,codex execpolicy check; consulted on 2026-11-13 - Advanced Configuration -
shell_environment_policy, order of application of the filters,ignore_default_excludes; consulted on 2026-11-13 - Non-interactive mode - default read-only sandbox of
codex exec,--full-autono longer supported; consulted on 2026-11-13 - Permissions - permission profiles (beta) and their incompatibility with
sandbox_mode; consulted on 2026-11-13
The table and the rule evaluator are my own models of the documented rules, run twice with Python 3.14 on Linux with the same output; the .rules file and the TOML scheme are schemes to adapt, validated only in form and never given to Codex.
← Part 2: Codex CLI, the first task Part 4: AGENTS.md and config.toml →
Commenti
Caricamento commenti...
Sign in to comment