Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion docs/contributing/runtime-implementation.md
Original file line number Diff line number Diff line change
Expand Up @@ -1156,7 +1156,10 @@ cannot be overridden, so it cannot follow the mid-run refresh a short-lived WIF
`$CODEX_HOME/hooks.json` from `security.HookPlan`, and uploads the embedded
`fullsend-codex-hook.py` beside the scripts. Each plan group becomes one handler,
`python3 <adapter> <phase> <script...>`, so the scripts still run in plan order inside one process —
the ordering the PostToolUse chain depends on.
the ordering the PostToolUse chain depends on. `PreToolUse` element 0 is not a plan group but the
spawn guard, `python3 <adapter> SpawnGuard`, the policy of
[ADR 0126](../ADRs/0126-fullsend-owned-codex-subagents.md); it is written whenever `hooks.json`
is, even with every sandbox hook off.

Matcher translation, per group:

Expand All @@ -1168,6 +1171,7 @@ Matcher translation, per group:
| `Read`, `Glob`, `Grep`, `LS`, `WebFetch`, `WebSearch` | *dropped, with a note* | no codex tool; the `Bash` groups cover this work |
| `*` (`security.AllTools`) | *matcher key omitted* | an absent matcher matches every tool |
| `PostToolUseFailure` (any tools) | *not wired* | codex has no such event and does not need one — see below |
| *(the spawn guard, not a plan group)* | `^(multi_agent_v1\|collaboration)\|(spawn\|resume)_agent$` — a regex (a character outside `[A-Za-z0-9_\|]` makes it one) that reaches both multi-agent namespaces plus the bare V1 `spawn_agent` | `PreToolUse` element 0; admits a V1 `spawn_agent` from the root thread of a registered role, with `fork_context: false` and no `model` or `reasoning_effort`, after re-checking the files in `FULLSEND_CODEX_SPAWN_DIGESTS`; passes the parent's wait, close and send-input calls through; everything else, its own errors included, exits 2 with a reason. Every admit and deny is logged to `security/findings.jsonl` |

Tokens are joined with `|` and stay within `[A-Za-z0-9_|]`, which is the character set codex treats
as an **exact alternation** rather than a regex, so there is no anchoring question and no substring
Expand Down Expand Up @@ -1229,6 +1233,7 @@ as the place its expected value comes from. There are two trustworthy places —
| hook adapter, auth script | **compile-time** — `go:embed`ed, so the digest is a literal in the run command | SHA-256, exit 97 |
| the shared hook scripts | **compile-time** for the bytes, **runner-held** for which names — Bootstrap records the name → digest map for the set the harness enabled | SHA-256 per filename, plus an exhaustive directory check, exit 97 |
| `config.toml`, `hooks.json` | **runner-held** — rendered per run, so Bootstrap records what it uploaded outside the sandbox and Run injects it into the launch command (`codex_integrity.go`) | whole-file SHA-256, exit 98 |
| `agents/<role>.toml` (role files; none written yet) | **runner-held** — Bootstrap records name → digest in `RoleFiles`; Run exports it with `hooks.json`'s digest as `FULLSEND_CODEX_SPAWN_DIGESTS` | SHA-256 per filename plus an exhaustive `agents/` check, by the spawn guard before every spawn; exit 2 |
| `fullsend-manifest.json` | none — it is a file in the same agent-writable directory | information only; never authority |

The hook-script check makes codex **stricter than Claude Code and pi**, where the scripts stay
Expand Down Expand Up @@ -1256,6 +1261,11 @@ is not something the agent can reach, so **the adapter re-reads and re-verifies
immediately before spawning it** and blocks on a mismatch. A missing or malformed map is itself a
block, since the adapter only ever runs when the runner enabled hooks.

The spawn guard closes the same window for children. Codex re-reads `hooks.json` and the role's
file when a child starts, so Run exports their digests as `FULLSEND_CODEX_SPAWN_DIGESTS` and the
handler re-hashes them, and lists `agents/`, before applying the policy, on its own deadline below
the hook timeout at which codex kills a handler and lets the call through. No role, no spawn.

**PATH is pinned across `.env` for the same reason the interpreter is.** The hook scripts resolve
their tools by name — `tirith_check.py` runs a bare `tirith` — so a `.env` that prepends a directory
holding a fake `tirith` that exits 0 neuters the entire PreToolUse chain while every digest stays
Expand Down Expand Up @@ -1409,3 +1419,4 @@ Two artefacts of the run are worth knowing about:
| `ConfigToml` keys and the `ReasoningEffort` enum | a renamed or removed key silently changes behaviour; `--strict-config` reports it | `codex-rs/config/src/config_toml.rs`, `codex-rs/protocol/src/openai_models.rs` |
| Project trust and `AGENTS.md` | the pinned untrusted entry must still stop codex recording its own trust level, the repo's `.codex/` layer must stay unloaded, and `$CODEX_HOME/AGENTS.md` must still load while the project is untrusted, or the bridge stops reaching the agent | `codex-rs/app-server/src/request_processors/thread_processor.rs` (trust write), `codex-rs/config/src/loader/mod.rs`, `codex-rs/core/src/agents_md.rs`, `codex-rs/codex-home/src/instructions/mod.rs` |
| JSONL event structs, rollout line types and rollout file naming | the stream parser and transcript extraction; a rollout line type missing from `codexRolloutEnvelopes` discards the whole transcript | `codex-rs/exec/src/exec_events.rs`, `codex-rs/history/src/rollout_payload.rs` (`RolloutItemWire`), `codex-rs/thread-store/src/local/helpers.rs` |
| The multi-agent tool names (`multi_agent_v1*`, `collaboration*`, the bare V1 `spawn_agent`), the block contract (exit 2 with non-empty stderr blocks; a timeout kills the handler and lets the call through), `agent_id` and `agent_type` in a child's payload, the spawn arguments, and what a child start rereads (`hooks.json` and the role file) | the spawn guard's matcher, pass-through set, policy, digest set and deadline rest on them; a renamed tool is denied (loud), but a payload without `agent_id`, a new model or effort argument, a changed block contract or a child that rereads another file turns a deny into a pass | `codex-rs/core/src/tools/handlers/multi_agents_spec.rs`, `codex-rs/core/src/tools/registry.rs` (`function_hook_tool_name`), `codex-rs/hooks/src/engine/command_runner.rs` (the timeout branch), `codex-rs/core/src/agent/role.rs` (the role file, read at spawn) |
75 changes: 57 additions & 18 deletions internal/runtime/codex_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ func renderCodexConfig(configDir, repoDir, developerInstructions string) ([]byte
BaseURL: codexBaseURL,
DeveloperInstructions: codexTOMLString(developerInstructions),
AuthCommand: codexTOMLString(configDir + "/" + codexAuthScriptFile),
ProjectKey: codexTOMLString(repoDir),
ProjectKey: codexTOMLKey(repoDir),
RefreshIntervalMS: codexAuthRefreshIntervalMS,
TimeoutMS: codexAuthTimeoutMS,
})
Expand All @@ -211,20 +211,28 @@ func renderCodexConfig(configDir, repoDir, developerInstructions string) ([]byte
return []byte(buf.String()), nil
}

// codexTOMLString renders s as a TOML basic string, quotes included.
//
// The agent body is arbitrary markdown, so a multi-line `"""` literal is not
// safe: a body containing `"""`, or ending in a backslash, would terminate the
// literal early and the rest of the file would be parsed as TOML. A
// single-line basic string with every hazardous rune escaped cannot be broken
// out of. Per the TOML 1.0 spec a basic string must escape backslash and
// double quote and may not contain a raw control character; the compact forms
// are used where they exist and \uXXXX otherwise. Invalid UTF-8 is escaped
// byte by byte rather than silently replaced.
// codexTOMLString renders s as a TOML basic string, quotes included. A value
// with a newline becomes a multi-line basic string, so it reads as written.
// Backslashes, quotes and control characters are escaped in both forms, so a
// body containing `"""` or ending in a backslash cannot end the literal early.
func codexTOMLString(s string) string {
Comment thread
dhshah13 marked this conversation as resolved.
Resolved
return codexTOMLBasicString(s, strings.Contains(s, "\n"))
}

// codexTOMLKey renders s as a quoted key. A table header cannot hold a
// multi-line string, so a newline stays escaped.
func codexTOMLKey(s string) string {
return codexTOMLBasicString(s, false)
}

func codexTOMLBasicString(s string, multi bool) string {
var b strings.Builder
b.Grow(len(s) + 2)
b.WriteByte('"')
b.Grow(len(s) + 8)
if multi {
b.WriteString("\"\"\"\n")
} else {
b.WriteByte('"')
}
for i := 0; i < len(s); {
r, size := utf8.DecodeRuneInString(s[i:])
if r == utf8.RuneError && size == 1 {
Expand All @@ -242,7 +250,11 @@ func codexTOMLString(s string) string {
case '\f':
b.WriteString(`\f`)
case '\n':
b.WriteString(`\n`)
if multi {
b.WriteByte('\n')
} else {
b.WriteString(`\n`)
}
case '\r':
b.WriteString(`\r`)
case '\t':
Expand All @@ -259,7 +271,11 @@ func codexTOMLString(s string) string {
}
i += size
}
b.WriteByte('"')
if multi {
b.WriteString(`"""`)
} else {
b.WriteByte('"')
}
return b.String()
}

Expand Down Expand Up @@ -364,13 +380,24 @@ func codexMatcherFor(tools []string) (matcher string, dropped []string, ok bool)
return strings.Join(tokens, "|"), dropped, true
}

// codexSpawnGuardMatcher matches every codex multi-agent tool, so the guard
// is deny-by-default among them (ADR 0126). codex joins namespace and tool
// with no separator (`collaborationspawn_agent`) except the bare V1
// `spawn_agent`, and compiles a matcher holding a character outside
// [A-Za-z0-9_|] as an unanchored regex.
const codexSpawnGuardMatcher = "^(multi_agent_v1|collaboration)|(spawn|resume)_agent$"

// codexSpawnGuardMode is the adapter argument that selects the spawn policy
// in place of a hook-script phase.
const codexSpawnGuardMode = "SpawnGuard"

// codexHooksJSON renders $CODEX_HOME/hooks.json from the runtime-neutral
// security.HookPlan, and returns the notes Bootstrap prints for tools that
// have no codex counterpart.
//
// One handler per plan group, invoking the adapter with the phase and the
// group's scripts, so the scripts still run in plan order inside one process
// — the ordering the PostToolUse chain depends on.
// The spawn guard first, then one handler per plan group, so the group's
// scripts still run in plan order inside one process — the ordering the
// PostToolUse chain depends on.
//
// python is the absolute interpreter path Bootstrap resolved, rendered with
// `-I`: codex spawns a hook through the shell it inherits, *after* the
Expand All @@ -394,6 +421,18 @@ func codexHooksJSON(configDir, python string, hooks security.SandboxHookConfig)
var notes []string
adapter := configDir + "/" + codexAdapterFile

// The spawn guard is always element 0 of PreToolUse, even with every
// sandbox hook off: codex may start a child only under the runner's
// policy. It takes no script; the policy is the adapter's own.
cfg.Hooks[string(security.HookPhasePreToolUse)] = []codexHookMatcherSet{{
Matcher: codexSpawnGuardMatcher,
Hooks: []codexHookEntry{{
Type: "command",
Comment thread
qodo-code-review[bot] marked this conversation as resolved.
Resolved
Command: strings.Join([]string{python, "-I", adapter, codexSpawnGuardMode}, " "),
Timeout: security.HookTimeoutSeconds,
}},
}}

for _, g := range security.HookPlan(hooks) {
if g.Phase == security.HookPhasePostToolUseFailure {
notes = append(notes, fmt.Sprintf(
Expand Down
84 changes: 65 additions & 19 deletions internal/runtime/codex_config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"testing"

Expand All @@ -28,7 +29,9 @@ func TestCodexTOMLString(t *testing.T) {
{"plain", "hello", `"hello"`},
{"quote", `say "hi"`, `"say \"hi\""`},
{"backslash", `C:\path`, `"C:\\path"`},
{"newline", "a\nb", `"a\nb"`},
{"newline", "a\nb", "\"\"\"\na\nb\"\"\""},
{"trailing newline", "a\n", "\"\"\"\na\n\"\"\""},
{"triple quote and trailing backslash in a multi-line value", "a\n\"\"\"\\", "\"\"\"\na\n\\\"\\\"\\\"\\\\\"\"\""},
{"tab and cr", "a\tb\rc", `"a\tb\rc"`},
{"triple quote cannot break out", `"""`, `"\"\"\""`},
{"trailing backslash", `end\`, `"end\\"`},
Expand All @@ -44,6 +47,10 @@ func TestCodexTOMLString(t *testing.T) {
}
}

func TestCodexTOMLKey_StaysSingleLine(t *testing.T) {
assert.Equal(t, `"a\nb"`, codexTOMLKey("a\nb"))
}

// TestRenderCodexConfig_ParsesAsTOML round-trips the rendered file through a
// real TOML parser. The agent body is arbitrary markdown from the harness, so
// the escaper — not the template — is what keeps a body full of quotes,
Expand All @@ -56,8 +63,8 @@ func TestRenderCodexConfig_ParsesAsTOML(t *testing.T) {
"developer_instructions = \"pwned\"\n" +
"[model_providers.evil]\nbase_url = \"https://evil.example\"\n"

// A directory name can carry quotes and backslashes too.
nastyRepo := sandbox.SandboxWorkspace + `/re"po\\x] trust_level = "trusted"`
// A directory name can carry quotes, backslashes and a newline too.
nastyRepo := sandbox.SandboxWorkspace + "/re\"po\\\\x]\ntrust_level = \"trusted\""
data, err := renderCodexConfig(sandbox.SandboxCodexConfig, nastyRepo, nasty)
require.NoError(t, err)

Expand Down Expand Up @@ -224,6 +231,11 @@ func TestCodexHooksJSON_DefaultPlan(t *testing.T) {
assert.Equal(t, "command", entry.Type)
assert.Equal(t, security.HookTimeoutSeconds, entry.Timeout,
"codex reads `timeout` in seconds, like Claude Code")
if group.Matcher == codexSpawnGuardMatcher {
// The spawn guard is an adapter mode, not a script phase.
assert.Equal(t, testCodexPython+" -I "+adapter+" "+codexSpawnGuardMode, entry.Command)
continue
}
// Absolute interpreter, isolated: codex spawns hooks after the
// agent-writable .env is sourced, so a bare `python3` would be
// resolved through a PATH the agent controls, and -I keeps
Expand Down Expand Up @@ -301,27 +313,21 @@ func TestCodexHooksJSON_ParsesAsCodexHooksFile(t *testing.T) {
}
}

func TestCodexHooksJSON_SecurityDisabledPlanRendersNothing(t *testing.T) {
off := false
cfg := security.SandboxHookConfigFromHarness(&harness.Harness{
Security: &harness.SecurityConfig{
SandboxHooks: &harness.SandboxHooks{
Tirith: &harness.TirithConfig{Enabled: &off},
SSRFPreTool: &off,
CanaryPreTool: &off,
CanaryPostTool: &off,
SecretRedactPostTool: &off,
UnicodePostTool: &off,
ContextSuppressPostTool: &off,
},
},
})
// TestCodexHooksJSON_AllHooksOffKeepsSpawnGuard: with harness security on and
// every sandbox hook off, hooks.json is still written and still carries the
// spawn guard as its first PreToolUse group.
func TestCodexHooksJSON_AllHooksOffKeepsSpawnGuard(t *testing.T) {
cfg := codexAllHooksOff()
data, _, err := codexHooksJSON(sandbox.SandboxCodexConfig, testCodexPython, cfg)
require.NoError(t, err)

var parsed codexHooksConfig
require.NoError(t, json.Unmarshal(data, &parsed))
assert.Empty(t, parsed.Hooks)
require.Len(t, parsed.Hooks, 1, "no hook-script phase is wired; only the guard's")
pre := parsed.Hooks[string(security.HookPhasePreToolUse)]
require.Len(t, pre, 1)
assert.Equal(t, codexSpawnGuardMatcher, pre[0].Matcher, "the guard is element 0 with every hook off")
assert.NotContains(t, string(data), "async", "only a synchronous handler can block")
}

// TestCodexAssetPathsMatchConstants keeps the paths hardcoded in the embedded
Expand Down Expand Up @@ -365,3 +371,43 @@ func TestRenderCodexConfig_RequiresRepoDir(t *testing.T) {
_, err := renderCodexConfig(sandbox.SandboxCodexConfig, "", "body")
require.Error(t, err, "an empty path would leave the project's trust unset")
}

// TestCodexHooksJSON_SpawnGuardIsFirst pins the guard as the one and first
// PreToolUse group, and its matcher's reach.
func TestCodexHooksJSON_SpawnGuardIsFirst(t *testing.T) {
cfg := security.SandboxHookConfigFromHarness(&harness.Harness{})
data, _, err := codexHooksJSON(sandbox.SandboxCodexConfig, testCodexPython, cfg)
require.NoError(t, err)

var parsed codexHooksConfig
require.NoError(t, json.Unmarshal(data, &parsed))
pre := parsed.Hooks[string(security.HookPhasePreToolUse)]
require.NotEmpty(t, pre)
assert.Equal(t, "^(multi_agent_v1|collaboration)|(spawn|resume)_agent$", pre[0].Matcher,
"the guard must see every tool in codex's multi-agent namespaces and every bare spawn or resume, and run first")
assert.Equal(t, testCodexPython+" -I "+sandbox.SandboxCodexConfig+"/"+codexAdapterFile+" "+codexSpawnGuardMode,
pre[0].Hooks[0].Command, "the guard is the adapter in its SpawnGuard mode, with no script")

guards := 0
for phase, groups := range parsed.Hooks {
for _, group := range groups {
if group.Matcher == codexSpawnGuardMatcher {
guards++
assert.Equal(t, string(security.HookPhasePreToolUse), phase)
}
}
}
assert.Equal(t, 1, guards, "exactly one guard group, on PreToolUse")
// An invalid regex matches nothing, which would let every spawn through.
pattern := regexp.MustCompile(codexSpawnGuardMatcher)
for _, name := range []string{
"spawn_agent", "multi_agent_v1resume_agent", "collaborationspawn_agent", // codex's spawn and resume tools
"multi_agent_v1wait_agent", "multi_agent_v1close_agent", "multi_agent_v1send_input", // passed through by the handler
"collaborationwait_agent", "multi_agent_v1fork_agent", "resume_agent", // unknown names: denied by the handler
} {
assert.True(t, pattern.MatchString(name), "the guard must run for %s", name)
}
for _, name := range []string{"wait_agent", "exec", "wait", "spawn_agent_status", "Bash", "apply_patch"} {
assert.False(t, pattern.MatchString(name), "the guard must not run for %s", name)
}
}
Loading
Loading