Part III — Advanced Systems · Chapter 14 · Lesson 4 of 5 · 11 min read
Lesson 4: Running Untrusted Scripts Safely
Lesson level: Advanced
Purpose: Many PeaLang hosts let customers, analysts, or partners upload their own rules. This lesson builds a layered approach to running that code: threat modeling, static checks before execution, a minimal sandbox at run time, strict boundaries for inputs and outputs, and an operating process for when something goes wrong.
Release note: The configuration keys, API names, and record fields in this lesson are illustrative. Verify exact names and syntax against the PeaLang v0.63 reference before you publish or teach from this material.
Learning objectives
By the end of this lesson you will be able to:
- Build a threat model for user-supplied scripts.
- Apply defense in depth: admission checks, sandbox policy, boundary validation, and process isolation.
- Reject unsafe scripts before execution with static checks.
- Run untrusted code with minimal capabilities and tight limits.
- Validate and constrain everything that crosses the host boundary.
- Plan monitoring, kill switches, and incident response for script platforms.
4.1 Who and what you are defending against
"Untrusted" does not always mean "malicious". Most harmful scripts are accidents: an infinite loop, an enormous list, a debug print inside a hot loop. A good design handles both careless and hostile authors.
| Threat | Example | Primary control |
|---|---|---|
| Runaway compute | while true {} | Instruction and time limits |
| Memory exhaustion | Building a list of ten million maps | Memory and collection limits |
| Data exfiltration | Sending inputs to an external URL | No http capability; egress allow-list |
| Host file access | Reading configuration or key files | No fs capability; read-root jail |
| Output flooding | Printing megabytes per call | Output limit |
| Boundary abuse | Returning huge or deeply nested values | Output schema validation and size caps |
| Cross-tenant leakage | Reading another tenant's cached data | Fresh isolate per tenant |
| Runtime vulnerabilities | A bug in the VM itself | OS-level process isolation |
4.2 Defense in depth
No single control is enough. Arrange several layers so that a failure in one is caught by another.
| Layer | When | What it does |
|---|---|---|
| 1. Admission | Upload time | Parse, check, lint, and reject unsafe code |
| 2. Policy | Load time | Grant only the capabilities the script needs |
| 3. Limits | Run time | Bound compute, memory, output, and I/O |
| 4. Boundary | Before and after each call | Validate inputs and outputs against schemas |
| 5. Isolation | Process level | Run the VM in a separate, low-privilege process or container |
| 6. Operations | Continuously | Audit, alert, and disable bad scripts quickly |
4.3 Admission checks at upload
Reject problems before any code runs. Admission should parse the script, run semantic checks, and compare requested imports with what the platform allows.
pea check uploads/acme_rules.pea --strict
pea lint uploads/acme_rules.pea --deny warnings
pea compile uploads/acme_rules.pea -o build/acme_rules.peac
fn admit_script(path: String, allowed_imports: List[String]) -> Result[Map, List[String]] {
let report = tooling.analyze(path)
let problems = []
for e in report.errors { problems.push("check: {e.message}") }
for imp in report.imports {
if !allowed_imports.contains(imp) {
problems.push("import not allowed: {imp}")
}
}
if report.source_bytes > 64_000 { problems.push("script too large") }
if problems.len() > 0 { return Err(problems) }
return Ok({"bytecode_sha256": report.bytecode_sha256, "exports": report.exports})
}
4.4 An import allow-list
Pure modules such as std.math, std.str, and std.json are generally safe. Modules that reach the outside world (std.fs, std.http, std.process) should be refused at admission even if the runtime would also block them later. Refusing early gives authors a clear message and removes a whole class of risk.
| Module group | Default for untrusted code |
|---|---|
| std.math, std.str, std.list, std.map | Allow |
| std.json, std.csv, std.regex | Allow, with size limits |
| std.datetime | Allow; clock reads may be fixed by the host |
| std.log | Allow, routed to a per-tenant sink |
| std.fs, std.http, std.process, std.env | Deny |
| Host modules (host.*) | Allow only named, reviewed functions |
4.5 The minimal sandbox policy
[sandbox.untrusted]
capabilities = ["log"]
host_functions = ["host.lookup_tier"]
[sandbox.untrusted.limits]
instructions = 1_000_000
time_ms = 50
memory_bytes = 16_777_216
max_recursion = 64
max_stack_depth = 256
max_collection_len = 10_000
output_bytes = 16_384
http_calls = 0
file_reads = 0
Start with nothing and add only what a real script needs. Every added capability should have a named owner and a reason in the review record.
4.6 Exposing host functions safely
Host functions are the main way untrusted code touches your systems, so treat each one like a public API. Make them narrow, read-only where possible, rate-limited, and scoped to the caller's tenant automatically. The script should never pass the tenant ID itself.
# Host side (Python)
def lookup_tier(ctx, customer_id: str) -> str:
if not re.fullmatch(r"C[0-9]{6}", customer_id):
raise HostError("INVALID_CUSTOMER_ID")
return tiers.get(ctx.tenant, customer_id) or "STANDARD"
runtime.register("host.lookup_tier", lookup_tier, max_calls_per_run=20)
Validate every argument on the host side; the script's types are not a security boundary.
Bind tenant and identity from the host context, not from script arguments.
Return portable values only, never host objects or handles.
Cap calls per run so a loop cannot turn a lookup into a denial-of-service attack.
4.7 Embedding untrusted code with the real runtime API
The Python embedding API is the reference host for this course. Three classes do most of the work: RuntimeOptions declares permissions and limits, PeaRuntime loads source and registers host functions, and PeaModule exposes the functions a script exports. Safe defaults grant no permissions and keep process execution disabled.
from pealang import PeaRuntime, RuntimeOptions
UNTRUSTED_OPTIONS = RuntimeOptions(
permissions=frozenset({"tier.read"}),
max_execution_ms=50,
max_instructions=200_000,
max_call_depth=32,
max_memory_bytes=8 * 1024 * 1024,
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,
)
runtime = PeaRuntime(UNTRUSTED_OPTIONS)
runtime.register_function("host.lookup_tier", lookup_tier, "tier.read")
Every host function is registered with a permission string. When a script calls a function whose permission is not in RuntimeOptions.permissions, the runtime raises PeaPermissionError instead of calling your code. Registering a function is therefore not the same as granting it.
4.8 A customer-uploaded discount rule
Use case: an e-commerce platform lets each merchant upload a discount rule. The script receives a portable cart map and must return a portable decision map. It may look up the customer tier, but it cannot read files, call HTTP endpoints, or start processes.
# merchant_discount.pea (uploaded by merchant ACME)
const max_discount_pct = 30
function line_total(item) {
return item.price * item.qty
}
function discount(cart) {
let subtotal = 0
for item in cart.items {
subtotal += line_total(item)
}
let pct = 0
let reason = "NONE"
let tier = host.lookup_tier(cart.customer_id)
if tier == "GOLD" and subtotal >= 100 {
pct = 15
reason = "GOLD_100"
} else if subtotal >= 250 {
pct = 10
reason = "BULK_250"
}
if pct > max_discount_pct {
pct = max_discount_pct
}
return {"subtotal": subtotal, "discount_pct": pct, "reason": reason}
}
export discount
The script owns the pricing idea. The host still owns identity, the final price, persistence, and payment. Note the explicit export discount: only exported names are callable from the host.
4.9 Loading and calling the script from the host
from pathlib import Path
from pealang import PeaPermissionError, PeaResourceLimitError, PeaRuntimeError
def evaluate_discount(merchant_id: str, cart: dict) -> dict:
source = Path(f"approved/{merchant_id}/merchant_discount.pea").read_text("utf-8")
module = runtime.load(source, source_name=f"{merchant_id}/merchant_discount.pea")
try:
raw = module.call("discount", cart)
except PeaPermissionError as exc:
return reject("PERMISSION_DENIED", exc)
except PeaResourceLimitError as exc:
return reject("RESOURCE_LIMIT", exc)
except PeaRuntimeError as exc:
return reject("SCRIPT_ERROR", exc)
usage = runtime.last_result
audit(merchant_id, instructions=usage.instructions, elapsed_ms=usage.elapsed_ms)
return validate_decision(raw)
Read the source from an approved location only, meaning the copy that passed admission. Never load the raw upload directly. The host reads the file; the script receives no file-read capability.
4.10 Validating what comes back
A script's return value is untrusted output. Validate its shape, types, and ranges before using it, and fail closed if anything is wrong.
ALLOWED_REASONS = {"NONE", "GOLD_100", "BULK_250"}
def validate_decision(raw) -> dict:
if not isinstance(raw, dict):
raise ValueError("decision must be a map")
pct = raw.get("discount_pct")
if not isinstance(pct, (int, float)) or not 0 <= pct <= 30:
raise ValueError("discount_pct out of range")
if raw.get("reason") not in ALLOWED_REASONS:
raise ValueError("unknown reason code")
return {"discount_pct": float(pct), "reason": raw["reason"]}
The script also caps the discount at 30 percent, yet the host checks again. Script-side checks improve correctness; host-side checks enforce the business boundary.
4.11 Isolating tenants and runs
One tenant's script must never observe another tenant's state. Create a fresh module for each tenant, and prefer a fresh load for each request when scripts keep mutable top-level state. Because tenant identity comes from the authenticated host context, a script cannot ask for another tenant's data by passing a different identifier.
def runtime_for(tenant_id: str) -> PeaRuntime:
rt = PeaRuntime(UNTRUSTED_OPTIONS)
def lookup_tier(customer_id: str) -> str:
if not re.fullmatch(r"C[0-9]{6}", str(customer_id)):
raise ValueError("INVALID_CUSTOMER_ID")
return tier_store.get(tenant_id, customer_id) or "STANDARD"
rt.register_function("host.lookup_tier", lookup_tier, "tier.read")
return rt
The closure captures tenant_id on the host side. The script sees only host.lookup_tier(customer_id), so the tenant boundary is enforced by construction, not by convention.
4.12 Mapping failures to safe responses
When untrusted rules run behind an API, map each failure class to a stable status and code. PeaLang's FastAPI integration uses this mapping:
| Exception | HTTP status | Error code |
|---|---|---|
| PeaPermissionError | 403 | PEA_PERMISSION_DENIED |
| PeaResourceLimitError | 429 | PEA_RESOURCE_LIMIT |
| PeaError, ValueError, KeyError | 400 | PEA_EXTENSION_ERROR |
| Anything else | 500 | PEA_INTERNAL_ERROR |
from fastapi import FastAPI
from pealang.fastapi_integration import install_exception_handlers
app = FastAPI()
install_exception_handlers(app)
@app.post("/merchants/{merchant_id}/discount")
def discount(merchant_id: str, cart: dict):
return evaluate_discount(merchant_id, cart)
Return the code and a short message to the caller. Keep stack traces, host paths, and script source in the internal audit log only. The import path shown for the handler helper is illustrative; confirm the module name in your installed package.
4.13 Process isolation for higher-risk tenants
In-process limits stop runaway PeaLang code, but they share an operating-system process with your application. For anonymous uploads or regulated workloads, run untrusted scripts in a separate worker, such as the Java sidecar or a dedicated container, with no network route to internal services, a read-only filesystem, a non-root user, and an external wall-clock timeout that kills the worker if it stops responding.
| Risk level | Suggested isolation |
|---|---|
| Internal teams, reviewed scripts | In-process PeaRuntime with strict options |
| Partner or customer scripts | Separate worker process per tenant pool |
| Anonymous or public uploads | Disposable container per run, no network, hard kill timeout |
4.14 An adversarial test suite
Prove the sandbox works by attacking it in tests. Each test below loads a hostile script and asserts that the host stays in control.
import pytest
from pealang import PeaRuntime, RuntimeOptions, PeaPermissionError
STRICT = RuntimeOptions(max_instructions=5_000, max_execution_ms=100)
def test_runaway_loop_is_stopped():
rt = PeaRuntime(STRICT)
with pytest.raises(Exception):
rt.eval("let x = 0\nwhile true { x = x + 1 }")
def test_unbounded_recursion_is_stopped():
rt = PeaRuntime(RuntimeOptions(max_call_depth=16))
src = "function f(n) { return f(n + 1) }\nexport f"
with pytest.raises(Exception):
rt.load(src).call("f", 0)
def test_ungranted_host_function_is_denied():
rt = PeaRuntime().register_function("host.secret", lambda: 42, "secret.read")
src = "function work() { return host.secret() }\nexport work"
with pytest.raises(PeaPermissionError):
rt.load(src).call("work")
def test_granted_function_works():
opts = RuntimeOptions(permissions=frozenset({"math.double"}))
rt = PeaRuntime(opts).register_function("host.double", lambda x: x * 2, "math.double")
src = "function work(x) { return host.double(x) }\nexport work"
assert rt.load(src).call("work", 4) == 8
Extend the suite with an oversized list, a large output string, a script that returns a negative discount, and a script that never exports the expected function. Each one should fail predictably and leave the host healthy for the next request.
4.15 Common mistakes
| Mistake | Consequence | Fix |
|---|---|---|
| Loading the raw upload instead of the admitted copy | Code that never passed admission checks runs in production | Load only from the approved store, keyed by the admitted hash |
| Registering a host function and assuming that limits access | Any granted permission silently exposes it to every script | Grant permissions per script from its review record, not per platform |
| Accepting a tenant ID as a script argument | One tenant can read another tenant’s data | Bind tenant identity in a host-side closure |
| Trusting script-side validation | A modified script returns out-of-range or malformed decisions | Validate shape, types, and ranges on the host and fail closed |
| Reusing one module across tenants | Mutable top-level state leaks between tenants or requests | Load a fresh module per tenant, or per request when state is mutable |
| Returning stack traces to callers | Host paths, source, and internals are disclosed | Return a stable error code; keep detail in the internal audit log |
| Relying only on in-process limits for anonymous uploads | A runtime defect can affect the whole application process | Use process or container isolation with a hard kill timeout |
| Testing only well-behaved scripts | Sandbox gaps are discovered in production | Maintain an adversarial test suite and run it in CI |
Guided practice
- Write a threat-model table for a tenant-uploaded tax rule, listing at least five threats and their primary controls.
- Draft an import allow-list for that rule and justify each module you allow.
- Write the RuntimeOptions for the rule with the smallest permission set that still lets it run.
- Wrap a host lookup function so that the tenant is captured on the host side and the argument is validated.
- Write a host-side validator for the rule’s return map that fails closed on any missing or out-of-range field.
- Map four failure classes to status codes and stable error codes for the API that calls the rule.
- Choose an isolation level for internal, partner, and anonymous authors, and explain each choice.
Hands-on lab
Build a merchant-rule service around the discount script from 4.8. Implement an admission step that parses the upload, runs semantic checks, and rejects any import outside the allow-list. Store admitted scripts by content hash, load them with strict RuntimeOptions, expose host.lookup_tier through a tenant-bound closure, validate every returned decision, and map failures to the error codes in 4.12. Finish by running the adversarial suite from 4.14, extended with the four additional cases.
Deliverable: the admission checker, the host service, the test suite with passing results, and a one-page threat model that links each threat to the control and test that covers it.
Review questions
- Why do most harmful scripts come from careless rather than malicious authors, and how does that affect design?
- Name the five defense-in-depth layers and when each one acts.
- Why refuse std.http at admission when the runtime would also block it?
- What is the difference between registering a host function and granting it?
- Why must tenant identity never be a script argument?
- Why does the host re-validate a discount that the script already caps?
- Which failure class maps to HTTP 429, and why is that status appropriate?
- When is in-process execution not enough, and what replaces it?
- What should an adversarial test assert besides the expected exception?
Applied challenge
A partner asks for a rule that calls its own pricing API. Design a safe way to support this without granting std.http to the script. Consider a host function that calls one pre-approved endpoint, a per-run call cap, response-size limits, timeouts, and audit records. Explain which risks remain and which isolation level you would require.
Lesson summary
Running untrusted scripts safely depends on several layers, not one setting. Admission rejects unsafe code before it runs. A minimal policy grants only the capabilities a reviewed script needs. Limits bound every run. Host-side validation checks inputs and results. Isolation contains anything that gets past the other layers. Bind tenant identity on the host, map failures to stable error codes, keep internal details out of responses, and prove the sandbox works with adversarial tests.
Transition to the Chapter 14 checkpoint
You now have capabilities, limits, budgets, audit trails, and a layered approach to untrusted code. The Chapter 14 checkpoint combines them into a hardened policy sandbox that you will build, attack, and document.
Lesson status: Ready for review.