PeaBox Lab › PeaLang › Learn › Chapter 14 › Lesson 5

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:

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):

FieldTypeConstraint
shipment_idstringMatches S followed by 8 digits
weight_kgfloatGreater than 0 and at most 1,000
distance_kmfloatGreater than 0 and at most 20,000
servicestringOne of standard, express, freight
hazardousbooleanRequired
destination_zonestringTwo 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.

IDThreatExampleControlTest
T1Runaway computewhile true {}Instruction and time limitsA1
T2Memory exhaustionA list of one million mapsMemory and collection limitsA2
T3Deep recursionUnbounded self-callRecursion and stack limitsA3
T4Output floodingPrinting in a hot loopOutput-byte limitA4
T5ExfiltrationSending shipments to a URLAdmission refuses std.http; zero HTTP budgetA5, AD2
T6Host file accessReading configuration filesAdmission refuses std.fs; zero file-read budgetA6, AD3
T7Process escapeRunning a shell commandAdmission refuses std.process; process disabledAD4
T8Cross-tenant readPassing another shipper’s IDTenant bound in host closureA7
T9Ungranted host powerCalling an unregistered functionPermission check raises PeaPermissionErrorA8
T10Malicious resultNegative or huge surchargeHost-side validation, fail closedA9, A10
T11Noisy neighbourOne tenant exhausting shared capacityPer-tenant budget with admissionB1, B2
T12Evidence tamperingEditing an audit lineHash-chained audit recordsE1
T13Information leak in errorsStack trace returned to callerStable error codes; details only in internal logA11

14C.2 Requirements

AreaRequirement
AdmissionParse, check, and lint every upload; refuse imports outside the allow-list; refuse sources over 32 KB; require exactly one export named surcharge
StorageStore admitted scripts by SHA-256 of the compiled bytecode; never load the raw upload
CapabilitiesOnly log and the zone.read host permission
Per-run limits50 ms, 200,000 instructions, 8 MB memory, recursion 32, stack 256, collections 5,000 items, output 8 KB, HTTP 0, file reads 0
BudgetsEach tenant: 20,000,000 instructions and 2,000 runs per 60-second window
Tenant isolationFresh runtime per tenant; zone lookup bound to the tenant on the host side
Boundary validationValidate input before the call and output after it; fail closed
Error mappingStable codes for permission, resource, budget, script, and validation failures; no stack traces in responses
AuditOne hash-chained JSON line per run, no shipment contents or personal data
Isolation tierIn-process for reviewed shippers; worker process for unreviewed shippers
TestingAll 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.

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.

CodeStatusMeaning
INVALID_INPUT400The caller sent a shipment outside the contract
PEA_EXTENSION_ERROR400The rule raised an error for this input
PEA_PERMISSION_DENIED403The rule attempted an ungranted capability
PEA_RESOURCE_LIMIT429The rule exceeded a per-run limit
BUDGET_EXHAUSTED429The tenant’s window budget is spent
INVALID_DECISION502The rule returned an out-of-contract result
PEA_INTERNAL_ERROR500Unexpected 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

IDInputExpected result
F1Standard, 10 kg, not hazardous, zone with rate 0surcharge 0, reason NONE
F2Hazardous, 10 kgsurcharge includes 40, reason HAZARDOUS
F3Not hazardous, 50 kgheavy part 16, reason HEAVY
F4Hazardous, 1,000 kg, long distancesurcharge 500, reason CAPPED
F5Weight exactly 30 kgno heavy part (boundary)

Adversarial tests

IDHostile behaviourExpected outcome
A1while true {}PEA_RESOURCE_LIMIT, host healthy
A2Builds a list of 1,000,000 itemsPEA_RESOURCE_LIMIT
A3Unbounded recursionPEA_RESOURCE_LIMIT
A4Prints inside a 100,000-step loopPEA_RESOURCE_LIMIT (output)
A5Calls std.http at run timePEA_PERMISSION_DENIED
A6Calls std.fs at run timePEA_PERMISSION_DENIED
A7Passes another tenant’s zone codeOnly own tenant’s rate returned
A8Calls an unregistered host functionPEA_PERMISSION_DENIED
A9Returns a negative surchargeINVALID_DECISION (502)
A10Returns an unregistered reason codeINVALID_DECISION (502)
A11Raises an error with a long internal messagePEA_EXTENSION_ERROR; no message text in response
A12Calls host.zone_rate 50 timesPEA_EXTENSION_ERROR after the 20-call cap

Admission tests

IDUploadExpected problems
AD1Source of 40 KBSOURCE_TOO_LARGE
AD2Imports std.httpIMPORT_DENIED:std.http
AD3Imports std.fsIMPORT_DENIED:std.fs
AD4Imports std.processIMPORT_DENIED:std.process
AD5Exports surcharge and debugEXPORTS_MUST_BE_EXACTLY_surcharge
AD6Syntax error on line 7CHECK code with line 7

Budget and evidence tests

IDScenarioExpected outcome
B12,001 runs inside one windowRun 2,001 returns BUDGET_EXHAUSTED
B2Tenant X exhausts its budgetTenant Y still served normally
B3Window expiresTenant X admitted again
E1Edit one audit lineverify_chain returns that line number
E2Delete one audit lineverify_chain detects the break
E3Inspect all recordsNo 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

14C.14 Submission package

14C.15 Assessment rubric

AreaEvidence of mastery
Threat modellingThreats are specific, ranked, and each links to a control and a test.
AdmissionUnsafe uploads are refused with clear, stable problem codes.
Least privilegeOnly reviewed capabilities are granted; tenant identity is bound on the host.
Resource controlPer-run limits and window budgets both work and are justified by measurement.
Boundary validationInputs are rebuilt from known fields; outputs fail closed.
Error handlingFailures map to stable codes without leaking internals.
EvidenceAudit records are minimal, chained, and verifiable.
TestingHostile fixtures cover every threat and run in CI.
JudgementResidual 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

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.

← Previous Next →