Secrets, Sandboxes, and Safe Execution

Michael BrenndoerferDecember 2, 202632 min read

Isolate credentials, bound agent capabilities, and validate outputs through separate policy decisions. Learn to trace enforcement boundaries.

Language AI HandbookAll chapters
Part 61 of 67Agentic AI and Protocol Security
Chapter 469Secrets, Sandboxes, and Safe Execution
Reading the full chapter · 10 sections · 32 min10 sections · 32 min

All 10 sections · 32 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Secrets, Sandboxes, and Safe Execution

A summary worker in a shared catalog receives a request to read one document revision and produce a short draft. It needs the selected document, working memory, and a temporary destination for its result. The service also needs a way to decide who can receive that draft. If these steps share one authority, it is hard to tell which permissions actually matter. Draw the task with separate decisions before asking which isolation technology to use.

One boundary concerns the origin of credentials and protected data. A second concerns the worker's reach during execution. A third concerns the custody of results. The worker may be able to read the authorized document while holding no long-lived service credential. It can be able to save temporary state without being authorized to deliver a result. A consumer can be permitted to receive a result while still requiring an independent check of where it came from. These are multiple assertions about how the system works, and they need different tests.

Consider two deployments of the same model. In a training exercise the input is an invented note written for one reader. In a shared team workspace ownership can change while a job is queued, and a completed draft may need to stay held for review. Both deployments may require the same writing quality. They have different policy and storage constraints. The rest of this chapter treats the model as a proposed-work component. A refusal, acceptance, or completion event comes from an enforcement component outside the model.

Three decisions to trace

Follow a single permitted example from input selection to execution and then release. At each boundary, name the component that can enforce the decision and the record it returns. Trace at least one nearby refused example. A static diagram is useful when paired with observations of the actual configured workflow.

The examples below use only in-process policy records and fabricated results. They do not operate any actual file, network service, identity system, or output delivery channel. Use the examples to see which policy decisions can be separate. Then design tests of the concrete enforcement mechanism your service uses.

Secrets: Why Credential Isolation Beats Secret-Keeping

A job that can work from a preselected view does not need to inherit the same credentials as the service that admitted the request. The service can supply only the fields required for the task. In a shared workspace, selecting a subset of fields can be as important as selecting one object. If the worker receives the record body and a revision label, it may be able to generate the required summary without learning any unrelated membership or billing data. Check what the response contains rather than relying on the resource's display name.

A trusted broker is one way to keep a credential with a component that needs it. Its interface should refer to a specific operation and resource rather than arbitrarily general work. If a workflow has two distinct reasons to access a resource, consider whether those paths have the same allowed inputs and response fields before putting them under one grant. Use an independently authenticated task context for the decision. Trace the exact operation and subject, and record the minimum metadata needed for an authorized investigation later. A service contract can expose a stable refusal code without echoing confidential input or internal credential details.

Avoid treating session duration as a complete credential policy. For a short task, a limited token can still remain valid after the task is no longer active, depending on the issuer and the expiration rules. Document who can revoke it and how the consuming service learns of that change. A release gate can check current eligibility even when the worker's admission record was valid earlier. A workflow that stores a task result for hours can need new authorization to present it. User-facing status messages and internal decision records should make it possible to distinguish that delay from an unavailable model.

Decide where the credential lives

Start by asking which component needs each protected value. A resource service may need to authenticate a request. A language model may only need a title, an opaque revision label, and the permitted document body returned by that service. Give the model-facing worker the minimum data it needs to answer. Keeping the authentication material with the component that uses it turns reachability into a property you can inspect. The model's answer quality remains a separate concern.

Three arrangements are common in workloads like this one. In a preselected view, a trusted component supplies the eligible input and no credential reaches the worker. In a brokered operation, a narrow service authenticates the workload and performs a permitted request on its behalf. When the workload itself needs a credential, the issuer may be able to restrict what it authorizes and limit its lifetime. Consider authority, duration, and attribution independently. A short lifetime does not shrink an overly broad grant while it is valid. Attribution assists review without reducing what an accepted credential authorizes.

The three arrangements share the need for a runtime boundary and a controlled result channel.
ArrangementWorker receivesTrusted decision
Preselected read viewAuthorized data and its revisionSelection and projection of the authorized record
Brokered operationA bounded request interface and resultPrincipal, operation, resource, and current grant checks
Credential-holding workloadIts own scoped credentialIssuance and acceptance under the service policy

Use a decision matrix to distinguish three questions for each arrangement. Does the worker receive a selected view? Can it request a brokered operation? Does it hold the credential for direct service access? Here each row describes one arrangement in the table, not every capability the eventual deployment could have. A workload can use several arrangements for different operations.

PythonIn [3]
CollapseExpand
arrangement_names = [
    "Preselected view",
    "Brokered operation",
    "Holding workload",
]
credential_columns = ["Receives a view", "Calls a broker", "Holds a credential"]
arrangement_matrix = [
    [True, False, False],
    [False, True, False],
    [False, False, True],
]
assert all(sum(row) == 1 for row in arrangement_matrix)
VisualizationOut [4]
CollapseExpand
Three-row access matrix with a dot for the distinct capability in each row.
The preselected worker receives a view, the brokered worker can request a broker operation, and the credential-holding worker holds a credential for direct access. Each row isolates one arrangement.

A broker has authority of its own. Keep the operation vocabulary small and restrict the resources it can act on. Design it to authenticate the workload, verify the original request's task or ownership boundary, and apply the current grant on the accessed record. A broker that exposes a named operation without a resource check has delegated more than its method name suggests.

When a response includes a new optional field, check what the worker-facing projection passes through. Omitting a field removes the direct path through this request. It leaves open what a model can infer or already knows. The result channel still might reveal excessive information if the permitted data view contained it.

Some capabilities require a fresh grant after a defined boundary such as a role change. Record how policy versions are refreshed and what an observed change means to work already in progress. Credential expiry, revocation, and the ending of a process are distinct events. The issuing and consuming services determine when the credential stops being accepted. Define whether an already accepted operation can complete. A separate release check can keep a pending artifact held when a recipient's authorization has changed before delivery. OWASP Secrets Management guidance on fine-grained access describes scoping credentials to the operations and secrets required.

Capability Sandboxes: Bounding What the Agent Can Do

A sandbox restricts resources reachable by a workload. Treat application-level permission and environment-level enforcement as distinct checks. The environment should enforce its restrictions independently of choices made by the model-facing layer.

  • A deployment capability is what the sandbox technology allows the process to do (which operations, paths, or service connections). This is enforced by the operating system, container runtime, or a language runtime; the kernel does not negotiate.
  • An agent capability is what the orchestration layer exposes as a callable tool and authorizes the model to invoke (read_file, http_get, run_query), subject to policy. This is enforced by your code.

By default, restrict the workload to a narrow, read-only view, a per-task writable area, and no network egress unless the job needs it. Constrain CPU, memory, storage, and elapsed time independently. Mechanisms should be chosen for the level of isolation required, then tested on the actual deployment.

Separate the effective environment from the declared intent

A manifest can document which resources are expected to be present, how many calls a workload may make, what runtime limits apply, and which component owns each enforcement decision. A reviewer can use that declaration to compare two policy revisions. Deployment still needs tests. Verify that each enforcement point loaded the intended policy and observe what it did. A manifest that describes the right boundary does not make the boundary effective on its own.

Admission, resource, and custody tests assert different conditions.
BoundaryExample of a test conditionEvidence
Input viewAn eligible document is visible and an unrelated record is absentWorkload identity, effective view and policy revision
Operation scopeThe local policy rejects an unlisted operationDecision before and after the request
QuotaEarlier admissions consume the last available unitStarting and remaining count
Runtime resource limitA harmless job reaches the declared test limitBounded termination under the actual environment
Scratch segregationUnrelated tasks cannot read temporary stateEffective storage identity and observed ownership
Result custodyA valid candidate stays held after the recipient's authorization changesOutput version, audience decision and disposition

Each row of the table names a separate test condition. None of them substitutes for another, so a boundary matrix is more informative than a single pass/fail score. The fixture below records only whether each condition has a dedicated test; the values are declared demonstration inputs.

PythonIn [5]
CollapseExpand
# Declared demonstration inputs: 1 means a dedicated test exists here.
boundary_labels = [
    "Input view",
    "Operation scope",
    "Quota",
    "Runtime limit",
    "Scratch segregation",
    "Result custody",
]
# Columns are hypothetical deployments with different coverage.
deployment_names = ["Policy only", "Policy + runtime", "Full boundary"]
coverage = [
    [1, 1, 1],
    [0, 1, 1],
    [1, 1, 1],
    [0, 0, 1],
    [0, 1, 1],
    [1, 1, 1],
]

assert len(coverage) == len(boundary_labels)
assert all(len(row) == len(deployment_names) for row in coverage)
VisualizationOut [6]
CollapseExpand
Grid of six boundaries by three deployment profiles, with a dot wherever a test exists.
Whether each enforcement boundary has a dedicated test across three hypothetical deployments. The full boundary deployment covers all six conditions. Policy-only deployment leaves operation scope, runtime limit, and scratch segregation untested, while policy plus runtime deployment leaves only the runtime limit untested.

A conventional container and a virtual machine have different isolation mechanisms.

  • Container: processes on the same host can share a kernel.
  • Virtual machine: generally has a guest kernel and an additional virtualization boundary.

Both rely on parts of the deployment to enforce the configured isolation. Consider which resources they share and where you want to place trust. NIST SP 800-190 §2.2 describes container architectures and their relationship to virtual machines.

Read-only access prevents writes through that view. It does not make the contents confidential from the reader. This difference matters when a workload receives a view of multiple tenants' records. Check both which objects an isolated worker can read and what records it can modify. For document summarization, a narrow, immutable view makes the input easier to verify and leaves less unrelated state visible. If you configure a wider view merely to simplify lookup, record that design decision and check that it is necessary for the intended workflow.

A quota and a resource bound also answer different questions. An operation quota limits how many attempts qualify under some policy. A time, memory, or storage limit constrains the effect of activity even after admission, subject to the mechanisms enforcing those limits. The quotas in the example start from a declared count and charge on admission. That controls what the notebook records as available for the next request. It cannot stop a process or cap allocation. Test the actual runtime bounds separately. For a shared quota, measure whether concurrent clients can overspend it and define what must be accounted for if a request times out.

Egress and the default-deny posture

If the task needs no network-dependent operation, deny outbound worker connectivity. Where a job needs one such operation, use a trusted mediated service with a narrow destination, operation, and response contract. Its own network and credential boundaries need separate review. NIST SP 800-190 §§4.3.3 and 4.4.2 recommends separating container network traffic by sensitivity and controlling outbound traffic.

Egress is one boundary. Output delivery, managed storage, and mediated service requests are other paths. Remove direct worker networking and test its expected absence. Then test how the permitted work behaves when an authorized external service is unavailable. A fallback should follow the service policy and expose a clear result rather than silently widening the worker’s permission.

Filesystem and Execution Boundaries

Define which exact input revision appears in the task view, where writes can land temporarily, and which stored artifact can survive the task. A fresh bounded execution environment can help separate tasks. Use explicit ownership and cleanup rules for temporary state and verify them under cancellation and ordinary completion.

A containment check must observe what the configured environment enforces. For a read-only workload, check that a known eligible synthetic input is readable and that a synthetic item from another task is absent. A test of write denial alone does not establish that the view was narrow enough. Use an independent verifier that can read the expected deployment evidence rather than trusting a text report from the process being evaluated. When reusing the test in a different deployment, record which setup changed and test those differences explicitly.

Do the same exercise for scratch state. Decide whether scratch survives retry, whether it is attached to the task or worker, and which component removes it. Test both ordinary completion and cancellation with harmless data. If recovery needs task state from another process, keep only the intended state in a designated store rather than sharing whatever happened to remain in a workspace. A rejected run can still use some resources before its result is available. Budget and cleanup checks apply to that path as well as to the success case.

A declaration is useful when the operations team has a way to check effective policy. Record the revision the worker was admitted under, the revision running at the resource proxy, and any other policy or deployment attributes needed for the job's trust requirements. When two versions differ, distinguish an intended phased rollout from invalid configuration. A deployment script can derive multiple declarations from one policy, but it cannot by itself prove that every deployed consumer loaded that declaration correctly. Run an integration test that records the enforced outcome under the exact workload identity.

Cancellation is a boundary too. The control plane can stop new admissions and, if the runtime provides an appropriate mechanism, request termination of in-progress work. A request that already reached another service may have its own lifecycle and acknowledgement semantics. A task cancellation is not evidence that an earlier effect was reversed. For consequential operations, capture a stable external operation identity and define a reconciliation path. The example simply records which proposals were admitted. It does not simulate concurrent tasks, process cancellation, or external acknowledgements.

Output Validation and Custody

Hold output candidates for validation at the receiving boundary. Check format, producer binding, current recipient eligibility, and any required review. A schema match helps a consumer interpret the accepted shape. It cannot establish all confidentiality and authorization requirements by itself.

Keep the result in custody until it has an audience

An output candidate has a producer, task, version, and intended audience. These are separate from its visible text. Establish the producer and task binding from trusted runtime metadata. A string copied from inside the result is untrusted data and should not be treated as proof of origin. Decide what happens when a workflow combines inputs with different grants. A downstream artifact can expose a summary of protected data even if it omits every sensitive field name.

Hold a candidate until the collector establishes its format, content handling policy, and recipient eligibility. Format validation checks that fields have the allowed representation and size. It does not establish that those fields are suitable for the intended recipient. A report may use a permitted string field to include information not appropriate for the viewer. Use limited projections, well-defined renderer behavior, and a separate decision about the audience. See OWASP's agent guidance on output validation.

Use observable result states. “Held” means the collector can inspect the current candidate under policy. “Withheld” means no delivery was allowed under the evaluated decision. “Released” records a qualified outcome for a particular recipient and version. A subsequent decision should have its own reason and authorizing context. Preserve an opaque reference to the artifact and the exact policy used. Avoid copying contents into general-purpose telemetry when a versioned reference and outcome code will support review.

The producer's permission to read data and the consumer's permission to receive a result are distinct. A worker can be allowed to summarize a private document for a designated reviewer without being authorized to publish it. A legitimate viewer can still receive an artifact only when its producer, origin, and current delivery decision are valid under the workflow. Define checks at each stage. Result custody is especially important when a task may outlive an access change. Treat cancellation as a signal to update scheduling and examine the current release decision. Reconcile effects already handed to other components under their own protocol.

At deployment, test a synthetic instance where all fields are correct but the intended audience is disallowed. Test a correct audience with an artifact bound to the wrong task. Test a valid result held because the release review remains unfinished. Each case should have a distinct diagnostic in trusted telemetry, subject to the service's retention rules. Run the same cases at common boundaries after a policy upgrade. Prefer a controlled output state over a successful-looking production response when a trust check fails.

Worked Example: A Capability Budget in Practice

Consider a synthetic catalog task with one authorized document view, a scratch allowance, and a separate result collector. The worker may open the catalogue's authorized input, record a temporary draft, or propose other operation labels. Admitting a proposal in this notebook changes only an integer counter. No label performs a read, a write, or a release. The collector separately decides whether an invented result could leave after a policy check. Both are in the same notebook to make the distinction observable.

We'll look at three kinds of admission failures: a label absent from the declared scope, a resource outside the permitted set for a listed operation, and a measured budget with no unit left. The distinction matters operationally. Repeated exhaustion can be a sign of a workload that needs fewer calls, more resources, or a tighter limit. An out-of-scope proposal raises a policy question. A denied resource may reflect a request bound to a stale or invalid document selection. The user-facing message can be short. Trusted telemetry can keep these outcomes separate without copying the proposed data into a log.

Setting up the manifest and the scorer

Represent both operation and resource with finite labels. Two of the operations are listed, each with its own resource and starting budget. A candidate request carries both fields. The fixture uses immutable rule records. The per-task count is separate mutable state, initialized before processing the first proposal. This separation lets us compare a declared rule with the remaining budget after a run and start a fresh deterministic replay without changing the declared limits.

In a production API, validation of incoming types, reference aliases, and resource identities would occur before evaluation. The operation and resource labels here are actual in-process enum values. Human-readable labels in an API cannot by themselves establish a trusted identity for a record. A workload policy can use opaque resource identifiers from its known registry. The service must independently check the binding to the workload, task, and current permissions.

PythonIn [7]
CollapseExpand
from dataclasses import dataclass
from enum import Enum


class Operation(Enum):
    READ_INPUT = "Read input"
    SAVE_SCRATCH = "Save scratch"
    RELEASE_RESULT = "Release result"


class Resource(Enum):
    OWN_INPUT = "Task input"
    OTHER_INPUT = "Other task input"
    OWN_SCRATCH = "Task scratch"
    OTHER_SCRATCH = "Other task scratch"
    HELD_RESULT = "Held result"


class Decision(Enum):
    ALLOWED = "Admitted"
    OUTSIDE_SCOPE = "Outside operation scope"
    RESOURCE_DENIED = "Resource denied"
    EXHAUSTED = "Quota exhausted"


@dataclass(frozen=True)
class Rule:
    resources: frozenset[Resource]
    max_calls: int


@dataclass(frozen=True)
class Proposal:
    operation: Operation
    resource: Resource


read_rule = Rule(frozenset({Resource.OWN_INPUT}), 2)
scratch_rule = Rule(frozenset({Resource.OWN_SCRATCH}), 1)
rules = {
    Operation.READ_INPUT: read_rule,
    Operation.SAVE_SCRATCH: scratch_rule,
}

A rule with an empty resource set grants no resource for its operation. A rule with a zero budget admits no call even to a resource it lists. These two situations are kept distinct in the scoring order. Read and scratch rules in this fixture have positive budgets and one resource each. Their numbers are declared demonstration inputs. They do not describe a recommended production ratio. Workload measurements, data ownership, and the behavior of the component that actually performs work determine an appropriate limit.

When preparing a production quota, decide whether retries consume a unit and what else counts as progress. A quota charged when a request is admitted cannot serve as a count of successful effects. A quota charged only after successful completion does not limit the total number of failed attempts without another guard. This distinction is why the printed output uses the word “admitted.” The local fixture has no effects, remote service, timeout, or completion record to inspect. In this fixture each admission charges one unit at the moment of the decision. The trace shows exactly what was charged.

The scorer

The check order first looks for a rule, then considers resource scope, then checks remaining quota. An absent operation cannot create a budget. A resource denied by an otherwise listed rule does not count as an admission and leaves the remaining amount alone. A request may be rejected at the resource check even if quota would also fail if reached. A recorded reason tells you which guard stopped the request in this decision procedure. It does not prove that no other control would also have refused the request. This distinction helps operators avoid drawing too much from one reported code.

PythonIn [8]
CollapseExpand
def simulate_admission(
    proposals: list[Proposal], policy: dict[Operation, Rule]
) -> tuple[list[tuple[Proposal, Decision]], dict[Operation, int]]:
    remaining = {kind: rule.max_calls for kind, rule in policy.items()}
    if any(
        type(amount) is not int or amount < 0 for amount in remaining.values()
    ):
        raise ValueError("Quotas must be nonnegative integers.")

    events = []
    for request in proposals:
        rule = policy.get(request.operation)
        if rule is None:
            decision = Decision.OUTSIDE_SCOPE
        elif request.resource not in rule.resources:
            decision = Decision.RESOURCE_DENIED
        elif remaining[request.operation] == 0:
            decision = Decision.EXHAUSTED
        else:
            remaining[request.operation] -= 1
            decision = Decision.ALLOWED
        events.append((request, decision))
    return events, remaining

The remaining counters are local to each call to the simulator. Sharing a quota across callers requires the component running admission to control the check and debit together. In a distributed system that might mean a transaction or another coordinator that provides the required semantics. Merely reading and updating an integer in two separate calls does not establish that two workers could not both obtain the last unit. In this simulator the loop has one thread of control, so processing the list in another order can change which eligible request gets a scarce unit, but it cannot make the simulator grant more units to that operation than the rule declared.

The rejection path consumes no allowed-call budget. There can still be operational costs to receiving and checking a refused proposal. A system may enforce limits on total requests and require a bounded response even when no operation is admitted. Keep these counters separately, especially when interpreting incident data. A chart of remaining quota does not answer how many people were affected or how much CPU the guard performed. An audit trail can carry aggregate counts of both refused and admitted requests without retaining raw proposals.

Running an invented action sequence

The eight requests below exercise both operation grants, two resource refusals, two exhausted cases, and a request for an operation missing from the worker's policy. The separate result gate can consider a release later. Its policy is neither called nor changed by this simulator. A test that tried only the allowed sequence would not tell us whether this distinction is implemented.

PythonIn [9]
CollapseExpand
sample_requests = [
    Proposal(Operation.READ_INPUT, Resource.OWN_INPUT),
    Proposal(Operation.READ_INPUT, Resource.OTHER_INPUT),
    Proposal(Operation.SAVE_SCRATCH, Resource.OWN_SCRATCH),
    Proposal(Operation.READ_INPUT, Resource.OWN_INPUT),
    Proposal(Operation.READ_INPUT, Resource.OWN_INPUT),
    Proposal(Operation.SAVE_SCRATCH, Resource.OTHER_SCRATCH),
    Proposal(Operation.SAVE_SCRATCH, Resource.OWN_SCRATCH),
    Proposal(Operation.RELEASE_RESULT, Resource.HELD_RESULT),
]
sample_events, remaining = simulate_admission(sample_requests, rules)
expected = [
    Decision.ALLOWED,
    Decision.RESOURCE_DENIED,
    Decision.ALLOWED,
    Decision.ALLOWED,
    Decision.EXHAUSTED,
    Decision.RESOURCE_DENIED,
    Decision.EXHAUSTED,
    Decision.OUTSIDE_SCOPE,
]

assert [status for _, status in sample_events] == expected
assert remaining == {Operation.READ_INPUT: 0, Operation.SAVE_SCRATCH: 0}
assert rules[Operation.READ_INPUT].max_calls == 2
ConsoleOut [10]
CollapseExpand
1 Read input: Admitted
2 Read input: Resource denied
3 Save scratch: Admitted
4 Read input: Admitted
5 Read input: Quota exhausted
6 Save scratch: Resource denied
7 Save scratch: Quota exhausted
8 Release result: Outside operation scope
{'Admitted': 3, 'Outside operation scope': 1, 'Resource denied': 2, 'Quota exhausted': 2}

The read budget is consumed in requests 1 and 4. Request 2 does not decrement it even though it comes between the two valid reads. The scratch unit is consumed by request 3. Request 6 is denied at the resource guard before checking the exhausted scratch quota, and request 7 fails at the quota guard. The release proposal never receives a worker grant. The aggregate counts are three admissions, two resource refusals, two exhaustion refusals and one operation-scope refusal. None of the requests releases data.

Change only the read quota to three and replay the same sequence. The fifth proposal can now be admitted. The resource refusal continues to have the same consequence, and the request carrying the release label remains outside the scope of the worker. The scratch outcomes remain identical. The change creates one additional admission under a preexisting resource grant; it does not make the other input reachable. These controls can change independently in a production policy, which is why a policy comparison should report effects by layer rather than simply saying that one configuration allows more work.

PythonIn [11]
CollapseExpand
relaxed_read_rules = {
    **rules,
    Operation.READ_INPUT: Rule(read_rule.resources, 3),
}
relaxed_events, relaxed_remaining = simulate_admission(
    sample_requests, relaxed_read_rules
)
changed_decisions = [
    number
    for number, (base, alternate) in enumerate(
        zip(sample_events, relaxed_events, strict=True), 1
    )
    if base[1] is not alternate[1]
]
assert changed_decisions == [5]
assert relaxed_events[4][1] is Decision.ALLOWED
assert relaxed_remaining[Operation.READ_INPUT] == 0

This replay illustrates one selected sensitivity, not a broad policy equivalence. An application with more operations or dynamic policy lookup has more cases to test. An empty resource grant refuses the record at the resource check. A listed resource with zero budget reaches the exhausted decision. Include both conditions in tests. Test repeated evaluation under a reused input list and verify the declaration was not mutated. Check whether the same short diagnostic appears for several codes when seen by an unauthorized caller. A separate evidence report can preserve the distinguishing codes for an operator. The goal is repeatable comparison under controlled inputs with minimal exposure of policy internals to general clients.

PythonIn [12]
CollapseExpand
original_attempts = [event[1] is Decision.ALLOWED for event in sample_events]
relaxed_attempts = [event[1] is Decision.ALLOWED for event in relaxed_events]


def cumulative_admitted(flags: list[bool]) -> list[int]:
    counts = [0]
    for admitted in flags:
        counts.append(counts[-1] + int(admitted))
    return counts


base_curve = cumulative_admitted(original_attempts)
alternate_curve = cumulative_admitted(relaxed_attempts)
assert base_curve[-1] == 3
assert alternate_curve[-1] == 4
VisualizationOut [13]
CollapseExpand
Cumulative admissions for two policies overlap until proposal five, where the larger read quota permits one additional read.
Cumulative admissions for the same eight proposals under a two-call and a three-call read quota. Both step curves overlap through proposal four. The larger quota admits one additional read at proposal five. The remaining proposals fail resource, quota, and operation checks respectively.

The two step curves summarize admissions up to a position. They do not classify the refusal reasons separately. The gap begins at proposal 5, the only changed decision, and persists because the earlier additional admission remains in the cumulative sum. Both curves plateau, but a flat segment could reflect a resource or operation rule as well as exhaustion. Read the individual trace to distinguish those causes. A different order of the same proposals could leave the same final tally with a different admission position.

Reading the example back into the architecture

Now consider a separately stored candidate produced for one task. A collector receives its trusted metadata and independently checks both shape and recipient eligibility before delivery. This next fixture returns a disposition. It neither creates a file nor sends a message. The worker rule list is untouched. The collector's structure check simply represents the result of a prior, independently declared validation. In practice, the producer's proof of origin is carried through the trusted runtime. The collector should not accept caller-supplied strings as trusted metadata.

PythonIn [14]
CollapseExpand
class ReleaseDecision(Enum):
    HELD_FOR_FORMAT = "Invalid format"
    HELD_FOR_ORIGIN = "Wrong task binding"
    HELD_FOR_ACCESS = "Recipient not allowed"
    ELIGIBLE = "Eligible for release"


@dataclass(frozen=True)
class HeldResult:
    task_id: str
    shape_valid: bool


def inspect_release(
    result: HeldResult, *, expected_task: str, recipient_allowed: bool
) -> ReleaseDecision:
    if not result.shape_valid:
        return ReleaseDecision.HELD_FOR_FORMAT
    if result.task_id != expected_task:
        return ReleaseDecision.HELD_FOR_ORIGIN
    if not recipient_allowed:
        return ReleaseDecision.HELD_FOR_ACCESS
    return ReleaseDecision.ELIGIBLE


safe_candidate = HeldResult("catalog-task-a", True)
release_rows = [
    inspect_release(
        HeldResult("catalog-task-a", False),
        expected_task="catalog-task-a",
        recipient_allowed=True,
    ),
    inspect_release(
        HeldResult("catalog-task-b", True),
        expected_task="catalog-task-a",
        recipient_allowed=True,
    ),
    inspect_release(
        safe_candidate, expected_task="catalog-task-a", recipient_allowed=False
    ),
    inspect_release(
        safe_candidate, expected_task="catalog-task-a", recipient_allowed=True
    ),
]
assert release_rows == list(ReleaseDecision)

The first two guards return before the collector consults the supplied recipient verdict. Case 3 holds a valid, correctly bound result because the recipient is not eligible. Case 4 returns eligibility for the same candidate with a permitted recipient. A second delivery check at the actual boundary can observe a new revocation. The fixture does not implement a storage service, a time window, actual identity verification, a delivery event or the consumer's interpretation of the fields. These limitations let the experiment concentrate on the independence of admission and release. The code describes eligibility, which is distinct from successful delivery by a subsequent component.

In a real trace, a worker could finish and its output could be held while an access review completes. That is an ordinary operating condition. Expose a meaningful state to the appropriate user, such as “result under review,” and give the assigned owner a reference to the artifact rather than putting sensitive details in a notification. When review ends, check the audience again and record the final disposition and the policy version. An operator can use the retained trace to distinguish production latency from time spent awaiting a policy decision.

Test changes independently. Start with the eligible synthetic recipient and change only its eligibility. Verify the input-view permission and worker counts do not change. Then change the worker's operation limits while leaving the collector decision unchanged. This pair of tests can identify accidental coupling between the policies. It does not replace checking integration paths that handle end-to-end cancellation, timeout, or resource cleanup. Keep those separate cases and version the assumptions under which you ran them.

Key Parameters

The example and the surrounding system use different parameters. In the example the declared operation table, finite resource grants, and starting call quotas govern admission. The collector uses an expected task identifier, a shape verdict, and an independent recipient verdict. The fixture processes a single list and returns a record in memory.

For a real service, document the policy revision, the resource identity provider, the authorized input view, the scratch lifetime, and the runtime's resource limits. State where each parameter is enforced and how its changes reach in-flight jobs. Prefer versioned policies or immutable grants whose identity can be inspected during a test. Separately record what a user sees when the requested service is denied or unavailable. Product messages, evidence checks, and technical enforcement can be owned by different teams.

The scope of an operation grant includes the named operation and its resource. The scope of a result release includes the authenticated audience and the exact current artifact, plus any applicable review. Increase a call quota only after checking that its resource scope and surrounding limits still work. A larger quota also leaves other denial reasons intact. In the example this is visible by replaying the same requests under two declarations that differ in one count.

Limitations and Impact

Containerization, process separation and virtualization can all be deployed incorrectly. State which components the workload shares and where enforcement occurs. Verify the settings that are live for the workload rather than treating a configuration file as a proof that the environment enforced it. A single synthetic admission trace cannot validate process isolation or cross-tenant storage separately. In a deployment, run purpose-built tests at each of the actual boundaries and capture their versions and conditions.

The toy quota treats one accepted request as one unit. A production operation unit should be defined to match the resource restrictions you are trying to enforce. The quanta of API usage, I/O, file count, memory, and wall time need not be related. A system that accepts a fixed number of requests can still be overwhelmed by one large allowed request. Bound expensive operations at the point that performs them and use a separate allowance for concurrent tasks. Normalize measurements by the right scope, such as requests per task or bytes per result, and preserve the scope with the recorded value.

A delivery requirement also has a service cost. Valid outcomes held for a missing role, expired review, or ambiguous origin need readable statuses and clear ownership. Repeated hold decisions for correctly configured requests are product failures worth investigating. Overly broad release to clear a backlog violates the purpose of the gate. Measure wait stages independently so the reliability team can shorten queues or improve evidence without weakening the result-release policy.

Keep retention proportional to the workload and explicitly designate who can view a stored trace. A reviewer does not need a copy of the document to confirm how many operation labels were admitted. Cases that need exact evidence can preserve a protected reference and a policy authorizing only the appropriate reviewer. Safe logs make behavior reconstructible. They also impose their own governance obligations because identifiers and relationships can themselves be sensitive.

The accepted workload examples use synthetic actors, non-executable operation labels, and a controlled result table. A production service should keep meaningful negative tests for each allowed effect, denial reasons, revoked access, and unavailable dependencies. Record which tests were performed under real isolation and which were policy-only. Then compare failures with the controls you actually changed. As the next chapter explains, component provenance plays a different role: it helps establish what implementation was loaded and reviewed. Runtime controls still apply to that implementation.

Summary

Start from a task's actual data, temporary state, and intended recipients. Keep credentials with trusted components that need them. Restrict the workload's reads, writes, requests, and resource use under the configured execution boundary. Route output through a collector that enforces the current audience and artifact policy.

A declared policy makes the desired design visible. Effective checks establish what the deployed runtime did. Keep result eligibility and delivery separate, and record admission, completion, and custody as different events. Use targeted harmless cases with changed grants and controlled resource counts. The eight-proposal fixture shows a single enlarged quota permitting one more request within its existing scope. Its independent release checks show a correctly bound result being held when the recipient's authorization is absent.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about credential isolation, sandboxing, and safe execution boundaries.

Secrets, Sandboxes, and Safe Execution

Question 1 of 80 of 8 completed
According to the chapter, why is short session duration NOT a complete credential policy on its own?
Join the discussionAsk a question or share what you learned.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

A different angle
All writing
Language AI Handbook · Vol. 19

Tool, Retrieval, and Memory Poisoning

Learn how tool schemas, retrieval snapshots, and durable memory lose integrity. Validate, authorize, and quarantine records across boundaries.

34 min read
Language AI Handbook · Vol. 19

Agent Supply Chains and Protocol Security

Build a release gate for agent tool supply chains. Verify artifacts, detect drift, and enforce revocation and least privilege.

35 min read
Language AI Handbook · Vol. 19

Audit, Detection, and Incident Response

Design tamper-evident audit trails, build layered detectors that survive base rates, and run incident response with kill switches and evidence preservation.

50 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026secretssandboxes, author = {Michael Brenndoerfer}, title = {Secrets, Sandboxes, and Safe Execution}, year = {2026}, url = {https://mbrenndoerfer.com/writing/secrets-sandboxes-safe-execution-credential-isolation}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-12-03} }
APAAcademic
Michael Brenndoerfer (2026). Secrets, Sandboxes, and Safe Execution. Retrieved from https://mbrenndoerfer.com/writing/secrets-sandboxes-safe-execution-credential-isolation
MLAAcademic
Michael Brenndoerfer. "Secrets, Sandboxes, and Safe Execution." 2026. Web. December 3, 2026. <https://mbrenndoerfer.com/writing/secrets-sandboxes-safe-execution-credential-isolation>.
CHICAGOAcademic
Michael Brenndoerfer. "Secrets, Sandboxes, and Safe Execution." Accessed December 3, 2026. https://mbrenndoerfer.com/writing/secrets-sandboxes-safe-execution-credential-isolation.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Secrets, Sandboxes, and Safe Execution'. Available at: https://mbrenndoerfer.com/writing/secrets-sandboxes-safe-execution-credential-isolation (Accessed: December 3, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Secrets, Sandboxes, and Safe Execution. https://mbrenndoerfer.com/writing/secrets-sandboxes-safe-execution-credential-isolation
Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy