返回 CodeWhale
AUTHORIZATION_ORDER.md
根目录 / docs / AUTHORIZATION_ORDER.md
1 # Authorization order
2
3 > 阅读简体中文版:[zh_hans/AUTHORIZATION_ORDER.md](zh_hans/AUTHORIZATION_ORDER.md)。
4
5 Codewhale combines tool availability, hooks, typed permission rules, approval
6 posture, repository policy, and sandboxing. An approval from one layer is not a
7 universal bypass: a later safety layer can still require review or block the
8 call, and an approval is not an operating-system sandbox grant.
9
10 This page records the order implemented by the interactive engine's
11 model-requested tool path. Entrypoints that use only part of that path, such as
12 the core runtime's direct tool API, keep the relative order of the layers they
13 do use.
14
15 ## Model tool-call pipeline
16
17 The interactive engine evaluates a model-requested tool call in this order:
18
19 | Order | Layer | Result |
20 |---:|---|---|
21 | 1 | Effective configuration and posture | User settings, command/runtime overrides, and the project overlay resolve before the turn. A project overlay may tighten `approval_policy`, `sandbox_mode`, or shell availability, but may not loosen them. |
22 | 2 | Mode and tool admission | Plan-mode restrictions, input parse errors, per-command tool deny/allow lists, caller restrictions, and missing execution registrations fail before policy rules are considered. A tool present in both command lists is denied. |
23 | 3 | Preparation, then `tool_call_before` hooks | Registry preparation is side-effect free (including `plugin_manager` read-only target resolution and scope checks, with zero network fetches before human approval). Foreground `tool_call_before` operator hooks from `config.toml` gate the root agent's tool calls only (they do not run for sub-agent tool calls; plugin hooks for sub-agents are not determined), fold as `deny > ask > allow`, and a strict matching hook that produces no verdict fails closed. The last `updatedInput` wins; the engine prepares the rewritten input again before later gates inspect it. |
24 | 4 | Registered-tool baseline | The prepared tool's `ApprovalRequirement` establishes its ordinary approval need. A hook `ask` is applied after that assignment so the baseline cannot erase it. Non-bypassable registered holds remain forced in postures that can prompt; Full Access auto-approves them instead of opening a contradictory modal. Plan mode also blocks write-capable tools here. |
25 | 5 | Typed `permissions.toml` rule | A matching `deny` blocks. In every posture except Auto-Review (including Ask, Accept Edits, and Never), a matching typed `allow` rule (including allow rules saved from the approval card's "Always allow this exact rule") clears ordinary registry approval, though never a matching `deny`, a hook `ask`, or a non-bypassable registered hold. In Auto-Review, broad typed allow rules (`exec_shell`/`bash` without a command, glob patterns such as `*`, `python*`, or `npm run *`, bare broad runners such as `python`, `node`, `npm run`, `cargo run`, `agent`/`subagent`/`spawn_agent`, `*`, and `write_file`, `edit_file` and `apply_patch` rules with no `path`) are suspended without altering `permissions.toml` and resume when leaving Auto-Review; only narrow typed allows (unwrapped statically expanded `exec_shell`/`bash` segments with exact or non-flag operand arguments, or exact non-agent non-plugin tool names with explicit `path` for file tools) clear ordinary registry approval and skip the Auto-Review reviewer when no safety floor, soft rule, hook hold, plugin hold, or `auto_review.review_all_shell` applies. A matching `ask` forces review in postures that can prompt, including Auto-Review when `owner_present` is true (on runtime threads, only the owner's surface can answer it), and refuses naming the rule when `owner_present` is false or in Never. Full Access/auto-approval is not downgraded into a prompt, while an explicit typed `deny` still blocks. |
26 | 6 | [Auto-Review](AUTO_REVIEW.md) policy and built-in safety floor | The engine assigns each turn's run origin (`Interactive` with owner present vs `Headless`, `Background`, or unattended; never configurable by request or host fields). Configured block rules run before the built-in floor, then named soft rules, plugin holds, `auto_review.review_all_shell` (when enabled), active narrow typed allow clearance, configured narrow `auto_review.allow` rules, and the deterministic fallback. Broad `[[auto_review.allow]]` rules (`shell`, `external`, `write`, `destructive`, or `publish` without a specific non-shell/non-agent tool, or `tool` matching `exec_shell`, `bash`, `agent`, or `*`) are ignored with a warning in Auto-Review, while specific non-shell/non-agent tool allow rules remain active. Setting `auto_review.review_all_shell = true` in user/managed config sends every shell command (including benign and narrow-allowed shell calls, after safety floor, block, soft-rule, and plugin gates) to the Auto-Review reviewer. This layer runs after typed permissions and can add a prompt or block, but cannot remove an earlier hold. The built-in floor refuses a shell command, shell input or verifier containing a hidden Unicode character (`hidden_unicode`), and holds publish-like actions, destructive unattended/background/headless actions and `curl`/`wget` credential uploads without prompting (blocking without opening an approval card in Auto-Review and Never). When `owner_present` is true in Auto-Review and no hard block (`hidden_unicode` or configured `block` rule) applies, non-plugin forced prompts (typed `ask` rules, `tool_call_before` hook `ask`, and prompt-only tools such as Computer Use consent/script cards) surface the approval card instead of consulting the guardian or failing closed; when `owner_present` is false, forced prompts refuse without registering a pending approval. Held plugin acts (`core/call`, broker acts, and held plugin host tools) route to the Auto-Review reviewer with their host-minted plugin identity instead of skipping review or failing closed, and cannot bypass via routine tiers, typed/auto-review allow rules, or one-use retry grants (while independent typed rules, hook holds, and safety-floor blocks still apply). For eligible non-child, non-plugin calls, an interactive owner can approve one exact Auto-Review-blocked call for a one-use retry (bound to `(tool_name, call_digest)` and still subject to every earlier and later gate). After 3 consecutive blocks, 20 total blocks in the conversation, or 3 consecutive unavailable reviews with `owner_present`, Auto-Review pauses to Ask and continues the batch; unattended runs continue past blocks without falling back to Ask and stop as interrupted at 20 total blocks or 10 consecutive unavailable checks. Headless `exec` still consults the model guardian on non-floor fallback holds, whereas ACP uses deterministic rules only. Full Access skips the built-in floor. |
27 | 7 | Repository law | Protected path invariants apply only to the file write tools `write_file`, `edit_file`, `apply_patch`, and `fim_edit` (not shell commands or MCP tools) and can only add a prompt or block. A repo-law prompt opens an approval card in Ask-family postures and in interactive Auto-Review with `owner_present`, and becomes a hard block in Full Access, Never, and unattended/headless Auto-Review (which have no contradictory or answerable approval modal). |
28 | 8 | Human approval | A remaining prompt is sent to the approval channel. Denial stops the call. Approval authorizes this planned call; session and persistent choices affect later matching calls but do not erase a later gate from this call. |
29 | 9 | Tool authority and execution sandbox | Worker authority envelopes, native tool path checks, and the selected OS or external sandbox still apply during execution. A sandbox denial remains a denial unless the user separately authorizes a supported elevation path. |
30
31 The ordering is intentionally monotonic after the typed permission layer:
32 auto-review and repository law can tighten a result, not turn a previous block
33 or prompt into an unreviewed execution. There are explicit posture choices
34 inside those layers—for example, Full Access does not create an interactive
35 publish prompt—but those choices do not let an earlier remembered grant erase
36 a hold that the layer actually produced.
37
38 ## Which control covers which surface
39
40 | Control | File tools (`read_file`, `write_file`, `edit_file`, `apply_patch`) | Shell | MCP tools | Sub-agent tool calls |
41 |---|---|---|---|---|
42 | Permission rules (`permissions.toml` allow / deny / ask) | applies to `read_file`, `write_file`, `edit_file` and `apply_patch` by those names (`write` and `edit` match nothing); `fim_edit` matches only a rule on its name with no `path` (read from code) | applies (`exec_shell` / `bash` tool and command matchers) (read from code) | applies on exact tool name with no `path` (read from code) | applies (read from code) |
43 | Path rules | applies on one exact path, for the named tool only: `read_file`, `write_file`, `edit_file`, `apply_patch`, `file_search`, `grep_files`, `list_dir`; `fim_edit` is not matched by path rules (read from code) | does not apply (read from code) | does not apply (read from code) | same file tools, exact path for the named tool (read from code) |
44 | The workspace boundary | applies unless trust mode or trusted paths allow outside access (read from code) | does not confine reads (in Auto-Review, the first read whose path is named in the command and resolves outside the workspace asks once per session; a read that a script opens itself is not detected); writes depend on the sandbox policy: `read-only` blocks them, `workspace-write` allows the workspace, extra roots and `/tmp`, and Full Access with no narrower `sandbox_mode`, external-sandbox or a missing wrapper impose no limit (read from code) | does not apply (read from code) | file tools only (read from code) |
45 | `sandbox_denied_read_paths` | applies to the read-side tools `read_file`, `list_dir`, `file_search`, `grep_files`, `read_media`, `image_ocr`, `pandoc`, `validate_data`, `verify`, `review`, `rlm_open` and the read in `fim_edit`; does not apply to `write_file`, `edit_file` or `apply_patch` (read from code) | sandboxed shell only (not Full Access with its default `danger-full-access` sandbox, external-sandbox or a missing wrapper) (read from code) | does not apply (read from code) | same read-side tools and sandboxed shell (read from code) |
46 | Repository law | applies to `write_file`, `edit_file`, `apply_patch` (and `fim_edit`), not `read_file` (read from code) | does not apply (read from code) | does not apply (read from code) | file write tools only (`write_file`, `edit_file`, `apply_patch`, `fim_edit`) (read from code) |
47 | Blocking hooks (`tool_call_before`) | applies to the root agent's calls (read from code) | applies to the root agent's calls (read from code) | applies to the root agent's calls (read from code) | operator hooks in `config.toml` do not apply; plugin hooks not determined (read from code) |
48 | Approval posture | applies (read from code) | applies (read from code) | applies (read from code) | applies, but a child's delegated calls (grant, role, accept-edits or workspace-write carve-out) skip ordinary approval, and whether a child can prompt depends on the parent (read from code) |
49
50 Blocking hooks fire only where hooks run: the interactive TUI, `codewhale exec --hooks` and Runtime API threads, and never in app-server or ACP. See the scope table in [Hooks](HOOKS.md).
51
52 ## Typed permission-rule selection
53
54 `permissions.toml` is currently a sibling of the active user `config.toml`.
55 There is no project-local permission-rule source today. An optional `workspace`
56 field scopes one user rule to a repository; it does not create a project
57 overlay. `/permissions` reports that source, matcher, scope, and whether the
58 scope applies to the current workspace.
59
60 The execution-policy engine evaluates matching rules as follows:
61
62 1. Normalize the tool, command, workspace, and any workspace-relative path.
63 Unsafe or external paths do not become matchable file rules.
64 2. Check denied command prefixes against the whole command and every chained
65 segment. These hard prefix denies are merged across rulesets and always win.
66 3. Compute a trusted-prefix candidate for an unchained shell command. This is a
67 candidate for the approval-mode fallback, not an immediate decision.
68 4. Select one matching typed rule by this lexicographic precedence:
69 1. higher source layer: `User > Agent > BuiltinDefault`;
70 2. stronger action inside that layer: `deny > ask > allow`;
71 3. the more specific matcher when layer and action tie.
72 5. Apply the selected typed action. `deny` forbids the call, `allow` skips the
73 execution-policy approval, and `ask` requires approval. A typed `ask`
74 overrides a trusted prefix.
75 6. If no typed action decides the result, apply the approval-mode fallback
76 using the trusted-prefix candidate.
77
78 Source layer is compared before typed action. Consequently, a user-layer typed
79 `allow` can override an agent-layer typed `deny`; inside the same layer, `deny`
80 still beats `ask`, which beats `allow`, regardless of file order or matcher
81 specificity. Hard denied prefixes are the exception: they are checked before
82 typed-layer selection and cannot be overridden by a typed allow.
83
84 Specificity is only a tie-breaker after source and action. A constrained
85 command, exact-command, path, or workspace matcher beats a tool-wide rule with
86 the same action in the same layer. Specificity never lets a narrow allow beat a
87 same-layer deny.
88
89 For chained shell commands, a trusted prefix never approves the whole chain. A
90 typed deny that wins for any individual segment blocks the full invocation.
91
92 Deny rules match commands by name against a static reading of the command
93 line. While any deny rule is configured, a command whose command word cannot be
94 read statically is refused (or prompts, where a person always sees the prompt):
95 a variable or substitution, a glob or brace list, a parenthesis glued to the
96 word, a word that is not a plain literal, or a call that rebinds names first
97 (`alias`, `hash`, `setopt`, `shopt`). Deny rules do not cover a script file, a
98 copy of a program under another name, or another program that does the same
99 job; the limits are listed at the top of `crates/execpolicy/src/shell_expand.rs`.
100 Containment is the sandbox's job, not the deny list's.
101
102 ## Approval posture and missing prompts
103
104 The execution-policy result is combined with the registered-tool baseline; the
105 two should not be interpreted independently.
106
107 - Ask and Auto-Review may surface tool safety approvals. In Auto-Review with
108 `owner_present` true, forced prompts (typed `permissions.toml` `ask` rules,
109 `tool_call_before` hook `ask`, prompt-only tool gates such as Computer Use
110 consent/script cards, repository-law holds that require a person, and forced
111 creator prompts) open the normal approval card unless a hard block
112 (`hidden_unicode` or a configured `auto_review.block` rule) applies; on
113 runtime threads, only the owner's surface may answer that card. Held plugin
114 calls in Auto-Review (both interactive and headless) route through the
115 Auto-Review reviewer with their host-minted plugin identity and never clear via
116 routine tiers or allow rules, while independent forced prompts on them still
117 follow the same interactive-vs-unattended rule. Unattended and headless runs
118 (`Background`, `Headless`, or `owner_present` false) refuse forced prompts
119 naming the rule and register no pending approval, while non-forced fallback
120 holds in Auto-Review continue to route through deterministic rules and the
121 model guardian without prompting. Model-authored user
122 questions (`request_user_input`) are a separate channel and reach the user in
123 every interactive posture, Auto-Review included. Only headless `exec` runs,
124 which have no responder, withhold the tool. Runtime threads (app
125 conversations, background tasks and automations) keep it: a question parks
126 the turn until someone answers or cancels it through the app or runtime API,
127 or until a positive `tools.user_input_timeout_seconds` expires. An omitted or
128 zero timeout waits indefinitely, the same way an Ask-posture approval parks.
129 - Creator `plugin_manager` read queries (`list_plugins`, `list_bundles`,
130 `list_version_exemptions`) execute across postures without prompts. State-changing
131 calls (`install_bundle`, `remove_bundle`, `set_bundle`, `set_plugin`) must be
132 top-level direct calls and are refused with `PermissionDenied` in `Plan`,
133 `sandbox_mode = "read-only"`, `Never`, `Background` runs, sub-agents, and nested
134 `execute_tools`:
135 inside-workspace local changes route through the human card in `Ask`/`Accept Edits`,
136 through the Auto-Review guardian (or configured `auto_review.allow` rules) in
137 `Auto-Review`, and run under `Full Access` (recording agent posture in
138 `plugins/state.json`), whereas outside-scope targets (paths outside the project,
139 remote specs or local folders with unresolved npm dependencies fetched from a
140 registry, bundles declaring stdio MCP connectors or hooks while shell execution is
141 disabled, person-approved plugins, or built-in switches) skip the Auto-Review
142 guardian and require a forced human `creator-human:` card even under
143 `Auto-Review` allow rules or `Full Access`. Remembered non-user grants, hooks,
144 and typed `allow` rules never waive that card, and unseen remote/npm-dependency
145 fetches never run before `"yes"` and always land disabled (`enabled = false`)
146 and untrusted until explicitly reviewed and enabled.
147 - Full Access and YOLO-compatible auto-approval paths do not let a typed `ask`
148 downgrade the session into prompting. Non-bypassable registered holds
149 auto-approve in Full Access. Typed deny, catastrophic background/headless
150 safety holds, and repository law still fail closed where their respective
151 layers apply.
152 - With `approval_policy = "never"`, a matching typed `ask` is forbidden because
153 the required prompt cannot be shown.
154
155 Runtime adapters may transport an approval decision differently from the
156 interactive modal. That transport and any continuation protocol are separate
157 from this ordering contract; see [Runtime API](RUNTIME_API.md).
158
159 ## Project overlays
160
161 The project config overlay at `<workspace>/.codewhale/config.toml` is not a
162 permission-rule layer. It can only move approval and sandbox posture toward
163 more restrictive values:
164
165 - approval: `auto` → `on-request`/`untrusted` → `never`;
166 - sandbox: `danger-full-access` → `workspace-write` → `read-only`;
167 - shell availability: `true` may become `false`, never the reverse.
168
169 Project config cannot add credentials, hooks, provider authority, or a
170 project-local `permissions.toml`. See
171 [Configuration](CONFIGURATION.md#per-project-overlay-485) for the complete
172 overlay allow-list.
173
174 ## Regression coverage
175
176 The contract is exercised by tests at the layers that own each decision:
177
178 - `authorization_order_contract_matches_documented_precedence` covers hard
179 prefix denial and the typed `layer → action → specificity → approval-mode`
180 sequence through the public execution-policy API.
181 - `hook_fold_deny_wins_over_ask_and_allow` covers foreground hook folding.
182 - `non_bypassable_registered_tools_auto_approve_in_full_access` covers
183 registered holds.
184 - `full_access_permission_allow_cannot_bypass_background_catastrophic_floor`
185 and `full_access_permission_allow_cannot_bypass_repo_law` cover later safety
186 layers overriding a remembered allow.
187 - `project_merge_only_tightens_approval_and_sandbox_policy` covers project
188 overlay monotonicity.
189
190 Focused commands:
191
192 ```bash
193 cargo test -p codewhale-execpolicy --test authorization_order --locked
194 cargo test -p codewhale-tui --lib --locked full_access_permission_allow_cannot_bypass
195 cargo test -p codewhale-config --locked project_merge_only_tightens_approval_and_sandbox_policy
196 ```
197
198 ## Related references
199
200 - [Configuration](CONFIGURATION.md) — rule schema, `/permissions`, hooks, and
201 project overlays
202 - [Modes](MODES.md) — Plan/Work and permission posture
203 - [Sandbox threat model](SANDBOX.md) — platform enforcement and fallbacks
204 - [Runtime API](RUNTIME_API.md) — approval events and remote resolution
205
205 lines MARKDOWN