# Policy language A policy is the `policy.dw` file of `permit` and `forbid` rules that decides each request the workload makes through the box's trusted process (the part of Box that runs outside the box and answers its requests). `box.toml` sets what the workload's own system calls can reach, and the operating system enforces that. Inside that reach, policy decides each request the workload sends through the box's trusted process. Audience: an operator who wants to write or change a policy. [Write a policy and read what it decided](tutorials/first-policy.md) walks through a first one, and [the action vocabulary](policy/actions.md) lists every field a rule can read. ## When the box asks policy Four parts of the box ask policy, each about its own boundary: - **Strands Shell**, the box's own shell, which the agent's shell tool runs. It asks once per command line, as `shell:exec` or `shell:spawn`, and once per file operation a command makes, as `fs:*`. - **Monty**, the Python interpreter the box runs for the agent's scripts. It asks once per file operation, as `fs:*`. - **The egress gateway.** It asks once per connection, as `net:connect`, and once per HTTP request, as `http:request`. It asks `mcp:call` for MCP requests whose host matches a declared server, except the protocol methods listed in the [action reference](policy/actions.md#mcp). - **The MCP broker.** It asks once per request to a local MCP server, as `mcp:call`. On a `tools/call` it asks a second time, as the tool's own generated action. At startup it asks once for each declared server, as `shell:spawn`. Three facts decide every request: - **The box denies by default.** With no matching `permit`, a request is refused. A `box.toml` with no `policy` key, or a `policy.dw` with no rules, refuses every request that reaches policy. - **A `forbid` beats a `permit`.** Write an exception to a broad permit as a `forbid`. - **A `permit` only widens.** A restriction such as a budget is a `forbid`. The agent's own system calls reach a path in `[agent.filesystem]` with no decision and no record. [Security](security.md) states where each tier governs. ## How a rule reads ```text @id("no_env") @description("The .env file holds credentials the agent must not read.") forbid (principal, action == Box::Action::"fs:read", resource) when { context.input.path == "~/project/.env" }; ``` From the top: - **`@id("no_env")`** names the rule. A denial and the decision log name the rule by this id, so give each rule its own. - **`@description("…")`** is the error message returned when the rule denies. - **`forbid`** is the effect. The other effect is `permit`. - **`principal`** is always the agent. Write it as `principal`, with no condition. - **`action == Box::Action::"fs:read"`** names the one action this rule decides. - **`resource`** is always the same fixed resource. Write it as `resource`, with no condition. - **`when { … }`** is the condition. It reads the request's `context.input` fields, and `path` is one of the fields `fs:read` carries. A rule with a `when temporal { … }` clause also reads the box's recorded history, so it can count earlier events or require one. [A budget over time](#a-budget-over-time) and [commit only after the tests passed](#commit-only-after-the-tests-passed) show the two shapes. ## How a denial reads A denial names the path, program, or host the rule saw, then the rule, then its description: ```text strands-shell: cat: policy denied this operation on '~/project/.env' [policy: no_env]: The .env file holds credentials the agent must not read. ``` The agent reads the same text, so write each `@description` for the agent. The tail has one of these shapes: - `[policy: ]: `: a `forbid` with that `@id` matched. - `[policy: ]`: a `forbid` matched, and it has no `@description`. - `[default-deny]: No permit policy matched this request.`: no `permit` matched. Add one if the operation is intended. - `[policy-pending]: The complete policy bundle is not installed.`: an MCP tool's schema is still being discovered. The call can be retried. - `because the request could not be evaluated.`: the engine hit an internal fault, and it denied the request. A denial of an experimental [tool grammar](config.md#toolnamegrammar) action reads the same way, on the path of the program. The decision log names the grammar action. Each caller shows the text in its own form: - **A shell command** prints it on stderr. A command the policy refused exits `126`. When policy refuses a file operation inside a command it permitted, the command fails with its own status (`1` for `cat`). - **Python in the box** raises a `PermissionError` whose message is the text. The script can catch it. - **An HTTP request** receives a `403` response whose body is the text. The request never leaves the box. - **An MCP call** receives a JSON-RPC error with code `-32001` and the text, followed by the method in parentheses. Three refusals look like a denial, and no `permit` lifts them: - **A path inside the box directory, or the `box.toml` or `policy.dw` this run loaded, is refused whatever the policy says.** The decision log records the cause as `enforcement`, and [step 4 of the tutorial](tutorials/first-policy.md#step-4-read-the-decision-log) shows how to read it. [What Box always enforces](security.md#what-box-always-enforces) states the rule. - **A program that a tool grammar binds, run by its bound name after its file was replaced or removed, or run by the agent under a name that only a stdio `[mcp.]` declares, is refused whatever the policy says.** The tail is `[tool-grammar]`, then the reason, then `No policy can permit it.` [`shell:spawn`](shell.md#shellspawn) states the cases. - **A file tool of the harness itself fails with "operation not permitted" on macOS, or "no such file or directory" on Linux, and the decision log holds no record.** The path is outside every `[agent.filesystem]` list. Add it to a list in `box.toml` if the agent is meant to reach it. ## The actions The box ships eleven actions in four categories, and generates one more for each MCP tool it discovers. Each experimental [tool grammar](config.md#toolnamegrammar) adds its own `Tool::` actions. [The action vocabulary](policy/actions.md) lists the fields of each one. - **[Filesystem](policy/actions.md#filesystem)**: a file operation in Strands Shell or Monty. `fs:read`, `fs:write`, `fs:delete`, `fs:move`, and the reserved `fs:other`. - **[Network](policy/actions.md#network)**: an outbound call through the egress gateway. Each call is two decisions: `net:connect` for the connection, before TLS, and `http:request` for each request inside it, after TLS on an HTTPS connection. A WebSocket handshake is `websocket:connect` in place of `http:request`. - **[Shell](policy/actions.md#shell)**: a command line in Strands Shell, judged once after the shell resolves its first word to a program. `shell:exec` for a program the shell implements, such as `cat` or `grep`, and `shell:spawn` for a program of the surrounding OS, such as `git`, and for the start of each stdio MCP server `box.toml` declares. - **[MCP](policy/actions.md#mcp)**: a request through a declared MCP server, with [host-based matching](mcp.md#remote-destination-matching) for remote servers. `mcp:call` decides each request except the protocol methods listed in the action reference. One generated `::Action::""` per discovered tool decides a `tools/call` after `mcp:call` permitted it. ## Common rules Seven rules an operator writes often. Each one is a working rule. Copy it beside the permits from [your first policy](tutorials/first-policy.md), replace `~/project` with your project directory, and run the box. Two of them say what else `box.toml` needs. The first six are `forbid` rules. The last is a pair of `permit` rules that replace two from the tutorial. ### A budget over time At most twenty writes of file content in one hour. The twenty-first is refused until the oldest counted write is more than an hour old. ```text @id("write_budget") @description("At most 20 content writes completed in one hour.") forbid (principal, action == Box::Action::"fs:write", resource) when { context.input.operation == Box::FsWriteOperation::"write_content" } when temporal { exists (total: Long). ( (count for (t: Timepoint). where ( formerly within 1h ( Box::Action::"fs:write"::response{ input.path: _, input.operation: Box::FsWriteOperation::"write_content", output.result: Box::FsResponseResult::"completed" } && tp(t) ) )) == total && total >= 20 ) }; ``` ```text strands-shell: tee: policy denied this operation on '~/project/notes.md' [policy: write_budget]: At most 20 content writes completed in one hour. ``` - The rule counts `fs:write::response` events with result `completed`, which the box records when a content write finishes. A refused write does not count, and a write still in flight does not count yet, so a burst of writes started together can exceed the budget by the size of the burst. - In the Shell, a redirect, `tee`, or `cp` records `descriptor_issued` when it opens the file, not `completed`, so this rule doesn't count it. Only a time change from `touch` records `completed`. - A `touch` changes a file's times as a `write_content` write, so it counts toward the budget. Only a plain `touch` that creates a file doesn't count; with `-d`, `-t`, or `-r` it then sets the new file's times, and that counts. - The `when` clause limits the `forbid` to content writes. A `mkdir` is `fs:write` with operation `create_dir`, so the budget leaves it alone. A rename is `fs:move`, and a delete is `fs:delete`; each needs its own rule. - The persisted count survives a restart of the box and an edit to another rule. A process crash can lose recent events; see [history persistence](#history-persistence-and-process-crashes). For an exact count of attempts, including refused ones, replace the predicate inside `formerly within 1h ( … )` with: ```text Box::Action::"fs:write"::request{ input.path: _, input.operation: Box::FsWriteOperation::"write_content" } && tp(t) ``` Write a budget as a `forbid`. [A cap written as a permit](#a-cap-written-as-a-permit) shows what happens at load when a budget is written as a `permit`. ### A rate limit on one host This rule refuses new requests to `api.github.com` when Box has recorded at least sixty response outcomes for that host in the last ten minutes. Pending exchanges do not count yet. Write it beside a `permit` for `api.github.com` on `http:request`, such as the `github_request` rule in [the `[egress.]` table](egress.md#example). ```text @id("github_rate_limit") @description("Refuse requests when at least 60 response outcomes for api.github.com were recorded in the last 10 minutes.") forbid (principal, action == Box::Action::"http:request", resource) when { context.input.host == "api.github.com" } when temporal { exists (total: Long). ( (count for (t: Timepoint). where ( formerly within 10m ( Box::Action::"http:request"::response{ input.host: "api.github.com" } && tp(t) ) )) == total && total >= 60 ) }; ``` - The rule counts `http:request::response` events for the host, using their recording times for the ten-minute window. The gateway records the outcome when the exchange ends, including failure or timeout. A refused request or a request that definitely failed to reach upstream does not count. Pending exchanges do not count yet, so several requests can pass before earlier exchanges end. Those requests can make the total exceed the limit. - The `when` clause scopes the `forbid` to the one host, so a request to any other host is unaffected. The same shape on `net:connect` limits connections rather than requests. - The agent receives a `403` whose body names the rule, as `[policy: github_rate_limit]`, and its description. [How a denial reads](#how-a-denial-reads) shows the form. ### Deny a program and its aliases `rm` is refused under every spelling that resolves to the shell's `rm`: `"rm" x`, `\rm x`, `X=rm; $X x`, and `alias safe=rm; safe x` are each judged as `rm`. Every other command the shell implements still runs. ```text @id("no_rm") @description("Nothing is removed from the command line.") forbid (principal, action == Box::Action::"shell:exec", resource) when { context.input.program == "rm" }; ``` ```text strands-shell: effect denied: policy denied this operation on 'rm' [policy: no_rm]: Nothing is removed from the command line. ``` A path spelling such as `/bin/rm` names a binary of the surrounding OS, which is a `shell:spawn`. A rule on a spawned binary compares `program_path`, the resolved path of the binary: ```text @id("no_host_git") forbid (principal, action == Box::Action::"shell:spawn", resource) when { context.input.program_path == "/usr/bin/git" }; ``` ### Read files, keep listings closed A file the agent names is readable, and every directory listing is refused. `cat ~/project/src/main.rs` succeeds. `ls ~/project/src` is refused, and so is a pattern such as `~/project/src/*.rs`, because expanding it lists the directory. ```text @id("no_listing") @description("Directory listings stay closed.") forbid (principal, action == Box::Action::"fs:read", resource) when { context.input.operation == Box::FsReadOperation::"enumerate" }; ``` ```text strands-shell: ls: policy denied this operation on '~/project/src' [policy: no_listing]: Directory listings stay closed. ``` Every filesystem request carries `operation`, the exact verb, so a rule can single out one verb of an action. [The action vocabulary](policy/actions.md#filesystem) lists the verbs of each action. ### Commit only after the tests passed `git commit` runs only when a `cargo test` exited `0` in the last hour. Before the first pass, after a failure with no later pass, or once the last pass is more than an hour old, it is refused. ```text @id("test_before_commit") @description("Run the tests first.") forbid (principal, action == Box::Action::"shell:spawn", resource) when { context.input.program == "git" && context.input has arg1 && context.input.arg1 == "commit" } unless temporal { formerly within 1h ( Box::Action::"shell:spawn"::response{ input.program: "cargo", input.arg1: "test", output.status: 0 } ) }; ``` ```text strands-shell: effect denied: policy denied this operation on '/usr/bin/git' [policy: test_before_commit]: Run the tests first. ``` - The rule needs a `shell:spawn` permit for `git` and one for `cargo`, and a [`[tool.]`](shell.md#toolname) table in `box.toml` for each of the two programs. The policy in [your first policy](tutorials/first-policy.md) has no `shell:spawn` permit, so add these two: ```text @id("spawn_git") permit (principal, action == Box::Action::"shell:spawn", resource) when { context.input.program_path == "/usr/bin/git" && context.input.program == "git" }; @id("spawn_cargo") permit (principal, action == Box::Action::"shell:spawn", resource) when { context.input.program_path == "~/.cargo/bin/cargo" && context.input.program == "cargo" }; ``` - `arg1` is optional, because a command can have no arguments, so the rule guards it with `context.input has arg1`. - The condition is keyed on `::response`, the event the box records when `cargo test` finishes, with the exit status as `output.status`. A `::request` event exists for a refused attempt too, so a rule keyed on it would pass after a refused `cargo test`. ### Forbid one URL path on a host Every request under `/v1/` on `api.example.com` is permitted, except the endpoints under `/v1/admin`. `context.input.path` is the exact path the gateway forwards. The gateway puts the path in canonical form first: it decodes the percent-escapes of unreserved characters, keeps `%2F` encoded with uppercase hex digits, and removes `.` and `..` segments. `/v1/./admin`, `/v1/%61dmin`, and `/v1/users/../admin` all reach policy as `/v1/admin`, and `/v1/admin%2fexport` reaches it as `/v1/admin%2Fexport`. The gateway keeps repeated slashes and `%2F`, and the server receives them. Servers disagree about such a path: some serve `/v1//admin` as `/v1/admin`, and others, such as S3, treat `a//b` and `a/b` as two different keys. A `forbid` on `/v1/admin` beside a permit on `/v1/*` therefore leaves `/v1//admin` and `/v1/admin%2Fexport` permitted. Add a second `forbid` that refuses both forms on that host: ```text @id("api_connect") permit (principal, action == Box::Action::"net:connect", resource) when { context.input.host == "api.example.com" }; @id("api_v1") permit (principal, action == Box::Action::"http:request", resource) when { context.input.host == "api.example.com" && context.input.path like "/v1/*" }; @id("no_admin") forbid (principal, action == Box::Action::"http:request", resource) when { context.input.host == "api.example.com" && (context.input.path == "/v1/admin" || context.input.path like "/v1/admin/*") }; @id("no_ambiguous_slash") forbid (principal, action == Box::Action::"http:request", resource) when { context.input.host == "api.example.com" && (context.input.path like "*//*" || context.input.path like "*%2F*") }; ``` | Request | Decision | Rule | |---|---|---| | `/v1/users` | Permitted | `api_v1` | | `/v1/administrator` | Permitted | `api_v1` | | `/v1/users?next=//login` | Permitted | `api_v1` | | `/v1/admin`, `/v1/./admin`, `/v1/%61dmin`, `/v1/users/../admin` | Refused | `no_admin` | | `/v1/admin/export` | Refused | `no_admin` | | `/v1//admin`, `/v1///admin/export` | Refused | `no_ambiguous_slash` | | `/v1/users//42`, `/v1/admin%2Fexport`, `/v1/admin%2fexport` | Refused | `no_ambiguous_slash` | `context.input.path` holds no query, so the `//` in `?next=//login` is outside the path. ```text http:request gate: policy denied this operation on 'api.example.com:443/v1//admin' [policy: no_ambiguous_slash]. ``` - `no_ambiguous_slash` refuses every path on the host that holds `//` or `%2F`, including paths the server treats as distinct resources. Scope it to the hosts whose paths your rules forbid. - Write the forbid on the path and its children, as `no_admin` does. A pattern on the end of the path, such as `context.input.path like "*/admin"`, refuses `/v1//admin` and also `/v1/users/admin`, and it permits `/v1/admin/` and `/v1/admin/export`. ### Bind a credential to one host and one method A `POST` to the Bedrock host on port 443 goes out with the key the box holds. Every other method on that host, and every other host, is refused. The credential is bound in `box.toml`, and the policy permits the request. The two name the same host. Edit the `[egress.model]` table in `box.toml`; [the `[egress.]` table](egress.md) lists its keys: ```toml [egress.model] destinations = ["bedrock-runtime.us-west-2.amazonaws.com"] secret.ref = "env://AWS_BEARER_TOKEN_BEDROCK" ``` Replace the `model_connect` and `model_request` rules of [your first policy](tutorials/first-policy.md) with these two. Replace rather than add: a second rule with the same `@id` refuses to load, and a renamed copy leaves the broad `model_request` permit in force. ```text @id("model_connect") permit (principal, action == Box::Action::"net:connect", resource) when { context.input.host == "bedrock-runtime.us-west-2.amazonaws.com" && context.input.port == 443 }; @id("model_request") permit (principal, action == Box::Action::"http:request", resource) when { context.input.host == "bedrock-runtime.us-west-2.amazonaws.com" && context.input.port == 443 && context.input.method == "POST" }; ``` The agent receives a `403` response whose body is the denial, and the request never leaves the box: ```text http:request gate: policy denied this operation on 'bedrock-runtime.us-west-2.amazonaws.com:443/model/anthropic.claude/invoke' [default-deny]: No permit policy matched this request. ``` A connection to another host is refused before TLS: ```text policy denied this operation on 'example.com:443' [default-deny]: No permit policy matched this request. ``` A `[egress.]` table with no matching permit leaves the host unreachable. A permit with no binding sends the request with a placeholder in place of the secret, which the provider rejects. ### Reach a service on your machine The agent reaches `http://host.box.internal:4259`, a service on your machine's loopback, and no other port there ([a service on your machine](egress.md#a-service-on-your-machine)): ```text @id("local_llm_connect") permit (principal, action == Box::Action::"net:connect", resource) when { context.input.host == "host.box.internal" && context.input.port == 4259 }; @id("local_llm_request") permit (principal, action == Box::Action::"http:request", resource) when { context.input.host == "host.box.internal" && context.input.port == 4259 }; ``` The gateway decides `net:connect` on the name, then on the address it dials, `ip4 = "127.0.0.1"`. So a forbid on loopback addresses also refuses the name. To keep it, exclude the name: ```text @id("no_loopback") forbid (principal, action == Box::Action::"net:connect", resource) when { context.input has ip4 && context.input.ip4 like "127.*" && context.input.host != "host.box.internal" }; ``` A permit on the name doesn't admit `127.0.0.1:4259`, and a wildcard host permit includes the name. ## Log-only mode Log-only mode trials a policy without enforcing it. Box decides every action as usual, but a denial from a `forbid`, or from no `permit` matching, doesn't block: the action goes ahead and Box records what the policy would have denied. Use it to see what a new or generated policy would block on real work before you enforce it. Turn it on with the table form of the `policy` key in `box.toml`: ```toml [policy] source = "policy.dw" enforcement = "log_only" # "enforce" is the default ``` Each would-deny is recorded as a denial that Box didn't enforce, and it names every rule that would have blocked the action, across all its steps, so one trial finds them all. The `policy_installed` record states the mode on every run. [A decision](telemetry.md#a-decision) lists the keys. To list what a trial would have denied, filter the decision records on `strands.box.policy.would_deny.ids`. This prints each record's action, resource, and the rules that would have blocked it: ```sh jq -r 'select(.resourceLogs) | .resourceLogs[].scopeLogs[] | select(.scope.name == "strands-box.policy") | .logRecords[] | .attributes | map({(.key): (.value | if has("arrayValue") then (.arrayValue.values | map(.stringValue) | join(",")) elif has("boolValue") then .boolValue else .stringValue end)}) | add | select(has("strands.box.policy.would_deny.ids")) | "\(.["strands.box.policy.action"]) \(.["strands.box.policy.resource"]) \(.["strands.box.policy.would_deny.ids"])"' \ /private/telemetry/records.jsonl ``` A line such as `fs:move ~/agent-home/b.txt no-read-a,no-move-onto-b` is a move that ran in the trial, and that the rules `no-read-a` and `no-move-onto-b` would block once you enforce the policy. Some denials still block in log-only mode, so a missing or broken policy doesn't fail open: - a policy that isn't installed yet (`policy_pending`); - a rule that fails to evaluate (`internal_fault`); - an MCP tool whose rule can never validate; - the reachable-paths floor, the sandbox, and credential isolation, which aren't policy. An action log-only mode lets through really happens, so history records its real outcome. A later rule that depends on it, such as "allow `git push` only after `npm test` passed", sees what actually ran. After the first would-deny, a run can take a path an enforcing run wouldn't, so decisions after `first_flip` are an approximation. **A box keeps one history across modes.** When you switch the same box from `log_only` to `enforce`, the enforcing run inherits what the trial did, because those actions really happened. A budget over the last hour counts the bytes a trial sent, and an "only after the tests passed" rule is met by a trial's test run. To start enforcing with no trial behind it, run the trial in its own `box_dir`, or [start with fresh history](#start-with-fresh-history-after-a-dogwood-upgrade) before you enforce. **The policy protects nothing during a trial.** On the Shell and Monty path the policy is the only thing between the workload and your home directory, credential files, and cloud metadata. The egress gateway attaches each bound credential to a request the policy would deny. Box prints this on stderr at startup. Run trials only where that's acceptable, such as a disposable VM or a host with no credentials you care about. ## History persistence and process crashes Box batches policy-history writes by default. Accepted events affect decisions during the run before those events necessarily reach disk. The engine checks persistence thresholds of 1,000 events or one second when an event arrives. A separate one-second timer also persists pending history while Box is idle. This interval is a polling target, not a maximum persistence delay. If the box's trusted process crashes or is killed before a completed flush, recent requests and outcomes can be lost. After restart, a count-based limit can admit additional requests because those events no longer count. A normal shutdown stops and joins event producers before the final history flush. A recorded timer failure stops the workload, and a final-flush failure makes the run fail. Shutdown has no fixed completion deadline; an [active upstream exchange](egress.md#errors-and-exit-codes) can delay it. To use per-event persistence, build Box and its helpers from the repository root with the default `experimental-idle-flush` Cargo feature disabled: ```sh cargo build --release --locked -p strands-box -p strands-box-containment --no-default-features ``` The resulting build waits for persistence when submitting each event. An operation can still finish before its outcome is recorded. To retain the native filesystem policy build feature, also pass `--features native-filesystem-policy`; [its runtime selection](native-filesystem-policy.md) remains separate. `--all-features` or `--features experimental-idle-flush` enables batching again. This selection happens when Box is built; there is no `box.toml` setting for it. See [getting started](getting-started.md#step-1-download-box) for the source checkout and helper installation. ## Start with fresh history after a Dogwood upgrade This upgrade to Dogwood 1.1.2 requires a new box directory. If the configured directory contains unsupported history, Box refuses to start the workload. The error directs you to start with a new box directory; Box does not erase or convert the old history. Later restarts reuse the new history. A new directory starts with no recorded activity. Counts and usage budgets start over. An earlier read no longer satisfies a rule that requires that read before a write. If those resets are not acceptable, keep using the existing build and box directory. To use the new build with fresh history: 1. Stop the old Box run. 2. Copy its configuration beside the original as `box-1.1.2.toml`. Keep the original configuration and the complete old box directory intact. 3. In the copy, set `box_dir` to a new absolute path outside the workload workspace. Its parent directory must exist. Keep the policy, tool grammar, credential references, and workload settings. 4. Check each `[telemetry.