# tapid-runner
[](https://github.com/LimeTip/tapid/actions/workflows/ci.yml)
[](https://crates.io/crates/tapid-runner)
[](https://crates.io/crates/tapid-runner)
[](https://docs.rs/tapid-runner)
[](https://github.com/LimeTip/tapid/blob/main/LICENSE)
[](https://www.rust-lang.org/)
Policy-aware package execution foundations for Tapid. Existing approval APIs bind an exact artifact digest to the SHA-256 hash of a normalized script.
`RunConfig::parse_toml` accepts checked-in `[run.defaults]` and `[run.scripts.<name>]` profiles. `parse_toml_bytes` enforces the same byte ceiling before UTF-8 decoding and deserialization, allowing callers to parse multiple policy sections from one bounded file snapshot. Profiles declare project-relative read/write grants, network access, environment-variable names, subprocess access, and optional resource limits. `/` is the sole portable path separator; backslashes are rejected on every host. Configuration is strict, denies unknown fields, and cannot disable required sandboxing.
The platform-neutral execution API validates requests and reports stable errors, termination states, and per-dimension containment evidence. ADR 0005 now distinguishes **Restricted** authority containment from **ManagedTree** lifecycle ownership. The schema selects Restricted explicitly with `assurance = "restricted"`; omission remains legacy-safe ManagedTree so existing strict profiles are not silently weakened. Restricted must enforce the requested filesystem/network authority, explicit environment/PATH and descriptor hygiene, and descendant propagation before spawn. It provides no cleanup guarantee, although a backend may report best-effort cleanup it actually attempted or observed. ManagedTree additionally requires race-free kernel- or VM-owned descendants, a complete cleanup/kill boundary, and configured tree-wide timeout, output, process-count, and memory semantics. The schema and experimental macOS Restricted backend plus a Linux Landlock/seccomp Restricted backend are implemented. Linux Restricted denies ptrace, process-memory read/write, and pidfd acquisition/descriptor access through seccomp, independently of host Yama tracing policy. Linux has targeted Ubuntu 24.04.5 x86_64 local-VM and hosted CI validation; the broader common probe matrix is pending. Linux ManagedTree now combines delegated cgroup v2 limits with private PID/mount namespaces and a read-only root view. macOS ManagedTree and Windows native containment remain unsupported.
Backend identities use checked construction: name, version, and optional deprecation text must be non-empty, free of control characters (including NUL), and no longer than `MAX_BACKEND_IDENTITY_BYTES`. Checked launch evidence distinguishes restrictions requested by policy, capabilities declared by the backend, capabilities observed by runtime probes, and restrictions actually enforced for the execution; it is valid only when enforcement exactly matches the request. Each state reports filesystem read, filesystem write, network, environment sanitization, subprocess restriction, descendant lifecycle, timeout, output, process-count, and memory dimensions independently. Evidence must also identify the mechanism, assurance level, enforcement scope, and limitation. Completion evidence is limited to lifecycle and cleanup results; it cannot re-confirm authority established only at launch. Restricted completion distinguishes no cleanup guarantee from best-effort cleanup actually attempted or observed, and best-effort lifecycle discovery cannot be represented as ManagedTree. Receipt fields and construction remain private, so external callers cannot manufacture enforcement claims.
`ExecutionRequestBuilder::executable_search_path` and `executable_search_paths` accept an ordered list of explicit executable-search directories. The request preserves that order for adapter-owned `PATH` construction and rejects exact duplicates rather than silently changing precedence. Before duplicate checks, every entry is independently bounded and checked for NUL and target-platform representation, then the complete list is serialized with the target platform's exact `std::env::join_paths` rules. Consequently Unix entries containing `:` are rejected; Windows entries containing `;` use the standard library's quoting behavior and entries containing `"` are rejected. Published limits bound the directory count, each directory in native units, and the cumulative serialized search path including separators and its terminating NUL. These checks run before any backend support probe. During generic preflight, every entry must be absolute, existing, canonical, and a directory; different spellings that resolve to the same canonical/platform-semantic directory are rejected deterministically. The macOS runner prepends a private directory containing only a byte-verified Node snapshot on a distinct inode before the CLI-supplied project `node_modules/.bin`, then the runtime directory. This preserves local command precedence without letting a project `node` replace the selected runtime. Each entry becomes a `BackendRuntime` read-only `DirectorySubtree` grant in the enforcement receipt. Search paths are visible only to private adapters; callers cannot supply `PATH` through the environment API.
`ExecutionRequest` carries only explicit caller environment values whose names are both valid and allowlisted by the selected policy. Private adapters receive the complete controlled child environment: those explicit entries plus one mandatory `PATH` serialized from the ordered executable-search directories. An empty generic search list produces `PATH=`. POSIX shells can interpret this as a current-directory search; it does not mean search nowhere. Security-sensitive callers should configure explicit directories. The CLI always supplies project and runtime directories, and the macOS backend prepends the reserved private Node directory. `MAX_ENVIRONMENT_BLOCK_UNITS` covers that complete block, counting every `name=value` entry terminator, `PATH=`, joined-path separators, and the final environment-block terminator exactly once. Published limits also bound the program, argument count, each argument, cumulative argv payload, project root, and each environment value. Lengths are measured in bytes on Unix and UTF-16 code units on Windows. Embedded NUL and values that the target platform cannot represent are rejected before support probing; Unix otherwise preserves non-UTF-8 program, argument, project-root, search-path, and environment bytes. On Windows, argv validation uses a conservative upper bound rather than exact serialization: it counts the quoted program, argument separators, surrounding argument quotes, the mandatory terminating NUL, and worst-case doubling for quote/backslash escaping. Backends must start from this controlled environment rather than inherit ambient variables.
The sandboxed `execute` path rejects `SandboxMode::Disabled` and validates containment evidence before its private backend seam can add runtime paths or spawn. Existing project grants are canonicalized and retain typed `ExactFile` or `DirectorySubtree` semantics. A missing read target is rejected. A missing write target is declared as a directory subtree; the adapter must securely materialize it, re-resolve it, and bind it before native sandbox installation, or return unsupported containment. Explicit backend runtime additions must be absolute, existing, canonical, and retain their file/directory kind.
Receipts expose each effective grant's path, access, declared kind, source, and binding evidence. `NativeObject` means the adapter holds and revalidates a native object handle/identity for setup; pathname equality alone never makes that claim. `CanonicalPath` means the adapter freshly re-resolved the path immediately before setup and is never equivalent to `NativeObject`. Canonical-path enforcement has a residual trusted-host assumption: a privileged or concurrently mutating host must not replace path components between revalidation and native sandbox installation. The generic layer binds the receipt's paths, access, kinds, sources, binding modes, enforcement dimensions, and configured limits to the exact private preflight and rejects mismatches. Outcome accounting checked-adds captured stdout and stderr byte lengths and requires their combined size to be no greater than the exact preflight `max_output_bytes`, when configured. `TimedOut`, `OutputLimitExceeded`, `ProcessLimitExceeded`, and `MemoryLimitExceeded` are accepted only when that exact preflight configured the corresponding limit. Support is gated by native sampled controls and exact request validation; the receipt carries the selected assurance.
The macOS Restricted adapter launches the current executable in private helper mode through deprecated `/usr/bin/sandbox-exec`, using deny-default parameter-bound Seatbelt profiles. The helper sends a fixed-size versioned, nonce-bound READY frame and blocks on a separate GO pipe. The parent registers kqueue `NOTE_EXEC | NOTE_EXIT` before sending GO. The helper directly execs the original byte-preserving argv. A receipt requires valid READY, kernel NOTE_EXEC, and EOF on the CLOEXEC status descriptor. Exec errors carry errno out of band. Missing and non-executable targets return `Spawn` without a receipt; immediate target exits 0 and 71 retain receipts. No exit status or stderr text proves launch. Native Seatbelt syscall controls still gate support. This backend remains experimental and path-based.
Startup controls use shipped native syscall code and `/bin/sh`, with profiles produced by the production compiler. They exercise positive and permission-denied read/write, fork, descendant write, TCP bind/connect, Unix bind, UDP connect, and nonblocking reserved-address connect, plus environment, null stdin, descriptor inheritance, and exec replacement. Ruby, Python, a compiler, and network services are not runtime dependencies. These sampled controls are not a complete proof of all Seatbelt operations, descendant transitions, or OS releases. A failed positive control makes support unavailable. Broader development regressions currently use system Ruby and must fail if it is absent.
Effective authority includes separate backend grants for `ReadData` on `ExactDirectory` `/` and `ReadMetadata` on `DirectorySubtree` `/`. Neither grants descendant file contents. Every filesystem allow rule is generated from typed evidence. Project grants remain distinct from implicit runtime grants. Project character devices, sockets, FIFOs, and other special files are rejected. Only backend-owned `/dev/null`, `/dev/random`, and `/dev/urandom` are accepted as `CharacterDevice`, with device, inode, and device-number identity rechecked before setup. Their path bindings still report `CanonicalPath`, not held native objects.
ManagedTree and every configured timeout, output, process-count, or memory limit are unsupported on macOS and fail before target execution. Captured stdout and stderr share one checked internal 16 MiB combined ceiling; this is a supervisor safety bound, not a configurable policy limit, receipt dimension, or complete tree guarantee. Live output is relayed through bounded per-stream sinks that close every unrelated inheritable caller descriptor at exec; sustained parent-output backpressure stops the owned process group before leader reaping and returns a checked error. Process-group cleanup is best effort; detached descendants can outlive the attempt, and a numeric group is never signalled after its leader has been reaped. Linux Restricted is implemented with Landlock and seccomp. Windows AppContainer/LPAC plus Job Object remain planned. `SandboxMode::Disabled` is rejected by `execute`; no unsandboxed fallback is implemented.
Consumers must call `tapid_runner::initialize_or_dispatch_private_launcher()` as the first operation in `main`. Normal invocation returns an opaque token retained by subsequent requests; private invocation never returns. Without initialization, Restricted support fails before process creation. Tapid's binary installs this dispatch before CLI parsing. The helper canonical path uses the fixed `H0` profile parameter and an exact BackendRuntime grant, and its device/inode is revalidated before launch. Protocol data uses argv and two private pipes, with no protocol environment variables. Only stdio reaches the target.
Executable-resolution receipts encode PATH and its ordered entries as exact Unix byte arrays. They disclose `caller_path_inherited = false`, reserved `node`, private path, trusted runtime, the private snapshot device/inode, byte and executable-metadata verification timing, cleanup observation, and residual host-race limitations. PATH order is private node directory, project `.bin`, trusted runtime parent, then any explicitly approved directories. The selected runtime must be outside project write authority. A held source object is copied and byte-compared into a distinct owner-private inode; Seatbelt denies hard links and writes to the snapshot while project writes remain allowed. Bare `node` and `/usr/bin/env node` are reserved; explicitly addressed project Node executables are outside this guarantee. The private Node snapshot guarantee described here applies only to macOS. Linux Restricted does not claim snapshot resolution.
The private snapshot accepts thin little-endian Mach-O runtimes only when every declared dynamic-library dependency and dynamic linker is an absolute Apple system path (`/usr/lib/` or `/System/Library/`, without traversal components). Inspection uses the held source descriptor before copying, bounds load-command storage to 1 MiB, and rejects malformed or unsupported images. Homebrew Node builds using `@rpath/libnode.*.dylib`, other external or relative dylib dependencies, dyld environment commands, and universal binaries fail closed with `PolicyViolation` before project code executes. Select a standalone thin Node distribution with only Apple system-library dependencies instead. Tapid does not rewrite or re-sign the runtime, inject `DYLD_*`, link back to installation libraries, or broaden write grants; external-library support would require a verified transitive dependency closure. Script fixtures retain their existing interpreter behavior. Development regressions for native executable relocation require the macOS command-line tools (`/usr/bin/clang`); the runner itself does not invoke a compiler.
The private Node binding outlives root completion whenever subprocess-enabled targets may have executed. This includes ambiguous confirmation failures after GO and post-launch execution errors. Restricted process-group cleanup cannot prove detached descendants have exited. Receipts therefore report `reserved_node.cleanup_observed = false` and an explicit retention limitation, independently of process cleanup confidence. Each attempt uses a fresh 128-bit random directory with mode `0700`, outside project write authority; retained directories are never reused. Pre-spawn failures and proven failed launches remove the directory immediately. A successful `subprocess=false` execution removes it after reaping the root, since the native profile denies process-fork and the support probes test that denial.
Retention consumes temporary storage until OS cleanup or host removal after all descendants exit. Tapid does not schedule later deletion: elapsed time and best-effort process-group cleanup cannot establish safety. OS or host removal while a descendant survives ends reserved-node protection. Host writes or races after final validation remain limitations. None of this provides ManagedTree ownership or complete cleanup.
## Dependency lifecycle execution
`DependencyLifecyclePolicy` validates exact checked-in approvals and derives keys bound to source, policy, script, toolchain, and graph. `dependency_toolchain_identity` fingerprints the Linux backend runtime and Tapid executable. ManagedTree requires all four ceilings and initialized private-launcher dispatch. See [dependency lifecycle scripts](../../docs/dependency-lifecycle.md) and [ADR 0008](../../docs/adr/0008-dependency-lifecycle-derived-trees.md) for authority, delegation, accounting, cleanup, and replay limitations.