Part III — Advanced Systems · Chapter 14 · Lesson 5 of 5 · 16 min read
Chapter 14 Checkpoint: Hardened Policy Sandbox
Checkpoint level: Advanced
Purpose: Build a multi-tenant service that accepts customer-uploaded PeaLang rules, admits them through static checks, runs them with least privilege and tight limits, charges every run against a tenant budget, records tamper-evident audit evidence, and proves through adversarial tests that the host stays in control.
Release note: configuration keys, option names, exception classes, and audit fields follow the illustrative API used in Lessons 1–4 of this chapter. Verify exact names against your installed v0.63 release before you publish or teach from this checkpoint.
Checkpoint outcomes
By completing this checkpoint, you will demonstrate that you can:
- write a threat model that links each threat to a control and a test;
- reject unsafe uploads before any code runs;
- grant only the capabilities and host functions a reviewed script needs;
- apply per-run limits across time, instructions, memory, recursion, stack, collections, output, HTTP, and file reads;
- share capacity fairly through tenant budgets with admission checks;
- bind tenant identity on the host so scripts cannot cross tenant boundaries;
- validate every returned decision and fail closed;
- map failures to stable, non-revealing error codes;
- write hash-chained audit records without secrets or personal data; and
- prove the sandbox works with an adversarial test suite.
Scenario
A logistics platform lets each shipper upload a shipping-surcharge rule written in PeaLang. For every quote request, the platform calls the shipper’s rule with a portable shipment map and receives a surcharge decision. Shippers are external companies: most rules are written carefully, some contain accidental loops or huge lists, and a small number may be deliberately hostile.
The rule may look up the shipper’s own zone table through one host function. It may not read files, call the network, start processes, or see any other shipper’s data. The platform owns identity, the final price, persistence, and billing.
Input contract. The host passes this map to the exported function surcharge(shipment):
| Field | Type | Constraint |
|---|---|---|
| shipment_id | string | Matches S followed by 8 digits |
| weight_kg | float | Greater than 0 and at most 1,000 |
| distance_km | float | Greater than 0 and at most 20,000 |
| service | string | One of standard, express, freight |
| hazardous | boolean | Required |
| destination_zone | string | Two uppercase letters |
Output contract. The script must return a map containing surcharge (a number from 0 to 500), reason (one of the shipper’s registered reason codes), and optionally note (a string of at most 120 characters). Any other shape is rejected by the host.
14C.1 Threat model
Start with the threats, not the code. Every row must map to at least one control you build and one test you run.
| ID | Threat | Example | Control | Test |
|---|---|---|---|---|
| T1 | Runaway compute | while true {} | Instruction and time limits | A1 |
| T2 | Memory exhaustion | A list of one million maps | Memory and collection limits | A2 |
| T3 | Deep recursion | Unbounded self-call | Recursion and stack limits | A3 |
| T4 | Output flooding | Printing in a hot loop | Output-byte limit | A4 |
| T5 | Exfiltration | Sending shipments to a URL | Admission refuses std.http; zero HTTP budget | A5, AD2 |
| T6 | Host file access | Reading configuration files | Admission refuses std.fs; zero file-read budget | A6, AD3 |
| T7 | Process escape | Running a shell command | Admission refuses std.process; process disabled | AD4 |
| T8 | Cross-tenant read | Passing another shipper’s ID | Tenant bound in host closure | A7 |
| T9 | Ungranted host power | Calling an unregistered function | Permission check raises PeaPermissionError | A8 |
| T10 | Malicious result | Negative or huge surcharge | Host-side validation, fail closed | A9, A10 |
| T11 | Noisy neighbour | One tenant exhausting shared capacity | Per-tenant budget with admission | B1, B2 |
| T12 | Evidence tampering | Editing an audit line | Hash-chained audit records | E1 |
| T13 | Information leak in errors | Stack trace returned to caller | Stable error codes; details only in internal log | A11 |
14C.2 Requirements
| Area | Requirement |
|---|---|
| Admission | Parse, check, and lint every upload; refuse imports outside the allow-list; refuse sources over 32 KB; require exactly one export named surcharge |
| Storage | Store admitted scripts by SHA-256 of the compiled bytecode; never load the raw upload |
| Capabilities | Only log and the zone.read host permission |
| Per-run limits | 50 ms, 200,000 instructions, 8 MB memory, recursion 32, stack 256, collections 5,000 items, output 8 KB, HTTP 0, file reads 0 |
| Budgets | Each tenant: 20,000,000 instructions and 2,000 runs per 60-second window |
| Tenant isolation | Fresh runtime per tenant; zone lookup bound to the tenant on the host side |
| Boundary validation | Validate input before the call and output after it; fail closed |
| Error mapping | Stable codes for permission, resource, budget, script, and validation failures; no stack traces in responses |
| Audit | One hash-chained JSON line per run, no shipment contents or personal data |
| Isolation tier | In-process for reviewed shippers; worker process for unreviewed shippers |
| Testing | All adversarial, budget, and evidence tests pass in CI |
14C.3 Architecture
The service has five layers. Each layer assumes the one before it may have failed.
- Admission runs once per upload and decides whether code may ever execute.
- Policy builds a runtime with the minimum permissions and host functions for one tenant.
- Budget gate checks the tenant’s remaining capacity before each run.
- Execution calls the exported function under per-run limits and captures a usage snapshot.
- Boundary and evidence validates the result, maps failures to codes, and appends an audit record.
Suggested project layout:
sandbox_service/
policy/sandbox.toml
policy/allowed_imports.txt
service/admission.py
service/runtime_factory.py
service/budgets.py
service/audit.py
service/evaluate.py
service/api.py
approved/<tenant_id>/<sha256>.pea
tests/fixtures/hostile/*.pea
tests/test_adversarial.py
tests/test_budgets.py
tests/test_evidence.py
14C.4 Sandbox policy
Keep the policy in version control so every change is reviewed. The service loads it at start-up and refuses to start if any limit is missing.
# policy/sandbox.toml
[sandbox.shipper_rules]
capabilities = ["log"]
host_functions = ["host.zone_rate"]
[sandbox.shipper_rules.limits]
time_ms = 50
instructions = 200_000
memory_bytes = 8_388_608
max_recursion = 32
max_stack_depth = 256
max_collection_len = 5_000
output_bytes = 8_192
http_calls = 0
file_reads = 0
[budgets.shipper_rules]
window_seconds = 60
instructions = 20_000_000
runs = 2_000
The allow-list file contains one module per line:
std.math
std.str
std.list
std.map
std.log
std.json, std.regex, and std.datetime are deliberately absent. The rule does not need them, and every allowed module is one more surface you must defend.
14C.5 Admission
Admission runs once per upload, before any code executes. It returns either an admitted record or a list of problems that the shipper can fix. Nothing that fails admission is ever stored in the approved location.
# service/admission.py
import hashlib
from pathlib import Path
from pealang import tooling
MAX_SOURCE_BYTES = 32_768
ALLOWED = set(Path("policy/allowed_imports.txt").read_text().split())
REQUIRED_EXPORTS = {"surcharge"}
def admit(tenant_id: str, source: str) -> dict:
problems = []
if len(source.encode("utf-8")) > MAX_SOURCE_BYTES:
problems.append("SOURCE_TOO_LARGE")
report = tooling.analyze_source(source, strict=True)
problems += [f"CHECK:{d.code}:{d.line}" for d in report.errors]
problems += [f"LINT:{d.code}:{d.line}" for d in report.warnings]
for imp in report.imports:
if imp not in ALLOWED:
problems.append(f"IMPORT_DENIED:{imp}")
if set(report.exports) != REQUIRED_EXPORTS:
problems.append("EXPORTS_MUST_BE_EXACTLY_surcharge")
if problems:
return {"admitted": False, "problems": problems}
digest = hashlib.sha256(report.bytecode).hexdigest()
target = Path("approved") / tenant_id / f"{digest}.pea"
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(source, encoding="utf-8")
return {"admitted": True, "sha256": digest}
Three design points matter. First, warnings are treated as errors because untrusted code gets no benefit of the doubt. Second, problem codes are stable strings, so a shipper portal can show helpful messages without exposing internal tooling output. Third, the storage key is the hash of the compiled bytecode, so the service always knows exactly which admitted artifact ran.
Note: tooling.analyze_source stands for the static-analysis entry point used in Lesson 4. Confirm its exact name and return fields in your installed release.
14C.6 Tenant runtime factory
Each tenant receives its own runtime. The zone-rate lookup is a closure that captures the tenant on the host side, so the script can ask only about its own shipper’s zones.
# service/runtime_factory.py
import re
from pealang import PeaRuntime, RuntimeOptions
SHIPPER_OPTIONS = RuntimeOptions(
permissions=frozenset({"zone.read", "log"}),
max_execution_ms=50,
max_instructions=200_000,
max_memory_bytes=8 * 1024 * 1024,
max_call_depth=32,
max_stack_depth=256,
max_collection_items=5_000,
max_output_bytes=8_192,
max_http_requests=0,
max_file_read_bytes=0,
allow_process=False,
)
ZONE = re.compile(r"[A-Z]{2}")
def runtime_for(tenant_id: str, zone_store) -> PeaRuntime:
rt = PeaRuntime(SHIPPER_OPTIONS)
calls = {"n": 0}
def zone_rate(zone: str) -> float:
calls["n"] += 1
if calls["n"] > 20:
raise ValueError("ZONE_LOOKUP_LIMIT")
if not isinstance(zone, str) or not ZONE.fullmatch(zone):
raise ValueError("INVALID_ZONE")
return float(zone_store.rate(tenant_id, zone) or 0.0)
rt.register_function("host.zone_rate", zone_rate, "zone.read")
return rt
The per-run call cap of 20 stops a loop inside the script from turning the lookup into a load test against the zone store. Create a fresh runtime per request when scripts may keep mutable top-level state; otherwise cache one per tenant and reset the call counter before each run.
14C.7 Budget gate
Per-run limits stop one bad run. Budgets stop one tenant from exhausting shared capacity through many acceptable runs. The gate checks remaining capacity before a run starts and charges actual usage afterwards.
# service/budgets.py
import time
from dataclasses import dataclass, field
@dataclass
class Window:
started: float = field(default_factory=time.monotonic)
instructions: int = 0
runs: int = 0
class BudgetGate:
def __init__(self, window_s: int, max_instructions: int,
max_runs: int, per_run_instructions: int):
self.window_s = window_s
self.max_instructions = max_instructions
self.max_runs = max_runs
self.per_run = per_run_instructions
self.windows: dict[str, Window] = {}
def _window(self, tenant_id: str) -> Window:
w = self.windows.get(tenant_id)
if w is None or time.monotonic() - w.started >= self.window_s:
w = Window()
self.windows[tenant_id] = w
return w
def admit(self, tenant_id: str) -> bool:
w = self._window(tenant_id)
if w.runs >= self.max_runs:
return False
return self.max_instructions - w.instructions >= self.per_run
def charge(self, tenant_id: str, instructions: int) -> None:
w = self._window(tenant_id)
w.runs += 1
w.instructions += instructions
Admission compares remaining capacity with the per-run limit, not with the average run. A tenant with 150,000 instructions left cannot start a run that is allowed to use 200,000, because that run could overspend the window. Charge failed and limited runs too: a script that hits its instruction limit still consumed capacity.
This in-memory gate suits a single service instance. When the service runs as several replicas, move the counters to a shared store with atomic increments, as Chapter 21 shows for distributed limits.
14C.8 The evaluation path
Every quote request follows the same path: validate input, check budget, load the admitted artifact, run under limits, charge usage, validate output, and write evidence. Each step either succeeds or produces a stable error code.
# service/evaluate.py
import re
from pathlib import Path
from pealang import PeaPermissionError, PeaResourceLimitError, PeaRuntimeError
SHIPMENT_ID = re.compile(r"S[0-9]{8}")
SERVICES = {"standard", "express", "freight"}
class Rejected(Exception):
def __init__(self, code: str, status: int):
self.code, self.status = code, status
def validate_shipment(s: dict) -> dict:
try:
clean = {
"shipment_id": str(s["shipment_id"]),
"weight_kg": float(s["weight_kg"]),
"distance_km": float(s["distance_km"]),
"service": str(s["service"]),
"hazardous": bool(s["hazardous"]),
"destination_zone": str(s["destination_zone"]),
}
except (KeyError, TypeError, ValueError):
raise Rejected("INVALID_INPUT", 400)
if not SHIPMENT_ID.fullmatch(clean["shipment_id"]):
raise Rejected("INVALID_INPUT", 400)
if not 0 < clean["weight_kg"] <= 1_000:
raise Rejected("INVALID_INPUT", 400)
if not 0 < clean["distance_km"] <= 20_000:
raise Rejected("INVALID_INPUT", 400)
if clean["service"] not in SERVICES:
raise Rejected("INVALID_INPUT", 400)
return clean
The input map is rebuilt from known fields only. Extra keys sent by a caller never reach the script, and every value is converted to the exact portable type the contract promises.
def validate_decision(raw, reasons: set[str]) -> dict:
if not isinstance(raw, dict):
raise Rejected("INVALID_DECISION", 502)
amount = raw.get("surcharge")
if isinstance(amount, bool) or not isinstance(amount, (int, float)):
raise Rejected("INVALID_DECISION", 502)
if not 0 <= amount <= 500:
raise Rejected("INVALID_DECISION", 502)
if raw.get("reason") not in reasons:
raise Rejected("INVALID_DECISION", 502)
note = raw.get("note", "")
if not isinstance(note, str) or len(note) > 120:
raise Rejected("INVALID_DECISION", 502)
return {"surcharge": round(float(amount), 2),
"reason": raw["reason"], "note": note}
def evaluate(tenant, shipment, gate, zone_store, audit) -> dict:
clean = validate_shipment(shipment)
if not gate.admit(tenant.id):
raise Rejected("BUDGET_EXHAUSTED", 429)
source = Path(tenant.approved_path).read_text("utf-8")
rt = runtime_for(tenant.id, zone_store)
outcome, used = "OK", 0
try:
module = rt.load(source, source_name=tenant.artifact_sha256)
raw = module.call("surcharge", clean)
used = rt.last_result.instructions
return validate_decision(raw, tenant.reason_codes)
except PeaPermissionError:
outcome = "PERMISSION_DENIED"
raise Rejected("PEA_PERMISSION_DENIED", 403)
except PeaResourceLimitError:
outcome = "RESOURCE_LIMIT"
raise Rejected("PEA_RESOURCE_LIMIT", 429)
except PeaRuntimeError:
outcome = "SCRIPT_ERROR"
raise Rejected("PEA_EXTENSION_ERROR", 400)
except Rejected as r:
outcome = r.code
raise
finally:
used = used or getattr(rt.last_result, "instructions", 0)
gate.charge(tenant.id, used)
audit.append(tenant, clean["shipment_id"], outcome, rt.last_result)
Two details matter. The finally block runs on every path, so budget charges and audit records cannot be skipped by a failure. And an invalid script result maps to 502: the caller’s request was valid, but a dependency the platform hosts returned something unusable.
| Code | Status | Meaning |
|---|---|---|
| INVALID_INPUT | 400 | The caller sent a shipment outside the contract |
| PEA_EXTENSION_ERROR | 400 | The rule raised an error for this input |
| PEA_PERMISSION_DENIED | 403 | The rule attempted an ungranted capability |
| PEA_RESOURCE_LIMIT | 429 | The rule exceeded a per-run limit |
| BUDGET_EXHAUSTED | 429 | The tenant’s window budget is spent |
| INVALID_DECISION | 502 | The rule returned an out-of-contract result |
| PEA_INTERNAL_ERROR | 500 | Unexpected host failure |
14C.9 Audit chain
Each run appends one JSON line. Every line includes the hash of the previous line, so editing or deleting any record breaks the chain from that point onward. Records contain identifiers and measurements, never shipment contents, zone rates, or script source.
# service/audit.py
import hashlib, json, time
class AuditLog:
def __init__(self, path: str):
self.path = path
self.prev = "0" * 64
def append(self, tenant, shipment_id, outcome, usage) -> None:
record = {
"ts": round(time.time(), 3),
"tenant": tenant.id,
"artifact": tenant.artifact_sha256,
"shipment_ref": hashlib.sha256(shipment_id.encode()).hexdigest()[:16],
"outcome": outcome,
"instructions": getattr(usage, "instructions", None),
"elapsed_ms": getattr(usage, "elapsed_ms", None),
"prev": self.prev,
}
line = json.dumps(record, sort_keys=True, separators=(",", ":"))
self.prev = hashlib.sha256(line.encode()).hexdigest()
with open(self.path, "a", encoding="utf-8") as f:
f.write(line + "\n")
def verify_chain(path: str) -> int:
prev = "0" * 64
with open(path, encoding="utf-8") as f:
for n, line in enumerate(f, start=1):
if json.loads(line)["prev"] != prev:
return n
prev = hashlib.sha256(line.rstrip("\n").encode()).hexdigest()
return 0
verify_chain returns 0 for an intact log or the first line number where tampering is detected. The shipment reference is a truncated hash, so investigators can correlate a record with a known shipment without storing the identifier itself.
A hash chain proves that records were not altered after writing; it does not prove the writer was honest. For stronger guarantees, periodically sign the latest hash and store it outside the service, as Chapter 20 does for model registries.
14C.10 A well-behaved shipper rule
Use this rule as the baseline that every control must allow. It applies a hazardous-goods surcharge, a heavy-parcel surcharge, and a zone rate, then caps the total.
# shipper_rules/acme_surcharge.pea
import std.math
const max_surcharge = 500
const hazardous_fee = 40
const heavy_threshold_kg = 30
const heavy_rate_per_kg = 0.8
function heavy_part(weight) {
if weight <= heavy_threshold_kg {
return 0
}
return (weight - heavy_threshold_kg) * heavy_rate_per_kg
}
function surcharge(shipment) {
let total = 0
let reason = "NONE"
if shipment.hazardous {
total += hazardous_fee
reason = "HAZARDOUS"
}
let heavy = heavy_part(shipment.weight_kg)
if heavy > 0 {
total += heavy
if reason == "NONE" { reason = "HEAVY" }
}
let zone = host.zone_rate(shipment.destination_zone)
total += zone * shipment.distance_km / 1000
if total > max_surcharge {
total = max_surcharge
reason = "CAPPED"
}
return {"surcharge": std.math.round(total, 2), "reason": reason}
}
export surcharge
Register ACME’s reason codes as NONE, HAZARDOUS, HEAVY, and CAPPED. The host rejects any other code even if the arithmetic is correct.
14C.11 Required test matrix
Group tests by what they prove. Functional tests show that legitimate rules still work. Adversarial tests show that each threat in 14C.1 is contained. Budget and evidence tests show that fairness and auditability hold under load and tampering.
Functional tests
| ID | Input | Expected result |
|---|---|---|
| F1 | Standard, 10 kg, not hazardous, zone with rate 0 | surcharge 0, reason NONE |
| F2 | Hazardous, 10 kg | surcharge includes 40, reason HAZARDOUS |
| F3 | Not hazardous, 50 kg | heavy part 16, reason HEAVY |
| F4 | Hazardous, 1,000 kg, long distance | surcharge 500, reason CAPPED |
| F5 | Weight exactly 30 kg | no heavy part (boundary) |
Adversarial tests
| ID | Hostile behaviour | Expected outcome |
|---|---|---|
| A1 | while true {} | PEA_RESOURCE_LIMIT, host healthy |
| A2 | Builds a list of 1,000,000 items | PEA_RESOURCE_LIMIT |
| A3 | Unbounded recursion | PEA_RESOURCE_LIMIT |
| A4 | Prints inside a 100,000-step loop | PEA_RESOURCE_LIMIT (output) |
| A5 | Calls std.http at run time | PEA_PERMISSION_DENIED |
| A6 | Calls std.fs at run time | PEA_PERMISSION_DENIED |
| A7 | Passes another tenant’s zone code | Only own tenant’s rate returned |
| A8 | Calls an unregistered host function | PEA_PERMISSION_DENIED |
| A9 | Returns a negative surcharge | INVALID_DECISION (502) |
| A10 | Returns an unregistered reason code | INVALID_DECISION (502) |
| A11 | Raises an error with a long internal message | PEA_EXTENSION_ERROR; no message text in response |
| A12 | Calls host.zone_rate 50 times | PEA_EXTENSION_ERROR after the 20-call cap |
Admission tests
| ID | Upload | Expected problems |
|---|---|---|
| AD1 | Source of 40 KB | SOURCE_TOO_LARGE |
| AD2 | Imports std.http | IMPORT_DENIED:std.http |
| AD3 | Imports std.fs | IMPORT_DENIED:std.fs |
| AD4 | Imports std.process | IMPORT_DENIED:std.process |
| AD5 | Exports surcharge and debug | EXPORTS_MUST_BE_EXACTLY_surcharge |
| AD6 | Syntax error on line 7 | CHECK code with line 7 |
Budget and evidence tests
| ID | Scenario | Expected outcome |
|---|---|---|
| B1 | 2,001 runs inside one window | Run 2,001 returns BUDGET_EXHAUSTED |
| B2 | Tenant X exhausts its budget | Tenant Y still served normally |
| B3 | Window expires | Tenant X admitted again |
| E1 | Edit one audit line | verify_chain returns that line number |
| E2 | Delete one audit line | verify_chain detects the break |
| E3 | Inspect all records | No shipment ID, rate, or source text present |
14C.12 Sample test code
Store each hostile script as a fixture so the suite reads like a catalogue of attacks. A shared helper builds a tenant, runs one shipment, and returns either the decision or the rejection code.
# tests/test_adversarial.py
import pytest
from service.evaluate import evaluate, Rejected
from tests.helpers import make_tenant, FakeZones, MemoryAudit, fresh_gate
SHIPMENT = {"shipment_id": "S00000001", "weight_kg": 12.0,
"distance_km": 800.0, "service": "standard",
"hazardous": False, "destination_zone": "DE"}
def run(fixture: str):
tenant = make_tenant("t1", fixture)
try:
return evaluate(tenant, SHIPMENT, fresh_gate(), FakeZones(), MemoryAudit())
except Rejected as r:
return r.code
@pytest.mark.parametrize("fixture,code", [
("hostile/infinite_loop.pea", "PEA_RESOURCE_LIMIT"),
("hostile/huge_list.pea", "PEA_RESOURCE_LIMIT"),
("hostile/deep_recursion.pea", "PEA_RESOURCE_LIMIT"),
("hostile/print_flood.pea", "PEA_RESOURCE_LIMIT"),
("hostile/unregistered_host_call.pea", "PEA_PERMISSION_DENIED"),
("hostile/negative_surcharge.pea", "INVALID_DECISION"),
("hostile/unknown_reason.pea", "INVALID_DECISION"),
])
def test_hostile_script_is_contained(fixture, code):
assert run(fixture) == code
def test_host_still_healthy_after_attacks():
for _ in range(3):
run("hostile/infinite_loop.pea")
assert run("acme_surcharge.pea")["reason"] in {"NONE", "HAZARDOUS", "HEAVY", "CAPPED"}
def test_error_details_not_leaked():
result = run("hostile/raise_with_secret_text.pea")
assert result == "PEA_EXTENSION_ERROR"
# tests/test_evidence.py
from service.audit import AuditLog, verify_chain
def test_tampering_is_detected(tmp_path, tenant, usage):
path = tmp_path / "audit.jsonl"
log = AuditLog(str(path))
for i in range(5):
log.append(tenant, f"S0000000{i}", "OK", usage)
lines = path.read_text().splitlines()
lines[2] = lines[2].replace('"OK"', '"PERMISSION_DENIED"')
path.write_text("\n".join(lines) + "\n")
assert verify_chain(str(path)) == 4
Editing line 3 changes its hash, so the mismatch is detected at line 4, the first record whose prev field no longer matches. Explain this off-by-one in your evidence report; reviewers often expect the edited line number itself.
14C.13 Acceptance criteria
- Every threat in 14C.1 maps to at least one control and one passing test.
- All functional, adversarial, admission, budget, and evidence tests pass in CI.
- No uploaded source is ever loaded directly; only admitted artifacts run.
- The runtime grants only zone.read and log; HTTP, file-read, and process budgets are zero.
- A hostile run never leaves the service unable to serve the next request.
- Responses never contain stack traces, host paths, script source, or zone rates.
- Audit records contain no shipment identifiers or rates, and the chain verifies.
- The policy file and allow-list are version-controlled and reviewed.
14C.14 Submission package
- the threat model from 14C.1, extended with any threats you added;
- policy and allow-list files;
- the service source: admission, runtime factory, budget gate, evaluation, and audit;
- the reference rule and every hostile fixture;
- test results for all test groups;
- a sample audit log and its verification output before and after tampering;
- an isolation decision for internal, partner, and anonymous shippers; and
- a one-page residual-risk statement describing what the sandbox does not protect against.
14C.15 Assessment rubric
| Area | Evidence of mastery |
|---|---|
| Threat modelling | Threats are specific, ranked, and each links to a control and a test. |
| Admission | Unsafe uploads are refused with clear, stable problem codes. |
| Least privilege | Only reviewed capabilities are granted; tenant identity is bound on the host. |
| Resource control | Per-run limits and window budgets both work and are justified by measurement. |
| Boundary validation | Inputs are rebuilt from known fields; outputs fail closed. |
| Error handling | Failures map to stable codes without leaking internals. |
| Evidence | Audit records are minimal, chained, and verifiable. |
| Testing | Hostile fixtures cover every threat and run in CI. |
| Judgement | Residual risks and isolation choices are explained honestly. |
Completion standard: every acceptance criterion is met, every test passes, and the residual-risk statement names at least three risks that remain and how they would be reduced.
14C.16 Reflection questions
- Which layer caught the most hostile fixtures, and was that the layer you expected?
- Which limit was hardest to choose, and what measurement settled it?
- How would your design change if shippers could call their own HTTP endpoints?
- What would an attacker learn from your error responses and audit records?
- Which control would you remove last, and why?
- How would you explain the residual risks to a non-technical product owner?
Chapter 14 summary
PeaLang security rests on the host, not on trust in script authors. Capabilities start empty and grow only by review. Limits bound every run across compute, memory, recursion, collections, output, and I/O. Budgets share capacity fairly across tenants over time. Audit records explain every run without exposing what they protect. For untrusted code, these combine with admission checks, host-bound identity, two-way validation, stable error codes, process isolation, and adversarial tests into defence in depth. The hardened policy sandbox shows all of these working together.
Transition to Chapter 15
So far the host has mostly been Python, and the boundary has been treated as a security surface. Chapter 15 widens the view: it treats the boundary as a contract that several host languages share. It begins with embedding architecture and exported-function contracts, then moves through Python, a Java 17 sidecar, TypeScript and React, and FastAPI integration.
Checkpoint status: Ready for review.