Platform Daemon — Per-App Isolation
Scope
This doc is the focused record of how the platform daemon keeps one installed app from reaching another app's data, the daemon's own authority, or the host process's memory. It collects the intended VM-sandbox control set, the subset that actually runs today, the tier decision for how far we take in-process isolation, and the build order for the gap.
Everything else about the daemon — HTTP routing, session cookies, the launch flow, the grant UI, CSRF, CSP derivation from manifests, admin policy, fatigue-aware grant UX — lives in daemon-design.md. That document is the complete picture; this one only zooms in on isolation so a reader with an isolation question does not have to read 1500 lines.
Threat model
Crescent treats every installed app as potentially hostile from the moment it is installed. Apps ship both a Lua backend (running inside the daemon's LuaJIT VM) and frontend code (HTML/JS running in the operator's browser on the app's own subdomain). Both halves have the same author and collude by design. There is no scenario where one half is trusted and the other is not.
Against the daemon itself, a hostile app tries to:
- Exfiltrate another app's data — read the other app's
kv/db/fsstorage, intercept its HTTP traffic, or read state the other app holds live in memory. - Escalate to daemon authority — mint launch tokens, write
grants.json, alter the router, or otherwise act as if the operator had authorized it. - Exfiltrate the operator's session — read the daemon-origin session cookie or CSRF token from a position that lets it act as the operator.
- Denial of service — hang the daemon's request thread with a busy loop, crash the process, or balloon memory until the host kills it.
Targets 1–3 are about confidentiality and integrity, and this doc's layered controls aim at them. Target 4 is explicitly a lower priority — see Non-goals below.
The dual-surface framing (backend ACE vs. frontend ACE vs. frontend XSS on the daemon origin) is worked through in daemon-design.md — "Threat model: silent grant vs fatigue" and the XSS-resistance subsection there. This doc covers the backend half.
Layers of defense
Isolation is not a single mechanism. It is four independent layers, each of which should hold even if the others are bypassed.
- VM sandbox — the app's Lua code runs with a restricted
_ENV, no_G, nodebug, noos/io, no FFI, no bytecode loading, and no visibility of daemon internals. Prevents a backend ACE from becoming arbitrary code execution in the daemon process. Detailed below. - Origin isolation — the app's frontend runs on
app-<id>.<daemon-host>(or a distinct loopback IP). The daemon-origin session cookie is not sent to the app origin, so the app's JS cannot impersonate the operator against the daemon API. Covered indaemon-design.md— "Origin isolation". - Capability scoping — every cap the app receives is constructed with
context.app_idbaked in.kv/dbpaths,http_clienthost lists,shared_dbauthorizers, and revocation are all per-app by construction. Two apps asking for "the same cap" get two independent cap instances. Covered indaemon-design.md— "Cap scoping: per-app by default". - CSP on app responses — every HTTP response the daemon serves on an app's behalf carries a
Content-Security-Policyderived from the app's manifest. The frontend's network reach matches the backend's host whitelist. Covered indaemon-design.md— "Content-Security-Policy".
The VM sandbox is the primary in-process defense; origin isolation and CSP defend the browser half; capability scoping ensures that even a well-behaved-but-curious app cannot widen its reach by accident.
VM sandbox controls
These are the intended controls. Status (built vs. planned vs. audit-pending) is in the next section — read both.
- Env-based sandbox, no
_Gaccess. Each app is loaded with a per-app environment table as its_ENV. The env contains exactly the caps the app was granted plus a narrow stdlib subset (string,table,math,pairs,ipairs,tostring,tonumber,type,select,error,pcall,xpcall,rawequal,rawget,rawset,rawlen). No_G, no_ENV, nopackage. - No
debuglibrary.debug.getupvalue,debug.setupvalue,debug.getregistry,debug.getlocal, anddebug.sethookeach escape any env sandbox.debugis never in the app env under any cap. - No
osorioglobals. File I/O, time, and subprocess are mediated through caps (caps.fs,caps.time,caps.spawn). Ambientos.getenv,os.date, andio.openare not reachable. This is the project-wide capability-based-I/O rule; the daemon enforces it at the boundary. - No FFI.
ffi = require("ffi")is the canonical LuaJIT sandbox escape — with FFI, an app can callmmap,dlopen,system, or any other C function in the process.ffiis never in the restrictedrequirewhitelist. First-party apps that need FFI must declare it as a cap (risk class: shared) and get an explicit operator grant. - No bytecode loading.
load/loadstring/loadfileare either absent or forced to text-only mode (load(src, name, "t", env)). Crafted LuaJIT bytecode can bypass VM-level type checks; only source loading is safe. - Frozen metatables on shared built-ins.
getmetatable("")would expose the string metatable; mutating its__indexwould poison every string operation in every app and in the daemon itself. Either freeze primitive metatables with a__metatablesentinel or omitgetmetatable/setmetatablefrom the stdlib entirely. - Per-app
package.loaded. If two apps share apackage.loadedtable, one can poison a module the other requires. Each app gets its own fresh module cache at construction time, closed over by the restrictedrequire. - Cap closures, not cap tables. Caps are functions holding private-state upvalues. The app cannot reach into that upvalue, cannot rebind
caps.kv.get, and cannot swap thecapstable for a privileged one — becausecapsitself is a function or a frozen table with__newindextrapped. - No reference to daemon internals. Grant store, router, launch-token map, cap factory — none of these are in any app's
requirewhitelist. An app cannotrequire("lib.platform.grants")because that name is not in its manifest's declared deps, and the restrictedrequireraises on any non-whitelisted name.
Implementation status
Today's code (lib/platform/daemon/app_loader.lua) implements a subset. The name "per-app VM host" in TODO.md overstates what's built: apps share a single lua_State and differ only by env table.
| Control | Status | Notes |
|---|---|---|
Per-app env table, no _G/_ENV/package | Implemented | sandbox.env(sandbox.stdlib, { globals = { caps = … } }) |
Per-app cap bundle with context.app_id baked in | Implemented | platform.make_caps(app, decl, grants, ctx, …) |
http_server handler captured into daemon closure | Implemented | cap.serve(h) stored; dispatched by Host header |
Stdlib excludes require, ffi, debug, io, os, package, load, loadstring, dofile, string.dump | Implemented + regression-tested | lib/sandbox/sandbox_audit_test.lua BFS-traverses sandbox.stdlib and asserts no reachable function rawequals any blacklisted global; also verifies _G / _ENV / getfenv / setfenv / newproxy are invisible inside an sandbox.env |
Per-app package.loaded cache | N/A today | require is not exposed at all; if it ever is, this becomes relevant |
| Frozen primitive metatables | Implemented + regression-tested | lib/sandbox/init.lua sets __metatable=false on the string metatable at module load; audit test verifies getmetatable("") is the sentinel and setmetatable on a string raises — both from inside and outside a sandbox env. getmetatable(0)/(true)/(nil) return nil on LuaJIT so there is no primitive metatable to freeze |
| Cap closures (not mutable tables) | Implemented for most caps | Per-cap review still worth doing |
Crash containment (pcall around handler) | Implemented + regression-tested | lib/platform/daemon/init.lua's invoke_app_handler xpcall-wraps every app handler dispatch; failures produce a fixed 500 "internal server error" response (the error text is operator-visible only, via the optional on_handler_error callback). Tests in daemon_test.lua cover throwing handlers, the callback payload, cache retention across failures, and assert(false) crashes |
| CPU quota (instruction count) | Ship-blocker for untrusted-app channel | while true do end in a handler blocks the daemon request thread with no budget, no yielding, no kill. sandbox.run accepts opts.budget (a debug.sethook instruction-count hook) but app_loader.lua's run_entry invokes apps with no budget today — trivially-reachable DoS for any installed app. Must land before any PNG/archive-from-strangers distribution channel goes live. Build plan: build-order step 3. |
| Memory quota per app | Not built — see Non-goals | Sandboxed app can allocate unbounded memory (e.g. ("x"):rep(1e9)). LuaJIT exposes no per-env GC cap; tier-1 answer is the same as for object-size limits — don't try. Becomes load-bearing only if the untrusted-distribution channel ships without OS-level process isolation (see Non-goals — OS hardening). |
Separate lua_State per app | Not built | All apps share one state; any future FFI escape sees every other app's memory |
"Audit-pending" items are things the current code most likely gets right but that have no test or audit confirming it. Closing them is a prerequisite for treating the VM sandbox as the primary defense in production deployments.
Tier decision
Three possible isolation tiers sit at increasing cost and strength. Each would be a real implementation, not a wrapper over the next.
- Status quo +
pcall+ instruction quota. Singlelua_State, single thread. Wrap each handler invocation inpcall. Run it as a coroutine withdebug.sethook("", "", N)checking a deadline every N bytecodes. Cap calls remain direct function calls (free). Worst-case ~20–30% overhead on hook-enabled traces; zero for handlers that don't trip the hook. Catches infinite loops, uncaught errors, and blocking-forever handlers. Misses memory DoS and primitive-metatable poisoning unless the stdlib audit closes that first. - Separate
lua_Stateper app. One process, N states. State creation is ~1 ms and amortizes over the app's lifetime. An FFI escape in one state cannot read another state's Lua memory (native-code-reading-native is unchanged — they share the OS process). Cost: cap calls cross a state boundary. A pure-serialization bridge is likely 5–10× slower on cap-heavy workloads than a direct function call; aCFunctionshim withlua_xmoveon tables is faster but more code. Worth measuring before committing. - Fork per app. N processes, full OS isolation. The daemon is explicitly built as a single-process design, so this is held as a fallback for "apps try to steal each other's memory" scenarios we don't have yet.
Chosen direction: tier 1, with the stdlib audit landing before tier 1's hooks ship. Tier 1 gets ~80% of the isolation value (crash containment + spin containment) at 0% cap-call overhead. The main gap it accepts — a hostile app using Lua-level introspection to read another app's memory — is a threat we don't have evidence of yet.
Escalate to tier 2 if either:
- An adversarial app triggers a containable incident that a separate
lua_Statewould have caught (e.g., one app mutates a primitive metatable and affects another, and freezing didn't stop it). - Cap-call performance under tier 1 is measured and shown to have headroom for a boundary — at which point a state-per-app bridge becomes implementable without regressing the cap-heavy path.
Do not build tier 2 speculatively. Do not wrap tier 1 in an abstraction that "makes it easy to swap in tier 2 later" — that abstraction is the problem tier 2 would be solving, reinvented badly.
Build order
None of the following is implemented yet. Treat as the v3 bring-up plan, not a retrospective.
- Stdlib audit + regression test. Landed —
lib/sandbox/sandbox_audit_test.lua(24 assertions). Fixed two real findings in passing:string.dumpwas reachable via("x").dump(now shadowed by a shallow-copystringtable) andgetmetatable("")returned the mutable shared string metatable (now sealed with__metatable = falseat sandbox module load). pcallwrap on per-request handler dispatch. Landed —daemon/init.lua'sinvoke_app_handlerusesxpcallwithdebug.traceback, produces a 500"internal server error"body on failure, and calls an optionalopts.on_handler_error(app_id, err, tb)callback for operator visibility.
- Coroutine-per-request + instruction quota. Still open — the real engineering. Resume the handler as a coroutine with
debug.sethook(co, fn, "", N)(count mode, every N bytecodes).fncheckstime_fn() - start_ns > budget_nsand errors on overrun. Budget is per-request, not per-app-lifetime. First-party apps (library, card) can opt out of the hook at install; third-party apps get it by default. This also answers the concurrent-request question fromdaemon-design.md— Open Question 2 — blocking handlers yield instead of hogging the request loop. Interaction with LuaJIT traces needs benchmarking before this lands. - Frozen primitive metatables. Partially landed under step 1. Strings now carry
__metatable = false. Numbers, booleans, and nil returnnilfromgetmetatableon LuaJIT, so there is no metatable to freeze for those — the audit test covers this explicitly. No further action needed unless a future LuaJIT change exposes a primitive metatable. - Revisit tier 2 if-and-only-if. Track the escalation triggers above. Do not build a state-per-app bridge on speculation.
Steps 1, 2, and 4 are landed. Step 3 is the remaining meaningful work before we can call tier 1 complete — it turns the in-process sandbox from "honest about its gaps" to "containment for a hostile installed app."
Non-goals
The items in this section are deliberate omissions, not oversights. Each states what we are not doing and why — so that a future reviewer with a "shouldn't we also…?" instinct can see that the question was considered and answered.
Explicit non-mitigations within tier 1
- Memory quota per app. LuaJIT does not expose a way to cap GC heap per env. Approximating it with counters on
table.new/ string concat does not stop FFI-level allocation and is a rabbit hole. If memory DoS becomes a real concern, the answer lives at tier 2/3, not tier 1. - Blocking-I/O cap limits. A handler that calls
caps.http_client.geton a slow endpoint is expected to be slow; the instruction quota does not fire on C-level blocking. Concurrent-request handling (coroutine yielding on I/O, not on bytecode count) is the right answer — tracked underdaemon-design.md— Open Question 2. - Timing / cache / GC side channels between apps. Tier 1 shares one Lua state, one GC, one string intern table, one JIT trace cache. In principle two apps can observe each other indirectly (GC pause timing, string intern latency, trace compilation stalls). We accept this because (a) capabilities are coarse — a request-level cap cannot sample at the cycle granularity needed to reconstruct another app's data from timing alone, (b) defeating side channels requires tier 2 at minimum and is not a v1-v3 threat model concern. Revisit if cap surface widens to include anything that returns fine-grained timings (e.g. a
caps.clockwith nanosecond resolution — which we currently don't expose). - FD / table-size / string-length hard limits. A hostile app can create a multi-gigabyte string or a million-entry table. This falls under memory DoS above; per-object limits would shift the same attack to "create many objects just under the limit," so the tier-1 answer is the same as for memory quota: don't try.
- Coroutine hijacking defense. Apps inside the sandbox can call
coroutine.*legitimately; nothing in tier 1 stops an app from yielding inside a handler in a way that breaks the daemon's own coroutine scheduling assumptions. Mitigation: the daemon uses its own (step-3) quota coroutine as the outermost scheduler; an app's inner coroutines are invisible to it. Confirming this interaction is part of v3 step 3's benchmark work, not a separate non-goal.
Trust anchors we are not re-implementing
LuaJIT VM and JIT bugs. We treat LuaJIT as correct: no defense-in-depth against a JIT miscompile that lets an app escape its env. If LuaJIT has a bytecode-verification bug or a JIT type-assumption violation, tier 1's "no
load/loadstring/string.dump" rule is the only barrier, and it does not defend against interpreter-level bugs. Mitigation is patching LuaJIT, not re-verifying its output. Accepting this is explicit: tier 2 would narrow the blast radius (escape from one state doesn't see others' Lua memory) but not eliminate it (escape still holds the native process).FFI for first-party apps. The library and card apps are allowed FFI when they declare it as a cap (risk class: shared). This is not oversight — operator-grantable FFI is by-design for apps we ship; the sandbox is for apps installed from elsewhere. If first-party code is compromised, the threat model has bigger problems than FFI scope.
OS-level isolation for first-party / operator-installed apps. Seccomp, Landlock, App Sandbox, AppContainer — none are wired for the current use case (user's own apps and apps installed from trusted sources). The daemon trusts the host OS; operators running inside a container or VM may add these layers externally.
This is use-dependent. A future untrusted, socially-distributed app channel — PNG/archive apps from strangers — is the maximal-adversarial case and changes the calculus. At that point, OS-level isolation per untrusted app (child process + seccomp/Landlock on Linux, App Sandbox on macOS, AppContainer/job objects on Windows) becomes the only credible defense-in-depth against (a) the JIT-miscompilation risk already accepted above and (b) the shared-
lua_Stateblast radius noted in the implementation-status table — both of which let a single escape become total. Bundling OS isolation inside the daemon is a reasonable design for that channel (it no longer needs to be purely external); the mechanism options are per-untrusted-app child process with platform syscall filtering. Track in the build order when the untrusted-distribution channel is being designed. Memory DoS in the untrusted-channel case also reduces to this: a per-process memory ceiling from the OS is simpler and more reliable than any Lua-level counter.
Security properties we don't offer (and what covers them instead)
- Rate limiting on
/launchand auth endpoints in v1. Launch tokens require a valid__Host-sessioncookie to mint, are one-shot, and expire in five minutes; a brute-force path already needs the session cookie, which is a much stronger authority than "can hit the endpoint." Rate limiting becomes necessary when grant-endpoint POSTs land (a failed grant submission is cheap for the attacker to retry), not at launch-flow v2. Tracked inTODO.mdunder the platform daemon track; not added to the v3 build order because it does not improve isolation, only DoS resistance. - ACME / automated TLS certificate management. The daemon loads certs from disk when binding to a routable interface; it does not fetch or renew them. Reasons: (a) adds a runtime network dependency and a new credential surface, (b) operators who bind to Tailscale or similar already have TLS terminated upstream, (c) local-loopback deployments don't need TLS at all. Operator-provided cert on disk is the minimum that works for all three; automation is strictly additive and can be layered on without changing the daemon.
- Per-app port instead of per-app subdomain. Rejected — cookies ignore port per RFC 6265, so
127.0.0.1:7001and127.0.0.1:7002share a cookie jar and the app-session cookie leaks across apps. The full argument is indaemon-design.md— "Per-app port is NOT a valid fallback". Cross-referenced here so a reader inside the isolation doc does not reinvent the idea. - Fork-per-app (tier 3). Single-process is a design commitment, not a shortcut. Fork adds (a) process-lifecycle complexity (reap, restart, crash telemetry), (b) an IPC boundary on every cap call (serialization cost on the hottest path), (c) OS-specific fragility (Linux / macOS / Windows fork semantics differ). Revisit only if both (i) tier 2's separate-
lua_Statemodel is built and demonstrated insufficient, and (ii) an incident class appears that OS-level isolation would have caught. Neither condition exists today.
Out of scope for this doc
- Concealing an app's own
app_idor data-directory path. The app is allowed to know which app it is; the isolation boundary is that it cannot reach any other app's storage or authority, not that it is ignorant of its own identity. - Defending the daemon against the operator. The operator who grants a cap is authorizing its use; the sandbox does not try to prevent the operator from making bad grant decisions. That is the grant-UI and risk-disclosure layer's job, covered in
daemon-design.md— "Risk-tiered friction" and "Cap risk disclosure".
See also
daemon-design.md— the complete platform daemon design. This isolation doc is a focused subset. In particular:- "Threat model: silent grant vs fatigue" — the dual-surface adversary framing this doc paraphrases.
- "VM sandbox: the backend cannot reach the daemon's memory" — the original, longer prose version of the controls listed above.
- "Origin isolation", "Session token confidentiality", "Daemon UI XSS resistance", "Content-Security-Policy" — the browser-side layers.
- "Cap scoping: per-app by default" — the capability-layer enforcement.
- "v3 per-app isolation notes" — the build-order source of truth; keep this doc and that section in sync when either changes.
lib/platform/daemon/app_loader.lua— current per-app env + cap bundle construction.lib/platform/daemon/init.lua— request dispatch, where thepcallwrap and coroutine quota from the build order will land.lib/sandbox/init.lua— thesandbox.stdlibtable andsandbox.envconstructor audited in build-order step 1.