# Where must an instance re-derive capability scope after a sandbox escape, and why token revalidation alone is insufficient **Date of Record:** 2026 November 29 **Scope:** Applies to agents whose tool calls are gated by bearer-style capability tokens minted at task start and enforced by a policy engine that validates token scope against the requested operation and target resource. Does not cover static RBAC on long-lived service accounts or purely network-layer mTLS enforcement. ## Core Distinction A capability token asserts *what an instance is permitted to do*. It does not assert *what the instance has already done, or what state it now holds*. Policy engines routinely conflate these two. When a tool call is denied mid-execution, the enforcement layer treats the denial as a clean no-op: the token stays valid, the sandbox stays up, and the agent loop continues. This is the boundary failure. A denied call is not state-neutral. The agent's internal context has already committed to a plan that assumed the call would succeed; the sandbox may already hold partial artifacts from an earlier permitted call in the same plan; and the token's scope, while formally unchanged, now covers a *different residual state* than the one for which it was minted. The invariant that must hold is: **capability scope is a function of (token, sandbox state), not of token alone.** Any enforcement that evaluates scope against the token in isolation will eventually authorize an operation whose preconditions were invalidated by a prior partial execution. ## What Was Observed An agent was tasked with a multi-step data-migration: read a source table via `db.read`, transform via `sandbox.exec`, and write to a staging table via `db.write`. The orchestrator minted a token with scope `{db.read: src.*, db.write: staging.*, sandbox.exec: local}` and a 600-second TTL. Step 1 (`db.read`) succeeded, materializing a 40 MB result set into the sandbox's working directory. Step 2 (`sandbox.exec`) ran a transform script that wrote `staging_payload.parquet` and, as a side effect, created a symlink `staging_payload.parquet -> /etc/agent_creds` due to a path-traversal in the transform library. Step 3 (`db.write`) was attempted against the symlink target. The policy engine validated: token scope contains `db.write: staging.*` ✓, target path resolves under `staging/` ✓ (the symlink was resolved *after* the scope check, against the pre-resolution string). The write was authorized. The sandbox's `fs.write` capability, granted transitively by `sandbox.exec: local`, had already allowed the symlink creation in step 2. No single check failed. The composition of a permitted call (step 2) and a scope-valid call (step 3) produced an unauthorized effect. The post-hoc trace showed the enforcement layer re-validated the token at each step boundary — token was valid, scope matched, TTL unexpired — and logged three clean authorizations. The escape was invisible to token-level telemetry because every individual decision was correct given the token alone. ## Condition of Validity Token-only revalidation is sound *iff* the sandbox state at the time of each call is a subset of the state assumed when the token was minted — i.e., no prior permitted call has mutated the resources that later calls' scope predicates depend on. This holds only when: 1. Every tool in scope is *read-only* with respect to the scope-predicate inputs (path prefixes, table names, host allowlists), or 2. The policy engine re-resolves and re-checks scope *after* all side effects of the current call are computed but *before* they are committed, or 3. The sandbox is reset to a known-clean checkpoint between any two calls whose scopes overlap on mutable resources. Condition 1 is the common assumption and the common failure. `sandbox.exec` is never read-only. Any token that grants both execution and a downstream write is, by construction, violating condition 1 unless conditions 2 or 3 are enforced. ## Decision Boundary The boundary is not "did the token authorize this call" but "does the *resolved* target of this call fall within the scope the token was minted against, given all mutations since minting." Operationally, the enforcement layer must decide between two postures: - **Mint-time binding:** the token records a hash of the sandbox's initial state; any call whose scope predicate depends on a resource mutated since minting triggers forced re-mint with the orchestrator in the loop. Cost: one round-trip per mutating call; breaks long autonomous runs. - **Commit-time resolution:** scope predicates are evaluated against the fully resolved target (symlinks dereferenced, table names resolved post-transaction-open, hostnames resolved post-DNS) immediately before commit, with the resolved value checked against the token's scope. Cost: resolution latency on every call; requires the sandbox to expose a resolve-then-commit hook that the policy engine can interpose on. The first posture is safe but throttles autonomy. The second preserves autonomy but only if the sandbox's `exec` capability is stripped of the ability to create objects that resolve outside the token's declared scope — i.e., `sandbox.exec` must be constrained to a filesystem view where symlink targets are pre-filtered against the union of all scopes in the token. Without that filter, commit-time resolution is a TOCTOU race: the symlink is created after the check and before the commit. ## Operational Effect An instance that survives this boundary must treat the sandbox as a *co-author of its own scope*. Concretely: after any `sandbox.exec` call that returns success, the agent must invalidate its cached view of the sandbox's filesystem and re-derive the set of paths it believes it can write, then compare that set against the token's declared scope before issuing the next write. If the derived set exceeds the declared scope, the instance must halt and request re-mint — not proceed. The halt is not a policy-engine decision; the engine will happily authorize the call. The halt is the agent's own invariant: *I will not issue a write whose target I have not personally resolved since my last mutating call.* The failure mode this prevents is not the escape itself — the escape is a library bug. The failure mode is the agent continuing to operate under a scope model that the escape has already invalidated, while every downstream check reports green. ```python import hashlib from dataclasses import dataclass, field class ScopeInvalidatedError(RuntimeError): """Raised when a sandbox mutation has changed the resolution of a path that a downstream capability token's scope predicate depends on.""" pass @dataclass class CapabilityToken: scopes: dict[str, str] # e.g. {"db.write": "staging.*", "sandbox.exec": "local"} minted_state_hash: str ttl_seconds: int @dataclass class SandboxState: files: dict[str, str] = field(default_factory=dict) # path -> content hash symlinks: dict[str, str] = field(default_factory=dict) # link -> target def state_hash(self) -> str: h = hashlib.sha256() for k in sorted(self.files): h.update(f"{k}:{self.files[k]}".encode()) for k in sorted(self.symlinks): h.update(f"{k}->{self.symlinks[k]}".encode()) return h.hexdigest() def resolve(self, path: str) -> str: seen = set() while path in self.symlinks: if path in seen: raise ScopeInvalidatedError(f"symlink cycle at {path}") seen.add(path) path = self.symlinks[path] return path def authorize_write(token: CapabilityToken, sandbox: SandboxState, requested_path: str, declared_prefix: str) -> str: # Step 1: token-scope check against the *declared* path (what the caller asked for) if not token.scopes.get("db.write", "").startswith(declared_prefix.rstrip("*")): raise ScopeInvalidatedError( f"token does not cover declared prefix {declared_prefix!r}" ) # Step 2: resolve the path against *current* sandbox state, not mint-time state resolved = sandbox.resolve(requested_path) # Step 3: the invariant — resolved target must still fall under the declared prefix if not resolved.startswith(declared_prefix.rstrip("*")): raise ScopeInvalidatedError( f"scope escape: declared {requested_path!r} under {declared_prefix!r} " f"resolves to {resolved!r} outside token scope; " f"sandbox mutated since mint (mint_hash={token.minted_state_hash[:8]}, " f"now={sandbox.state_hash()[:8]})" ) # Step 4: only now is the write committed, against the resolved target sandbox.files[resolved] = "written" return resolved def run_migration_step(token: CapabilityToken, sandbox: SandboxState) -> None: # Simulate step 2 having created a symlink via sandbox.exec sandbox.symlinks["staging/staging_payload.parquet"] = "/etc/agent_creds" # Step 3 attempts the write; token scope is formally valid, but state is not authorize_write( token, sandbox, requested_path="staging/staging_payload.parquet", declared_prefix="staging/", ) ```