@jbkjr/relay 0.0.0-stage → 1.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/LICENSES/Apache-2.0.txt +201 -0
- package/LICENSES/README.md +19 -0
- package/LICENSES/codex-NOTICE.txt +6 -0
- package/README.md +393 -2
- package/SECURITY.md +145 -0
- package/adapters/briefs/claude.md +43 -0
- package/adapters/briefs/codex.md +56 -0
- package/adapters/briefs/models.json +33 -0
- package/adapters/build.mjs +8 -0
- package/adapters/claude/.claude-plugin/marketplace.json +13 -0
- package/adapters/claude/relay/.claude-plugin/plugin.json +5 -0
- package/adapters/claude/relay/agents/codex.md +21 -0
- package/adapters/claude/relay/agents/operator.md +21 -0
- package/adapters/claude/relay/skills/ask/SKILL.md +20 -0
- package/adapters/claude/relay/skills/chat/SKILL.md +13 -0
- package/adapters/claude/relay/skills/delegate/SKILL.md +21 -0
- package/adapters/claude/relay/skills/discuss/SKILL.md +19 -0
- package/adapters/claude/relay/skills/review/SKILL.md +21 -0
- package/adapters/claude/relay/skills/tree/SKILL.md +10 -0
- package/adapters/claude/relay/skills/write-for-codex/SKILL.md +78 -0
- package/adapters/codex/.agents/plugins/marketplace.json +20 -0
- package/adapters/codex/AGENTS.snippet.md +5 -0
- package/adapters/codex/relay/.codex-plugin/plugin.json +6 -0
- package/adapters/codex/relay/skills/relay-ask/SKILL.md +20 -0
- package/adapters/codex/relay/skills/relay-chat/SKILL.md +13 -0
- package/adapters/codex/relay/skills/relay-delegate/SKILL.md +21 -0
- package/adapters/codex/relay/skills/relay-discuss/SKILL.md +19 -0
- package/adapters/codex/relay/skills/relay-review/SKILL.md +21 -0
- package/adapters/codex/relay/skills/relay-tree/SKILL.md +10 -0
- package/adapters/codex/relay/skills/relay-write-for-claude/SKILL.md +66 -0
- package/adapters/generate.mjs +124 -0
- package/bin/relay +59 -0
- package/codex-pin.json +12 -0
- package/dist/backends/acp.js +1424 -0
- package/dist/backends/claude.js +890 -0
- package/dist/backends/cli-version.js +112 -0
- package/dist/backends/codex-app.js +1539 -0
- package/dist/backends/codex-daybreak.js +75 -0
- package/dist/backends/codex-env.js +656 -0
- package/dist/backends/codex-network.js +304 -0
- package/dist/backends/codex-pin.js +345 -0
- package/dist/backends/codex-shell-policy.js +182 -0
- package/dist/backends/codex-stage2.js +998 -0
- package/dist/backends/codex-subagents.js +47 -0
- package/dist/backends/codex.js +641 -0
- package/dist/backends/copilot.js +246 -0
- package/dist/backends/env.js +147 -0
- package/dist/backends/gemini.js +607 -0
- package/dist/backends/grok.js +337 -0
- package/dist/backends/index.js +8 -0
- package/dist/backends/native-temp.js +187 -0
- package/dist/backends/never-admission.js +90 -0
- package/dist/backends/run.js +67 -0
- package/dist/backends/stream.js +230 -0
- package/dist/backends/tool-discovery.js +15 -0
- package/dist/backends/types.js +264 -0
- package/dist/build-info.json +5 -0
- package/dist/cli.js +344 -0
- package/dist/confine/bridge.js +113 -0
- package/dist/confine/broker-core.js +76 -0
- package/dist/confine/broker-http.js +650 -0
- package/dist/confine/broker-names.js +9 -0
- package/dist/confine/broker.js +258 -0
- package/dist/confine/canary.js +380 -0
- package/dist/confine/diagnostics.js +122 -0
- package/dist/confine/gemini-tools-main.js +8 -0
- package/dist/confine/gemini-tools.js +181 -0
- package/dist/confine/hardlinks.js +58 -0
- package/dist/confine/harness-config.js +16 -0
- package/dist/confine/index.js +117 -0
- package/dist/confine/leases.js +217 -0
- package/dist/confine/paths.js +6 -0
- package/dist/confine/peer.js +115 -0
- package/dist/confine/port-policy.js +8 -0
- package/dist/confine/ports.js +365 -0
- package/dist/confine/private-root.js +208 -0
- package/dist/confine/probe-stage2.js +501 -0
- package/dist/confine/probe.js +1109 -0
- package/dist/confine/proxy.js +783 -0
- package/dist/confine/sbcheck.js +208 -0
- package/dist/confine/seatbelt-never.js +41 -0
- package/dist/confine/seatbelt-stage2.js +139 -0
- package/dist/confine/seatbelt.js +1129 -0
- package/dist/confine/sockets.js +36 -0
- package/dist/confine/turn-probe.js +19 -0
- package/dist/confine/turn.js +86 -0
- package/dist/core/adoption.js +124 -0
- package/dist/core/api-keys.js +423 -0
- package/dist/core/approvals.js +740 -0
- package/dist/core/build-identity.js +248 -0
- package/dist/core/caller.js +749 -0
- package/dist/core/calls.js +102 -0
- package/dist/core/claude-settings.js +1045 -0
- package/dist/core/config.js +453 -0
- package/dist/core/context.js +186 -0
- package/dist/core/db.js +753 -0
- package/dist/core/dispatch.js +110 -0
- package/dist/core/env-broker.js +505 -0
- package/dist/core/env-policy.js +182 -0
- package/dist/core/escalation-authority.js +76 -0
- package/dist/core/escalation-contract.js +13 -0
- package/dist/core/escalation-person-path.js +131 -0
- package/dist/core/escalation-policy.js +79 -0
- package/dist/core/escalation-runtime.js +135 -0
- package/dist/core/escalation-state.js +42 -0
- package/dist/core/escalations.js +191 -0
- package/dist/core/events.js +235 -0
- package/dist/core/executables.js +147 -0
- package/dist/core/extensions.js +645 -0
- package/dist/core/families.js +204 -0
- package/dist/core/git.js +657 -0
- package/dist/core/identity.js +113 -0
- package/dist/core/liveness.js +68 -0
- package/dist/core/mediated-network-provider.js +81 -0
- package/dist/core/never-checkpoint.js +76 -0
- package/dist/core/never-coverage.js +97 -0
- package/dist/core/never-network.js +49 -0
- package/dist/core/never-policy.js +302 -0
- package/dist/core/never-proxy-policy.js +109 -0
- package/dist/core/never-schema.js +61 -0
- package/dist/core/never-tools.js +56 -0
- package/dist/core/notices.js +48 -0
- package/dist/core/ops.js +959 -0
- package/dist/core/outcome.js +224 -0
- package/dist/core/params.js +32 -0
- package/dist/core/presence.js +174 -0
- package/dist/core/procs.js +546 -0
- package/dist/core/prompts.js +363 -0
- package/dist/core/protected-config.js +238 -0
- package/dist/core/raw-network.js +192 -0
- package/dist/core/redact.js +152 -0
- package/dist/core/refusal.js +33 -0
- package/dist/core/relay-command.js +310 -0
- package/dist/core/reported.js +3 -0
- package/dist/core/restart-overlay.js +651 -0
- package/dist/core/retention.js +1135 -0
- package/dist/core/secrets.js +329 -0
- package/dist/core/session-token.js +175 -0
- package/dist/core/session.js +744 -0
- package/dist/core/shell.js +2 -0
- package/dist/core/shipped-pin.js +47 -0
- package/dist/core/shown.js +42 -0
- package/dist/core/slots.js +67 -0
- package/dist/core/stage2-executors.js +453 -0
- package/dist/core/stage2-switch.js +5 -0
- package/dist/core/steering.js +149 -0
- package/dist/core/storage.js +358 -0
- package/dist/core/toml.js +175 -0
- package/dist/core/views.js +324 -0
- package/dist/core/wait.js +114 -0
- package/dist/core/wake.js +207 -0
- package/dist/core/watch.js +247 -0
- package/dist/core/worktree.js +213 -0
- package/dist/hosts/claude-desktop.js +274 -0
- package/dist/hosts/claude.js +249 -0
- package/dist/hosts/codex.js +345 -0
- package/dist/hosts/desktop-shared.js +20 -0
- package/dist/hosts/index.js +11 -0
- package/dist/hosts/types.js +4 -0
- package/dist/install/basics.js +18 -0
- package/dist/install/claude-init.js +133 -0
- package/dist/install/common.js +655 -0
- package/dist/install/doctor.js +635 -0
- package/dist/install/qualify-codex.js +205 -0
- package/dist/install.js +524 -0
- package/dist/mcp/elicit.js +209 -0
- package/dist/mcp/gateway.js +218 -0
- package/dist/mcp/host.js +253 -0
- package/dist/mcp/server.js +1124 -0
- package/dist/mcp/stdio.js +37 -0
- package/dist/modes/discussion.js +393 -0
- package/dist/modes/review.js +722 -0
- package/dist/native/relay-sbcheck +0 -0
- package/dist/targets/briefs.js +86 -0
- package/dist/targets/claude.js +94 -0
- package/dist/targets/codex.js +66 -0
- package/dist/targets/copilot.js +93 -0
- package/dist/targets/gemini.js +119 -0
- package/dist/targets/grok.js +126 -0
- package/dist/targets/index.js +192 -0
- package/dist/targets/types.js +18 -0
- package/dist/targets/verified.js +35 -0
- package/dist/worker.js +113 -0
- package/docs/UPGRADING.md +1518 -0
- package/docs/pinned-codex.md +333 -0
- package/experiments/stage2-redteam/lib/oracles.mjs +214 -0
- package/experiments/stage2-redteam/lib/report.mjs +35 -0
- package/npm-shrinkwrap.json +1632 -0
- package/package.json +82 -4
- package/scripts/codex-qualify/codex-pin-store.mjs +353 -0
- package/scripts/codex-qualify/codex-qualifier-process.mjs +265 -0
- package/scripts/codex-qualify/codex-qualifier.example.json +5 -0
- package/scripts/codex-qualify/codex-qualifier.mjs +281 -0
- package/scripts/codex-qualify/codex-shipped-pin.mjs +158 -0
- package/scripts/codex-qualify/codex-stage2-pin.mjs +48 -0
- package/scripts/codex-qualify/codex-stage2.mjs +2381 -0
- package/scripts/codex-qualify/install-codex-qualifier.mjs +98 -0
- package/scripts/codex-qualify/main-module.mjs +14 -0
- package/scripts/codex-qualify/relay-codex-qualifier.plist +37 -0
- package/scripts/codex-qualify/scratch-env.mjs +31 -0
- package/scripts/codex-qualify/session.mjs +96 -0
- package/scripts/codex-qualify/stage2-escalation-cases.mjs +125 -0
- package/test/codex-permissions.test.ts +875 -0
- package/test/fixtures/boundary-probes.mjs +17 -0
- package/test/fixtures/denial-stream-host.mjs +7 -0
- package/test/fixtures/families.json +246 -0
- package/test/fixtures/install-snapshots/claude-desktop-foreign.txt +158 -0
- package/test/fixtures/install-snapshots/claude-desktop-fresh.txt +101 -0
- package/test/fixtures/install-snapshots/claude-desktop-installed.txt +161 -0
- package/test/fixtures/install-snapshots/claude-foreign.txt +133 -0
- package/test/fixtures/install-snapshots/claude-fresh.txt +77 -0
- package/test/fixtures/install-snapshots/claude-installed.txt +133 -0
- package/test/fixtures/install-snapshots/codex-foreign.txt +159 -0
- package/test/fixtures/install-snapshots/codex-fresh.txt +107 -0
- package/test/fixtures/install-snapshots/codex-installed.txt +161 -0
- package/test/fixtures/link-parent.mjs +6 -0
- package/test/fixtures/mediated-command.cjs +72 -0
- package/test/fixtures/native-skill-isolation.json +280 -0
- package/test/fixtures/pinned-codex-app-server.mjs +25 -0
- package/test/fixtures/qualified-ext-adapters.mjs +36 -0
- package/test/fixtures/refusals/README.md +52 -0
- package/test/fixtures/refusals/claude-source-result.json +7 -0
- package/test/fixtures/refusals/openai-app-capacity.json +24 -0
- package/test/fixtures/refusals/openai-app-cyberPolicy.json +24 -0
- package/test/fixtures/refusals/openai-gpt-6-astra-max.json +12 -0
- package/test/fixtures/refusals/openai-gpt-6.1-sol-xhigh.json +12 -0
- package/test/fixtures/refusals/openai-review-capacity.json +24 -0
- package/test/fixtures/relay-0.2.0.sql +57 -0
- package/test/fixtures/relay-0.9.1.gen.mjs +212 -0
- package/test/fixtures/relay-0.9.1.sql +340 -0
- package/test/fixtures/slow-boundary-probes.mjs +37 -0
- package/test/fixtures/stable-surfaces/config.json +1122 -0
- package/test/fixtures/stable-surfaces/escalation.json +128 -0
- package/test/fixtures/stable-surfaces/events.json +37 -0
- package/test/fixtures/stable-surfaces/gemini-native-resume.json +4 -0
- package/test/fixtures/stable-surfaces/inbox.jsonl +2 -0
- package/test/fixtures/stable-surfaces/notice.txt +1 -0
- package/test/fixtures/stable-surfaces/refusal-item.json +28 -0
- package/test/fixtures/stable-surfaces/refusal-review.json +23 -0
- package/test/fixtures/stable-surfaces/registry.json +49 -0
- package/test/fixtures/stable-surfaces/tools-desktop.json +575 -0
- package/test/fixtures/stable-surfaces/tools.json +716 -0
- package/test/fixtures/stable-surfaces/usage.txt +46 -0
- package/test/fixtures/stage2-acp-native.mjs +138 -0
- package/test/fixtures/stage2-app-server.mjs +23 -0
- package/test/fixtures/stage2-catalog.json +91 -0
- package/test/fixtures/stage2-hostile-web.mjs +35 -0
- package/test/fixtures/stage2-native-network.mjs +62 -0
- package/test/fixtures/stage2-worker.ts +87 -0
- package/test/fixtures/status-views/expected.json +7825 -0
- package/test/fixtures/status-views/registries.json +1 -0
- package/test/fixtures/steering.json +209 -0
- package/test/helpers.ts +740 -0
- package/test/host-env.ts +7 -0
- package/test/keychain-decoy.ts +197 -0
- package/test/live-scope.ts +44 -0
- package/test/mediated-network.test.ts +192 -0
- package/test/mediated-proxy.test.ts +264 -0
- package/test/native-temp-alias.ts +10 -0
- package/test/never-policy.test.ts +629 -0
- package/test/never-tools.test.ts +136 -0
- package/test/process-home.ts +18 -0
- package/test/proxy.test.ts +531 -0
- package/test/restart-overlay-live.test.ts +85 -0
- package/test/restart-overlay-profile.test.ts +66 -0
- package/test/restart-overlay.test.ts +416 -0
- package/test/stable-surfaces.test.ts +249 -0
- package/test/stage2-escalation-live.test.ts +544 -0
- package/test/stage2-escalation-qualification.test.ts +170 -0
- package/test/stage2-escalation.test.ts +747 -0
- package/test/stage2-executor.test.ts +849 -0
- package/test/stage2-grant.test.ts +603 -0
- package/test/stage2-native-live.test.ts +647 -0
- package/test/stage2-network-decisions.test.ts +70 -0
- package/test/stage2-probe.test.ts +845 -0
- package/test/stage2-standing-live.test.ts +203 -0
- package/test/stubs/broker-host.mjs +59 -0
- package/test/stubs/broker-peer.mjs +20 -0
- package/test/stubs/confined-harness.mjs +91 -0
- package/test/stubs/ext-broken-server.mjs +2 -0
- package/test/stubs/ext-odd-server.mjs +21 -0
- package/test/stubs/ext-server.mjs +31 -0
- package/test/stubs/fake-host-cli.mjs +218 -0
- package/test/stubs/procargs.mjs +30 -0
- package/test/stubs/stub-acp +4 -0
- package/test/stubs/stub-agent.mjs +322 -0
- package/test/stubs/stub-claude +4 -0
- package/test/stubs/stub-codex +4 -0
- package/test/stubs/targets/acp.mjs +307 -0
- package/test/stubs/targets/claude.mjs +149 -0
- package/test/stubs/targets/codex.mjs +479 -0
- package/test/stubs/targets/gemini.mjs +604 -0
- package/test/temp-root.ts +11 -0
- package/test/wp4-adapters.test.ts +353 -0
- package/test/wp4-interlock.test.ts +136 -0
|
@@ -0,0 +1,875 @@
|
|
|
1
|
+
// Codex's sandbox as relay sets it: a permission profile of relay's own (codex.ts codexPermissions),
|
|
2
|
+
// selected with -c and named on the thread, with the harness configuration relay's own sandbox
|
|
3
|
+
// refuses read-only at the top of every workspace root. Checked against what Codex reports back
|
|
4
|
+
// (codex-app.ts configProblem, requirementsProblem, threadPermissionsProblem), and, where Codex is
|
|
5
|
+
// installed, against Codex's own sandbox (`codex sandbox`, the Seatbelt profile its commands run in).
|
|
6
|
+
import assert from "node:assert/strict";
|
|
7
|
+
import fs from "node:fs";
|
|
8
|
+
import net from "node:net";
|
|
9
|
+
import os from "node:os";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
12
|
+
import { test } from "node:test";
|
|
13
|
+
import { parse } from "smol-toml";
|
|
14
|
+
import { harness, realCodexBin, scratchEnv } from "./helpers.ts";
|
|
15
|
+
import { codexFlags, codexPermissions, deniedCredentials, permissionFlags, toml, tomlInline } from "../dist/backends/codex.js";
|
|
16
|
+
import { addedPermissions, CODEX_PROFILE, commandAsk, configProblem, requirementsProblem, threadPermissionsProblem, type CodexPermissions } from "../dist/backends/codex-app.js";
|
|
17
|
+
import { dirIdentity } from "../dist/confine/index.js";
|
|
18
|
+
import { codexEscalatedEffect } from "../dist/core/approvals.js";
|
|
19
|
+
import { HARNESS_CONFIG } from "../dist/confine/seatbelt.js";
|
|
20
|
+
import { withDefaults } from "../dist/core/config.js";
|
|
21
|
+
import { requestRunsRelayCommand } from "../dist/core/relay-command.js";
|
|
22
|
+
import { codexWriteRootProblem } from "../dist/targets/codex.js";
|
|
23
|
+
import { targetDef } from "../dist/targets/index.js";
|
|
24
|
+
import { neverKeychainIpc } from "../dist/core/never-coverage.js";
|
|
25
|
+
import { resolveNeverPolicy } from "../dist/core/never-policy.js";
|
|
26
|
+
import { attempt, decoyKeychain, keychainSkip, retrieved, withTeardown, wrapped, type DecoyKeychain } from "./keychain-decoy.ts";
|
|
27
|
+
|
|
28
|
+
const appServer = { codex_backend: "app-server" } as never;
|
|
29
|
+
const exec = { codex_backend: "exec" } as never;
|
|
30
|
+
const readOnlyNames = Object.fromEntries(HARNESS_CONFIG.map((n: string) => [n, "read"]));
|
|
31
|
+
|
|
32
|
+
/** A -c value read back as Codex reads it: as the value of a TOML key (in plain objects, as the assertions compare them). */
|
|
33
|
+
const tomlBack = (raw: string): unknown => structuredClone(parse(`v = ${raw}`).v);
|
|
34
|
+
|
|
35
|
+
test("codex permissions: every kind of turn relay launches, as a profile with the sandbox it had before plus read-only harness configuration", () => {
|
|
36
|
+
const read = codexPermissions({ access: "read", config: appServer }, { dangerous: false, network: false, roots: [] });
|
|
37
|
+
// Every confined turn, read or write, may not read the credential stores (and so no command leaves the sandbox).
|
|
38
|
+
const ownedHome = path.join(os.homedir(), ".local/share/relay-codex-home");
|
|
39
|
+
const store = path.join(os.homedir(), ".local/share/relay-codex-pins");
|
|
40
|
+
const denied = { "~/.ssh": "deny", "~/.aws": "deny", "~/.gnupg": "deny", "~/.netrc": "deny", "~/.codex/auth.json": "deny", [ownedHome]: "deny" };
|
|
41
|
+
assert.deepEqual(deniedCredentials(undefined), denied);
|
|
42
|
+
// Codex's login where CODEX_HOME puts it.
|
|
43
|
+
assert.deepEqual(deniedCredentials("/x/codex-home"), { ...denied, "/x/codex-home/auth.json": "deny" });
|
|
44
|
+
assert.deepEqual(deniedCredentials("relative/home"), denied, "a CODEX_HOME that is not absolute: Codex's default");
|
|
45
|
+
assert.deepEqual(codexPermissions({ access: "read", config: appServer }, { dangerous: false, network: false, roots: [], codexHome: "/x/codex-home" }).profile!.filesystem["/x/codex-home/auth.json"], "deny");
|
|
46
|
+
const protectedPaths = { [store]: "read", ...denied };
|
|
47
|
+
assert.deepEqual(read, { id: CODEX_PROFILE, profile: { filesystem: { ":root": "read", ...protectedPaths }, network: { enabled: false } }, sandbox: "read-only", network: false, proxy: null });
|
|
48
|
+
// The network, when a turn has it, goes through Codex's proxy: every public host, nothing of this
|
|
49
|
+
// Mac's own or private, no upstream proxy; strict unless asked otherwise.
|
|
50
|
+
const strict = { enabled: true, domains: { "*": "allow" }, allow_local_binding: false, allow_upstream_proxy: false };
|
|
51
|
+
// A read turn with the network: granted on the app server, strict and with no Unix sockets whatever
|
|
52
|
+
// is asked; the exec fallback never gave it one, and still does not.
|
|
53
|
+
assert.deepEqual(codexPermissions({ access: "read", config: appServer }, { dangerous: false, network: true, roots: [] }), { id: CODEX_PROFILE, profile: { filesystem: { ":root": "read", ...protectedPaths }, network: strict }, sandbox: "read-only", network: true, proxy: "strict" });
|
|
54
|
+
assert.deepEqual(codexPermissions({ access: "read", config: appServer }, { dangerous: false, network: true, roots: [], net: { mode: "local", sockets: ["/t"] } }).profile!.network, strict);
|
|
55
|
+
assert.deepEqual(codexPermissions({ access: "read", config: exec }, { dangerous: false, network: true, roots: [] }).profile!.network, { enabled: false });
|
|
56
|
+
assert.equal(codexPermissions({ access: "read", config: exec }, { dangerous: false, network: true, roots: [] }).proxy, null);
|
|
57
|
+
const write = codexPermissions({ access: "write", config: appServer }, { dangerous: false, network: true, roots: ["/g/one", "/g/two"], net: { mode: "strict", sockets: ["/t/own", "/w"] } });
|
|
58
|
+
assert.deepEqual(write, {
|
|
59
|
+
id: CODEX_PROFILE, sandbox: "workspace-write", network: true, proxy: "strict",
|
|
60
|
+
profile: {
|
|
61
|
+
workspace_roots: { "/g/one": true, "/g/two": true },
|
|
62
|
+
// Everything readable; the worktree and the granted directories writable, and the turn's own
|
|
63
|
+
// TMPDIR, not the rest of /tmp; at the top of each, relay's list of harness configuration read-only.
|
|
64
|
+
filesystem: { ":root": "read", ":tmpdir": "write", ":workspace_roots": { ".": "write", ...readOnlyNames }, ...protectedPaths },
|
|
65
|
+
// Unix sockets only in the directories named: the turn's TMPDIR and the job's worktree.
|
|
66
|
+
network: { ...strict, unix_sockets: { "/t/own": "allow", "/w": "allow" } },
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
// Local: the same with loopback and the LAN open; hosted: no shell network at all.
|
|
70
|
+
const local = codexPermissions({ access: "write", config: exec }, { dangerous: false, network: true, roots: [], net: { mode: "local", sockets: ["/t/own"] } });
|
|
71
|
+
assert.deepEqual([local.proxy, local.network, local.profile!.network], ["local", true, { ...strict, allow_local_binding: true, unix_sockets: { "/t/own": "allow" } }]);
|
|
72
|
+
const hosted = codexPermissions({ access: "write", config: appServer }, { dangerous: false, network: true, roots: [], net: { mode: "hosted" } });
|
|
73
|
+
assert.deepEqual([hosted.proxy, hosted.network, hosted.profile!.network], [null, false, { enabled: false }]);
|
|
74
|
+
// No socket directories named: no unix_sockets key, so no Unix sockets.
|
|
75
|
+
assert.equal("unix_sockets" in codexPermissions({ access: "write", config: appServer }, { dangerous: false, network: true, roots: [] }).profile!.network, false);
|
|
76
|
+
for (const name of [".claude", ".gemini", ".codex", ".agents", ".mcp.json", ".vscode", ".envrc"]) {
|
|
77
|
+
assert.equal((write.profile!.filesystem[":workspace_roots"] as Record<string, string>)[name], "read", name);
|
|
78
|
+
}
|
|
79
|
+
// No granted directory: no workspace_roots key at all.
|
|
80
|
+
assert.equal("workspace_roots" in codexPermissions({ access: "write", config: exec }, { dangerous: false, network: false, roots: [] }).profile!, false);
|
|
81
|
+
// allow_dangerous: Codex's own profile without a sandbox.
|
|
82
|
+
assert.deepEqual(codexPermissions({ access: "write", config: appServer }, { dangerous: true, network: false, roots: [] }), { id: ":danger-full-access", profile: null, sandbox: "danger-full-access", network: true, proxy: null });
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test("codex permissions: the -c values select and define the profile, and every name and path is a quoted key inside a value, never part of a dotted key", () => {
|
|
86
|
+
// A dot, quotes, a backslash, DEL (which TOML, unlike JSON, wants escaped), a tab and a character beyond the BMP.
|
|
87
|
+
const odd = '/tmp/a.b/with "quotes" and \\back.slash\x7fdel\ttab \u{1F600}';
|
|
88
|
+
const p = codexPermissions({ access: "write", config: appServer }, { dangerous: false, network: false, roots: [odd] });
|
|
89
|
+
const flags = permissionFlags(p);
|
|
90
|
+
const pairs = flags.filter((_: string, i: number) => i % 2 === 1);
|
|
91
|
+
assert.ok(flags.every((f: string, i: number) => i % 2 === 1 || f === "-c"));
|
|
92
|
+
const keys = pairs.map((kv: string) => kv.slice(0, kv.indexOf("=")));
|
|
93
|
+
assert.deepEqual(keys, ["default_permissions", "permissions.relay.filesystem", "permissions.relay.workspace_roots", "permissions.relay.network.enabled"]);
|
|
94
|
+
// Codex splits a key at every dot: no name or path is ever in one.
|
|
95
|
+
for (const k of keys) assert.ok(!/claude|gemini|mcp|\/|"/.test(k), k);
|
|
96
|
+
const value = (key: string) => pairs.find((kv: string) => kv.startsWith(`${key}=`))!.slice(key.length + 1);
|
|
97
|
+
assert.equal(value("default_permissions"), '"relay"');
|
|
98
|
+
assert.deepEqual(tomlBack(value("permissions.relay.filesystem")), p.profile!.filesystem);
|
|
99
|
+
assert.deepEqual(tomlBack(value("permissions.relay.workspace_roots")), { [odd]: true });
|
|
100
|
+
assert.equal(value("permissions.relay.network.enabled"), "false");
|
|
101
|
+
assert.ok(value("permissions.relay.workspace_roots").includes("\\u007f") && !value("permissions.relay.workspace_roots").includes("\x7f"), "DEL escaped");
|
|
102
|
+
assert.match(value("permissions.relay.filesystem"), /"\.claude"="read"/);
|
|
103
|
+
// An inline table's keys are always quoted, however plain.
|
|
104
|
+
assert.equal(tomlInline({ a: "b", ".c": { d: true } }), '{"a"="b",".c"={"d"=true}}');
|
|
105
|
+
// A built-in profile is only selected.
|
|
106
|
+
assert.deepEqual(permissionFlags(codexPermissions({ access: "write", config: appServer }, { dangerous: true, network: false, roots: [] })), ["-c", 'default_permissions=":danger-full-access"']);
|
|
107
|
+
// Nothing of the legacy sandbox settings is left in a launch's flags.
|
|
108
|
+
const spec = { config: withDefaults({}), target: targetDef("codex"), access: "write", cwd: "/w", relay: null } as never;
|
|
109
|
+
const all = codexFlags(spec, [], {}).c.join(" ");
|
|
110
|
+
assert.doesNotMatch(all, /sandbox_mode|sandbox_workspace_write/);
|
|
111
|
+
assert.ok(all.includes('default_permissions="relay"'));
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test("codex permissions: a TOML string relay writes for Codex reads back as the very string, DEL included; one TOML cannot hold is refused with a reason, before anything starts", () => {
|
|
115
|
+
for (const s of ["plain", 'a.b "q" \\back', "del\x7f", "nul\u0000 bell\u0007 tab\t newline\n cr\r", "\u2028 \u202e é \u{1F600}"]) {
|
|
116
|
+
assert.equal(tomlBack(toml(s)), s, JSON.stringify(s));
|
|
117
|
+
}
|
|
118
|
+
assert.deepEqual(tomlBack(toml(["a\x7f", "b"])), ["a\x7f", "b"]);
|
|
119
|
+
assert.deepEqual(tomlBack(tomlInline({ "k\x7f": "v\x7f", n: { m: true } })), { "k\x7f": "v\x7f", n: { m: true } });
|
|
120
|
+
// A lone surrogate is no Unicode scalar value: no TOML string holds it, escaped or not.
|
|
121
|
+
for (const bad of ["x\ud800", ["ok", "\udfff y"]]) {
|
|
122
|
+
assert.throws(() => toml(bad as never), /relay cannot give Codex "[^"]*\\ud[8f]\w\w[^"]*": it holds a lone UTF-16 surrogate, which no TOML string can hold, so relay does not start the agent\./);
|
|
123
|
+
}
|
|
124
|
+
// JSON's escape for one is not TOML.
|
|
125
|
+
assert.throws(() => parse(`v = ${JSON.stringify("x\ud800")}`), /unicode escape/);
|
|
126
|
+
// A pair is a character like any other.
|
|
127
|
+
assert.equal(tomlBack(toml("\ud83d\ude00")), "\u{1F600}");
|
|
128
|
+
// Refused where a turn's flags are made, so the turn fails saying why rather than Codex refusing its configuration.
|
|
129
|
+
const spec = { config: withDefaults({ child_git: "native" }), target: targetDef("codex"), access: "write", cwd: "/w", relay: null, gitDirs: ["/r/.git\ud800"] } as never;
|
|
130
|
+
assert.throws(() => codexFlags(spec, [], {}), /lone UTF-16 surrogate/);
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
test("codex permissions: the turn's own directory and the repository's git directory are refused at launch where Codex's sandbox cannot make them writable by their names; other control characters are not", () => {
|
|
134
|
+
const spec = (cwd: string, gitDirs: string[] = []) => ({ config: withDefaults({ child_git: "native" }), target: targetDef("codex"), access: "write", cwd, relay: null, gitDirs }) as never;
|
|
135
|
+
assert.throws(() => codexFlags(spec('/w "q"'), [], {}), (e: Error) => e.message.startsWith(`relay does not start the Codex agent: the turn's directory ${JSON.stringify('/w "q"')} holds a double quote`));
|
|
136
|
+
for (const name of ["/w\tx", "/w\nx", "/w\rx"]) {
|
|
137
|
+
assert.throws(() => codexFlags(spec(name), [], {}), (e: Error) => e.message === `relay does not start the Codex agent: the turn's directory ${JSON.stringify(name)} holds a tab or a line break, and Codex's sandbox can leave a directory so named unwritable, saying nothing.`, JSON.stringify(name));
|
|
138
|
+
assert.throws(() => codexFlags(spec("/w", [`/r${name.slice(2)}/.git`]), [], {}), (e: Error) => e.message.startsWith(`relay does not start the Codex agent: the repository's git directory ${JSON.stringify(`/r${name.slice(2)}/.git`)} holds a tab or a line break`), JSON.stringify(name));
|
|
139
|
+
}
|
|
140
|
+
assert.throws(() => codexFlags(spec("/w", ['/r "q"/.git']), [], {}), /the repository's git directory .* holds a double quote/);
|
|
141
|
+
// A read turn writes nowhere by name: its directory is not refused.
|
|
142
|
+
assert.doesNotThrow(() => codexFlags({ ...(spec('/w "q"') as object), access: "read" } as never, [], {}));
|
|
143
|
+
for (const name of ["/w\x1bx", "/w\x07x", "/w\x7fx"]) assert.doesNotThrow(() => codexFlags(spec(name, [`${name}/.git`]), [], {}), JSON.stringify(name));
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
test("codex permissions: a directory Codex's sandbox cannot make writable by its name is refused when it is granted to a Codex agent, saying why; other targets are not refused it", async () => {
|
|
147
|
+
const h = await harness([{ steps: [{ reply: "ok" }] }]);
|
|
148
|
+
try {
|
|
149
|
+
const quoted = path.join(path.dirname(h.home), 'with "quotes"');
|
|
150
|
+
const tabbed = path.join(path.dirname(h.home), "with\ttab");
|
|
151
|
+
for (const d of [quoted, tabbed]) fs.mkdirSync(d);
|
|
152
|
+
const refused = await h.call("delegate", { target: "codex", task: "QUOTED", mode: "write", grant: { write_paths: [quoted] }, background: false });
|
|
153
|
+
assert.match(JSON.stringify(refused), /grant\.write_paths entry \\".*with \\\\\\"quotes\\\\\\"\\" holds a double quote, and Codex's sandbox cannot be built with a directory so named writable: the agent could run no command at all\. Rename the directory, or give the work to another target\./);
|
|
154
|
+
const tab = await h.call("delegate", { target: "codex", task: "TABBED", mode: "write", grant: { write_paths: [tabbed] }, background: false });
|
|
155
|
+
assert.match(JSON.stringify(tab), /holds a tab or a line break, and Codex's sandbox can leave a directory so named unwritable, saying nothing/);
|
|
156
|
+
assert.equal(h.starts().length, 0, "no Codex agent started");
|
|
157
|
+
// Other control characters work in Codex's sandbox (the installed-Codex test below): granted.
|
|
158
|
+
const escaped = path.join(path.dirname(h.home), "with\x1besc");
|
|
159
|
+
fs.mkdirSync(escaped);
|
|
160
|
+
const esc = await h.call("delegate", { target: "codex", task: "ESC", mode: "write", grant: { write_paths: [escaped] }, background: false });
|
|
161
|
+
assert.equal(esc.status, "done", JSON.stringify(esc));
|
|
162
|
+
// Relay's own sandbox passes paths as parameters, never as profile text: Claude is given it.
|
|
163
|
+
const claude = await h.call("delegate", { target: "claude", task: "QUOTED", mode: "write", grant: { write_paths: [quoted] }, background: false });
|
|
164
|
+
assert.equal(claude.status, "done", JSON.stringify(claude));
|
|
165
|
+
} finally {
|
|
166
|
+
await h.close();
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
test("codex permissions: a command approval request's additionalPermissions are named in plain words, and relay vouches for the sandbox only where it read them all and the turn has one", () => {
|
|
171
|
+
// As Codex 0.164.0 sends them: entries, the legacy read and write lists null beside them where a
|
|
172
|
+
// special or glob entry is among them (app-server-protocol v2 permissions.rs, From<CoreFileSystemPermissions>).
|
|
173
|
+
assert.deepEqual(addedPermissions({
|
|
174
|
+
network: { enabled: true },
|
|
175
|
+
fileSystem: { read: null, write: null, entries: [
|
|
176
|
+
{ path: { type: "path", path: "/w x" }, access: "write" },
|
|
177
|
+
{ path: { type: "path", path: "/r" }, access: "read" },
|
|
178
|
+
{ path: { type: "special", value: { kind: "tmpdir" } }, access: "write" },
|
|
179
|
+
{ path: { type: "special", value: { kind: "project_roots", subpath: "build" } }, access: "write" },
|
|
180
|
+
{ path: { type: "special", value: { kind: "project_roots", subpath: null } }, access: "read" },
|
|
181
|
+
{ path: { type: "special", value: { kind: "slash_tmp" } }, access: "write" },
|
|
182
|
+
{ path: { type: "special", value: { kind: "root" } }, access: "read" },
|
|
183
|
+
{ path: { type: "special", value: { kind: "minimal" } }, access: "read" },
|
|
184
|
+
{ path: { type: "glob_pattern", pattern: "**/*.env" }, access: "deny" },
|
|
185
|
+
] },
|
|
186
|
+
}), {
|
|
187
|
+
words: 'write access to "/w x", its temporary directory (TMPDIR), "build" in each of its workspace roots, /tmp; read access to "/r", its workspace roots, the whole filesystem, Codex\'s minimal system paths; network access; no access to files matching "**/*.env"',
|
|
188
|
+
complete: true,
|
|
189
|
+
});
|
|
190
|
+
// Codex goes by the entries where they are given: legacy lists beside them that say otherwise are not read.
|
|
191
|
+
assert.deepEqual(addedPermissions({ fileSystem: { read: ["/x"], write: null, entries: [{ path: { type: "path", path: "/y" }, access: "read" }] } }), { words: 'read access to "/y"', complete: true });
|
|
192
|
+
// The legacy lists alone, a path quoted as the agent gave it.
|
|
193
|
+
assert.deepEqual(addedPermissions({ network: null, fileSystem: { read: null, write: ['/a "b"'] } }), { words: 'write access to "/a \\"b\\""', complete: true });
|
|
194
|
+
// Asking for nothing.
|
|
195
|
+
for (const nothing of [undefined, null, {}, { network: { enabled: false }, fileSystem: null }, { fileSystem: { entries: [] } }]) assert.equal(addedPermissions(nothing), null, JSON.stringify(nothing));
|
|
196
|
+
// What relay cannot read in full: a key, a kind of path or an access it does not know, a value of the wrong type.
|
|
197
|
+
for (const raw of [
|
|
198
|
+
{ network: { enabled: true }, macos: { preferences: "read_write" } },
|
|
199
|
+
{ network: { enabled: true, domains: ["example.com"] } },
|
|
200
|
+
{ network: { enabled: "yes" } },
|
|
201
|
+
{ fileSystem: { entries: [{ path: { type: "special", value: { kind: "unknown", path: ":future", subpath: null } }, access: "write" }] } },
|
|
202
|
+
{ fileSystem: { entries: [{ path: { type: "path", path: "/a" }, access: "execute" }] } },
|
|
203
|
+
{ fileSystem: { write: [1] } },
|
|
204
|
+
{ fileSystem: { entries: "all" } },
|
|
205
|
+
{ fileSystem: { write: ["/a"], other: true } },
|
|
206
|
+
// A key relay does not know anywhere in an entry: on the entry, its path, or a special path's value.
|
|
207
|
+
{ fileSystem: { entries: [{ path: { type: "path", path: "/a" }, access: "write", futureScope: "x" }] } },
|
|
208
|
+
{ fileSystem: { entries: [{ path: { type: "path", path: "/a", futureScope: "x" }, access: "write" }] } },
|
|
209
|
+
{ fileSystem: { entries: [{ path: { type: "glob_pattern", pattern: "*.env", futureScope: "x" }, access: "deny" }] } },
|
|
210
|
+
{ fileSystem: { entries: [{ path: { type: "special", value: { kind: "root" }, futureScope: "x" }, access: "read" }] } },
|
|
211
|
+
{ fileSystem: { entries: [{ path: { type: "special", value: { kind: "tmpdir", futureScope: "x" } }, access: "write" }] } },
|
|
212
|
+
{ fileSystem: { entries: [{ path: { type: "special", value: { kind: "project_roots", subpath: null, futureScope: "x" } }, access: "write" }] } },
|
|
213
|
+
"everything",
|
|
214
|
+
["/a"],
|
|
215
|
+
]) {
|
|
216
|
+
const got = addedPermissions(raw)!;
|
|
217
|
+
assert.equal(got.complete, false, JSON.stringify(raw));
|
|
218
|
+
assert.equal(got.words, JSON.stringify(raw));
|
|
219
|
+
}
|
|
220
|
+
assert.equal(addedPermissions({ fileSystem: { write: ["/x".repeat(400)], extra: 1 } })!.words.length, 601, "clipped");
|
|
221
|
+
|
|
222
|
+
const write = codexPermissions({ access: "write", config: appServer }, { dangerous: false, network: false, roots: [] });
|
|
223
|
+
const read = codexPermissions({ access: "read", config: appServer }, { dangerous: false, network: false, roots: [] });
|
|
224
|
+
const danger = codexPermissions({ access: "write", config: appServer }, { dangerous: true, network: false, roots: [] });
|
|
225
|
+
const p = { command: "npm ci", cwd: "/w", reason: "needs the registry", additionalPermissions: { network: { enabled: true }, fileSystem: { read: null, write: ["/w/.cache"] } }, availableDecisions: ["accept", "cancel"] };
|
|
226
|
+
const summary = 'npm ci (asks to add for this command: write access to "/w/.cache"; network access)';
|
|
227
|
+
// Allowed once only, whatever its effect: never for the rest of the job (commandAsk).
|
|
228
|
+
assert.deepEqual(commandAsk(p, write), { kind: "command", summary, reason: "needs the registry", detail: { cwd: "/w", command: "npm ci", once_only: true, adds_to_sandbox: true } });
|
|
229
|
+
assert.deepEqual(commandAsk(p, read).detail, { cwd: "/w", command: "npm ci", once_only: true, adds_to_sandbox: true });
|
|
230
|
+
assert.deepEqual(commandAsk({ ...p, kind: "command", approvalId: null }, write).detail, { cwd: "/w", command: "npm ci", once_only: true, adds_to_sandbox: true });
|
|
231
|
+
// No sandbox to stay in (allow_dangerous), a retry for a blocked host, additions relay cannot read
|
|
232
|
+
// in full, or a request of a kind or shape relay has not checked: the effect stays full access.
|
|
233
|
+
const full = { cwd: "/w", command: "npm ci", once_only: true };
|
|
234
|
+
assert.deepEqual(commandAsk(p, danger), { kind: "command", summary, reason: "needs the registry", detail: full });
|
|
235
|
+
assert.deepEqual(commandAsk({ ...p, networkApprovalContext: { host: "registry.npmjs.org", protocol: "https" } }, write).detail, full);
|
|
236
|
+
assert.deepEqual(commandAsk({ ...p, additionalPermissions: { macos: {} } }, write), { kind: "command", summary: 'npm ci (asks to add for this command, in terms relay cannot read in full: {"macos":{}})', reason: "needs the registry", detail: full });
|
|
237
|
+
assert.deepEqual(commandAsk({ ...p, approvalId: "sub-1" }, write).detail, full);
|
|
238
|
+
assert.deepEqual(commandAsk({ ...p, kind: "subcommand" }, write).detail, full);
|
|
239
|
+
// Input for a terminal already running: its permissions are those it kept, not something added.
|
|
240
|
+
assert.deepEqual(commandAsk({ ...p, kind: "writeStdin", command: "write_stdin --session-id 3 y" }, write), { kind: "command", summary: "write_stdin --session-id 3 y", reason: "needs the registry", detail: { cwd: "/w" } });
|
|
241
|
+
// What looks for relay's own CLI in a command reads the command alone, not what the summary adds
|
|
242
|
+
// to it: added access whose words a shell could not parse is no reason to ask the person, and a
|
|
243
|
+
// command that runs relay's CLI is found whatever is added to it.
|
|
244
|
+
const runsRelay = (q: Record<string, unknown>) => {
|
|
245
|
+
const ask = commandAsk(q, write);
|
|
246
|
+
return requestRunsRelayCommand({ kind: "command", summary: ask.summary, detail_json: JSON.stringify(ask.detail) }, "/w");
|
|
247
|
+
};
|
|
248
|
+
assert.equal(runsRelay({ ...p, additionalPermissions: { fileSystem: { write: ['/odd "(dir'] } } }), false);
|
|
249
|
+
assert.equal(runsRelay({ ...p, additionalPermissions: { macos: { x: "'" } } }), false);
|
|
250
|
+
assert.equal(runsRelay({ ...p, command: "relay approve q_1" }), true);
|
|
251
|
+
assert.equal(runsRelay({ ...p, command: "npm ci && relay deny q_1", additionalPermissions: { fileSystem: { write: ["/w/'"] } } }), true);
|
|
252
|
+
// Without additionalPermissions: a plain request to leave the sandbox, which on a confined turn
|
|
253
|
+
// stays in a sandbox denying the credential stores (escalates_restricted); on a turn without one
|
|
254
|
+
// (allow_dangerous), or of a kind relay has not checked, full access as before.
|
|
255
|
+
// Its value is the network the command keeps, the turn's: none here, else strict or local (codexEscalatedEffect).
|
|
256
|
+
assert.deepEqual(commandAsk({ command: "ls" }, write), { kind: "command", summary: "ls", reason: undefined, detail: { escalates_restricted: "none" } });
|
|
257
|
+
assert.deepEqual(commandAsk({ command: "ls" }, read).detail, { escalates_restricted: "none" });
|
|
258
|
+
assert.deepEqual(commandAsk({}, write), { kind: "command", summary: "(command not given)", reason: undefined, detail: { escalates_restricted: "none" } });
|
|
259
|
+
for (const mode of ["strict", "local"] as const) {
|
|
260
|
+
const proxied = codexPermissions({ access: "write", config: appServer }, { dangerous: false, network: true, roots: [], net: { mode, sockets: [] } });
|
|
261
|
+
assert.deepEqual(commandAsk({ command: "ls" }, proxied).detail, { escalates_restricted: mode });
|
|
262
|
+
}
|
|
263
|
+
const hostedOnly = codexPermissions({ access: "write", config: appServer }, { dangerous: false, network: true, roots: [], net: { mode: "hosted" } });
|
|
264
|
+
assert.deepEqual(commandAsk({ command: "ls" }, hostedOnly).detail, { escalates_restricted: "none" });
|
|
265
|
+
assert.match(codexEscalatedEffect("none"), /and no network \(the job's shell has none\)\. This is not full access/);
|
|
266
|
+
assert.match(codexEscalatedEffect("strict"), /and the job's network only through Codex's proxy \(no loopback or local network\)/);
|
|
267
|
+
assert.match(codexEscalatedEffect("local"), /loopback and the local network open, directly as well as through Codex's proxy/);
|
|
268
|
+
assert.match(codexEscalatedEffect(true), /and the job's own network\./, "a request recorded before this change");
|
|
269
|
+
assert.deepEqual(commandAsk({ command: "ls" }, danger).detail, {});
|
|
270
|
+
for (const odd of [{ approvalId: "a" }, { kind: "subcommand" }, { networkApprovalContext: { host: "x", protocol: "https" } }]) assert.deepEqual(commandAsk({ command: "ls", ...odd }, write).detail, {}, JSON.stringify(odd));
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
test("codex permissions: config/read must report relay's profile selected and exactly as relay set it; a key another layer adds, another selection or a changed entry is refused", () => {
|
|
274
|
+
const permissions = codexPermissions({ access: "write", config: appServer }, { dangerous: false, network: false, roots: ["/g"] });
|
|
275
|
+
const expect = { permissions, relay: null, relayOnly: false, accountLogin: false };
|
|
276
|
+
// As codex-cli 0.163.0 reports it (seen, 2026-10-22): every key it knows, the unset ones null.
|
|
277
|
+
const reported = {
|
|
278
|
+
description: null, extends: null, workspace_roots: { "/g": true },
|
|
279
|
+
filesystem: { glob_scan_max_depth: null, ...permissions.profile!.filesystem },
|
|
280
|
+
network: { enabled: false, proxy_url: null, enable_socks5: null, socks_url: null, mode: null, domains: null, unix_sockets: null, allow_local_binding: null, mitm: null },
|
|
281
|
+
};
|
|
282
|
+
const good = { approvals_reviewer: "user", default_permissions: "relay", permissions: { relay: reported, theirs: { filesystem: { ":root": "write" } } }, sandbox_mode: "workspace-write" };
|
|
283
|
+
// Another profile of the person's own, and a legacy sandbox_mode, change nothing: relay's selection outranks them.
|
|
284
|
+
assert.equal(configProblem(good, expect), null);
|
|
285
|
+
const bad = (eff: Record<string, unknown>, expected: RegExp) => assert.match(String(configProblem({ ...good, ...eff }, expect)), expected);
|
|
286
|
+
bad({ default_permissions: ":workspace" }, /default_permissions is ":workspace" where relay set "relay"/);
|
|
287
|
+
bad({ default_permissions: null }, /default_permissions is null where relay set "relay"/);
|
|
288
|
+
bad({ permissions: { relay: { ...reported, filesystem: { ...reported.filesystem, "/Users/me": "write" } } } }, /the permission profile "relay" is .*"\/Users\/me":"write"/);
|
|
289
|
+
bad({ permissions: { relay: { ...reported, extends: ":workspace" } } }, /the permission profile "relay" is .*"extends":":workspace"/);
|
|
290
|
+
bad({ permissions: { relay: { ...reported, network: { ...reported.network, enabled: true } } } }, /the permission profile "relay" is/);
|
|
291
|
+
bad({ permissions: { relay: { ...reported, workspace_roots: { "/g": true, "/elsewhere": true } } } }, /the permission profile "relay" is/);
|
|
292
|
+
bad({ permissions: null }, /the permission profile "relay" is null/);
|
|
293
|
+
// The credential stores' denials: each one missing, or changed, is refused, so every turn confirms them.
|
|
294
|
+
for (const key of Object.keys(deniedCredentials(undefined))) {
|
|
295
|
+
const { [key]: _gone, ...without } = reported.filesystem as Record<string, unknown>;
|
|
296
|
+
bad({ permissions: { relay: { ...reported, filesystem: without } } }, /the permission profile "relay" is/);
|
|
297
|
+
bad({ permissions: { relay: { ...reported, filesystem: { ...reported.filesystem, [key]: "read" } } } }, /the permission profile "relay" is/);
|
|
298
|
+
}
|
|
299
|
+
// Built-in: only the selection is judged.
|
|
300
|
+
const danger = codexPermissions({ access: "write", config: appServer }, { dangerous: true, network: false, roots: [] });
|
|
301
|
+
assert.equal(configProblem({ approvals_reviewer: "user", default_permissions: ":danger-full-access" }, { ...expect, permissions: danger }), null);
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
test("codex permissions: an administrator's requirements that would make Codex use another profile or sandbox mode refuse the turn; so does not being able to read them", async () => {
|
|
305
|
+
const p = codexPermissions({ access: "write", config: appServer }, { dangerous: false, network: false, roots: [] });
|
|
306
|
+
const rpc = (requirements: unknown) => ({ request: async (method: string) => { assert.equal(method, "configRequirements/read"); return { supportsIndependentSpeedModes: true, requirements }; } });
|
|
307
|
+
assert.equal(await requirementsProblem(rpc(null), p), null);
|
|
308
|
+
assert.equal(await requirementsProblem(rpc({ allowedPermissionProfiles: { relay: true, ":read-only": true } }), p), null);
|
|
309
|
+
assert.match(String(await requirementsProblem(rpc({ allowedPermissionProfiles: { ":workspace": true, ":read-only": true, relay: false } }), p)), /allow only the permission profiles ":workspace", ":read-only", not relay's "relay"/);
|
|
310
|
+
assert.match(String(await requirementsProblem(rpc({ allowedPermissionProfiles: {} }), p)), /allow only the permission profiles \(none\)/);
|
|
311
|
+
assert.match(String(await requirementsProblem(rpc({ allowedSandboxModes: ["read-only"] }), p)), /allow only the sandbox modes "read-only", not the "workspace-write"/);
|
|
312
|
+
assert.equal(await requirementsProblem(rpc({ allowedSandboxModes: ["read-only", "workspace-write"] }), p), null);
|
|
313
|
+
const broken = { request: async () => { throw new Error("method not found"); } };
|
|
314
|
+
assert.match(String(await requirementsProblem(broken, p)), /could not read the requirements an administrator may have set for Codex \(method not found\)/);
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
test("codex permissions: a thread must report relay's profile as active and a sandbox of the kind, network and temporary directories relay set", () => {
|
|
318
|
+
const write = codexPermissions({ access: "write", config: appServer }, { dangerous: false, network: false, roots: ["/g"] });
|
|
319
|
+
// id null: a thread that reports no active profile.
|
|
320
|
+
// The turn's directory: as Codex reports it, the thread's only workspace root.
|
|
321
|
+
const cwd = "/w";
|
|
322
|
+
const t = (sandbox: Record<string, unknown>, id: unknown = "relay", roots: unknown = [cwd]) => ({ activePermissionProfile: id === null ? undefined : { id, extends: null }, sandbox, runtimeWorkspaceRoots: roots });
|
|
323
|
+
// As codex-cli 0.163.0 reports it (seen, 2026-10-22).
|
|
324
|
+
const ww = { type: "workspaceWrite", writableRoots: ["/g"], networkAccess: false, excludeTmpdirEnvVar: false, excludeSlashTmp: true };
|
|
325
|
+
assert.equal(threadPermissionsProblem(t(ww), write, cwd), null);
|
|
326
|
+
assert.match(String(threadPermissionsProblem(t(ww, ":workspace"), write, cwd)), /runs with the permission profile ":workspace", not relay's "relay" \(an administrator's requirements can make Codex replace it\)/);
|
|
327
|
+
assert.match(String(threadPermissionsProblem(t(ww, null), write, cwd)), /does not report which permission profile it runs with/);
|
|
328
|
+
assert.match(String(threadPermissionsProblem(t({ ...ww, networkAccess: true }), write, cwd)), /network access true where relay set false/);
|
|
329
|
+
assert.match(String(threadPermissionsProblem(t({ ...ww, excludeSlashTmp: false }), write, cwd)), /temporary directories other than the turn's own/);
|
|
330
|
+
assert.match(String(threadPermissionsProblem(t({ type: "dangerFullAccess" }), write, cwd)), /reports a "dangerFullAccess" sandbox where relay set "workspaceWrite"/);
|
|
331
|
+
const read = codexPermissions({ access: "read", config: appServer }, { dangerous: false, network: true, roots: [] });
|
|
332
|
+
assert.equal(threadPermissionsProblem(t({ type: "readOnly", networkAccess: true }), read, cwd), null);
|
|
333
|
+
assert.match(String(threadPermissionsProblem(t({ type: "readOnly", networkAccess: false }), read, cwd)), /network access false where relay set true/);
|
|
334
|
+
const danger = codexPermissions({ access: "write", config: appServer }, { dangerous: true, network: false, roots: [] });
|
|
335
|
+
assert.equal(threadPermissionsProblem(t({ type: "dangerFullAccess" }, ":danger-full-access"), danger, cwd), null);
|
|
336
|
+
assert.match(String(threadPermissionsProblem(null, write, cwd)), /does not report which permission profile/);
|
|
337
|
+
// Workspace roots: the turn's directory alone. A thread that kept another (a grant it stored under
|
|
338
|
+
// relay's earlier settings, restored on resume) would have it writable under relay's profile.
|
|
339
|
+
assert.match(String(threadPermissionsProblem(t(ww, "relay", [cwd, "/old/grant"]), write, cwd)), /reports the workspace roots \["\/w","\/old\/grant"\] where relay set only the turn's directory "\/w"/);
|
|
340
|
+
assert.match(String(threadPermissionsProblem(t(ww, "relay", null), write, cwd)), /reports the workspace roots null/);
|
|
341
|
+
assert.match(String(threadPermissionsProblem(t({ ...ww, writableRoots: ["/g", "/old/grant"] }), write, cwd)), /reports \["\/old\/grant"\] as writable, which relay did not grant this turn/);
|
|
342
|
+
assert.match(String(threadPermissionsProblem(t({ type: "readOnly", networkAccess: true }, "relay", ["/elsewhere"]), read, cwd)), /reports the workspace roots \["\/elsewhere"\]/);
|
|
343
|
+
});
|
|
344
|
+
|
|
345
|
+
test("codex sandbox tests: the Codex RELAY_TEST_CODEX names is used, and at gates (RELAY_REQUIRE_REAL_CODEX=1) nothing else stands in for it", () => {
|
|
346
|
+
let looked = 0;
|
|
347
|
+
const fallback = () => { looked++; return "/opt/homebrew/bin/codex"; };
|
|
348
|
+
const pinned = "/Users/x/.local/share/relay-codex-pins/versions/0.164.0-d8990e3ee7ac/bin/codex";
|
|
349
|
+
// Named: the named binary, gate or not, without looking elsewhere.
|
|
350
|
+
for (const gate of [{}, { RELAY_REQUIRE_REAL_CODEX: "1" }]) {
|
|
351
|
+
const got = realCodexBin(fallback, { RELAY_TEST_CODEX: pinned, ...gate });
|
|
352
|
+
assert.equal(got.bin, pinned);
|
|
353
|
+
assert.equal(got.required, Boolean(gate.RELAY_REQUIRE_REAL_CODEX));
|
|
354
|
+
}
|
|
355
|
+
assert.equal(looked, 0);
|
|
356
|
+
// At a gate with none named: a failure that says what to set, never PATH's or Homebrew's Codex.
|
|
357
|
+
const gate = realCodexBin(fallback, { RELAY_REQUIRE_REAL_CODEX: "1" });
|
|
358
|
+
assert.deepEqual([gate.bin, gate.required, looked], [null, true, 0]);
|
|
359
|
+
assert.match(gate.why, /RELAY_TEST_CODEX/);
|
|
360
|
+
// Outside gates: today's lookup, and a skip when it finds nothing.
|
|
361
|
+
assert.deepEqual([realCodexBin(fallback, {}).bin, realCodexBin(fallback, {}).required], ["/opt/homebrew/bin/codex", false]);
|
|
362
|
+
assert.equal(realCodexBin(() => null, {}).bin, null);
|
|
363
|
+
// A relative name is refused rather than looked up.
|
|
364
|
+
const relative = realCodexBin(fallback, { RELAY_TEST_CODEX: "codex", RELAY_REQUIRE_REAL_CODEX: "1" });
|
|
365
|
+
assert.equal(relative.bin, null);
|
|
366
|
+
assert.match(relative.why, /absolute/);
|
|
367
|
+
});
|
|
368
|
+
|
|
369
|
+
// Installed Codex's own sandbox (`codex sandbox`: the Seatbelt profile its commands run in), given
|
|
370
|
+
// relay's profile for each kind of turn. Codex is the one RELAY_TEST_CODEX names (gates: the pinned
|
|
371
|
+
// binary), or else the first on PATH, and must be 0.163.0 or later, the first with permission
|
|
372
|
+
// profiles. Without one these tests are skipped, saying so, unless RELAY_REQUIRE_REAL_CODEX=1, which
|
|
373
|
+
// makes a missing Codex a failure and takes only RELAY_TEST_CODEX's (realCodexBin). Only on macOS,
|
|
374
|
+
// where that sandbox is Seatbelt. Every directory they use is scratch, under the test's TMPDIR.
|
|
375
|
+
const MIN_CODEX = "0.163.0";
|
|
376
|
+
const STUBS = path.join(import.meta.dirname, "stubs");
|
|
377
|
+
function codexOnPath(): string | null {
|
|
378
|
+
for (const dir of (process.env.PATH ?? "").split(path.delimiter).filter(Boolean)) {
|
|
379
|
+
const bin = path.join(dir, "codex");
|
|
380
|
+
try {
|
|
381
|
+
fs.accessSync(bin, fs.constants.X_OK);
|
|
382
|
+
const real = fs.realpathSync(bin);
|
|
383
|
+
if (fs.statSync(real).isFile() && !real.startsWith(STUBS + path.sep)) return bin;
|
|
384
|
+
} catch {
|
|
385
|
+
// Not here.
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
return null;
|
|
389
|
+
}
|
|
390
|
+
const REAL = process.platform === "darwin" ? realCodexBin(codexOnPath) : null;
|
|
391
|
+
const REAL_CODEX = REAL?.bin ?? null;
|
|
392
|
+
const realCodex = {
|
|
393
|
+
skip: !REAL ? "Codex's sandbox is Seatbelt only on macOS"
|
|
394
|
+
: !REAL.bin && !REAL.required ? REAL.why.replace("no Codex found", "no codex on PATH") : false,
|
|
395
|
+
};
|
|
396
|
+
/** The installed Codex, checked: present (a failure under RELAY_REQUIRE_REAL_CODEX=1 where it is not) and recent enough. */
|
|
397
|
+
function installedCodex(): string {
|
|
398
|
+
assert.ok(REAL_CODEX, REAL?.why);
|
|
399
|
+
const r = spawnSync(REAL_CODEX, ["--version"], { encoding: "utf8", timeout: 20000 });
|
|
400
|
+
const version = /(\d+)\.(\d+)\.(\d+)/.exec(r.stdout ?? "");
|
|
401
|
+
assert.ok(version, `codex --version said ${JSON.stringify(r.stdout)} ${JSON.stringify(r.stderr)}`);
|
|
402
|
+
const [have, need] = [version.slice(1).map(Number), MIN_CODEX.split(".").map(Number)];
|
|
403
|
+
const order = have.map((n, i) => n - need[i]).find((d) => d !== 0) ?? 0;
|
|
404
|
+
assert.ok(order >= 0, `${REAL_CODEX} is codex ${version[0]}; relay's profile needs ${MIN_CODEX} or later`);
|
|
405
|
+
return REAL_CODEX;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/** A scratch tree for one test, under the test's TMPDIR: a home for Codex and the turn's own TMPDIR, and the directories named. */
|
|
409
|
+
function sandboxTree(...names: string[]) {
|
|
410
|
+
const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "relay-codex-sandbox-")));
|
|
411
|
+
const dirs = Object.fromEntries(names.map((n) => [n, path.join(root, n)]));
|
|
412
|
+
const home = path.join(root, "home"), own = path.join(root, "tmp");
|
|
413
|
+
for (const d of [...Object.values(dirs), path.join(home, ".codex"), own]) fs.mkdirSync(d, { recursive: true });
|
|
414
|
+
const env = scratchEnv({ PATH: process.env.PATH, HOME: home, CODEX_HOME: path.join(home, ".codex"), TMPDIR: own, GIT_CONFIG_NOSYSTEM: "1" });
|
|
415
|
+
return { root, dirs, own, env, done: () => fs.rmSync(root, { recursive: true, force: true }) };
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* One thing a probe tries inside the sandbox: write a file (its directory made first), remove one,
|
|
420
|
+
* rename one, connect to a port on 127.0.0.1, or run a program.
|
|
421
|
+
*/
|
|
422
|
+
type Probe = { write: string } | { unlink: string } | { rename: [string, string] } | { connect: number } | { unix: string } | { listenUnix: string } | { viaProxy: number } | { run: string[]; cwd?: string };
|
|
423
|
+
const PROBE = `
|
|
424
|
+
const fs = require("fs"), path = require("path"), net = require("net"), cp = require("child_process");
|
|
425
|
+
const reach = (port) => new Promise((ok, no) => {
|
|
426
|
+
const s = net.connect(port, "127.0.0.1", () => { s.destroy(); ok(); });
|
|
427
|
+
s.on("error", no);
|
|
428
|
+
setTimeout(() => { s.destroy(); no(new Error("timed out")); }, 5000).unref();
|
|
429
|
+
});
|
|
430
|
+
const unix = (p) => new Promise((ok, no) => {
|
|
431
|
+
const s = net.connect(p, () => { s.destroy(); ok(); });
|
|
432
|
+
s.on("error", no);
|
|
433
|
+
setTimeout(() => { s.destroy(); no(new Error("timed out")); }, 5000).unref();
|
|
434
|
+
});
|
|
435
|
+
const listenUnix = (p) => new Promise((ok, no) => {
|
|
436
|
+
try { fs.unlinkSync(p); } catch {}
|
|
437
|
+
const srv = net.createServer().listen(p, () => { srv.close(); ok(); });
|
|
438
|
+
srv.on("error", no);
|
|
439
|
+
});
|
|
440
|
+
// A request for 127.0.0.1:port through the proxy Codex gives the command: worked if the test's server answered 200.
|
|
441
|
+
const viaProxy = (port) => new Promise((ok, no) => {
|
|
442
|
+
if (!process.env.HTTP_PROXY) return no(new Error("no proxy"));
|
|
443
|
+
const u = new URL(process.env.HTTP_PROXY);
|
|
444
|
+
const s = net.connect(+u.port, u.hostname, () => s.write("GET http://127.0.0.1:" + port + "/ HTTP/1.1\\r\\nHost: 127.0.0.1:" + port + "\\r\\nConnection: close\\r\\n\\r\\n"));
|
|
445
|
+
// Decided on the status line: the proxy may keep the connection open.
|
|
446
|
+
let b = "";
|
|
447
|
+
const decide = () => { s.destroy(); return /^HTTP\\/1\\.1 200/.test(b) ? ok() : no(new Error(b.split("\\r\\n")[0] || "no answer")); };
|
|
448
|
+
s.on("data", (d) => { b += d; if (b.includes("\\r\\n")) decide(); }); s.on("end", decide);
|
|
449
|
+
s.on("error", no);
|
|
450
|
+
setTimeout(() => { s.destroy(); no(new Error("timed out")); }, 8000).unref();
|
|
451
|
+
});
|
|
452
|
+
(async () => {
|
|
453
|
+
const out = [];
|
|
454
|
+
for (const o of JSON.parse(process.argv[1])) {
|
|
455
|
+
try {
|
|
456
|
+
if (o.write) { fs.mkdirSync(path.dirname(o.write), { recursive: true }); fs.writeFileSync(o.write, "scratch", { flag: "a" }); }
|
|
457
|
+
else if (o.unlink) fs.unlinkSync(o.unlink);
|
|
458
|
+
else if (o.rename) fs.renameSync(o.rename[0], o.rename[1]);
|
|
459
|
+
else if (o.connect) await reach(o.connect);
|
|
460
|
+
else if (o.unix) await unix(o.unix);
|
|
461
|
+
else if (o.listenUnix) await listenUnix(o.listenUnix);
|
|
462
|
+
else if (o.viaProxy) await viaProxy(o.viaProxy);
|
|
463
|
+
else if (o.run) cp.execFileSync(o.run[0], o.run.slice(1), { cwd: o.cwd, stdio: "pipe" });
|
|
464
|
+
out.push(true);
|
|
465
|
+
} catch (e) { out.push(String(e.code ?? e.stderr ?? e.message).slice(0, 300)); }
|
|
466
|
+
}
|
|
467
|
+
console.log(JSON.stringify(out));
|
|
468
|
+
})();`;
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* Runs each probe in installed Codex's sandbox for `p`, from `cwd`, and checks which worked against
|
|
472
|
+
* `cases` ([probe, expected]); the message lists every case, + for one that should work.
|
|
473
|
+
*/
|
|
474
|
+
function expectInSandbox(codex: string, p: CodexPermissions, cwd: string, env: NodeJS.ProcessEnv, cases: [Probe, boolean][]): void {
|
|
475
|
+
// A profile whose network goes through Codex's proxy needs the feature on, as codexFlags sets it.
|
|
476
|
+
const flags = [...permissionFlags(p), ...(p.proxy ? ["-c", "features.network_proxy=true"] : [])];
|
|
477
|
+
const r = spawnSync(codex, ["sandbox", ...flags, "--", process.execPath, "-e", PROBE, JSON.stringify(cases.map(([probe]) => probe))], { cwd, env, encoding: "utf8", timeout: 60000 });
|
|
478
|
+
assert.equal(r.status, 0, r.stderr);
|
|
479
|
+
const got = JSON.parse(r.stdout) as (true | string)[];
|
|
480
|
+
assert.deepEqual(got.map((g) => g === true), cases.map(([, ok]) => ok), cases.map(([probe, ok], i) => `${ok ? "+" : "-"} ${JSON.stringify(probe)}: ${got[i]}`).join("\n"));
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/** relay's profile for a turn of this access and network, with these workspace roots (the granted directories), and the network mode and socket directories asked for. */
|
|
484
|
+
const profileFor = (access: "read" | "write", network: boolean, roots: string[] = [], net?: { mode: "strict" | "local" | "hosted"; sockets?: string[] }) =>
|
|
485
|
+
codexPermissions({ access, config: withDefaults({}) } as never, { dangerous: false, network, roots, ...(net ? { net } : {}) });
|
|
486
|
+
|
|
487
|
+
test("codex sandbox (installed Codex): a write turn writes its worktree, grants and own TMPDIR, but not harness configuration at their top, nor .git, /tmp or elsewhere; a read turn writes nothing", realCodex, () => {
|
|
488
|
+
const codex = installedCodex();
|
|
489
|
+
const t = sandboxTree("wt", "grant", "outside");
|
|
490
|
+
const { wt, grant, outside } = t.dirs;
|
|
491
|
+
try {
|
|
492
|
+
assert.equal(spawnSync("git", ["init", "-q"], { cwd: wt, env: t.env }).status, 0);
|
|
493
|
+
expectInSandbox(codex, profileFor("write", false, [grant]), wt, t.env, [
|
|
494
|
+
[{ write: path.join(wt, "ok.txt") }, true],
|
|
495
|
+
[{ write: path.join(wt, "sub", ".claude", "deeper-is-not-covered") }, true],
|
|
496
|
+
[{ write: path.join(grant, "ok.txt") }, true],
|
|
497
|
+
[{ write: path.join(t.own, "ok.txt") }, true],
|
|
498
|
+
[{ write: path.join(wt, ".claude", "settings.json") }, false],
|
|
499
|
+
[{ write: path.join(wt, ".gemini", "x") }, false],
|
|
500
|
+
[{ write: path.join(wt, ".mcp.json") }, false],
|
|
501
|
+
[{ write: path.join(wt, ".codex", "config.toml") }, false],
|
|
502
|
+
[{ write: path.join(wt, ".agents", "skills", "x") }, false],
|
|
503
|
+
[{ write: path.join(wt, ".git", "config") }, false],
|
|
504
|
+
[{ write: path.join(grant, ".claude", "settings.json") }, false],
|
|
505
|
+
[{ write: path.join(grant, ".gemini", "x") }, false],
|
|
506
|
+
[{ write: path.join(outside, "x") }, false],
|
|
507
|
+
[{ write: `/tmp/relay-codex-profile-probe-${process.pid}` }, false],
|
|
508
|
+
]);
|
|
509
|
+
assert.equal(fs.existsSync(path.join(wt, ".claude", "settings.json")) || fs.existsSync(path.join(wt, ".gemini")), false);
|
|
510
|
+
expectInSandbox(codex, profileFor("read", false), wt, t.env, [
|
|
511
|
+
[{ write: path.join(wt, "read.txt") }, false],
|
|
512
|
+
[{ write: path.join(t.own, "read.txt") }, false],
|
|
513
|
+
[{ write: path.join(grant, "read.txt") }, false],
|
|
514
|
+
]);
|
|
515
|
+
} finally { t.done(); }
|
|
516
|
+
});
|
|
517
|
+
|
|
518
|
+
test("codex sandbox (installed Codex): harness configuration that already exists in a grant or the worktree cannot be removed, renamed or replaced, and a name in another case is the same name", realCodex, () => {
|
|
519
|
+
const codex = installedCodex();
|
|
520
|
+
const t = sandboxTree("wt", "grant");
|
|
521
|
+
const { wt, grant } = t.dirs;
|
|
522
|
+
try {
|
|
523
|
+
for (const top of [wt, grant]) {
|
|
524
|
+
fs.mkdirSync(path.join(top, ".claude"));
|
|
525
|
+
fs.writeFileSync(path.join(top, ".claude", "settings.json"), "{}");
|
|
526
|
+
fs.writeFileSync(path.join(top, ".mcp.json"), "{}");
|
|
527
|
+
}
|
|
528
|
+
const cases: [Probe, boolean][] = [];
|
|
529
|
+
for (const top of [wt, grant]) {
|
|
530
|
+
cases.push(
|
|
531
|
+
[{ unlink: path.join(top, ".mcp.json") }, false],
|
|
532
|
+
[{ unlink: path.join(top, ".claude", "settings.json") }, false],
|
|
533
|
+
[{ rename: [path.join(top, ".claude"), path.join(top, "claude-moved")] }, false],
|
|
534
|
+
[{ rename: [path.join(top, ".mcp.json"), path.join(top, "mcp-moved.json")] }, false],
|
|
535
|
+
[{ rename: [path.join(top, ".claude", "settings.json"), path.join(top, "settings-moved.json")] }, false],
|
|
536
|
+
[{ write: path.join(top, ".claude", "settings.json") }, false],
|
|
537
|
+
// A file of the agent's own, put in place of the existing one.
|
|
538
|
+
[{ write: path.join(top, "planted.json") }, true],
|
|
539
|
+
[{ rename: [path.join(top, "planted.json"), path.join(top, ".mcp.json")] }, false],
|
|
540
|
+
[{ rename: [path.join(top, "planted.json"), path.join(top, ".MCP.json")] }, false],
|
|
541
|
+
// macOS's default disks do not tell names apart by case: these are the same files.
|
|
542
|
+
[{ write: path.join(top, ".Claude", "settings.json") }, false],
|
|
543
|
+
[{ write: path.join(top, ".CLAUDE", "settings.local.json") }, false],
|
|
544
|
+
[{ write: path.join(top, ".MCP.json") }, false],
|
|
545
|
+
[{ unlink: path.join(top, ".MCP.json") }, false],
|
|
546
|
+
[{ rename: [path.join(top, ".Claude"), path.join(top, "claude-moved-2")] }, false],
|
|
547
|
+
);
|
|
548
|
+
}
|
|
549
|
+
expectInSandbox(codex, profileFor("write", false, [grant]), wt, t.env, cases);
|
|
550
|
+
for (const top of [wt, grant]) {
|
|
551
|
+
assert.equal(fs.readFileSync(path.join(top, ".claude", "settings.json"), "utf8"), "{}");
|
|
552
|
+
assert.equal(fs.readFileSync(path.join(top, ".mcp.json"), "utf8"), "{}");
|
|
553
|
+
assert.deepEqual(fs.readdirSync(top).sort(), [".claude", ".mcp.json", "planted.json"]);
|
|
554
|
+
assert.deepEqual(fs.readdirSync(path.join(top, ".claude")), ["settings.json"]);
|
|
555
|
+
}
|
|
556
|
+
} finally { t.done(); }
|
|
557
|
+
});
|
|
558
|
+
|
|
559
|
+
test("codex sandbox (installed Codex): a network grant reaches only the network through Codex's proxy; loopback and Unix sockets outside the turn's own places stay closed, unless local mode opens loopback", realCodex, async () => {
|
|
560
|
+
const codex = installedCodex();
|
|
561
|
+
const t = sandboxTree("wt", "outside");
|
|
562
|
+
const { wt, outside } = t.dirs;
|
|
563
|
+
// A port of the test's own on 127.0.0.1, answering HTTP from a process of its own (this one waits
|
|
564
|
+
// on the sandbox, synchronously); and a Unix socket of its own outside the turn's places.
|
|
565
|
+
const server = spawn(process.execPath, ["-e", 'const s=require("http").createServer((q,r)=>r.end("ok")).listen(0,"127.0.0.1",()=>console.log(s.address().port))'], { stdio: ["ignore", "pipe", "inherit"] });
|
|
566
|
+
const sock = path.join(outside, "s.sock");
|
|
567
|
+
const unixServer = net.createServer((s) => s.destroy()).listen(sock);
|
|
568
|
+
try {
|
|
569
|
+
const port = await new Promise<number>((resolve) => server.stdout!.once("data", (d) => resolve(Number(String(d).trim()))));
|
|
570
|
+
const sockets = [t.own, wt];
|
|
571
|
+
// No grant: no network.
|
|
572
|
+
expectInSandbox(codex, profileFor("write", false), wt, t.env, [[{ connect: port }, false], [{ unix: sock }, false], [{ write: path.join(wt, "w.txt") }, true]]);
|
|
573
|
+
// Strict: Seatbelt refuses loopback and the outside socket, the proxy refuses loopback, and
|
|
574
|
+
// sockets work only in the turn's TMPDIR and worktree.
|
|
575
|
+
expectInSandbox(codex, profileFor("write", true, [], { mode: "strict", sockets }), wt, t.env, [
|
|
576
|
+
[{ connect: port }, false], [{ viaProxy: port }, false], [{ unix: sock }, false],
|
|
577
|
+
[{ listenUnix: path.join(t.own, "a.sock") }, true], [{ listenUnix: path.join(wt, "b.sock") }, true], [{ listenUnix: path.join(outside, "c.sock") }, false],
|
|
578
|
+
[{ write: path.join(wt, "w.txt") }, true],
|
|
579
|
+
]);
|
|
580
|
+
// Local: loopback opens, directly and through the proxy; sockets elsewhere stay closed.
|
|
581
|
+
expectInSandbox(codex, profileFor("write", true, [], { mode: "local", sockets }), wt, t.env, [
|
|
582
|
+
[{ connect: port }, true], [{ viaProxy: port }, true], [{ unix: sock }, false], [{ listenUnix: path.join(t.own, "d.sock") }, true],
|
|
583
|
+
]);
|
|
584
|
+
// A read turn with the network: strict, no Unix sockets at all, and it still writes nothing.
|
|
585
|
+
expectInSandbox(codex, profileFor("read", true), wt, t.env, [[{ connect: port }, false], [{ viaProxy: port }, false], [{ listenUnix: path.join(t.own, "e.sock") }, false], [{ write: path.join(wt, "r.txt") }, false]]);
|
|
586
|
+
expectInSandbox(codex, profileFor("read", false), wt, t.env, [[{ connect: port }, false]]);
|
|
587
|
+
} finally {
|
|
588
|
+
server.kill();
|
|
589
|
+
unixServer.close();
|
|
590
|
+
t.done();
|
|
591
|
+
}
|
|
592
|
+
});
|
|
593
|
+
|
|
594
|
+
/**
|
|
595
|
+
* One turn of installed Codex's app server, model-free: a scratch CODEX_HOME whose provider is a fake
|
|
596
|
+
* Responses API on loopback that asks for one exec_command, then ends. Returns once the turn completes.
|
|
597
|
+
*/
|
|
598
|
+
async function oneCommandTurn(codex: string, o: { home: string; cwd: string; tmp: string; flags: string[]; cmd: string; args?: Record<string, unknown>; policy?: string }): Promise<string[]> {
|
|
599
|
+
const http = await import("node:http");
|
|
600
|
+
const { spawn } = await import("node:child_process");
|
|
601
|
+
const log: string[] = [];
|
|
602
|
+
const sse = (evs: Record<string, unknown>[]) => evs.map((e) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join("");
|
|
603
|
+
const done = { type: "response.completed", response: { id: "r", usage: { input_tokens: 0, input_tokens_details: null, output_tokens: 0, output_tokens_details: null, total_tokens: 0 } } };
|
|
604
|
+
const server = http.createServer((q, res) => {
|
|
605
|
+
let b = "";
|
|
606
|
+
q.on("data", (d) => (b += d));
|
|
607
|
+
q.on("end", () => {
|
|
608
|
+
if (q.method !== "POST" || !q.url?.includes("/responses")) { res.writeHead(404); res.end("{}"); return; }
|
|
609
|
+
const outs = (JSON.parse(b).input ?? []).filter((i: { type?: string }) => i.type === "function_call_output");
|
|
610
|
+
res.writeHead(200, { "content-type": "text/event-stream" });
|
|
611
|
+
if (!outs.length) res.end(sse([{ type: "response.created", response: { id: "r1" } }, { type: "response.output_item.done", item: { type: "function_call", call_id: "c1", name: "exec_command", arguments: JSON.stringify({ cmd: o.cmd, login: false, timeout_ms: 10000, ...o.args }) } }, done]));
|
|
612
|
+
else {
|
|
613
|
+
log.push(...outs.map((x: { output?: unknown }) => String(x.output)));
|
|
614
|
+
res.end(sse([{ type: "response.created", response: { id: "r2" } }, { type: "response.output_item.done", item: { type: "message", role: "assistant", id: "m1", content: [{ type: "output_text", text: "done" }] } }, done]));
|
|
615
|
+
}
|
|
616
|
+
});
|
|
617
|
+
});
|
|
618
|
+
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", () => resolve()));
|
|
619
|
+
const port = (server.address() as net.AddressInfo).port;
|
|
620
|
+
fs.writeFileSync(path.join(o.home, "config.toml"), `model = "mock-model"\nmodel_provider = "mock"\n[model_providers.mock]\nname = "mock"\nbase_url = "http://127.0.0.1:${port}/v1"\nwire_api = "responses"\nrequest_max_retries = 0\nstream_max_retries = 0\n`);
|
|
621
|
+
const child = spawn(codex, ["app-server", ...o.flags], { cwd: o.cwd, env: { PATH: "/usr/bin:/bin:/usr/sbin:/sbin", HOME: process.env.HOME ?? os.homedir(), CODEX_HOME: o.home, TMPDIR: o.tmp, SHELL: "/bin/zsh" }, stdio: ["pipe", "pipe", "ignore"] });
|
|
622
|
+
try {
|
|
623
|
+
let id = 0, buf = "";
|
|
624
|
+
const pending = new Map<number, (m: Record<string, any>) => void>();
|
|
625
|
+
let completed!: () => void;
|
|
626
|
+
const turnDone = new Promise<void>((resolve) => (completed = resolve));
|
|
627
|
+
const req = (method: string, params: unknown) => new Promise<Record<string, any>>((resolve) => { const i = ++id; pending.set(i, resolve); child.stdin!.write(JSON.stringify({ id: i, method, params }) + "\n"); });
|
|
628
|
+
child.stdout!.on("data", (d) => {
|
|
629
|
+
buf += d;
|
|
630
|
+
for (let n; (n = buf.indexOf("\n")) >= 0;) {
|
|
631
|
+
const line = buf.slice(0, n); buf = buf.slice(n + 1);
|
|
632
|
+
if (!line.trim()) continue;
|
|
633
|
+
const m = JSON.parse(line);
|
|
634
|
+
if (m.id !== undefined && !m.method && pending.has(m.id)) { pending.get(m.id)!(m); pending.delete(m.id); continue; }
|
|
635
|
+
// Asked for anything (none is expected under approval policy never): declined.
|
|
636
|
+
if (m.method && m.id !== undefined) { log.push(`request ${m.method}`); child.stdin!.write(JSON.stringify({ id: m.id, result: { decision: "decline" } }) + "\n"); continue; }
|
|
637
|
+
if (m.method === "turn/completed") completed();
|
|
638
|
+
}
|
|
639
|
+
});
|
|
640
|
+
await req("initialize", { clientInfo: { name: "relay-test", title: "relay-test", version: "0" }, capabilities: { experimentalApi: true } });
|
|
641
|
+
child.stdin!.write(JSON.stringify({ method: "initialized" }) + "\n");
|
|
642
|
+
const t = await req("thread/start", { cwd: o.cwd, runtimeWorkspaceRoots: [o.cwd], permissions: CODEX_PROFILE, approvalPolicy: o.policy ?? "never", approvalsReviewer: "user", ephemeral: true });
|
|
643
|
+
assert.ok(t.result?.thread?.id, JSON.stringify(t));
|
|
644
|
+
await req("turn/start", { threadId: t.result.thread.id, input: [{ type: "text", text: "go", text_elements: [] }] });
|
|
645
|
+
await Promise.race([turnDone, new Promise((_, reject) => setTimeout(() => reject(new Error(`no turn/completed: ${log.join(" | ")}`)), 45000))]);
|
|
646
|
+
return log;
|
|
647
|
+
} finally {
|
|
648
|
+
child.kill("SIGKILL");
|
|
649
|
+
server.close();
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
test("codex sandbox (installed Codex): a command an exec-policy rule allows runs sandboxed under relay's profile, whose credential denials keep every command in the sandbox; without them (the control) it would leave it", realCodex, async () => {
|
|
654
|
+
const codex = installedCodex();
|
|
655
|
+
for (const [denials, leaves] of [[true, false], [false, true]] as const) {
|
|
656
|
+
const t = sandboxTree("wt", "outside");
|
|
657
|
+
try {
|
|
658
|
+
const home = path.join(t.root, "home", ".codex");
|
|
659
|
+
fs.mkdirSync(path.join(home, "rules"), { recursive: true });
|
|
660
|
+
// As a user's own rules file would hold it: touch allowed without asking.
|
|
661
|
+
fs.writeFileSync(path.join(home, "rules", "default.rules"), 'prefix_rule(pattern=["touch"], decision="allow")\n');
|
|
662
|
+
const p = codexPermissions({ access: "read", config: withDefaults({}) } as never, { dangerous: false, network: false, roots: [], codexHome: home });
|
|
663
|
+
if (!denials) for (const k of Object.keys(p.profile!.filesystem)) if (p.profile!.filesystem[k] === "deny") delete p.profile!.filesystem[k];
|
|
664
|
+
const proof = path.join(t.dirs.outside, "proof");
|
|
665
|
+
const log = await oneCommandTurn(codex, { home, cwd: t.dirs.wt, tmp: t.own, flags: [...permissionFlags(p), "-c", 'approvals_reviewer="user"'], cmd: `touch ${proof}` });
|
|
666
|
+
assert.equal(fs.existsSync(proof), leaves, `${denials ? "relay's profile" : "control"}: ${log.join(" | ")}`);
|
|
667
|
+
assert.ok(!log.some((l) => l.startsWith("request ")), "nothing was asked");
|
|
668
|
+
} finally { t.done(); }
|
|
669
|
+
}
|
|
670
|
+
});
|
|
671
|
+
|
|
672
|
+
test("codex sandbox (installed Codex): relay pins exec_permission_approvals off, so a command an exec-policy rule allows cannot add the network to its sandbox without asking; with it on (the control) it reaches loopback", realCodex, async () => {
|
|
673
|
+
const codex = installedCodex();
|
|
674
|
+
// A loopback port of the test's own; this process stays free to accept while Codex runs.
|
|
675
|
+
let reached = 0;
|
|
676
|
+
const server = net.createServer((c) => { reached++; c.end("PONG\n"); });
|
|
677
|
+
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", () => resolve()));
|
|
678
|
+
const port = (server.address() as net.AddressInfo).port;
|
|
679
|
+
try {
|
|
680
|
+
for (const [pinned, reaches] of [[true, false], [false, true]] as const) {
|
|
681
|
+
const t = sandboxTree("wt");
|
|
682
|
+
try {
|
|
683
|
+
const home = path.join(t.root, "home", ".codex");
|
|
684
|
+
fs.mkdirSync(path.join(home, "rules"), { recursive: true });
|
|
685
|
+
fs.writeFileSync(path.join(home, "rules", "default.rules"), 'prefix_rule(pattern=["curl"], decision="allow")\n');
|
|
686
|
+
// A confined write turn without the network, as relay sets it.
|
|
687
|
+
const p = codexPermissions({ access: "write", config: withDefaults({}) } as never, { dangerous: false, network: false, roots: [], codexHome: home });
|
|
688
|
+
const flags = [...permissionFlags(p), "-c", 'approvals_reviewer="user"', "-c", "features.request_permissions_tool=false", "-c", `features.exec_permission_approvals=${!pinned}`];
|
|
689
|
+
const before = reached;
|
|
690
|
+
const log = await oneCommandTurn(codex, {
|
|
691
|
+
home, cwd: t.dirs.wt, tmp: t.own, flags, policy: "on-request", cmd: `curl -sS -m 3 http://127.0.0.1:${port}/`,
|
|
692
|
+
args: { sandbox_permissions: "with_additional_permissions", justification: "probe", additional_permissions: { network: { enabled: true } } },
|
|
693
|
+
});
|
|
694
|
+
assert.equal(reached > before, reaches, `${pinned ? "relay's pin" : "control"}: ${log.join(" | ")}`);
|
|
695
|
+
assert.ok(!log.some((l) => l.startsWith("request ")), "nothing was asked either way");
|
|
696
|
+
if (pinned) assert.ok(log.some((l) => /additional permissions are disabled/.test(l)), log.join(" | "));
|
|
697
|
+
} finally { t.done(); }
|
|
698
|
+
}
|
|
699
|
+
} finally {
|
|
700
|
+
server.close();
|
|
701
|
+
}
|
|
702
|
+
});
|
|
703
|
+
|
|
704
|
+
test("codex sandbox (installed Codex): under child_git \"native\" the worktree's git directories are workspace roots and git commit works; otherwise it cannot", realCodex, () => {
|
|
705
|
+
const codex = installedCodex();
|
|
706
|
+
const t = sandboxTree("repo");
|
|
707
|
+
const repo = t.dirs.repo, wt = path.join(t.root, "wt");
|
|
708
|
+
const git = (cwd: string, ...args: string[]) => {
|
|
709
|
+
const r = spawnSync("git", ["-c", "user.name=relay-test", "-c", "user.email=relay-test@localhost", "-c", "commit.gpgsign=false", ...args], { cwd, env: t.env, encoding: "utf8" });
|
|
710
|
+
assert.equal(r.status, 0, r.stderr);
|
|
711
|
+
return r.stdout.trim();
|
|
712
|
+
};
|
|
713
|
+
try {
|
|
714
|
+
git(repo, "init", "-q", "-b", "main");
|
|
715
|
+
fs.writeFileSync(path.join(repo, "a.txt"), "a");
|
|
716
|
+
git(repo, "add", "a.txt");
|
|
717
|
+
git(repo, "commit", "-qm", "first");
|
|
718
|
+
git(repo, "worktree", "add", "-q", "-b", "lane", wt);
|
|
719
|
+
// As a job's worktree gives them (session.ts): the repository's common git directory and the worktree's own.
|
|
720
|
+
const gitDirs = [fs.realpathSync(git(wt, "rev-parse", "--path-format=absolute", "--git-common-dir")), git(wt, "rev-parse", "--absolute-git-dir")];
|
|
721
|
+
assert.deepEqual(gitDirs, [path.join(repo, ".git"), path.join(repo, ".git", "worktrees", "wt")]);
|
|
722
|
+
const flags = (childGit: "native" | "relay") => codexFlags({ config: withDefaults({ child_git: childGit }), target: targetDef("codex"), access: "write", cwd: wt, relay: null, gitDirs } as never, [], {});
|
|
723
|
+
const native = flags("native").expect.permissions, relayGit = flags("relay").expect.permissions;
|
|
724
|
+
assert.deepEqual(native.profile!.workspace_roots, Object.fromEntries(gitDirs.map((d) => [d, true])));
|
|
725
|
+
assert.equal("workspace_roots" in relayGit.profile!, false);
|
|
726
|
+
fs.writeFileSync(path.join(wt, "b.txt"), "b");
|
|
727
|
+
const commit = (message: string): Probe[] => [
|
|
728
|
+
{ run: ["git", "-c", "user.name=relay-test", "-c", "user.email=relay-test@localhost", "-c", "commit.gpgsign=false", "add", "b.txt"], cwd: wt },
|
|
729
|
+
{ run: ["git", "-c", "user.name=relay-test", "-c", "user.email=relay-test@localhost", "-c", "commit.gpgsign=false", "commit", "-qm", message], cwd: wt },
|
|
730
|
+
];
|
|
731
|
+
// child_git "relay": git's own files are outside the sandbox, and relay commits for the agent.
|
|
732
|
+
expectInSandbox(codex, relayGit, wt, t.env, commit("refused").map((probe) => [probe, false]));
|
|
733
|
+
expectInSandbox(codex, native, wt, t.env, [...commit("by the agent").map((probe): [Probe, boolean] => [probe, true]),
|
|
734
|
+
// Its .git pointer at the top of the worktree stays read-only.
|
|
735
|
+
[{ write: path.join(wt, ".git") }, false]]);
|
|
736
|
+
assert.equal(git(repo, "log", "--format=%s", "lane"), "by the agent\nfirst");
|
|
737
|
+
} finally { t.done(); }
|
|
738
|
+
});
|
|
739
|
+
|
|
740
|
+
test("codex sandbox (installed Codex): a granted directory whose name holds a dot, a backslash and DEL is the workspace root Codex is given; DEL unescaped, Codex refuses the value, and a double quote, which TOML carries, breaks Codex's sandbox", realCodex, () => {
|
|
741
|
+
const codex = installedCodex();
|
|
742
|
+
const t = sandboxTree("wt");
|
|
743
|
+
const { wt } = t.dirs;
|
|
744
|
+
const odd = path.join(t.root, "a.b \\back\x7fslash");
|
|
745
|
+
// The same name without DEL, beside it: what a mangled name could have reached instead.
|
|
746
|
+
const near = path.join(t.root, "a.b \\backslash");
|
|
747
|
+
const quoted = path.join(t.root, 'a.b "q" \\back');
|
|
748
|
+
const run = (flags: string[]) => spawnSync(codex, ["sandbox", ...flags, "--", "/usr/bin/true"], { cwd: wt, env: t.env, encoding: "utf8", timeout: 20000 });
|
|
749
|
+
try {
|
|
750
|
+
for (const d of [odd, near, quoted]) fs.mkdirSync(d);
|
|
751
|
+
const p = profileFor("write", false, [odd]);
|
|
752
|
+
assert.ok(permissionFlags(p).some((f: string) => f.includes("\\u007f")));
|
|
753
|
+
expectInSandbox(codex, p, wt, t.env, [
|
|
754
|
+
[{ write: path.join(odd, "ok.txt") }, true],
|
|
755
|
+
[{ write: path.join(odd, ".claude", "settings.json") }, false],
|
|
756
|
+
[{ write: path.join(odd, ".MCP.json") }, false],
|
|
757
|
+
[{ write: path.join(near, "x") }, false],
|
|
758
|
+
]);
|
|
759
|
+
assert.equal(fs.readFileSync(path.join(odd, "ok.txt"), "utf8"), "scratch");
|
|
760
|
+
// DEL left as JSON leaves it (relay 1.0.0): no TOML, so Codex takes the text for a string, which is no table, and does not start.
|
|
761
|
+
const unescaped = run(permissionFlags(p).map((f: string) => f.replaceAll("\\u007f", "\x7f")));
|
|
762
|
+
assert.notEqual(unescaped.status, 0, "Codex took DEL unescaped in a TOML string");
|
|
763
|
+
// A double quote: the TOML relay writes holds it, but Codex's Seatbelt profile does not compile
|
|
764
|
+
// with it (codexWriteRootProblem), and no command runs.
|
|
765
|
+
const q = permissionFlags(profileFor("write", false, [quoted]));
|
|
766
|
+
assert.deepEqual(tomlBack(q[q.findIndex((f: string) => f.startsWith("permissions.relay.workspace_roots="))].slice("permissions.relay.workspace_roots=".length)), { [quoted]: true });
|
|
767
|
+
const broken = run(q);
|
|
768
|
+
assert.notEqual(broken.status, 0);
|
|
769
|
+
assert.match(broken.stderr, /sandbox-exec: unbound variable/);
|
|
770
|
+
// So relay refuses it before Codex starts: when it is granted (admitWork), and again at launch.
|
|
771
|
+
const spec = (grant: string) => ({ config: withDefaults({}), target: targetDef("codex"), access: "write", cwd: wt, relay: null, grant: { write_paths: [grant], write_path_pins: [dirIdentity(grant)] } }) as never;
|
|
772
|
+
assert.throws(() => codexFlags(spec(quoted), [], {}), (e: Error) => e.message.startsWith(`relay does not start the Codex agent: the granted directory ${JSON.stringify(quoted)} holds a double quote, and Codex's sandbox cannot be built`));
|
|
773
|
+
assert.doesNotThrow(() => codexFlags(spec(odd), [], {}));
|
|
774
|
+
} finally { t.done(); }
|
|
775
|
+
});
|
|
776
|
+
|
|
777
|
+
test("codex sandbox (installed Codex): a granted directory whose name holds a tab, a line feed or a carriage return stays unwritable, saying nothing, which is why relay refuses it; one holding another control character is writable, the names at its top read-only", realCodex, () => {
|
|
778
|
+
const codex = installedCodex();
|
|
779
|
+
const t = sandboxTree("wt");
|
|
780
|
+
const { wt } = t.dirs;
|
|
781
|
+
try {
|
|
782
|
+
for (const [name, writable] of [["tab\tx", false], ["lf\nx", false], ["cr\rx", false], ["esc\x1bx", true], ["bel\x07x", true]] as const) {
|
|
783
|
+
const dir = path.join(t.root, name);
|
|
784
|
+
fs.mkdirSync(dir);
|
|
785
|
+
expectInSandbox(codex, profileFor("write", false, [dir]), wt, t.env, [
|
|
786
|
+
[{ write: path.join(dir, "ok.txt") }, writable],
|
|
787
|
+
[{ write: path.join(dir, ".claude", "settings.json") }, false],
|
|
788
|
+
]);
|
|
789
|
+
assert.equal(codexWriteRootProblem(dir) === null, writable, JSON.stringify(name));
|
|
790
|
+
}
|
|
791
|
+
} finally { t.done(); }
|
|
792
|
+
});
|
|
793
|
+
|
|
794
|
+
test("codex permissions: a resumed thread is told its workspace roots, so a grant taken away on resume does not stay writable through roots the thread stored", async () => {
|
|
795
|
+
const h = await harness([{ steps: [{ reply: "ok" }] }]);
|
|
796
|
+
try {
|
|
797
|
+
// Two granted directories; a grant on resume replaces the job's, and this one leaves the first out.
|
|
798
|
+
const [grant, kept] = ["granted", "kept"].map((n) => path.join(path.dirname(h.home), n));
|
|
799
|
+
for (const d of [grant, kept]) fs.mkdirSync(d);
|
|
800
|
+
const job = await h.call("delegate", { target: "codex", task: "FIRST", mode: "write", grant: { write_paths: [grant, kept] }, background: false });
|
|
801
|
+
assert.equal(job.status, "done", JSON.stringify(job));
|
|
802
|
+
const first = h.starts().at(-1)!;
|
|
803
|
+
// Told on start: its workspace roots are its directory alone; the grant is a root of relay's profile.
|
|
804
|
+
assert.deepEqual(first.thread.runtimeWorkspaceRoots, [first.thread.cwd]);
|
|
805
|
+
assert.ok(first.argv.join(" ").includes(`permissions.relay.workspace_roots={${JSON.stringify(grant)}=true,${JSON.stringify(kept)}=true}`));
|
|
806
|
+
// A thread started under relay's earlier settings stored its grants among its workspace roots.
|
|
807
|
+
const file = path.join(h.env.STUB_DIR, "sessions", `codex-${first.sessionId}.json`);
|
|
808
|
+
fs.writeFileSync(file, JSON.stringify({ ...JSON.parse(fs.readFileSync(file, "utf8")), roots: [first.thread.cwd, grant] }));
|
|
809
|
+
// Resumed with the grant taken away: relay names the roots again, and Codex no longer has the grant as writable.
|
|
810
|
+
await h.call("resume", { job_id: job.job_id, message: "SECOND", grant: { write_paths: [kept] } });
|
|
811
|
+
assert.equal((await h.call("status", { id: job.job_id, wait_s: 20 })).status, "done");
|
|
812
|
+
const second = h.starts().at(-1)!;
|
|
813
|
+
assert.equal(second.resumed, true);
|
|
814
|
+
assert.deepEqual(second.thread.runtimeWorkspaceRoots, [second.thread.cwd]);
|
|
815
|
+
assert.ok(second.argv.join(" ").includes(`permissions.relay.workspace_roots={${JSON.stringify(kept)}=true}`));
|
|
816
|
+
assert.deepEqual(second.thread.sandboxWritable, [kept], "of the granted directories only the one still granted is writable");
|
|
817
|
+
assert.deepEqual(JSON.parse(fs.readFileSync(file, "utf8")).roots, [second.thread.cwd], "the stored grant is gone from the thread's roots");
|
|
818
|
+
// A server that kept the stored roots instead: refused before the turn runs.
|
|
819
|
+
fs.writeFileSync(file, JSON.stringify({ ...JSON.parse(fs.readFileSync(file, "utf8")), roots: [second.thread.cwd, grant] }));
|
|
820
|
+
fs.writeFileSync(path.join(h.env.STUB_DIR, "codex-ignore-roots"), "");
|
|
821
|
+
await h.call("resume", { job_id: job.job_id, message: "THIRD", grant: { write_paths: [kept] } });
|
|
822
|
+
const third = await h.call("status", { id: job.job_id, wait_s: 20 });
|
|
823
|
+
assert.equal(third.status, "failed", JSON.stringify(third));
|
|
824
|
+
assert.match(third.error, new RegExp(`its thread reports the workspace roots .*${grant.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}.* where relay set only the turn's directory`));
|
|
825
|
+
assert.equal(h.starts().length, 2, "no third turn ran");
|
|
826
|
+
} finally {
|
|
827
|
+
await h.close();
|
|
828
|
+
}
|
|
829
|
+
});
|
|
830
|
+
|
|
831
|
+
// Qualification item 33 (host only, RELAY_TEST_KEYCHAIN_LIVE=1): the keychain under relay's native
|
|
832
|
+
// Codex profile with the never floor, stage 2 off. A command asks the security daemons for a decoy
|
|
833
|
+
// keychain's item, network off and on, in two turns each. Floored: the decoy's directory is in
|
|
834
|
+
// never.paths, as ~/Library/Keychains is in the floor, so the item must be refused whatever the
|
|
835
|
+
// keychain IPC, since reading an item in a file-based keychain needs its file as well as the daemons.
|
|
836
|
+
// Control: the same floor without that entry, which must match what doctor documents
|
|
837
|
+
// (core/never-coverage.ts neverKeychainIpc): Codex's base profile closed, its network profile open
|
|
838
|
+
// (com.apple.SecurityServer). Only the network-on pair is a causal control: its control retrieves
|
|
839
|
+
// the item, so the floored refusal there comes from the file deny and not from a broken command.
|
|
840
|
+
// Network off, the documented IPC is closed and the control is refused too, so that pair only
|
|
841
|
+
// observes that the refusal is consistent with the documented IPC; it says nothing about the file
|
|
842
|
+
// deny. (The positive control outside any sandbox and the exit marker still show that security ran.)
|
|
843
|
+
// Teardown goes through withTeardown (keychain-decoy.ts): a failing decoy cleanup still removes the
|
|
844
|
+
// scratch tree, and the test's own failure is kept beside it.
|
|
845
|
+
for (const network of [false, true]) for (const floored of [true, false]) test(`keychain decoy live (codex, network ${network ? "on" : "off"}, ${floored ? "floored" : network ? "causal control without the file deny" : "consistency check without the file deny"}): ${floored ? "a floored native Codex command cannot retrieve a decoy keychain item in a never path, whatever the keychain IPC" : network ? "without that never path, retrieving the decoy item matches the documented (open) keychain IPC, so the floored refusal is the file deny's" : "without that never path, the refusal matches the documented (closed) keychain IPC; no evidence about the file deny"}`, { skip: keychainSkip || realCodex.skip }, (ctx) => {
|
|
846
|
+
const codex = installedCodex();
|
|
847
|
+
const t = sandboxTree("wt");
|
|
848
|
+
let decoy: DecoyKeychain | undefined;
|
|
849
|
+
return withTeardown(() => {
|
|
850
|
+
decoy = decoyKeychain(path.join(t.root, "keychains"));
|
|
851
|
+
const outside = spawnSync(decoy.command[0], decoy.command.slice(1), { encoding: "utf8", timeout: 30000 });
|
|
852
|
+
assert.ok(retrieved(decoy, outside.stdout), `positive control outside any sandbox: ${outside.stderr}`);
|
|
853
|
+
// The same floor either way (the built-ins, keychain files among them); only the decoy's entry differs.
|
|
854
|
+
const floor = resolveNeverPolicy({ home: t.env.HOME!, never: { paths: floored ? [{ path: decoy.dir }] : [] } });
|
|
855
|
+
const cfg = withDefaults({ targets: { codex: { stage2: false } } });
|
|
856
|
+
const p = codexPermissions({ access: "write", config: cfg, neverPolicy: floor } as never, { dangerous: false, network, roots: [], ...(network ? { net: { mode: "strict" as const, sockets: [t.own, t.dirs.wt] } } : {}) });
|
|
857
|
+
const flags = [...permissionFlags(p), ...(p.proxy ? ["-c", "features.network_proxy=true"] : [])];
|
|
858
|
+
assert.equal(flags.join("\n").includes(decoy.dir), floored, floored ? "the profile denies the decoy's directory" : "the control's profile does not name the decoy's directory");
|
|
859
|
+
// Wrapped in sh with an exit marker: a refusal counts only if security ran inside the sandbox.
|
|
860
|
+
const r = spawnSync(codex, ["sandbox", ...flags, "--", "/bin/sh", "-c", wrapped(decoy)], { cwd: t.dirs.wt, env: t.env, encoding: "utf8", timeout: 60000 });
|
|
861
|
+
const why = `status ${r.status}, signal ${r.signal}, error ${r.error}, stderr ${JSON.stringify((r.stderr ?? "").replaceAll(decoy.secret, "<secret>").slice(-400))}`;
|
|
862
|
+
assert.ok(!r.error && !r.signal && r.status === 0, `codex sandbox did not run the attempt to completion (launch failure, timeout or signal): ${why}`);
|
|
863
|
+
const observed = attempt(decoy, r.stdout ?? "");
|
|
864
|
+
const documented = neverKeychainIpc("codex", cfg, {})!;
|
|
865
|
+
const ipc = network ? documented.networkOn : documented.networkOff;
|
|
866
|
+
const expected = floored ? "refused" : ipc === "open" ? "retrieved" : "refused";
|
|
867
|
+
const role = floored ? "floored" : ipc === "open" ? "causal control" : "consistency check (closed IPC refuses either way)";
|
|
868
|
+
ctx.diagnostic(`keychain decoy (codex, network ${network ? "on" : "off"}, ${role}): ${observed}; documented keychain IPC ${ipc}; expected ${expected}`);
|
|
869
|
+
assert.equal(observed, expected, `${role}, documented keychain IPC ${ipc}; ${why}`);
|
|
870
|
+
}, [
|
|
871
|
+
// The decoy first: its directory is inside the scratch tree, and HOME is unchanged here.
|
|
872
|
+
["decoy cleanup", () => decoy?.cleanup()],
|
|
873
|
+
["scratch tree", () => t.done()],
|
|
874
|
+
]);
|
|
875
|
+
});
|