Skip to content
Agent Field Notes
Course contentsExpand a topic to choose a lesson.

SYSTEMATIC LEARNING / FOUR-LEVEL COURSE

Isolate resources and capabilities when executing code

Examine files, networks, processes, credentials, and resource limits.

Learning objectives: Code execution risk depends on the capabilities the process actually possesses. Restrictions must be enforced by the execution environment over files, networks, credentials, process trees, and resources, and conventions in the prompt are not a substitute for isolation.

Content checked: 2026-10-30 · Each level has independent explanations, tasks and inspections

Choose a starting point based on your familiarity with this topic. Current level: Design · Explain the trade-offs. After completing the task, continue to the next level. Reading and self-checks alone do not establish mastery.

On this level

Review the prerequisites

Suitable for: Backend developers learning Agent applications.

Isolate resources and capabilities when executing code
Code execution risk depends on the capabilities the process actually possesses. Restrictions must be enforced by the execution environment over files, networks, credentials, process trees, and resources, and conventions in the prompt are not a substitute for isolation.

How does the mechanism work?

Step-by-step explanation
  1. What are the risks of mounting a Docker socket?

    Access to control sockets can expand a container's capabilities, so describe those capabilities explicitly.

  2. What should I do if the main process exits after the code opens a background subprocess?

    Execution lifetime limits need to cover the entire process tree.

  3. Can restricting only file paths prevent symlinks from going out of bounds?

    File access restrictions must account for path resolution and race conditions.

Design · Explain the trade-offs

Changed constraints and integration decision

Objectives of this level: manifest capability and three independent resource bounds — Apply a changed constraint and scope the proposed platform adapter.

Visual guide · Admission is before enforcement

Admission is before enforcement

The local function plans admission only. An executor must enforce mounts, network, credentials, process-tree lifetime and limits; a prompt cannot enforce them. Select the figure to open it at full size.

Changed constraints and integration decision

Change the allowed capabilities to read_csv only: a request still containing write_chart must deny/capability. Then lower max_memory_mb to63: the original64MB request must deny/memory_budget. Separately design a worker adapter with enforced process-tree termination, credential/network/mount policy and artifact extraction checks; leave each unexecuted attack/lifecycle test planned. Deliver a new-input JSON/result pair, an adapter boundary sketch and a short ADR comparing two alternatives, rejection/reconciliation behavior, ownership and reversal conditions. State implemented_local versus planned; connect to the same after-sales proposal/approval/merchant/receipt chain without inventing existing runtime features. Save the following block as coding_sandbox_boundary_variants.py beside your student module, then run it after implementation. It imports your own function, reads the public complete inputs and changes the declared fields; these two rule-visible variants are not unseen assessment.

import copy, json
from pathlib import Path
from coding_sandbox_boundary_student import sandbox_plan

checks = json.loads(Path("cases/coding-sandbox-boundary.json").read_text())["checks"]

payload = copy.deepcopy(checks[0]["input"])
payload["policy"]["capabilities"] = ["read_csv"]
before = copy.deepcopy(payload)
try:
    actual = sandbox_plan(payload)
except ValueError as exc:
    actual = "ValueError:" + str(exc)
assert payload == before, "input_mutation"
expected = {'decision': 'deny', 'reason': 'capability'}
assert actual == expected, (actual, expected)
print(json.dumps({"variant":1,"input":payload,"actual":actual}, sort_keys=True))

payload = copy.deepcopy(checks[0]["input"])
payload["policy"]["max_memory_mb"] = 63
before = copy.deepcopy(payload)
try:
    actual = sandbox_plan(payload)
except ValueError as exc:
    actual = "ValueError:" + str(exc)
assert payload == before, "input_mutation"
expected = {'decision': 'deny', 'reason': 'memory_budget'}
assert actual == expected, (actual, expected)
print(json.dumps({"variant":2,"input":payload,"actual":actual}, sort_keys=True))
python3 coding_sandbox_boundary_variants.py

Starting point and evidence

Download the source-only ZIP, extract it, and work in extended-agent-practice-v1 with lab_runner.py beside cases/. Python3.9+ standard library; no model, cloud, network or business request is made. Scaffold once in a fresh directory; it refuses overwrite. Reuse your module in later tracks. The empty template must exit1 on grade; scaffold exits0, overwrite exits2. Grade exits0 only when every fixed case passes and otherwise exits1.

  • https://ai.lwkjob.com/downloads/extended-agent-practice-v1.zip
  • https://ai.lwkjob.com/lab/extended-practice/lab_runner.py
  • https://ai.lwkjob.com/lab/extended-practice/cases/coding-sandbox-boundary.json
python3 lab_runner.py scaffold --course coding-sandbox-boundary --out coding_sandbox_boundary_student.py
python3 lab_runner.py grade --course coding-sandbox-boundary --module coding_sandbox_boundary_student.py --out coding_sandbox_boundary_before.json

This course has10 public fixed cases. Each calls your sandbox_plan(payload), records input/expected/actual/error, strict JSON types, input immutability and no output-container aliases, plus module/runner/cases SHA and Python version. Inputs are complete JSON fixtures. Unknown or missing keys, null outside explicitly allowed fields, wrong types, duplicate IDs/list members where uniqueness is required raise ValueError:input_shape; booleans are not integers. Exceptions match exact class:message. Return fresh JSON values without mutating input.

Trusted identity, approvals, receipts and policy/index metadata are fixtures assembled by the exercise. In a real service the server must obtain them from authenticated/current authority sources; accepting client JSON with these labels does not authenticate it. The function is a decision over that trusted snapshot, not the adapter or race-proof enforcement.

Local function contract

payload has exactly principal/request/policy. principal={tenant:nonempty str,enabled:strict bool}. request={tenant:nonempty str,capabilities:unique nonempty str list,cpu_ms:positive strict int,memory_mb:positive strict int,artifact_bytes:nonnegative strict int}. policy={capabilities:unique nonempty str list,max_cpu_ms:positive strict int,max_memory_mb:positive strict int,max_artifact_bytes:nonnegative strict int}. Empty capability lists are legal. Validate all nested shapes first. Then deny in this order: tenant_mismatch, principal_disabled, capability (requested set is not a subset), cpu_budget, memory_budget, artifact_budget. Equality with a maximum is allowed. Return exactly decision and reason: deny plus the first reason, or allow/bounded_manifest. No execution or cleanup occurs.

def sandbox_plan(payload):
    raise NotImplementedError("Implement the public local contract")

Three reviewable inputs

at-all-limits

{
  "principal": {
    "tenant": "acme",
    "enabled": true
  },
  "request": {
    "tenant": "acme",
    "capabilities": [
      "read_csv",
      "write_chart"
    ],
    "cpu_ms": 100,
    "memory_mb": 64,
    "artifact_bytes": 1000
  },
  "policy": {
    "capabilities": [
      "read_csv",
      "write_chart"
    ],
    "max_cpu_ms": 100,
    "max_memory_mb": 64,
    "max_artifact_bytes": 1000
  }
}

Expected / 预期: {"decision": "allow", "reason": "bounded_manifest"}

cpu-over

{
  "principal": {
    "tenant": "acme",
    "enabled": true
  },
  "request": {
    "tenant": "acme",
    "capabilities": [
      "read_csv",
      "write_chart"
    ],
    "cpu_ms": 101,
    "memory_mb": 64,
    "artifact_bytes": 1000
  },
  "policy": {
    "capabilities": [
      "read_csv",
      "write_chart"
    ],
    "max_cpu_ms": 100,
    "max_memory_mb": 64,
    "max_artifact_bytes": 1000
  }
}

Expected / 预期: {"decision": "deny", "reason": "cpu_budget"}

host-socket

{
  "principal": {
    "tenant": "acme",
    "enabled": true
  },
  "request": {
    "tenant": "acme",
    "capabilities": [
      "host_socket"
    ],
    "cpu_ms": 100,
    "memory_mb": 64,
    "artifact_bytes": 1000
  },
  "policy": {
    "capabilities": [
      "read_csv",
      "write_chart"
    ],
    "max_cpu_ms": 100,
    "max_memory_mb": 64,
    "max_artifact_bytes": 1000
  }
}

Expected / 预期: {"decision": "deny", "reason": "capability"}

Responsibility and limits

Junior delivers a strict manifest decision and boundary tests. Intermediate connects a proposed admission adapter to the chart stage with observable rejection and per-task cleanup ownership. Senior compares process/container/VM boundaries and specifies host control-plane isolation, resource reservations and artifact failure windows. Only the pure decision is implemented here; actual OS isolation remains unverified. The four tracks are learning activities, not job ranks. Fixed authored examples and known repairs cannot prove independent diagnosis, real-world security or hiring readiness. Keep source, initial failure, personal diff, same-input rerun and a declared changed-condition result. A reviewer-new complete contract and observed personal work are separate; disclose assistance. The five-second worker guard is not a performance SLO or hostile-code sandbox.

From policy function to an executed process boundary

The production integration course adds a separate actual subprocess exercise: an environment allowlist omits a parent sentinel secret, a wall-clock deadline terminates the child, and the parent reaps it. This is stronger evidence than deciding allow/deny in this policy function, but it still does not deny arbitrary filesystem or network access. A hostile-code deployment needs a separately verified container/microVM or OS sandbox, credential proxy, mount/egress policy and lifecycle tests. Recipes without execution remain design proposals.

code example

Changed constraints and integration decision — host-socket

Additional review: explain why this case follows the contract and which single-field change would alter the branch. Public case: host-socket Expected / 预期: {"decision": "deny", "reason": "capability"} https://ai.lwkjob.com/lab/extended-practice/cases/coding-sandbox-boundary.json

Acceptance task for this level

manifest capability and three independent resource bounds — Execute the declared changed inputs and deliver result pairs plus an adapter/ADR with implemented versus planned boundaries.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

What remains after every case is green?

Further explanations and practice

When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.

All linked explanations and exercises (1 )

Sources and verification scope

The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.