Map: core / capabilities & sandbox
The grant mechanism in two halves: an in-process decision layer
and an OS process sandbox that enforces it for external commands — each
authoritative exactly where the other is blind ([[design/two-enforcers|two
enforcers]]). Authority is attenuated by intersection — a grant block can only
narrow.
The model — core/src/authority/policy/
authority::policy owns the resolved model and its judgments: GrantLayer
(one layer, resolved), GrantStack (their dynamic composition) and the folds
over it. A grant is authored as a grant value, a record decoded where it lands
by shell::grant::decode_grant over decode_capability_map; authority::grant owns the freezing and
all construction that reads the host, including the system reads
(a-grant-is-decoded-where-it-lands).
The in-process guard (core/src/authority/guard/) and the OS sandbox
(core/src/authority/sandbox/projection.rs) enforce the resolved model
(capability-is-data). Every judgment
combines the layers’ evidence (authority-is-belnap-evidence); there is no meet of two layers into a layer
(object-not-name). Why the grant value,
the live judgment, and SandboxProjection are distinct and not one is argued in
capability-carriers.
Submodules:
lattice.rs— the types and their algebra:GrantLayer, one layer in force, resolved where it was decoded (byshell::grant::decode_capability_map, the one walker, reached throughdecode_grantanddecode_fragment, whichShell::decode_grantapplies to a grant value from another host; freeze boundary), holding its rules and nothing beside them;GrantPath<R> { written, real }, a spelling and what its walk made of it,RanExtent(Everywhere, orUnder { position, passed }: a position and what the walk passed on the way) for an allowance (Everywhereis the root spelling/on any host, or a Unix walk that reached/) and anExcludedfor an exclusion;Net(Offline, the one opinion a layer holds on the network),Gpu(Withheld, the one opinion a layer holds on the GPU), the verb setsBTreeSet<EditorVerb>andBTreeSet<ShellVerb>(eachOption: absent inherits),GrantStack(withpush,remove,rehold),Meet,Join,Axis(join_top,is_top),Evidence { positive, negative }andFragment, the extension file’s result (decode_fragment), consumed only byGrantLayer::extend(roles are types: a policy’s omitted axis ist, a fragment’s is⊥). Behindcfg(any(test, feature = "test-util")), inauthority/grant/builder.rs, sit the test buildersCapabilities,ExecGrant(twoBTreeSet<ExecKey>s,ExecGrant::of(allow, deny)),ExecKey::{Name, Path, Dir}andFsPolicy:Capabilities::valuespells aGrantValueandtest_helper::decodeddecodes it, so a test grant meets the decoder’s refusals. No grant spells every program (no-grant-spells-every-program).GrantLayer::valueis what shows a layer: itsLayerValue, decode’s inverse, built fromGrantLayer::axesthrough the typed encoder (a-grant-has-one-outward-form).Flag(Editor(EditorVerb),Shell(ShellVerb)) andGrantStack::permits(Flag)are the one verb vocabulary: membership, a meet over the layers, silence permitting.is_restrictiveis the denotational activation predicate, each axis throughis_top: exec unlessAnywith no exclusion, fs unless it writesEverywhereand excludes nothing,NetwhenOffline,GpuwhenWithheld, a verb set unless it lists every verb;table.rs—Table<A, D>, authority as two sets, allowances and exclusions (authority-tables):Allows(contains,own) andDenies(matches, answering aMatchedBy),supports,excludes,evidence(computed, never stored),live,withheld(aWithheld:MissingAllowance, orExcludedciting the exclusion that matches the least way),rehold_with, andMeet/Join for Table, exclusions joining and allowances meeting at their own subjects; the meet’s obligations and the generic law test are its property tests;fs.rs— the fs instance:FsOp,FsAllow { Prefix(GrantPath<Extent>), RunPlace(RealPath) },FsDeny(GrantPath<Excluded>),FsRules = Table<FsAllow, FsDeny>, andFsLayer { read, write }, the two tables a layer holds, each with every exclusion;region(stack, op, baseline), each supplying layer’s tables met (writing reads) and the system reads fromBaselinejoined;Baselinealso supplies the bundled-tool image and protected boot identities, assembled inauthority.rs, without a policy-to-sandbox dependency;ReadRegion, the one read table (run placesP≤Lincluded) folded once for a walk that judges many objects.GrantStack::judgeandlocate, each one function over the sealedpath::Handle(LocatedorDir), are where the stack’s evidence becomes authority: the pinned-binary veto (Refused::Guarded) first, then the fold, then the handle markedO, minted byHandle::judgedagainst aVerdictonly this file makes, asReadRegion::judgeandUngoverned::{read, write}mint too;GrantStack::readis the read judgment,region(Read)alone;exec.rs— the exec instance (authority-tables) and its judgment:Program(ToolorFile { arg0, located }, one ownedLocated) and theSubjectit is judged as (Program,Dir,Tool,Any);ExecAllow(Any,Dir,File,Tool) andExecDeny(Name,Dir,File);ExecRules = Table<ExecAllow, ExecDeny>;rules, the stack’s table;places, the run places. Authored exec targets are resolved byauthority::grant, not here;GrantStack::admit(baseline, program)judges the table then reading and is the only mint ofAdmitted(Program<Reading>, a private field); a refusal is data,ExecDenial::{Run(Withheld<ExecDeny>), Read(Withheld<FsDeny>)}, the refused program dropped;admitreads throughread_region(baseline)and vouches for a file throughReadRegion::judge; it carries no argv.GrantStack::admit_namejudges a failed walk’sTraceby the same exec table andGrantStack::read, without minting a handle.ExecRules::for_kernelis the table as the kernel holds it,KernelRules = Table<KernelAllow, ExecDeny>:KernelAllow(Any,Dir,File) has no tool, the kernel seeing ral’s own binary for one, and holds what itsExecAllowholds (a property test);with_supportjoins the live support asFileallows;allowed_filesthe live file allowances the carriers are computed over.ExecDeny::matchesis the one reading both tables give an exclusion. A veto (ExecDeny::Name(Veto)) keeps the name as written, which it shows, beside itspath::command_name_key, which it judges and renders by;deputy.rs—deputy_prefixes, the confused-deputy report: the prefixes a grant makes bothexec-admitted andfs-writable, the live part ofR ∧ W, the exec region (each exec layer’sDirkeys with full evidence, the root forevery) met withfs::region(FsOp::Write), so each writable island under a runnable directory is named and a directory wholly excluded on either side is not. What it locates is where a write becomes runnable, not an escalation: within one projection the dropped binary is spawned under the confinement that wrote it, and only a runner outside the projection turns the shape into an escape — so it reports and never denies. Findings are recorded only into an open audit trail, as a layer is pushed (ral --audit --capabilities <profile> -c true; grant).
The shell::load module holds shell/load/profile.rs —
load_capabilities_from_path / _from_str for .ral capability profiles,
checked against Σ and run under Σ through evaluate_closed, with
typecheck::table::declared(Form::Grant). It sees no session bindings and
its helper lets never enter the session. A profile ends in
grant’s options written out (SPEC §15.3): check_options checks each key
during generation, recursing immediately into written exec: and fs:
records. A bound or computed tail is T0077; an unwritten nested table is
T0079. All profile keys are optional, so () or an empty file states nothing
(the policy top, or an empty extension fragment). Runtime grant decoding
retains shape, keyset and domain checks because it also accepts grants
received as data, including wire grants and spawn restrictions.
The guard — core/src/authority/guard/
The model’s in-process enforcer: free guard::check_*(&GrantStack, …)
functions fold the whole stack — a module boundary rather than a typestate
(witness-collapse). It consumes resolved
authority and returns domain data, never runtime values or control flow.
enforce.rs— the guards over the model’s judgments:check_exec(GrantStack::admit),check_exec_name(GrantStack::admit_name, a head’s failed-walk name judged as running it would be),fs_denial(projection ofRefused::{Guarded, Withheld}),check_flag, andcheck_device_name. Exec checks returnResult<_, Box<Denial>>;fs_denialreturnsDenial; flag and device checks returnResult<(), Denial>.fact::Denialretains only the portable request and cause: no stored error, check, hint or missing-allowance flag.audit_checkandmissing_allowancederive their answers from those facts;describeandadvicederive presentation. The judgment is reusable without the report:GrantStack::refusal_fsdecides —Refused::Guardedfirst, for a write onto a boot-pinned sandbox binary (the suppliedBaseline’s protected identities), before any grant is folded: the empty stack is exactly the case that veto must catch.GrantStack::admits_fsis the quiet twin a write asks before reading its before- and after-images.
The shell adapter — core/src/shell/runtime/state/checks.rs
impl Shell:check(Flag, who),exec_refused,baseline,locate,locate_dir,locate_existing,locate_if_admitted(each excusing the discard deviceLexicalPath::is_discardand refusing a reserved device name before either region is consulted),judge(an object a caller already holds),admits_fs,sandbox_projection, and the grant scope guards (with_layer,push_session_capabilities,audit_deputy_prefixes,has_active_capabilities).Shell::locateis the one path every read and open takes: the device-name refusal, thenGrantStack::locate(path::walkto the object,GrantStack::judgeon its transcript), handing back the handle vouched for.Shell::refusedrecords the selected denial’s derived check throughShell::record_checkwith noMooring, so on the trail alone, then mintsReason::Deniedand itsBreak.Shell::exec_refused, taking theDenialthatguard::check_execorcheck_exec_namereturned to a head ortest_access, records an exec refusal against its call’sMooringand mints itsBreak.GrantStack::judge_failurejudgesfailure_tracefor the requested operation before an error is disclosed;GrantStack::locateapplies it for every caller and either handle kind, andlocate_existingjudges failed walks through it.
Construction — core/src/authority/grant/
authority::grant owns freezing, directory selectors, authored resolution
and host system-read discovery. It builds the resolved model that policy
judges, without naming a shell or runtime value; the Value decoder and
spawn adapter live in shell::grant.
paths.rs—Polarand grant-path walking: allowances keep positions, exclusions hold objects;resolve.rs—Keyedandname_rules: how a walked exec target becomes the rules a layer holds, by polarity, including PATH lookup;value.rs— the grant value as typed data:Axes(ExecTable,FsTable,Target,Place) encodes to aGrantValue, the only way a host spells one, andGrantValue::deny_allis the value that withholds all positive authority;builder.rs— the test builder overAxes(Capabilities, above);host.rs—Baseline::of_env/of_home: the system readstoolchains::system_reads_inkeeps, as prefixes, refusing with anError(hint kept);authority.rsattaches the sandbox’s boot pins to form the runtimeBaseline;freeze.rs— the one place a grant’sPlaceorSelectorbecomes aFrozenPath(a folded spelling, whichdecodethen walks), against one anchor:FreezeCtx::at(an ownedenviron::EnvVarsandCwdPath: theResolverpair, with optional scratch) and itsplace(Noneis a dead grant, anabsolutepayload classified on the raw string bylive_absolutethroughlex::grant_eligibility(EligibleOn/GrantRefusal) overlex::parse_bytes: aHeadKind::DeviceorHeadKind::Malformedhead, a mixed-separator opening (/\x,\/x,GrantRefusal::MixedHead) included, is refused first, though Windows reads it as absolute; a\??\NT object-manager head (HeadKind::DrivelesswithNamespace::Object,GrantRefusal::NtObject), read as Win32 reads it, is refused under every tag with its own refusal; thenHeadKind::PosixisEligibleOn::Posix, a non-verbatim//srv/shshare isEligibleOn::Both, and aHeadKind::Driveor otherHeadKind::Unc, a verbatim root included, isEligibleOn::Windows, dead under POSIX) andselector;host_absolute, the one classifier of a path the host holds or chooses (exarch’s carve-outs,PATHentries, toolchain and system-read directories), classified on its native text and frozen as anabsolutegrant, refused withGrantRefusal::ForeignOrRelativewhere a payload would be dead, so exarch’s deny layer fails closed, in words about the path alone: its caller names who chose it, and only a payload’s refusal (live_absolute) adds, as a hint, how a grant writes it; the tagsabsolute,cwd,home,tempdir,scratch,gitdirandxdg-*, the root-program refusalroot_program, thegitdirrefusals (bad_pointer, fromBadPointer),Selector(Path | Toolchain(Toolchain)) and thepathselector (path_dirs_in, which classifies each absolutePATHentry raw, as anabsolutepayload, before the freeze folds it), andrefuse_the_world, the guard both it and every kept toolchain directory call, overthe_world, the one predicate for a root, the home or an ancestor of it, which system-read discovery uses too;FrozenPath::freezerefuses a path that is not Unicode;toolchains.rs— the directories the host chooses, as one table:enum Toolchain(systemand the package managers), each a fewLocations of overrides and defaults, from one exhaustivematch, andLISTED, each platform’s system reads no selector names,Locations too (Windows’ are%SystemRoot%,%ProgramFiles%and%ProgramFiles(x86)%as overrides).chosenselects over an injected host environment and home;walked, the one walker of chosen directories, holds each byhost_absolute(a malformed one refused, naming the variable or default and what would hold it), walks it byGrantPath::walkedand drops the absent.expand_inkeeps the directories and checks each followed trace against the world, naming either its override or its default spelling in a refusal (Chosen::subject), beforeW::grantretains the allowance position or exclusion objects.FreezeCtx::selectorcalls it with the freeze’s environment, overlay then host (FreezeCtx::var), the one environment a barename,dirpathand every toolchain selector read, so aPATHan overlay sets governs all three; the publicexpandwrapper returns the surviving spellings as nativePathBufs.system_reads_inwalksLISTEDand the rows ofSYSTEM_READS(homebrew,macports,nix,pkgsrc), keeping what exists, a file included, outside the process's home andthe_world(keeps_system_read`) (grant §Selectors states the rules).
Runtime decoding — core/src/shell/grant/
shell/grant.rs supplies Shell::freeze_ctx (env, logical cwd and scratch)
and the Error → Break conversion; substantive freezing stays in
authority::grant::freeze.
decode.rs—decode_capability_map, the one grant walker (crate-private), which reads agrant [...]/--capabilitiesValuemap into a resolvedGrantLayer;decode_grantanddecode_fragmentare its public entries for a grant value one host authored for another (Shell::decode_grant, inshell/grant.rs, applies it against the receiving shell’s anchor), one dimension decoder perexec/fs/net/gpu/editor/shellkey, nested tables and verb lists read as sets — every one of them authority, none of them a recording switch (audit). Its exec targets freeze and walk throughauthority::grantdirectly into exec rules: adirselector expands once per directory, a bare name reads the decoding environment’sPATH, a path allowance holds the position its walk reached, and an exclusion the objects held;spawn.rs—SpawnGrant(Inherit,Base,Restrict), a spawn’s grant as it crosses to a child that has not yet resolved it, frozen against the child’s ownFreezeCtxthroughShell::freeze_ctx;GrantNarroweris the host-suppliedfn(&str, &FreezeCtx) -> Result<GrantLayer, Error>that resolves a named base.
Path resolution
Path resolution is core/src/path/: lexical stages, then one walk, plus
which.rs for PATH search. path.rs’s doc names every module. An item used
outside path/ has one path, crate::path::Item, re-exported there from a
private module; the public modules tree (tree::Walk, tree::Glob,
tree::bytes), git (git::Pointer, git::work_tree_chain) and complete
(complete::PartialPath, complete::TildeReading) are namespaces, whose items
are named through them and re-exported nowhere.
- expand —
sigil.rs(run-time~andxdg:expansion of ordinary paths, never in a grant; the placescwd,tempdir,scratch,gitdirare policy-only, expanded at freeze bygrant::freeze(scratchagainst the spelling of the session’s scratch that theFreezeCtxcarries, which plain ral has none of);git.rsbacksgitdirdiscovery, following a.gitpointer file only to a git directory whosegitdirback-pointer orcore.worktreenames the working tree back, judged by the positions the two walks reach, never by identity; a bad pointer is a path-levelBadPointer, phrased as a grant error by the caller),tilde.rs(~and~/subonly; an unsetHOMEisNone, and each caller picks its own honest answer;TildePath::shownis the one spelling~,homeand a~/…command head share, andTildePath::expandthe path such a head runs, the suffix read onto an exact verbatim home byverbatim_joined). The expansionexpand_path_prefixanswers is native, in the host’s own spelling, for the resolver to hand on to the OS.sigil::SigilHeadis the one reading of a path’s head —Tilde,Xdg, orUnknownXdg(anxdg:no kind answers to, passed through literally) — that expansion,literal_relativeand a grant’s refusal of a sigil all ask. Anxdg:sub-path naming a volume of its own under Windows rules — a drive component, or a share or namespace head opening it — would re-root the join, soexpand_path_prefixleaves the whole path as written: it fails closed, a prefix matching nothing rather than a fabricated path, while a grant refuses the gap outright ingrant::freeze; - lex —
lex.rs, the one surface overlex/, split by concern:head.rs(the parser and every head judgment, andwindows_components, a path’s names pastwindows_head, the one split every Windows identity takes),eligibility.rs(grant_eligibility,classify_subpath),anchoring.rs(anchor, andanchor_onfor a caller that may have no cwd:PATHentries, git pointers). Anchoring uses native separators in a relative suffix and leaves its dot components and absolute inputs as written, except onto an exact\\?\verbatim drive or share, past whose head Win32 hands the kernel/as a name byte and./..as names: therefold::verbatim_joinedreads the suffix as Win32 would — either separator splits,.and empty names drop,..takes a name of the base but never its volume, a trailing separator stays — and a root-relative\xjoins the volume’s root. Every composer that appends a Win32 suffix to a possibly-verbatim base goes through it:anchor,TildePath::expandandjoin_relative(soxdg:).fold.rs,join.rs,name.rs(a path’s names by spelling:file_name,spelled_parent,extension,utf8,relative_keyand its inversekey_within) andcommand.rs(names_a_path, the Windows exec extensions,is_batch_image). One structural parser,parse_bytes, reading a byte slice underPathRulesintoParsed { raw, rules, kind: HeadKind, spelling: HeadSpelling, head_len }, from which resolution,./..folding and every head judgment project.HeadKindnames the structural head (Posix,Drive { letter, volume },Unc { volume },Driveless,DriveRelative { letter },Relative,Devicefor\\.\, andMalformedfor a two-separator or\\?\head that is no well-formed drive, share or device);HeadSpellingrecords the opening separator and namespace facts once (namespace: Option<Namespace>—Verbatim { exact }for\\?\,Device { exact }for\\.\,Objectfor\??\, withexact/Namespace::is_exacttrue when all three separator bytes of that 4-byte prefix are\—mixed_openingfor/\or\/, andopens_with_slash).fold_dots_under(overfold_bytes) is one kernel under either rules from any host,fold_dotsits host instance on a held path:head_lenmarks where the head ends and only the names past it fold, joined with the rules’ separator, so a fold preservesHeadKind,volumeand (save when..climbs into the??component of a\??\driveless path)HeadSpelling::namespace; under Windows rules a non-namespaceDrive,Unc,Driveless,DriveRelativeorRelativehead (Parsed::respell_head) is respelled with\too (C:/a/bfolds toC:\a\b,//srv/shto\\srv\sh), so such a path has one separator throughout, while every head whose kind or meaning turns on its spelling is kept as written: aPosix/(as\it would beDriveless), a slash-spelled verbatim head (//?/C:/xis a device path Win32 normalises, so its tail pasthead_lenfolds), and aDeviceorMalformedpath, or an exact\\?\verbatim path (Namespace::is_exact,head_len == raw.len(): Win32 hands its rest to the kernel uninterpreted,/a name byte and./..names), all head and kept whole,..included; a relative path’s drive-shaped first name keeps a.\before it;is_unparsed_head, a Windows path absolute to the kernel in whichstd::pathfinds no prefix and so would descend or climb from the current drive, which the walk refuses. Every head predicate projects fromparse_bytes: whether a path is absolute under either rules set (absolute_under/Parsed::is_absolute: POSIX,HeadKind::Posix; Windows,Drive,Unc,DeviceorMalformed) and on this host (is_absolute,absolute_underthe host’s rules, the one absoluteness ral asks,anchorincluded;Path::is_absoluteis banned in clippy.toml in its favour);is_working_directory(Posix, orDrive/Uncunder Windows);is_bare_root(one separator alone under the givenPathRules);has_drive(non-namespaceDriveorDriveRelative);Parsed::is_mixed_headandParsed::is_nt_object, shared bygrant_eligibilityandclassify_subpath(SubpathRefusal), whichgrant::freezemaps to its messages;is_network(HeadKind::Unc),is_verbatim_drive(Namespace::Verbatim+HeadKind::Drive) andis_volume_guid(has_os_namespace_headwith aVolume{namespace_tail), which the Windows DACL backend asks rather than parsing prefixes itself;Parsed::has_os_namespace_head(Namespace::is_exact), whatshowleaves unfolded;Parsed::without_verbatim_prefix, what the Windows identity fold slices; andParsed::namespace_tail, what the discard device check reads underHeadKind::Device;utf8, a path’s native spelling as text orNotUtf8naming it, the one strict conversion for a path that must travel as a string (--capabilitiesprofiles,SourceFile), asshownis the one lossy conversion, for display only;spelled_parent, a path with its last name dropped by spelling alone, for a program’s own layout (the folder a file it writes sits in, its install tree, a run folder it made) and never for a name a grant judges, which asksRealPath::parent; a final component’sextension;relative_suffixstrips a sub-path’s leading separators under the rules, andjoin_underjoins a sub-path onto a base string one component at a time with the separator of the given rules, on every host alike (GuestPath::joinis it under Posix rules), and refuses (Rerooting) a sub-path naming a volume of its own under Windows rules — absolute there, or a drive at any component;join_relativeis it under the host’s rules onto a host-held path, andjoin_slashis that for a/-separated constant subpath the program spells, panicking if one re-roots;identity.rs: name identity and containment, a command name’scommand_name_key, andwindows_collision_keynaming a kernel object by an absolute path undercollision_keyper component, coarser than NTFS’s own fold so a lock merges every spelling NTFS equates;device.rs: device names, andwin32_trimmed, a final component with the trailing dots and blanks Win32 drops, the one copy of that rule (reserved device names, batch images); - complete —
complete.rs, the path half of completing a typed word:PartialPathsplits it, under aTildeReading(home, or a literal~inside quotes), into the directory to list and the needle, says which entries are offered, and spells a chosen one back as ral shows a path (typed~kept,/-separated; expanded viaTildePath::shownonly when the spelling must be quoted); - slug —
slug.rs,project_slug: a launch cwd as one directory-name component, for keying per-project state. It is a readable part (/Users/x/proj→-Users-x-proj, lossy, for a person scanning a listing), a-, and 16 hex digits of the SHA-256 of the cwd’s exact OS bytes (UTF-16 units on Windows), so two cwds that differ at all key apart:-Users-x-proj-25cf7293a3713b73; - canon —
canon.rs, the names one object answers to for the kernel sandboxes: firmlink twins (twins), whichrender.rsrenders as rule text (render_real, refusing a name that is not UTF-8) and whose ancestors it takes (proper_ancestors); what an object is, and where a spelling reaches it, is the walk’s to say; - locate —
handle.rsexports one resolver fromhandle/:names.rsvalidates spellings,trace.rsholds evidence, andexclusion.rskeeps deny anchors.object.rsowns private handles and authority conversions; operations inobject/, traversal inresolve.rs, and host adapters are its child modules.object/write.rs::create_scoped_dircreates a secret directory through a write-judged absent target;ScopedDirholds it and permits only empty-root rollback on drop. Recursive cleanup (Located::remove_all) requires a fresh write judgment ofcleanup_target, the actual held tree, not its original absent name, and of every descendant before it is entered or removed. A refused descendant stops the removal and stays, with its ancestors; an I/O failure names the entry it happened at.create_writable_fileexclusively creates a secret or public regular file without requiring read authority. Scoped creation validates physical Unix ancestors through held..handles: current-user/root ownership, no group/other writes unless sticky. Linux POSIX ACL permissions are bounded by the mode’s group mask; macOS additionally refuses extended ACL entries. Windows holds parents without delete sharing, proves a safe owner/ACL inheritance chain to a protected boundary, then revalidates top-down. The opened workspace is checked too. Windows secret directories use protected, inheritable owner-only DACLs; replacements and editor backups inherit privacy. This cross-user proof excludes same-user or privileged interference and retained attackerWRITE_DAC/WRITE_OWNERhandles granted by a formerly unsafe Windows ACL: changing a DACL does not revoke existing handles.walkdescends from the root through directory handles with no symlink followed by the kernel, splicing each link into the name itself (a link’s target read through the handle held on it), and hands back aLocated— the directory handle, the leaf, and theTracewhoseRealPathis symlink-free and whosepassednames each link whose target it read and each directory a..climbed out of — whose every operation is handle-relative. A held link never reads a replacement’s target: if the filesystem refuses its read after unlink (APFS on macOS 26), the read refuses rather than looking the name up again. Each step is one host primitive,step, reading the child’s stored name and identity from the handle just opened (Linux the nameopenatresolved, macOS the parent’s listing for that identity, Windows the normalized name checked against the parent’s path). A..is physical, the kernel’s rule, even from a link target (the user’s own path keeps its logical fold); the splice count is bounded byMAX_HOPS.handle/error.rs::failure_trace, exported byhandle.rs, takesloop_trace’s actual failed-link transcript from a spent-budget error, else walks the name leniently withLeafMode::Follow. The fs doors judge it for their operation, heads for running, before disclosing the error. Every restart, the given name and each splice alike, is put to onerootedcheck, so a link target relative to a drive’s current directory or with an unparsed head is refused as the name itself would be.walk_dir,walk_lenient(a grant spelling’s transcript, as far as the disk goes),walk_excluded(an exclusion’sExcluded, the link and its target held) andopen_discardare the other entries;Dir,LocatedandHoldare the three holders andUnjudged,Reading,WritingandInstallingwho vouched (path-judgment); - match —
identity.rs:RealPath::contains, an allowance by position, names as stored (on Windowswindows_stored_components, preserving stored case and unifying/vs\, and\\?\-verbatim spellings), andExcluded::matches, an exclusion by position undercollision_key(compatibility caseless matching of the uppercase image, ICU4X, the coarsest identity any filesystem gives a name) or by the object its walk held, answering aMatchedBy(denies-hold-under-every-spelling); the form-blindpath_withinis private to the file; - name a device —
device::is_discard_device, behindLexicalPath::is_discard:/dev/null, or on Windows exactly the device-namespace spelling\\.\NUL(either slash, any case), and no other path. Every other Windows path whose last component is a DOS reserved device name —NUL,CON,PRN,AUX,COM1–COM9,LPT1–LPT9,COM¹–COM³,LPT¹–LPT³, any case, any extension, trailing dots and blanks trimmed — is refused, not excused:device::reserved_device_refusalphrases the error (forNUL, as the question “did you mean\\.\NUL?”), andguard::check_device_nameasks it at the fs entries,Shell::locateand its siblings, ahead of any grant. A resolved path keeps its last component, so the check needs no raw spelling. Like the identity rules above both takewindowsas a parameter rather than readingcfg!, so neither table is dark on the other host.
resolver.rs composes the stages — Resolver::resolve and
Resolver::anchor are the sole constructors of a LexicalPath
(forms.rs, with its grant-side twin FrozenPath), so a walk
cannot run before lexing: the ordering is in the types, not convention.
resolve takes surface text and expands sigils first; anchor takes a path
the host already holds, a walked entry say, and expands nothing, so a file
named ~ stays that file and a non-UTF-8 name is never renamed by a string
round trip.
path::spelled anchors a host-held path against the process’s cwd with
Resolver::anchor, returning a sentence if that cwd is unavailable.
A Resolver is a environ::EnvVars and a CwdPath: ~ reads env.home(), xdg:
the XDG_*_HOME of env through get_or_host, so a within [env: …] overlay
reaches both. Resolver::at builds one for a caller with no shell to mint one; resolve_in_script is
resolve for a path written in a ral script, which reads it beside itself:
it is resolve itself with the script’s directory for the cwd, so the two
agree: sigils expand first, only a still-relative result joins the
script’s directory, and an absolute one, a malformed head included, is kept
as resolve keeps it, never lent the directory’s drive. The directory is
the native parent of the file’s SourceOrigin, never a re-parsed rendering
of it, anchored as anchor takes it, so a script under a directory named
~ stays there. A virtual source has no directory,
and its paths resolve against the cwd.
A module read has one candidate: the path written at use. The loader
resolves and judges it with shell.locate at check time, using the containing
file as anchor (the session cwd for a virtual source), check-time environment
for sigil heads, and the grant then in force. No surrounding within or
grant, or earlier cd in the unit, changes that read. The lexical grant
still governs the module’s runtime effects. A denial is stamped at use and
survives in the dispatch trail on static refusal. --check boots and applies
profiles before taking this same compile path. ral reads no RAL_PATH;
plugins likewise name one file (plugins).
tree.rs is the one directory-tree walk, tree::Walk: ral enumerates, with
Dir::read_dir and Dir::open_dir, depth first in name order, and ignore only
matches (tree/ignore.rs is the rule engine over ignore::gitignore, opening
nothing). A Walk is told what it may enter (respecting_ignores;
work_tree, which keeps dotfiles but skips every .git; all; or search,
the walk every search reads: ignore rules kept, or with hidden all but .git,
on one file system; a depth; link following; a Filter) and which region it may read (readable_by), judges every directory it enters, every file
it reads for its own guidance and every entry it yields against it, polls the
cancel scope at each entry, and yields WalkEntry { shown, names, found },
which tells a pruning from a refusal from an entry unseen. A Filter is an
automaton the walk runs: its State is carried from each directory’s frame
down to its entries (step drops an entry with all beneath it), and yields
and enters decide the rest. () is no filter, and a predicate on an
EntryName is one by a blanket impl. The root comes first whatever the
filter says, which decides only whether it is entered. Entries append through
LexicalPath::join, preserving the parent’s spelling, including dots in
Windows verbatim paths; PathBuf::join would normalize those away. An entry
carries its names beneath the root (names), and no reader takes shown
apart to recover them: WalkEntry::key slash-joins them (synod’s manifest
keys), and WalkEntry::name follows the root’s cwd-relative spelling with
them, or with none is absolute, returning Result<String, path::NotUtf8> with
no runtime types. A relative name is never the entry with the cwd stripped off:
a verbatim cwd (\\?\C:\d) folds .. as Win32 reads it, so ..\x anchors to a
path the cwd no longer prefixes. Relative names omit a leading . name but
retain .., and the root spelled . or nothing is .. A name reads back as
itself: one a sigil would claim is spelled ./~/x (sigil::literal_relative),
and one no ral string can hold is refused (path::to_text).
tree/glob.rs is glob’s pattern language, a Filter. Glob::parse lexes the
pattern as a path is (parse_bytes): its head and the names before the first
wildcard are the prefix, kept as written (never reassembled by PathBuf::push,
which re-roots on a drive name and folds verbatim ..), and a head the lexer
reads whole (exact verbatim, device, malformed) is the whole pattern. Past it,
. names drop, .. is refused, and each name is a literal (matched byte for
byte), a wildcard (globset, never a hidden name) or **. A name the
pattern follows with a separator is a directory: a trailing separator, or a
** after the name that matches nothing, asks for one (Filter::yields is
told is_dir, a followed link included), so a.txt/ and a.txt/** match
nothing. The glob’s state is how the entry matches (Match: by its name, or
as a directory) and the steps a name beneath it may take; ** never passes
beneath a link, though it names one, and a link another step takes is passed
through. The root matches only where the prefix
spells it, so no match is named by nothing.
Shell::admitted_walk (shell/runtime/walk.rs) wraps a walk beneath a path as
AdmittedWalk: Resolver::resolve_named gives the root and, after one
~/xdg: expansion, its spelling where that reads against the whole cwd
(Windows \x and D:x give absolute names); Shell::locate_existing asks
the grant of the root, so a denied root, there or not, is refused and an
absent one is None; it selects the live region and scope, raises a root the
walk could not see or enter, skips unseen entries beneath it, and converts
cancellation to a non-catchable stop and naming failures to contextual errors.
glob takes None as no match; Shell::walk_beneath, which exarch’s
grep-files, grep-hidden, find-files and explore-dir use over
Walk::search, takes it as NotFound.
which.rs is the one PATH walk. Its anchor is an Option<&CwdPath>: the
shell’s cwd cell, or None for a shell-less caller — and CwdPath has one
constructor, so no call site can choose “here” for itself.
names_a_path(lex/command.rs, with the rest of the command-name lexing) is the one answer to “is this command name a path?”: it bears a separator under the host’sPathRules(PathRules::is_separator:/everywhere,\under Windows alone), so off Windowsa\bis a bare name forPATH.names_a_path_fortakes the rules, and the lexer’sWord::Path,ir::CommandName::of, the walk itself and the grant decoder’s`namecheck all ask it.path_dirsis the sole directory list behindlocateandsearch; it drops emptyPATHelements on every platform, so a trailing;or:never means the cwd..and./binare honoured, as written.locate_inis a Linux-only, unmemoised search over directories a caller already holds (path_dirs(…, None)for bwrap’s pin, absolute entries alone), so no list is re-joined into a string to be split again.searchwalks every candidate inPATHorder at most once and hands each walk, aCandidate, to the judgment; none with noPATH. The memo’sAnswerremembers the first candidate whose walk found a program (Located::holds_program, the one executable predicate), an undisclosed ordering hint: that candidate is walked first and judged at itsPATHplace.locateis the unjudged fold of the same walk.preparereads the judged fold’s verdict without probing.- On Windows,
%PATHEXT%suffixes append:build.ps1yieldsbuild.ps1,build.ps1.EXE, …, neverbuild.exe. - Grant construction walks the
PATHof the decoding environment with no anchor, so neither a scopedPATHnor a relative entry can redirect a bare key.
A FrozenPath (forms.rs) is a spelling and nothing else: folded, shown,
ordered. What it names is the walk’s to say, once,
when the layer is decoded: GrantPath { written, real }.
Every authority is judged on `real`:
RealPath::contains for an allowance, Excluded::matches for an exclusion —
and no other way: path_within and its string twin are pub(super) to
identity.rs, so the form-blind kernel does not leave core/src/path/, and
outside the module a spelling leaves the type only as a string (as_str,
into_string) for rendering. That is enforced rather than documented because the
xdg-* freeze guard once chose the form for itself — asking on the surface while
the check it guarded matched the real form — and read a symlink out of HOME as
contained.
The set-level algebra over prefixes is not in path/: it is
authority::policy::table, which names polarities and never identities, so every
spelling question stays here. RealPath (handle/trace.rs) is the position a walk
ends at and the identity of a run place, ordered as the host identifies files.
XDG base directories resolve through one resolver, path/basedir.rs
(XdgKind, the pure resolve_xdg_in; host::xdg reads the host env, the xdg: sigil and the freeze an EnvVars; app_dir spells an application’s own $XDG_<kind>_HOME/<app>/ for ral and exarch alike): an absolute XDG_*_HOME override else the
home-joined Linux default on every platform, and None where there is neither
— a host fact answers with an Option, so each caller picks its own fallback
rather than inheriting a fabricated home. For the program’s own layout alone
(host::xdg, host::layout_home and host::home_dot) the home falls back, where no HOME is bound, to
the account’s own from the user database (the AccountHome site), so app_dir,
OwnDir, UserFile and the credential denies all see the same base; a ~ in a
script (host::home) is unchanged. Where even that fails, own refuses with an
error naming what to set, and no temp dir stands in. Both the xdg-* grant places
(sigil.rs, grant::freeze) and the host’s own config/data loaders (host::xdg) defer to
it, so a grant and the rc/history/plugin paths can never name different
directories — xdg-resolver-consolidation.
The files a program touches on its own account, outside any shell, are
core/src/own.rs’s, under one authority, the crate-private write side of
authority::policy::Ungoverned:
OwnDir— what the program keeps for itself (state, tokens, logs, caches, records, scratches): a held directory reached from an XDG root, one entry name per operation, no link followed beneath it;UserFile— a file the user writes at a place the program chooses (the rc,config.ral, house rules): links followed, a replace staged beside the link’s target so the link survives,seedwriting only where nothing stands;read_named,read_named_source,open_named,kind_named,create_named— a file the user names, the one write being a new file.read_named_sourcereturns text and the real path of the same held object, fixing a script’s identity before boot can change cwd. They take any path, soclippy.tomlbans them, and each caller is a typed site that says why the name is the user’s: a CLI argument, a TUI command, the install tree.
own/site.rs holds two authority-mint sites, Silent::{Read, Write}, for
clippy-banned Ungoverned methods, but no syscall sites:
each syscall it needs is a walk primitive
(walk_dir_made, Located::{remove, rename, open_data}, and Visibility’s
Public, Private and Secret). The config home holds only what the user
writes (own-files).
OS sandbox — core/src/authority/sandbox/
External commands inside a grant block run under an OS sandbox enforcing the
declared filesystem and network capabilities — and exec, wherever a
backend carries the allow-list into the kernel, so a grant whose only opinion
is exec engages the sandbox too (sandbox::EXEC_ENFORCED, the one statement
of that fact, read by SandboxProjection::of). Exec is
guarded in-process on every platform (guard::check_exec) before the
spawn; both Unix
backends additionally render the same rules into the kernel, catching the
re-execs the in-process guard never sees (sh -c, find -exec) — macOS as
Seatbelt process-exec forms, positives then negatives, Linux as a Landlock Execute
ruleset the payload enters inside the bwrap envelope over admits the parent
opened in the host (linux/landlock.rs;
Landlock being allow-list only, a deny inside an allowed directory is
subtracted from it, entry by entry over the tree at launch; Any lowered against
the bind plan, which is computed before the ruleset). carriers.rs computes the
live support the kernel must admit beside the table for a script to start,
under any confined launch whose fs or exec is restricted: system-vouched #!
interpreters and macOS shims, by trusted_real — regular files only, judged
against the effective uid — never env’s target
(exec-carriers). The AppContainer on
Windows has no path-exec filter, so there the in-process guard stands alone (the deny-by-default fs projection still bounds
which images a child can read, and so load, at all). Exec-deny ACEs and
directory execute/traverse semantics remain unimplemented. Native Windows
verification of stored-case walks, verbatim image launch, launch refusals and
handle-inheritance serialization is outstanding; cross-compilation alone does
not establish them.
Pathname Unix sockets outside a host envelope follow stated fs writes:
linux/landlock.rs handles REFER | RESOLVE_UNIX on every ABI >= 9 launch,
adding EXECUTE for a restricted exec; directory writes are lowered onto the
bind roots and file writes admit the opened file alone. bwrap masks fs denies.
macos.rs::emit_fs_restricted emits outbound, bind and inbound socket clauses
per write name and the corresponding denies afterwards. Unrestricted fs admits
no outside socket, so exec-only, net-only and gpu-only grants admit none via fs.
The macOS resolver additionally rides net; Linux admits no resolver socket
and falls back to DNS over IP. Below ABI 9 every pathname socket a bind shows
remains reachable, even offline
(the ABI migration).
A sibling launch needs a write covering the server socket. A write covering
a deputy admits it, and a writable foreign socket can be unlinked and replaced
to intercept later clients; the five restrictive bundled profiles write only cwd, gitdir and scratch.
exarch’s $TMPDIR is $EXARCH_SCRATCH/tmp: hardcoded /tmp is per-command
memory on Linux and refused on macOS.
unix-sockets-follow-writes
records the policy and its limits.
Inside a guest, ral-guest starts the engine as
--guest-engine <cgroup-root>, named by guest_abi::layout::ENGINE_FLAG.
The daemon and jail share layout::EXEC_CONTROLLERS. The role installs the
spawn jail, so Command::prepare
(shell/exec/command.rs) uses it for every command: the one unprivileged
GUEST_ID and a per-exec cgroup, the envelope’s seccomp deny-set, and
close-on-exec marking above stderr. The daemon disables the user namespaces bwrap needs.
GrantStack::net, the stack’s one veto, carries any layer’s to both the host projection
and JailPlan: an offline guest command gets a fresh network namespace with
loopback up. IP egress and outside abstract Unix sockets are out of reach;
the guest jail installs no Landlock domain, so pathname socket reachability
is determined by its shared filesystem.
The in-process guards apply unchanged (docs/SPEC.md §12.11): fs and exec
bind the command head, and the guest builds no filesystem or executable
projection to constrain an admitted program’s descendants (rg --pre,
env, find -exec). Their filesystem and execution boundary is the jail
and the VM wall. The seccomp deny-set and offline namespace bind descendants.
pin()andboot()— startup:pinpins ral’s own executable (reexec::OWN) and, on Linux, the bwrap envelope (linux::pin_envelope, walked on the process’s ownPATHbefore any shell exists);bootispinand, on Windows, the boot-time orphan sweep (windows::session::boot_recover) that deletes a crashed prior session’s AppContainer profiles, matching their ledger owner by PID, image and creation time. A test binary is the same multicall executable a confined child re-execs, so it must serve these flags from its own pre-main#[ctor](it reachesmainonly through libtest).invocation::serve(&role, installers)(core/src/invocation.rs) is the one pre-maindispatch, over the rolecore/src/role.rs’sclassifynamed — run byral, exarch and every test#[ctor]alike, surfacing a served role’s exit code so the caller can terminate. It serves aWarrantrole first (serve_warrant), before any pin, so the trampoline pins and opens nothing before it is confined; the pipeline anchor spawns nothing and runs unpinned. Every other role — the engine, the shell — runsbootfirst, and theBundledToolmulticall onlypins, so an--engineprocess has bwrap pinned exactly as the shell does. Skip it andOWNstays unpinned, so the per-command launcher refuses to re-exec a binary it cannot vouch for.test_helper::confinementshares live enforcement evidence across core, ral and exarch tests.require_confinement!obtains a cachedConfiningonly after an fs-confined/bin/echoexits successfully with its exact marker (cmd /c echoon Windows), under a read-only grant on a fresh temporary working directory. An unavailable envelope or an already-profiled Seatbelt runner prints the test’s skip reason locally;RAL_REQUIRE_SANDBOXmakes that a failure. CI requires it in Linux containers and native CI runs.admittedchecks a successful control and its marker;deniedtakes that control under the same grant and checks the denied operation cannot return the marker. A masked file can read as empty with exit zero, so status alone cannot establish denial. Coverage includes top-level dispatch, grant, spawn, par, pipeline stages and out-of-grant reads on both Unix backends. Test constructors also serveRAL_TEST_PROBE, a JSON argument array for descriptor, socket, resolver and platform IPC probes. Warrants and anchors take precedence; an ordinary probe runs before boot opens any descriptors. A Landlock ABI test (landlock_reaches) fails under the requirement where Landlock is absent, below ral’s own minimum (BASELINE_ABI, ABI 1:planrefuses an exec-restricting grant without it); a kernel at or above it but below the test’s ABI skips throughskip_beyond_baseline, never a failure. Volume prerequisites name their skip reason independently of the confinement requirement.core/tests/local_ipc.rscovers live host socket refusals, online IP controls (UDP requires the host peer’s echo), macOS resolver and shared-memory access, and Linux abstract peers inside one launch (Landlock ABI 6). Windows session tests inspect the staged launch’s network SIDs across offline/online transitions; AppContainer loopback cannot supply a live peer control.core/tests/sandbox_assurance.rschecks rename targets, directory removal, and a detached child’s read released by pipe only after its host exits. The macOS warrant test approaches the socket-buffer ceiling: the complete warrant arrives, or preparation refuses before spawning.reexec.rs—Pinned, an executable pinned at boot: the one shape everyCommandthe sandbox execs is built from, so nothing a session does to its environment can choose the file. Two are pinned: this executable (OWN), so a confined re-exec runs the same binary even under an on-disk swap, and on Linux the bwrap envelope (linux::ENVELOPE). Its methods arearg0(the on-disk path,argv[0]of every exec),command(theCommandthat execs the pin: through/proc/self/fd/<N>on Linux, by name elsewhere),object_id, on Linuxfd(the pinned descriptor) andnames(the inode’s current name,Noneonce unlinked), and on macOSverify;reexec::launch(role)is the one launch entry for the unconfined re-execs (the pipeline anchor, a bundled tool), through the pin when there is one, andreexec::own()is ral’s own pin as aResult, so a sandboxed launch refuses when ral could not pin itself. A swap is askable where the host can say so: on Linux the retained descriptor makes/proc/self/fd/Nresolve to the boot inode; on macOSverifyre-walks the name and compares itsObjectIdbefore each spawn; on Windows nothing is pinned, since there is no parent-side self re-exec for a guard to protect andlaunchtakes the livecurrent_exe. On Windows there is no child re-entry at all — confinement is the AppContainer token the parent attaches atCreateProcessW, so a child asking to confine itself (--warrant) is refused with 126, and the pinned self serves to grant the container read on the bundled-tool re-exec image.Pinned::verify, the parent-side swap guard, is macOS’s alone, which execs the trampoline by name; Linux execs it from ral’s pin, lent like every descriptor, so there is no name to verify.projection.rs— the sandbox’s own view of authority:SandboxProjection::of(&GrantStack, &Baseline, Option<&Admitted>)meet-folds the stack once, at spawn, intoFsProjection(read: Vec<FsAllow>, the live positives of the read region with run places and live support among them, beside the write prefixes, the system reads and the exclusions; allowances keep their resolved positions up to rendering, exclusions stay the read table’sFsDenys and render from the resolved real paths their walks held; deny comes from the read region alone, the two regions holding the same exclusions, so a disk change between the two folds can only drop a write allow, which fails closed;FsLists, whoseSandboxProjection::renderedderivespinned_dirsand whoseread_withheldgives the read table’s verdict; no write reach classification) andExecProjection::Restricted(KernelRules), the stack’s table compiled once here,for_kernel, joined with the live support (sandbox::carriers);Admittedbrings only the launched file whose carriers are support. It takes noShell;Shell::sandbox_projection(shell/runtime/state/checks.rs) is the entry.WITHHOLDS_GPU(sandbox.rs) — read bySandboxProjection::ofand byprotocol::probe::Grants::ofintowithholds_gpu: the one place the host’s inability to withhold the GPU (Windows) is stated. A withheld GPU there projects as left on and refuses nothing.sandbox::unavailable(defined inprocess/launch.rs, re-exported bysandbox.rs) — mints theErrorfor a confinement this host cannot establish, so that nothing ran and it is never the command’s fault: there was no bwrap onPATHto pin at boot (linux::envelope, asked at the first launch that needs it), or the pinned envelope failed to spawn.Launch::new(process/launch.rs) builds the unsandboxed external exec image;Command::preparereaches it directly when no projection is active.launch.rs(Confinement::launch,ProgramLaunch,sandboxed_command) — the per-command launcher.ProgramLaunchisDirect(Launch)or, on Linux,Enveloped(EnvelopedLaunch);launch_mutconfigures either inner launch, andspawnandspawn_detacheddispatch once.Confinement::denial_pidsnames the pids whose kernel denials a spawned child owns. Unconfined and guest-jail launches are always direct. macOS builds a directLaunch::trampolinedwith its report fixed at construction; Windows keeps its direct launch and token description. Linuxbwrappedandenvelopedreturn the envelope’s own launch type, with mandatory report and diagnostics.Command::prepare(shell/exec/command.rs) routes an external or bundled child through here whenever a projection is active and the process is not already confined, confining that one child, theAdmitted’s program: aProgram::Fileby the real path the guard judged, its spelling asargv[0], or aProgram::Tool. macOS and Linux share one trampoline: the pinned ral itself, whose whole argv isral --warrant <w> <r>(Role::Warrant), the warrant’s descriptor and the report socket’s. The confinement to enter and the program to run cross in aWarrant(sandbox/warrant.rs, its fields private) compiled in the parent. The confinement isConfinement, one type per platform withspell,parseandenter: on macOS the profilemacos::build_profilecompiled, and on Linux anOption<Landlocked>, spelledunconfined,landlock@<fd>orlandlock+refer@<fd>, the ruleset’s descriptor; the program is anImage: a file carries its real path andargv[0], a tool a&'static strfrom the bundled-tool table. Head resolution and warrant decoding use the same lookup; unknown tools and nonabsolute files refuse.Warrant::confineis the only way to the program: receive and verify the warrant, enter the confinement (macos::apply_profile,Landlocked::enter), sweep every descriptor above stderr but the report’s, and yield aConfined, whoserunsays on the report what became of the program. macOSexecves a host file in place and runs a bundled tool here (uutils::serve); Linux supervises, spawning the file or forking the tool and reporting the exact wait status (a-supervisor-never-execs, the-trampoline-is-a-supervisor).serve_warrantserves the child and exits with a verdict only where a report cannot carry one: a failure to enter the confinement is arefusedrecord, a program that cannot start anunstarted(errno)(a-launchs-report-is-the-trampolines-alone). The encoding is NUL-terminated fields behind aral-warrant/5magic: afileis its real path, then itsargv[0]spelling, then its argc and argv (the interpreter, read by the parent, stays the parent’s); atoolits name, then its argc and argv; canonical (decode re-encodes and compares) and at most 8 MiB. It rides a descriptor, only its number in argv: a sealed memfd on Linux, checked again after sealing, and on macOS a prefilled socketpair whose writer closes before the child exists; the child refuses an unsealed memfd or a non-socket. Every descriptor a launch hands down crosses at the number aHandoff(warrant/handoff.rs) lifted it to, from 98 up (Slot): bwrap’s--args, the warrant,--info-fd(a socketpair, which unlike a pipe cannot be reopened through/proc) and the payload’s copy of its writer, whose sweep ends the parent’s read once the payload’s group exists, the Landlock ruleset, ral’s pin, the trampoline bwrap execs, the seccomp programs (sealed memfds) and one mount handle per bind. The handoff’s onepre_execonly clears close-on-exec: nothing isdup2’d, so no descriptor it still uses (std’s exec-error pipe,detach’s handshake) can be displaced. Each number is named as data: to bwrap in its options, the ruleset’s in the warrant’s confinement, the warrant’s in the trampoline’s argv. The Linux child sweeps everything above stderr withclose_rangeafterLandlocked::enterconsumes the ruleset. macOS lists descriptors withproc_pidinfo(PROC_PIDLISTFDS)and closes each above stderr before Seatbelt entry, including those above a lowered soft limit. The warrant role opens nothing before the sweep; aConfinedpromises both confinement and stdio alone. macOS spawns the trampoline directly; Linux spawns it underbwrap(bwrap_command), giving the full shape bwrap → ral trampoline → Landlock → the program, its child. The real argv isbwrap --args <a> -- /proc/self/fd/<t> --warrant <w>:bwrap_argvis pure in descriptor numbers and returns bwrap’s options alone, which bwrap takes from--args. The order is forced rather than chosen: a Landlock domain handling any fs right forbidsmount(2), bwrap’s first act, so the layer can only be entered inside the envelope bwrap has already built. Linux’s confinement names no path: the parent opens every admit by handle, never through a symlink, so each rule reaches the file a grant froze.landlock::buildplans the handled set from the parent’s one probe (plan), creates theRulesetby raw syscall, and admits each allowed file as itself and each live allowed directory as its hierarchy less what the table blocks beneath it (expand, which stops where a bind mount loops back onto a directory it is listing), each opened in the host byopen_nofollow/open_dir_nofollow(RealPath’s walk with every link refused, held asInstalling); an absent admit is dropped, a file admit whose path has since become a directory is dropped, not admitted as a hierarchy, a symlink since planted refuses the launch, and a restricting exec projection is refused where Landlock is unavailable. The payload probes nothing: it takes the ruleset at its slot, adds onlyReferon its own root, which exists nowhere else, and fails closed if a promised ruleset never arrived.bwrap_commandtakes theEnvelope(bwrap’s pin, the trampoline’s, and theHostEnvelopeprobed once by running that trampoline as a pipeline anchor), the image (Program::File’s real path, the file the trampoline execs), the handoff so far and the rendered projection, and refuses outright under a bwrap that builds no envelope, in bwrap’s own words, or one without--ro-bind-fd(HostEnvelope::builds).Binds::openis the one place a launch opens what it mounts: the read-only defaults, the read and write prefixes, the image, each allowed file and live allowed directory of theExecRulesof theExecProjection, and the cgroup tree in theOverlayer, each object (render_objects: a path’s canonical spelling, its other spellings mounted too unless within another bind) opened once byopen_nofollowand lent once per bind. A read-only bind within another bind is dropped, a writable one only within a writable one; an absent object drops its binds, and so does a system default this user may not reach, while a name now reaching outside what was rendered refuses the launch. Every allowance is bound as its resolved real position, a redirected one refusing the launch, and each deny mask goes on wherever the final bind layers show the denied path (Binds::names): names beneath anOverdestination are replaced by what that bind shows, so cgroup exclusions follow the re-rooted tree. A mount laid inside one bind of an object does not show at another, so a prefix written through a symlink, two binds of one handle, is masked at both. A deny hiding/procis refused, the envelope starting its trampoline through it, and so is one holding the working directory, which no--chdircan enter. The two pins join theOverlayer by copies of their own descriptors, read-only at the names their inodes hold now (pinned, overPinned::names), an unlinked pin binding nothing.bwrap_argvemits--ro-bind-fd/--bind-fdfrom the same vector,Shown, before/procand/dev,Overafter.--chdircarries the context’s absoluteCwdPathbytes, while every rendered name refuses a position that is not Unicode rather than go lossy into bwrap’s argv. A malformed or unreadableInfoFdrecord makesEnvelopedLaunch::spawnkill and reap the envelope before returning its error; an empty record means bwrap died before reporting its payload. Windows builds the target’sLaunchdirectly with aConfineddescribing its token, and everyLaunch::spawnrunswindows::session::confine, which stamps and returns its projection’s AppContainer LowBoxSECURITY_CAPABILITIESforCreateProcessW, so the parent’s own spawn is the confinement point — never a re-exec child. The process module’sspawn_lock::lock_inheritanceserializes rawLaunchcreation and temporary inherit-flag restoration with helper-backedCommand::spawn, releasing before Job Object placement/resume and waits. The raw child’s explicit handle list restricts only that child; unrelated dependency spawns remain outside ral’s mutex and may still inherit temporarily exposed handles. A bundled tool there is a plainral --ral-bundled-tool <tool>carrying no warrant, andserve_warrantrefuses--warrantoutright. The launcher also takes anOwnership(Kept/Surrendered, the second variantcfg(unix)since only there does the verb that makes the distinction exist): it reaches the Linux backend alone, which decides the two ties between the session and the envelope — death (--die-with-parent) and address (--info-fd) — so adetached survivor keeps the birthing frame’s projection, namespaces included, for life while dropping both (runtime). The grant body itself evaluates locally, external children being confined per-command (sandbox-external-children).- Backends:
macos.rs(Seatbelt,macos-base.sbpl;Profile, a record whose field order is the rule precedence (no freeze section), and in every profile ral’s own file is write-denied and its ancestors unlink-denied),process/limits/fork_brake.rs(macOS’s process budget: the confined child’sRLIMIT_NPROC, the user’s count at launch plus 512, bounded by the system ceiling and inherited hard limit; failedsetrlimitrefuses the launch, andlimits::failure_hintexplains a possible fork refusal on status 128 without asserting its cause),linux.rs(bwrap: thePinnedenvelope, exec’d by descriptor and never by name, its own file read-only bound inside every envelope after the projection’s binds; the argv —--new-session, the ipc/uts/cgroup namespaces and, by host fact, the pid one,--procon both projections, the seccomp deny-set (sandbox/linux/seccomp.rs:Filter,Syscall,explain; process reach includespidfd_getfd,process_madvise,process_mreleaseandkcmp, withmodify_ldtalso killed on x86-64;kill,pidfd_openandpidfd_send_signalremain admitted;ioctlrefusesTIOCSTIandTIOCLINUX;socketadmits only Unix, IPv4, IPv6 and routing netlink,socketpaironly Unix, and io_uring is refused withEPERM;Whenholds alternatives of conjunctions, checked at compile time;Programsretains compiled BPF and installs it without allocating or locking;linux.rs::seccomp_programsserialises per launch);InfoFd, the payload’s pid read back for aKeptlaunch;linux/host.rs,HostEnvelope, the probed host facts the render is pure in;linux/gpu.rs,GpuNodes, the GPU’s device nodes and sysfs found at each launch and bound by name), andwindows.rs(Job Objects capping the child tree at 512 processes, plus the AppContainer backend inwindows/:appcontainer.rsowns profiles and LowBoxSECURITY_CAPABILITIES;dacl/mod.rsexposes the path-derived capability-SID engine;session.rscomposes them). Withindacl/,stamp.rsowns completion witnesses,mutex.rsper-path locks (named by the path’s Windows collision key, folded beyond ASCII and at least as far as NTFS folds, where the witness and capability name are not: a lock errs toward merging, a witness toward splitting, and the stamp store is locked by an environment-spelled path two sessions may spell apart),ledger.rsprofile recovery, andacl.rsqueried descriptors and borrowed ACEs. Both files keep their JSON in one heldOwnDir,$XDG_STATE_HOME/ral/sandbox-dacl/(ledger_dir), each replaced whole byOwnDir::store.windows/local.rsowns Win32 local allocations. Kernel handles useOwnedHandle; the path mutex guard stays on its acquiring thread. Ported units retain their MXC provenance.
The Windows backend is path-keyed: each (canonical path, kind) grant —
kind ∈ {rw, ro, ls} — derives a deterministic capability name
ral.fs.<kind>.<128-bit-truncated SHA-256 of the canonical path> — hashed as-is,
never case-folded, so a case-sensitive directory’s two distinct names cannot
merge into one authority — and thence a capability SID via
DeriveCapabilitySidsFromName (dacl::fs_capability_name).
dacl::ensure_frozen_grant stamps that SID’s
inheritable ACE once and never reverts it. A read-write grant is two
permanent mutations, and neither witnesses the other: the mandatory-integrity
check runs before the AppContainer pass, and an unlabeled object defaults to
Medium, refusing every Low-IL child whatever the DACL says — so
ensure_low_integrity_label also stamps a Low SYSTEM_MANDATORY_LABEL_ACE,
asked before anything about the ACE, even where the well-known AppContainer
SIDs make the ACE itself redundant, and witnessed under its own stamp key and
its own SACL probe. For each mutation two witnesses gate skipping it —
the completion store (stamps.json in that directory, replaced whole and atomically by OwnDir::store, per-path
named-mutex merge) recording completed propagations, and a probe of the root’s
own DACL confirming its ACE remains. Before an ACE is reapplied, its old
completion witness is removed under the path mutex; recording follows
the apply, so a crash mid-propagation leaves no witness and the next grant
re-stamps idempotently while a child in the interim fails closed. A spawn’s
kernel-checked reach is then exactly the capability SIDs session::confine
mints into its token, those of its own launch’s grants and no other’s, so
attenuation shrinks-only: a narrowed grant or subagent gets a token lacking the
wider paths’ capabilities. An ACE lives on the NTFS
object and Windows does not re-inherit on a same-volume rename, so stamped
authority is object-sticky where a grant rule is path-based — dacl/mod.rs’s module
header records the resulting drift in both directions
(path-derived-capability-sids).
Every frozen allowance is checked before the session’s memo and stamped through a held handle on the very object checked, no redirecting reparse point on its path (a redirected one refuses the launch; a name surrogate redirects, a cloud placeholder does not; confined-launch), and a position that is not Unicode refused as DaclError::NotUnicode, since a Windows grant names its object by text; and a launch whose fs projection holds the universal prefix is refused before anything is stamped.
Within that shape: an AppContainer profile is still minted per distinct fs
projection (SessionSandbox maps ProjectionKey to profile) for the
deny-by-default token and named-object namespace separation, carrying no fs
authority, and DaclManager is the profile ledger — teardown deletes profiles
but restores no ACEs. The session caches Arc<OwnedContainerSid>,
Arc<OwnedCapabilitySid> and Arc<CapabilitySids>; each staged Launch
retains those owners independently of teardown. The spawn builds its raw SID
array locally and holds it through CreateProcessW, so deleting a profile
registration cannot free a launch’s SID allocations. A deny stamps nothing: the AppContainer pass of the
access check matches a deny ACE against the token’s ordinary groups only, never
its capability SIDs, so Windows cannot take back what a grant’s ACE admits
(path-derived-capability-sids,
amendment of 2026-10-20). So session::confine first carves each exclusion out
of the allowances around it: sandbox::carve::carve, a pure planner over an
injected lister and tested on every host, replaces such an allowance with its
existing entries less the excluded ones, down to each exclusion, and grants each
directory on the way only its own listing (GrantKind::List, an ACE nothing
inherits), so a name made there later, the excluded one included, reaches
nothing granted; links among the entries are neither granted nor followed. An
exclusion on or around an allowance, the program image included, cannot be
carved, and session::refuse_deny_meeting_grant refuses it before anything is
stamped. For every exclusion dacl/deny.rs’s ensure_unreachable then runs AuthzAccessCheck at each
launch, in an AuthZ context carrying the child’s package and capability SIDs,
on every object beneath it, refusing the launch if any right is granted — an
ALL APPLICATION PACKAGES ACE, or a hard link carrying a granted file’s ACE.
The walk checks reparse points as themselves without following them, polls
cancel per entry, and refuses an exclusion it cannot read. The child’s program image
is granted read-only, to its own launch, so a user-installed binary or the bundled-tool self image
can load at all, handed to session::confine as a RealPath, so the
canonical form the pin and the stamp’s local-prefix allow-list demand is the
type’s, not the caller’s care; and net: `offline is enforced by withholding the network
capability SIDs — a LowBox token without them cannot open a socket, so
the network axis is enforced on Windows.
macos-base.sbpl is the policy-independent Seatbelt base every rendered macOS
profile inherits, and build_profile lays the grant’s rules over it. Its POSIX
shared-memory allowance reads only apple.shm.notification_center and
com.apple.featureflags.shm, with no write allowance. Both are
read rule by rule — what each admits, what it withholds and why, and what the
backend pays to express an object policy in Seatbelt’s name language — in
seatbelt-profile.
Path-scoped exec confinement on Linux is a Landlock layer the payload enters inside the envelope; a deny inside an allowed directory is subtracted over the tree at launch, and only a veto under a trusted admit stays with the in-process guard — landlock-exec-layer.
diag.rs (with per-platform readers in diag/macos.rs / diag/linux.rs) turns
a kernel-reported sandbox denial into an actionable hint on the
failing command’s Error: it reads the kernel log over the call’s wall window
(Seatbelt on macOS, the seccomp record inside bwrap on Linux), and retains only
parsed Records whose pid the call’s start claimed
(an-external-end-to-end). The heading says
“sandbox denials were recorded for this command’s processes:”; a denial beside
a failure does not establish its cause. The parsed operation decides the
remedy, and the hint answers once per class present: a
file-read* path is offered to the grant’s read set and a file-write* one
to write (advice that fails twice, otherwise), a process-exec path to the
exec set — the layer a re-exec through sh -c or find -exec reaches, and
the only one that sees it — a network-* denial to the net axis alone, a
Metal device, IOSurface or compiler denial to the gpu axis alone, and a
mach-*/ipc-* operand to nothing at all, because a service is the base
profile’s to decide and no grant widens one. Denied is that taxonomy as a
type, and every operand it holds is an Inert: C0, C1 and DEL become visible
escapes, at most 512 Unicode scalar values are taken, and truncation is marked.
Raw log lines never enter the rendered hint. A service name cannot arrive where
a path is expected; withheld services
carrying a reason (macos.rs::withheld_service, the .sbpl’s prose as data) are
quoted with it and lead the hint, since they are the one class the reader
cannot act on — the securityd denial that broke cargo fetch was once ranked
below a .GlobalPreferences.plist probe and answered with a grant that would
have changed nothing. macOS logs fully-resolved paths, so the hint names the
exact path with the symlink caveat; on Linux, an operandless denial first tries
describe_denial, which consults
the seccomp deny-set by
syscall number and the parsed code= action. It repeats a rule’s reason only
when both match, including the errno value; another action earns no ral
explanation. A foreign-ABI record (an arch= mismatch) receives the arch
prologue’s explanation only for KILL_PROCESS; only where the
deny-set has nothing to say does the hint fall back, and it then says the
record names no operand rather than guessing at a set to widen. Windows has no
kernel denial log to scrape at
all, so its arm gates on the exit code alone: only an access-denied-shaped
exit (ERROR_ACCESS_DENIED / STATUS_ACCESS_DENIED) under an active sandbox
yields the fixed, pathless hint: never a fabricated path.
A script refused at its start reads no log: interpreter_hint asks the
launch’s own projection what withholds its #! interpreter, the kernel exec
table and then the read table (FsLists::read_withheld), and names an
exclusion first (no allowance reopens one), then a missing exec allowance, then
a missing read, each with the grant entry that admits it. The last is the case
bwrap shows as an absent interpreter.
collect(Collector) runs fixed absolute system paths: /usr/bin/log show --style ndjson on macOS; /usr/bin/journalctl or /bin/journalctl with
-k -o json on Linux, falling back to /usr/bin/dmesg or /bin/dmesg.
Each collector has a 2-second deadline and a 1 MiB stdout ceiling, and is
reaped on every outcome. A bound or failure supplies no hint, leaving the
command’s own error. JSON is decoded before eventMessage or MESSAGE is
parsed, so an operand’s newline cannot start another record. The macOS message
must begin with Sandbox: and its first (<digits>) deny(<digits>) supplies
the PID, followed by the operation and inert operand.
This boundary is what exarch reuses as its sandbox. Bundled
tools route through the exec chokepoint in-process; their filesystem
access has no in-process guard, so a bundled tool is never inlined — it is
spawned as a ral --ral-bundled-tool child and, under a restrictive grant,
floored by the OS profile of the per-command sandbox it runs in
(bundled-tools-as-exec-images,
bundled-tools-always-reexec).
That single binary carrying both ral and its coreutils is part of why ral
is a single-binary. docs/SPEC.md gives the
formal capability calculus.
Every fs/process constructor in this layer is a typed site: the workspace
bans the raw constructors via clippy disallowed_methods, so each call is
wrapped in site! with a variant that names it, a Surface one for the exec
image that raises a card (Launch::new, Surface::ProcessLaunch) and a
Silent one for infrastructure (the self re-exec, the
pinned binaries’ exec (Pinned::command), the ps denial sampler, the
boot-time binary pin). Raw libc::{syscall, socket, connect, bind, fork} and
rustix::fs::stat are banned too: each Landlock operation, the inherited-fd
sweep and both core forks have distinct Silent sites. Guest crates retain
their crate-root exemptions; test code
carries one blanket per module. The enums are the list: core/src/site.rs
for cross-domain sites, and domain-local site.rs declarations in path,
host, own, process and sync, each variant documenting why its place is
exempt. Ungoverned::{read, region, write}
are also clippy-banned, so each authority mint is a documented typed site.
core/src/own/site.rs declares the two own-file authority mints
(Silent::{Read, Write}, the second over a file or a directory), used in own.rs,
but no syscall sites, since every syscall it needs is a walk primitive
(own-files). The site
shapes and their rail rendering live in io-surface; here
the sites are only declared and accounted, with clippy failing CI on a
constructor under no site and on a site that no longer wraps one, and
core/tests/sites.rs on any other exemption, on a lint group that silences the
lint, and on a member outside the workspace’s lints
(typed-sites).