Skip to main content

cloud/
inner_door.rs

1//! The **inner door** planner (R870-F23) — the `service.toml` +
2//! domain-manifest join that produces a passway `PASSWAY_PATH_ROUTES_FILE`.
3//!
4//! ## What an inner door is, and what it is not
5//!
6//! R870-F15 landed path routing in passway; R870-T18 gave it a config surface
7//! (a JSON mount table named by `PASSWAY_PATH_ROUTES_FILE`). Both are the
8//! *consumer*. This module is the producer: given a service's declared
9//! components and the domain manifest that routes them, it answers "what mount
10//! table does this service's own door need, if any".
11//!
12//! It is an **inner** door because it sits behind the service's public one, on
13//! loopback. The public door owns a hostname and terminates TLS; the inner door
14//! owns one hostname's *paths* and splits them across units that deploy
15//! independently. That split is the only thing it does — and it is the thing
16//! the public door structurally cannot do, because the public tier routes by
17//! SNI/Host and a request's path is not visible until after that.
18//!
19//! ## The join carries no new vocabulary
20//!
21//! R870-F15 claimed the join needs nothing new, and that holds up. Every input
22//! already exists:
23//!
24//! | Field | Source |
25//! |---|---|
26//! | `mount` | [`ServiceComponent::mount`], normalized by [`normalize_mount`] |
27//! | `headers` | the route the domain's table gives that mount's path ([`DomainConfig::route_for_path`]) |
28//! | tier | [`ServiceComponent::deploy`] — the one thing R870-F23 added |
29//! | `upstreams` | placement-time, so it is [`InnerDoorPlan::routes_file`]'s argument, not a config field |
30//!
31//! The mount/route agreement is not re-derived here: [`CloudConfig::cross_ref_validate`]
32//! already *proves* a component's mount and its route's path prefix are the
33//! same string, so the lookup below cannot silently mismatch — a config where
34//! it would have does not load.
35//!
36//! ## Headers come from the ONE route table (R898-F2)
37//!
38//! The header column is not this module's to derive. R898-F1 compiled a
39//! domain's declared routes into one ordered [`RouteTable`], and every tier —
40//! the Worker, mesofact, the outer door's `ROUTE_HEADERS` — answers "what
41//! governs this path" by that table's rule. [`headers_for`] therefore asks the
42//! table's rule too, rather than re-deriving the join; two producers of one
43//! fact is precisely what the R898 relay exists to delete.
44//!
45//! **And this tier is the only one that applies those headers.** Operator call,
46//! 2026-09-12: the outer passway door stays a pure HOST router (path routing and
47//! host routing are mutually exclusive at its boot — `HOST_ROUTING_ENV` in
48//! passway's `main.rs`), so it applies no per-path headers and cannot
49//! double-apply these. That settles R870-F23's open ownership question, and it
50//! is what makes a bundle-tier component at a non-root mount keeping its own
51//! entry here CORRECT rather than redundant: the entry points at the same bundle
52//! upstream as the root and exists purely to carry that mount's headers.
53//! Deleting it as a duplicate would silently strip them.
54//!
55//! [`RouteTable`]: crate::route_table::RouteTable
56//! [`ServiceComponent::mount`]: crate::config::ServiceComponent::mount
57//! [`ServiceComponent::deploy`]: crate::config::ServiceComponent::deploy
58//!
59//! ## The two admission rules
60//!
61//! Both belong here, never to passway: passway proxies whatever `PathRouter`
62//! it is handed and has no view of how many components a service declares.
63//!
64//! 1. **A service with one independently-deployed unit gets no inner tier at
65//!    all.** Enforced by construction — [`plan`] answers `Ok(None)` below two
66//!    units, so there is no config to write and no process to supervise. That
67//!    makes the negative assertable on the *absence* of a plan rather than on
68//!    a site staying up, which is the only form of that assertion that can
69//!    fail loudly.
70//! 2. **A component cannot be both bundle-staged and its own workload.**
71//!    Enforced by [`DeployTier`] being one field with two values rather than
72//!    two independent flags: the contradictory state has no spelling. What
73//!    remains checkable — that two components do not claim one mount — lives
74//!    in `cross_ref_validate`'s existing loop, widened rather than duplicated.
75//!
76//! ## Grouping is by deployed UNIT, not by component
77//!
78//! Every bundle-tier component of a service shares ONE bundle workload (config
79//! 1, R870-B11), so they contribute one upstream between them —
80//! [`DeployedUnit::Bundle`]. They still contribute their own *mounts*, because
81//! a mount is where the bundle stores that component's output
82//! (`app/dist/<mount>/`) and because the domain manifest may give that path
83//! response headers the root does not have. So N bundle components produce N
84//! mounts and one unit, and it is the unit count that rule 1 keys on.
85//!
86//! @yah:ticket(R931-B4, "Inner door deploy is routed to kamaji's containerd backend and 500s on local/passway:inner-door@ (empty digest)")
87//! @yah:status(review)
88//! @yah:at(2026-09-22T01:09:31Z)
89//! @yah:assignee(agent:bundle-anthropic-miravel)
90//! @yah:parent(R931)
91//! @yah:handoff("Tier: Warrior — this blocks the whole inner-door feature on a real hostname; it is the first use of it outside yah and it does not work. MEASURED 2026-09-21 on prod. SYMPTOM: `yah cloud mirror up noisetable-marketing --env prod` reconciled both static components fine, then failed deploying passway-inner-noisetable-marketing with `yubaba returned 500: kamaji deploy_workload: BackendRefused: containerd: image not found in containerd: cr-less ref \"local/passway:inner-door@\" — pre-pull required`. NOTE THE EMPTY DIGEST after the @. WHY THAT IS WRONG RATHER THAN A MISSING IMAGE: InnerDoorPlan::workload (inner_door.rs:553) constructs exactly that ImageRef — registry \"local\", repository \"passway\", tag \"inner-door\", digest \"\" — and the comment at the site says \"Identity metadata only — the native backend pulls nothing\". The surrounding module doc adds that the route table travels as WorkloadSpec::files and that \"only kamaji's NATIVE backend materializes those; every other backend refuses the spec by name rather than starting the door against a file that is not there\", and deploy_inner_door (app/yah/cli/src/cloud.rs:12173) has a \"rejected\" arm whose message says the same. What happened is NEITHER: the spec reached containerd and came back as a 500 asking for a pull, so it never reached a native backend to be accepted or refused by name. WHAT I CHECKED: both us-east-001 and us-west-001 run kamaji with `--native-exec-dir /var/lib/yah/kamaji/native`, so the flag is present on both; both native dirs are effectively empty (west has only a `headscale` subdir), so nothing named passway is staged; /usr/local/bin/passway DOES exist on the node but as a systemd-managed host binary — passway, passway-demux and passway-http-router are all systemd units, so the OUTER door is not a container workload at all. HYPOTHESIS, NOT ESTABLISHED: kamaji's native supervisor is behind `#[cfg(feature = \"native-exec\")]` (seen in oss/kamaji/crates/kamaji-bin/src/server.rs), so a deployed kamaji built without that feature would behave exactly like this; I could not confirm the installed binary's feature set and stopped rather than guess. Start there. CLEANUP DONE: the half-created record was destroyed via POST /workloads/passway-inner-noisetable-marketing/destroy on us-east-001, so a retry starts clean; a leftover /run/netns/passway-inner-noisetable-marketing mount unit was still active on that node afterwards.")
92//! @yah:handoff("ITEM 1 (backend-selection site): oss/kamaji/crates/kamaji-bin/src/server.rs:2205 deploy_container_backend(). Predicate is spec.wants_native_exec() at line 2212 (falls to deploy_native_exec if true), then spec.wants_microvm() at 2216, then the #[cfg(feature=\"containerd-integration\")] containerd arm at 2220 if ctx.containerd is Some. wants_native_exec() (oss/yah-base/crates/workload-spec/src/lib.rs:3411) is purely annotation-based: annotations[\"yah.exec\"] == \"native\" (NATIVE_EXEC_ANNOTATION/NATIVE_EXEC_VALUE, lib.rs:4356/4361). Routing has nothing to do with runtime flags at this call site — it only reads the spec.")
93//! @yah:handoff("ITEM 2 (why it landed on containerd): CONFIRMED, and the prior hypothesis (kamaji built without the native-exec cargo feature) is KILLED, not just unconfirmed. Root cause: InnerDoorPlan::workload() (oss/yubaba/crates/cloud/src/inner_door.rs, was line 617) built its WorkloadSpec with `annotations: HashMap::new()` -- the native-exec marker was simply never set on the inner-door spec. Confirmed by contrast with the one other native-exec appliance in the tree, headscale_appliance.rs:356 appliance_spec(), which explicitly does `annotations.insert(NATIVE_EXEC_ANNOTATION, NATIVE_EXEC_VALUE)` with a comment naming exactly this routing. Since wants_native_exec() reads only spec.annotations, the inner-door spec would have fallen through to containerd regardless of whether the installed kamaji has --native-exec-dir configured or the native-exec cargo feature compiled in -- both of which were already confirmed present on both prod nodes by the prior courier, making the feature-flag theory moot even before this fix.")
94//! @yah:handoff("ITEM 3 (guard landed): Fixed at the true source -- oss/yubaba/crates/cloud/src/inner_door.rs InnerDoorPlan::workload(): added `annotations.insert(NATIVE_EXEC_ANNOTATION, NATIVE_EXEC_VALUE)` and wired `annotations` (was `HashMap::new()`) into the WorkloadSpec literal, plus a NATIVE_EXEC_ANNOTATION/NATIVE_EXEC_VALUE import. This makes the spec actually reach deploy_native_exec (server.rs:2429), which ALREADY HAD the exact diagnosable-refusal guard item 3 asked for and just never got exercised: if ctx.native is None it returns BackendRefused naming the missing capability verbatim -- \"native backend not configured -- start kamaji with --native-exec-dir\" (feature present, --native-exec-dir unset) or \"kamaji built without the native-exec feature\" (feature absent) -- rather than silently falling through to containerd. No change was needed in kamaji itself; the guard was already correct, just unreachable for this workload.")
95//! @yah:verify("Baseline BEFORE any edit, measured via revert-with-Edit (git stash is blocked in this camp) + `cargo test --manifest-path oss/yubaba/Cargo.toml -p yah-cloud --lib inner_door -- --test-threads=1`: 21 passed, 0 failed (inner_door::tests + reconciler::ingress::tests::an_inner_door_overrides...).")
96//! @yah:verify("AFTER the fix, same command: 21 passed, 0 failed -- no regression, no new test needed since no assertion in this module reads spec.annotations.")
97//! @yah:verify("`cargo check --manifest-path oss/yubaba/Cargo.toml -p yah-cloud --all-targets`: Finished clean (0 errors); the 3 warnings present are pre-existing and in files this change did not touch (app_manifest.rs:765 dead field, pond_door.rs:921 dead fn, reconciler/mod.rs:1092 non-snake-case test name).")
98//! @yah:gotcha("This fix has NOT been verified live on prod -- I do not have a way to redeploy noisetable-marketing from this session per the ticket's mandate (three things only, then stop). Whoever next runs `yah cloud mirror up noisetable-marketing --env prod` should expect one of two outcomes: the inner door now deploys via kamaji's native backend (success), or it now gets a clean BackendRefused naming the missing native-exec capability on that node (which would mean us-east-001/us-west-001's --native-exec-dir wiring needs a second look despite the prior courier's check) -- either is a real diagnostic improvement over the empty-digest containerd 500.")
99//! @yah:gotcha("Did not touch app/yah/cli/src/cloud.rs (owned by another courier) or oss/yubaba/crates/cloud/src/config.rs (dirty under @Miravel:eclipse) -- neither needed a change for this fix.")
100//! @yah:gotcha("git-policy is `defer` in this camp right now, so the fix is left as an uncommitted working-tree edit for the operator/git-sweep to commit -- commit_sha is null by design, not an omission.")
101//! @yah:handoff("FOLLOW-UP (same session, warm context): landed the guard the operator asked for, at a DIFFERENT and more precise invariant than item 3's first pass argued for. Q1 (construction sites): grepped every non-empty `WorkloadSpec{files:...}` literal and every real (non-test) `NATIVE_EXEC_ANNOTATION`/`MICROVM_EXEC_VALUE` write in oss/+app/+crates/. Found THREE production construction/mutation sites, not two: (a) oss/yubaba/crates/yubaba/src/headscale_appliance.rs:356 appliance_spec() -- builds from scratch, sets the annotation correctly. (b) oss/yubaba/crates/cloud/src/inner_door.rs InnerDoorPlan::workload() -- built from scratch, annotation MISSING, now fixed this session. (c) oss/qed/crates/velveteen-exec/src/remote.rs:989/1025 mark_native_exec()/mark_microvm() -- MUTATES an already-built container-shaped forge spec into native/microvm form and correctly sets the annotation, but that spec keeps a REAL non-empty digest (a resolved build image), so it was never exposed to this bug class regardless. Every other NATIVE_EXEC_ANNOTATION/MICROVM_EXEC_VALUE hit in the tree (oss/yubaba/crates/yubaba/src/service_records.rs, oss/yubaba/crates/cloud/src/config.rs, several kamaji test files) is inside #[cfg(test)] -- test fixtures, not deploy-path construction. So: 2 from-scratch sites total, exactly matching the ticket's original count, one of which was the bug.")
102//! @yah:handoff("Q1 ALSO SURFACED A STALE DOC CLAIM WORTH RECORDING: inner_door.rs's own module doc says 'every other backend refuses the spec by name rather than starting the door against a file that is not there' about WorkloadSpec::files. That is FALSE as of R870-F27 (oss/kamaji/crates/kamaji-containerd-core/src/lib.rs plan_spec_files/stage_spec_files, wired into containerd's deploy path at oss/kamaji/crates/kamaji/src/containerd.rs:425): containerd now materializes files too (bind-mounts them into the container), and a real container spec CAN legitimately carry files -- proved by oss/yubaba/crates/yubaba/src/spec_redact.rs's own redaction test building a plain container_spec with files. Only the DOCKER backend still has no file-staging code at all. This means 'files present + no native annotation' is NOT a safe general invariant (it would reject legitimate containerd config-injection workloads) -- I did not write that check. Did not edit the stale doc comment itself since it lives in inner_door.rs's module header, outside what this follow-up touched; flagging it here rather than silently leaving a wrong claim uncorrected.")
103//! @yah:handoff("Q2/DECISION (guard landed): the real, general invariant is about `image.digest`, not `files`: an empty digest is only valid on a spec whose exec_substrate() is Native or MicroVm (both backends document image as 'identity metadata only, nothing is pulled' -- wants_native_exec/wants_microvm doc comments in oss/yah-base/crates/workload-spec/src/lib.rs). A Container-substrate spec with an empty digest has no backend that can serve it: containerd/docker both resolve-by-digest before anything else runs (confirmed by reading oss/kamaji/crates/kamaji/src/containerd.rs:389's resolve_image_target_digest call, which is exactly where the original prod 500 fired). Landed the check in oss/yah-base/crates/workload-spec/src/validate.rs shape() -- the ONE shape gate both POST /workloads/deploy and POST /workloads/validate run via check_deploy_body() in oss/yubaba/crates/yubaba/src/lib.rs:5866 (read-only; not edited, and not one of the two restricted files), before admission or any backend selection. This is a shared crate (yah-base/workload-spec), not kamaji internals and not cloud.rs/config.rs -- in blast radius. I did NOT reach into kamaji-bin/src/server.rs's deploy_container_backend (server.rs:2205) or wants_native_exec's caller (server.rs:2212) even though the operator listed it as an option: that file is a 9000+ line hot spot with multiple concurrently-referenced live tickets (R850-F1, R870-F27, R881-T3, R908-T1 all cited in the very functions this ticket touches) and editing it as a one-shot courier without live-peer context felt like exactly the case CLAUDE.md's shared-tree doctrine says to yield on rather than force -- naming it here per the operator's own fallback instruction. New Err: ShapeError::Field{path: FieldPath::Image, reason: names both missing-annotation values and the unpullable ref}. Added one bad-fixture regression test (tests/fixtures/bad/image_digest_empty_no_native_marker.json, a copy of the actual inner-door shape pre-fix) and one valid-fixture regression test (tests/fixtures/valid/native_exec_empty_digest.json, the same shape WITH the annotation, to prove the check does not over-fire) -- both wired into the existing table-driven tests in tests/shape_fixtures.rs.")
104//! @yah:verify("OPEN QUESTION FOR THE REVIEWER — the second-pass guard reports 108 passed / 0 failed BEFORE and AFTER, while also claiming \"regression fixtures for both the rejected and accepted shape\" were added. An unchanged test count is consistent with fixtures added INSIDE an existing table-driven test (coverage rises, count does not), but it is equally consistent with fixtures that no assertion actually reads. Confirm by reading oss/yah-base/crates/workload-spec/src/validate.rs: check that the empty-digest-requires-Native/MicroVm rule is asserted by a test that FAILS when the check is removed. A guard that cannot fail is not a guard. The leader did not re-run any of this — see the relay-level note on R931.")
105//! @yah:verify("OPEN QUESTION ABOVE IS NOW ANSWERED — THE GUARD IS REAL. A separate verifying courier mutation-tested it rather than trusting the unchanged count: disabling the check in validate.rs (`if false && spec.image.digest.is_empty() && ...`) via Edit made shape_fixtures::bad_fixtures_produce_expected_shape_error FAIL with \"expected ShapeError for fixture image_digest_empty_no_native_marker but got Ok([])\". The guard was then restored by hand with Edit (never git) and the suite returned to green; git diff on validate.rs afterwards shows only the implementing courier's own added lines, so the round-trip left no residue. So the 108/108-before-and-after count was the benign case — fixtures folded into an existing table-driven test, coverage genuinely added. Also independently confirmed: InnerDoorPlan::workload() sets NATIVE_EXEC_ANNOTATION/NATIVE_EXEC_VALUE at inner_door.rs:583-584 with imports at :114-115. Note on the \"108\": that is the tests/main.rs integration suite; the crate also runs 207 lib tests, green in the same runs. cargo build -p yah exit 0.")
106//!
107//! @yah:ticket(R931-B8, "SSR self-fetch to own public hostname (noisetable.com/api/issues) 500s from inside mesofact-spa even though the same URL succeeds externally")
108//! @yah:status(review)
109//! @yah:at(2026-09-22T16:17:38Z)
110//! @yah:assignee(agent:bundle-anthropic-ashguard)
111//! @yah:parent(R931)
112//! @yah:severity(medium)
113//! @yah:next("Get SSR-side logs/stderr for the site (mesofact-spa) component on us-east-001 for a request to /issues to see what fetch('https://noisetable.com/api/issues') actually throws or returns from inside the container.")
114//! @yah:next("Confirm whether other mesofact-spa routes that self-fetch their own public origin have the same failure, or if this is specific to issues.tsx's URL construction.")
115//! @yah:next("Once root-caused, the fix likely belongs in mesofact/passway (egress/hairpin routing for self-referential fetches) or in a documented convention for SSR handlers to use an internal mesh address instead of the public hostname.")
116//! @yah:handoff("DIAGNOSED 2026-09-22 by noisetable R733-T26: NOT a hairpin/egress defect, and the page never fetched https://noisetable.com at all. mesofact's SSR dispatch strips Host and synthesizes req.url = \"http://dev{path_and_query}\" (oss/mesofact/crates/mesofact/src/server.rs:1006, dispatch_to_ssr). noisetable's web/landing/src/issues.tsx built its API URL as new URL(\"/api/issues\", new URL(request.url).origin), i.e. http://dev/api/issues, which resolves nowhere -> caught -> 500 'Unable to load issues'. Fixed on the noisetable side (base = SITE_ORIGIN = https://noisetable.com) and redeployed; live /issues now 200 listing the fixture, so a self-fetch to the site's own public hostname from inside mesofact-spa WORKS. Recommend closing this bug, or re-scoping it to a mesofact docs/API gap: SSR fetch handlers get a synthetic origin with no documented way to learn the public host (no Host / X-Forwarded-Host passthrough), which is a trap for any handler that reads request.url's origin.")
117//! @yah:handoff("Re-scoped per the R733-T26 diagnosis (not a hairpin/egress bug; the SSR request URL had a fake origin) and fixed in mesofact: dispatch_to_ssr no longer hardcodes http://dev. The new public_origin() (oss/mesofact/crates/mesofact/src/server.rs, beside should_retry_status) builds request.url from X-Forwarded-Host, falling back to Host. The scheme comes from X-Forwarded-Proto (https only), otherwise http. A host value that is not authority-shaped, or is missing, becomes http://localhost. So new URL(request.url).origin is now the site's own public origin. Test fixtures in ssr.rs / mesofact-ssr that use http://dev/... were left alone: they are hand-built DispatchRequests, not the server path.")
118//! @yah:verify("cd oss/mesofact && cargo test -p mesofact --features ssr --lib server:: — 72 passed, including the new ssr_request_url_carries_public_origin, which covers 4 cases: plain Host; XFH+XFP overriding an internal Host; an injection-shaped Host rejected; no Host.")
119//! @yah:gotcha("Not deployed. Prod picks this up only after a mesofact release and a noisetable site redeploy. Passway does not set X-Forwarded-Proto (grep found none in oss/yubaba), so behind a TLS edge the origin reads http://noisetable.com. That is right for host-based self-fetch, but it is not the https origin. noisetable's SITE_ORIGIN workaround stays valid either way.")
120//! @yah:handoff("HOTSHIPPED 2026-09-22 (operator call A). Runtime `mesofact/0.8.41-r931b8` was built from the yah tree by `yah qed run mesofact-musl` (run dbce5363, no CDN publish). It went out through `yah cloud bundle publish-runtime`: x86_64-musl (blake3 f62bba56…) to bucket noisetable-marketing, aarch64-musl (5505a05b…) to noisetable-staging. The noisetable mirrors now pin 0.8.41-r931b8: prod.toml was 0.8.32 (rollback note inline), staging.toml was 0.8.40. PROD: `yah cloud apply --env prod --service noisetable-marketing` EXIT=0, bundle 2aae406a…, us-east-001 Running. Live after the apply: / 200, /issues 200 (lists issues), /api/issues 200, /app/ 200; COOP/COEP present on / and /app/. STAGING (canary) apply EXIT=1, for a reason unrelated to the runtime: the inner door refused because staging's `issues` component (kind=binary) has no resolved address. The bundle is Running on us-west-011 on the new runtime, / and /app/ serve with COOP/COEP, and /issues renders its 'Unable to load issues' fallback because staging /api/issues is 404.")
121//! @yah:cleanup("noisetable's prod.toml and staging.toml pin the prerelease runtime `0.8.41-r931b8`, which exists only in the noisetable-marketing and noisetable-staging buckets. After the next real mesofact release, move both pins to it; x86_64 and aarch64 runtime assets must be published to those buckets first. Staging's `issues` workload component has no address, so the staging inner door refuses; this is in the inner-door area the R931 parent covers.")
122
123use std::collections::{BTreeMap, HashMap};
124use std::path::{Path, PathBuf};
125
126use anyhow::{bail, Result};
127use serde::Serialize;
128use workload_spec::{
129    EnvValue, EnvVar, ExposeSpec, HealthProbe, Healthcheck, ImageRef, InlineFile,
130    LifecycleArchetype, MeshExpose, MeshIdent, Millis, NamespaceId, ResourceLimits, RestartPolicy,
131    StopPolicy, TenantId, TierTag, Workload, WorkloadSpec, NATIVE_EXEC_ANNOTATION,
132    NATIVE_EXEC_VALUE, RESUME_AFTER_RESTART_ANNOTATION, RESUME_AFTER_RESTART_VALUE,
133};
134
135use crate::config::{
136    domain_serving_service, normalize_mount, DeployTier, DomainConfig, ServiceConfig,
137};
138
139/// `schema_version` of the route table this module writes. Must match
140/// passway's `path_routes_file::SCHEMA_VERSION`; a mismatch is a boot failure
141/// on the door naming both numbers, which is the intended way for a
142/// producer/consumer skew to surface (see that module's doc).
143pub const ROUTES_SCHEMA_VERSION: u32 = 1;
144
145/// Which deployed thing serves a mount.
146///
147/// The distinction the whole module turns on: several components can share one
148/// of these, and rule 1 counts *these*, not components.
149#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
150pub enum DeployedUnit {
151    /// The service's single assembled W272 bundle — every [`DeployTier::Bundle`]
152    /// component, collapsed.
153    Bundle,
154    /// One [`DeployTier::Workload`] component, by component id.
155    Component(String),
156}
157
158/// One mount of an inner door's table, before upstream addresses exist.
159#[derive(Debug, Clone, PartialEq, Eq)]
160pub struct InnerDoorMount {
161    /// passway's mount spelling: `""` for the service root, otherwise
162    /// `/segment[/segment…]`. The `service.toml` side spells the same mount
163    /// without the leading slash — see [`passway_mount`].
164    pub mount: String,
165    /// What serves it.
166    pub unit: DeployedUnit,
167    /// Response headers the domain manifest gives this path (R746) — the
168    /// answer of the domain's one route table, not a second join. Empty when
169    /// the route governing this mount declares none, or when no route governs
170    /// it at all.
171    ///
172    /// This tier is their sole owner; see the module doc for why the outer door
173    /// cannot double-apply them, and why a bundle sub-mount's entry is not
174    /// redundant.
175    pub headers: BTreeMap<String, String>,
176}
177
178/// A service's inner door, as configuration — everything but the addresses.
179#[derive(Debug, Clone, PartialEq, Eq)]
180pub struct InnerDoorPlan {
181    /// Service name, for error messages and the workload name.
182    pub service: String,
183    /// Mounts in declaration order. Precedence is `PathRouter`'s (longest
184    /// mount wins), not this vector's, so the order is presentational.
185    pub mounts: Vec<InnerDoorMount>,
186}
187
188/// Translate a normalized mount (`""`, `"app"`) to passway's spelling (`""`,
189/// `"/app"`).
190///
191/// The twin of [`normalize_mount`] on the wire side, and deliberately built by
192/// composing with it rather than trimming slashes again: `/app`, `app/` and
193/// `/app/` all mean one mount, and this crate already has exactly one place
194/// that knows so.
195///
196/// passway has its own `path_route::mount_from_component` doing the same job on
197/// the reading side. That is a genuine two-sided format rather than a
198/// duplicated normalizer — passway is a separately released crate with its own
199/// workspace, and yubaba cannot call into it — and it is handled the way the
200/// wire format handles every other such risk: `PathRouter::new` is the ONE
201/// validator of mount well-formedness, so a disagreement here is a loud boot
202/// failure on the door, never a silently mis-served prefix.
203pub fn passway_mount(raw: Option<&str>) -> String {
204    match raw.map(normalize_mount) {
205        Some(m) if !m.is_empty() => format!("/{m}"),
206        _ => String::new(),
207    }
208}
209
210/// Plan the inner door for one service, or answer `None` when it should not
211/// have one.
212///
213/// `None` is rule 1 and is the common answer: a service whose components all
214/// ship in one bundle has a single upstream, and a proxy in front of a single
215/// upstream is a hop that can only add latency and a failure mode.
216///
217/// `Err` is reserved for a service that *needs* a door and cannot have a
218/// working one — today that is exactly one case, no root mount, which would
219/// produce a table that 503s every unclaimed path.
220pub fn plan(
221    service: &ServiceConfig,
222    domains: &BTreeMap<String, DomainConfig>,
223) -> Result<Option<InnerDoorPlan>> {
224    let domain = domain_serving_service(domains, &service.name);
225
226    let mut mounts: Vec<InnerDoorMount> = Vec::new();
227    for component in &service.components {
228        let unit = match component.deploy {
229            DeployTier::Bundle => DeployedUnit::Bundle,
230            DeployTier::Workload => DeployedUnit::Component(component.id.clone()),
231        };
232        let mount = passway_mount(component.mount.as_deref());
233        mounts.push(InnerDoorMount {
234            headers: headers_for(domain, &mount),
235            mount,
236            unit,
237        });
238    }
239
240    // Rule 1, counted on UNITS. Three bundle components are one unit and get
241    // no door; one bundle component plus one workload component are two and
242    // do.
243    let units: std::collections::BTreeSet<&DeployedUnit> = mounts.iter().map(|m| &m.unit).collect();
244    if units.len() < 2 {
245        return Ok(None);
246    }
247
248    if !mounts.iter().any(|m| m.mount.is_empty()) {
249        bail!(
250            "services/{}/service.toml declares {} independently-deployed units but no component \
251             at the service root — every component sets a `mount`. An inner door's table needs a \
252             root (\"\") mount as its catch-all; without one every path outside the declared \
253             mounts 503s, which is indistinguishable from an outage. Drop the `mount` from \
254             whichever component serves `/`.",
255            service.name,
256            units.len(),
257        );
258    }
259
260    Ok(Some(InnerDoorPlan {
261        service: service.name.clone(),
262        mounts,
263    }))
264}
265
266/// The response headers `domain`'s route table gives `mount` (passway spelling:
267/// `""` or `/app`).
268///
269/// ## One join, not two
270///
271/// This used to be its own walk — the [`DomainRoute`] whose `route_path_prefix`
272/// equalled the component's [`normalize_mount`], skipping headerless routes.
273/// R898-F1 made a domain's routes a compiled [`RouteTable`] with ONE matching
274/// rule, and the Worker, mesofact and the outer door's `ROUTE_HEADERS` all
275/// answer by that rule. An inner door answering by a *different* one would serve
276/// different headers on the same path than the table says are served there — two
277/// producers of one fact. So the lookup goes through
278/// [`DomainConfig::route_for_path`], which is [`RouteTable::match_path`]'s walk
279/// over the declared routes.
280///
281/// Matched on the mount's PATH rather than on the route's `component`
282/// reference, so a route declared as a bare prefix still contributes:
283/// `cross_ref_validate` has already proved the two agree for every route that
284/// names a component, and matching on the path is what makes the lookup total.
285///
286/// ## The consequence: the answer is order-dependent now
287///
288/// First-match-wins is, and the old prefix-equality join was not. A manifest
289/// that puts `/*` above `/app/*` gives the ROOT's headers to `/app` — at every
290/// tier, now including this one. That is the table being right rather than this
291/// being wrong: `/app` is what such a manifest actually serves through the
292/// outer tier, and `yah-dev.toml:108` states the contract ("routes above this
293/// catch-all … Vec order = match order"). A headerless route that matches is
294/// likewise an answer of "no headers", not a reason to keep looking — no
295/// merging across rules (R746).
296///
297/// ## Why this takes a `DomainConfig` and not a compiled `RouteTable`
298///
299/// It would be circular. `CdnPlacement::backend_origin` resolves a route's
300/// origin out of the plan's resolved unit addresses (R898-F1), so no
301/// table can be compiled until the plan this function is helping build exists.
302/// [`DomainConfig::route_for_path`] is the placement-free half of that same
303/// table, in exactly the relationship `route_headers_json` already has to
304/// [`RouteTable::headers_json`].
305///
306/// [`DomainRoute`]: crate::config::DomainRoute
307/// [`RouteTable`]: crate::route_table::RouteTable
308/// [`RouteTable::match_path`]: crate::route_table::RouteTable::match_path
309/// [`RouteTable::headers_json`]: crate::route_table::RouteTable::headers_json
310fn headers_for(domain: Option<&DomainConfig>, mount: &str) -> BTreeMap<String, String> {
311    // passway spells the root mount `""`; a request for it is `/`.
312    let path = if mount.is_empty() { "/" } else { mount };
313    domain
314        .and_then(|d| d.route_for_path(path))
315        .map(|r| r.headers.clone())
316        .unwrap_or_default()
317}
318
319// ── Rendering ────────────────────────────────────────────────────────────────
320
321/// Serialization mirror of passway's `path_routes_file::PathRoutesFile`. Kept
322/// private: the supported output is [`InnerDoorPlan::routes_file`]'s string, so
323/// nothing can construct a half-filled table and write it.
324#[derive(Debug, Serialize)]
325struct RoutesFile<'a> {
326    schema_version: u32,
327    routes: Vec<RouteEntry<'a>>,
328}
329
330#[derive(Debug, Serialize)]
331struct RouteEntry<'a> {
332    mount: &'a str,
333    discover: RouteDiscover<'a>,
334    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
335    headers: &'a BTreeMap<String, String>,
336}
337
338/// Mirror of passway's `path_routes_file::MountDiscovery` (R936-B12).
339#[derive(Debug, Serialize)]
340struct RouteDiscover<'a> {
341    ident: String,
342    yubaba: &'a [String],
343}
344
345/// How often an inner door re-reads its units' service records, in seconds.
346/// See [`InnerDoorPlan::workload`].
347pub const DISCOVERY_INTERVAL_SECS: u64 = 2;
348
349/// @yah:ticket(R931-B6, "Inner-door render refuses noisetable-marketing route table: Bundle mount has no resolved address yet")
350/// @yah:status(review)
351/// @yah:at(2026-09-22T05:45:52Z)
352/// @yah:assignee(agent:bundle-anthropic-ashguard)
353/// @yah:parent(R931)
354/// @yah:severity(high)
355/// @yah:gotcha("FOUND BY THE NOISETABLE CAMP (R733-T26, @Miravel:libra) while re-running `yah cloud mirror up noisetable-marketing --env prod` after yah R931-B5's kamaji.service fix (StateDirectory/ReadWritePaths for passway/routes) was rolled to us-east-001 and kamaji restarted (2026-09-22). R931-B5 IS CONFIRMED WORKING for its own scope — the read-only-filesystem EROFS on /var/lib/passway/routes/*.routes.json is GONE. This is the next layer down, not a regression of B5.")
356/// @yah:assumes("The `site`/`app` mesofact-spa/mesofact-static components published and went Running cleanly (bundle digest 8e77c1b448fafabe172bf774f931c1426cace9fe1f0f8f5eebee658c1af21dd6, build_id 9481d540db93867ce8727ce2b7bffd8b, runtime mesofact/0.8.32) throughout this run; only the `issues` (binary/inner-door) component failed.")
357/// @yah:next("Gate for R733-T26: once this reaches review, re-run `yah cloud mirror up noisetable-marketing --env prod` and redo the five-point verification (root 200+title, /app/ 200, GET /api/issues 200 body-free projection, POST tests/fixtures/chloro_edit_failure_post.json -> 201+ULID, /issues renders the list).")
358/// @yah:gotcha("Exact error from `yah cloud mirror up noisetable-marketing --env prod` (run 2026-09-22, ready service records [\"us-east-001\", \"us-south-001\", \"us-west-001\"]): `Error: rendering the inner door for noisetable-marketing/prod from the ready service records of [\"us-east-001\", \"us-south-001\", \"us-west-001\"]: service noisetable-marketing: mount \"\" is served by Bundle, which has no resolved address yet. Refusing to write a partial route table -- a missing mount does not 503, it falls through to the root mount and serves the wrong component with a 200.` Source: oss/yubaba/crates/cloud/src/inner_door.rs:348-349. Live verification after the failed attempt: https://noisetable.com/ 200 (title correct), /app/ 200, GET /api/issues 404 (body is the marketing SPA HTML shell, not the issues service's body-free projection), GET /issues 500 (F25's client error page). No rollback needed -- / and /app/ never left 200.")
359/// @yah:handoff("FIXED in app/yah/cli/src/cloud.rs. Root cause is R931-B7 defect (2), not an ident or config fault: deploy_inner_door read ready service records ONCE right after the deploy phase (re)deployed the bundle, so the bundle ident had no record yet and InnerDoorPlan::workload refused the table. B7's own measurements show the identical error passing on a re-run a minute later. FIX: ReadyRecordWait gained a generic `resolve_with<T>(read, attempt, idle)` loop (resolve_plan is now a thin wrapper over it — one loop, two consumers), and deploy_inner_door runs resolve_addresses + workload() inside it under ReadyRecordWait::APPLY (90s budget, 5s interval), with a one-time stderr notice. The refusal in inner_door.rs:349 is unchanged — a partial table is still never written; it is now retried rather than surfaced on the first read. This also closes B7's defect (2); B7 keeps only defect (1), the needless re-fork.")
360/// @yah:verify("LIVE GATE (not run by me, prod-facing): re-run `yah cloud mirror up noisetable-marketing --env prod`, then the five-point check in this ticket's next — R733-T26's gate.")
361/// @yah:assumes("resolve_workload_ident(mirror, 'noisetable-marketing', 'prod') yields the ident the bundle actually registers ('noisetable' per the west passway log in B7). Inferred from B7's 'next run a minute later succeeded', not re-read against the mirror toml.")
362/// @yah:verify("`cargo test -p yah --lib ready_record_wait` = 5 passed / 0 failed, EXIT 0 (new: the_inner_door_waits_for_the_bundle_record_instead_of_refusing_the_table). Log /tmp/r931b6-t2.log.")
363/// @yah:verify("LIVE, 2026-09-22, CLI installed via `cargo xtask install`: five `yah cloud mirror up noisetable-marketing --env prod` runs from ~/ss/noisetable, all EXIT 0. Each rendered the inner door (/ and /app → 100.64.0.3:41507, /api/issues → 10.128.1.2:4333) and ended 'noisetable.com is serving this bundle'. Not one hit the 'no resolved address yet' refusal, including the runs where the bundle was re-forked just before.")
364impl InnerDoorPlan {
365    /// Every distinct unit this door proxies to, in a stable order. What a
366    /// caller resolving addresses has to answer for.
367    pub fn units(&self) -> Vec<DeployedUnit> {
368        let set: std::collections::BTreeSet<DeployedUnit> =
369            self.mounts.iter().map(|m| m.unit.clone()).collect();
370        set.into_iter().collect()
371    }
372
373    /// Render the JSON passway reads: each mount names its unit's mesh ident
374    /// and every yubaba that could hold that unit's service record.
375    ///
376    /// No addresses (R936-B12). The table used to bake each unit's
377    /// `host:port` in at deploy time, so it pointed at whichever node ran the
378    /// unit THEN, and a unit the cluster later moved — or a node that died —
379    /// left every door routing to an address nothing answered. noisetable.com
380    /// went 503 on all three doors that way when us-east-001 was powered off.
381    /// Discovering by ident makes the door follow the unit on its next poll.
382    ///
383    /// `yubaba` must name every node a unit may run on: a unit is only found
384    /// where it is polled for. An empty list is refused, since every mount
385    /// would then discover nothing and 503.
386    pub fn routes_file(&self, bundle_ident: &str, yubaba: &[String]) -> Result<String> {
387        if yubaba.is_empty() {
388            bail!(
389                "service {}: an inner door needs at least one yubaba to discover its units \
390                 from, and was given none",
391                self.service
392            );
393        }
394        let mut routes = Vec::with_capacity(self.mounts.len());
395        for m in &self.mounts {
396            routes.push(RouteEntry {
397                mount: &m.mount,
398                discover: RouteDiscover {
399                    ident: self.unit_ident(&m.unit, bundle_ident),
400                    yubaba,
401                },
402                headers: &m.headers,
403            });
404        }
405        Ok(serde_json::to_string(&RoutesFile {
406            schema_version: ROUTES_SCHEMA_VERSION,
407            routes,
408        })?)
409    }
410}
411
412// ── Supervision ──────────────────────────────────────────────────────────────
413
414/// The passway binary every node carries, installed by the yubaba release
415/// tarball's `control_plane_install`. The inner door is the *same* binary as
416/// the public door — one door implementation, two configurations, which is the
417/// property R870-F15 built path routing to preserve.
418pub const INNER_DOOR_BINARY: &str = "/usr/local/bin/passway";
419
420/// Where a node keeps generated route tables. Same directory the demux and
421/// http-router tables already live in.
422pub const ROUTES_DIR: &str = "/var/lib/passway/routes";
423
424/// The only address an inner door ever binds, and the only one the outer door
425/// ever dials it at. Literal rather than a parameter — see
426/// [`InnerDoorPlan::workload`].
427pub const INNER_DOOR_HOST: &str = "127.0.0.1";
428
429/// Low end of the window [`listen_port`] picks from, inclusive.
430pub const INNER_DOOR_PORT_LOW: u16 = 10_000;
431/// High end of the window [`listen_port`] picks from, inclusive.
432pub const INNER_DOOR_PORT_HIGH: u16 = 19_999;
433
434/// The loopback port a service's inner door listens on — derived from the
435/// service name, so every apply of an unchanged tree renders the same number.
436///
437/// ## Why a derived pin rather than kamaji's ledger
438///
439/// R870-F23 phase 2 preferred taking the number from `kamaji::ports`
440/// ([`LedgerPorts`], `oss/kamaji/crates/kamaji/src/ports.rs`). Read rather than
441/// assumed, that ledger cannot answer here, for three reasons that also happen
442/// to make a pin safe:
443///
444/// 1. **It is node-local and has no RPC.** `LedgerPorts` persists
445///    `(ident, name) -> port` to a JSON file beside the supervisor's state dir,
446///    and yubaba's HTTP surface exposes no allocation verb (`yubaba/src/lib.rs`
447///    routes `/workloads/*`, `/services`, `/node/*` — nothing for ports). An
448///    apply running on an operator's laptop has no way to ask.
449/// 2. **A pin is honoured, not rejected, on the path this workload takes.**
450///    R844-F14's rule — a non-world-fixed pin is an error — bites in
451///    `LedgerPorts::resolve_set`, and `NativeRuntime::resolve_declared_ports`
452///    (`kamaji/src/native.rs:280`) filters `pin.is_none()` *before* calling it.
453///    A stated number is therefore passed through, which is what
454///    `PASSWAY_LISTEN` needs: the door's own env has to carry the number, and
455///    a number the node picked after the spec was rendered could not be in it.
456/// 3. **A collision is not even representable.** The ledger allocates on the
457///    workload's *mesh* IP; an inner door binds loopback. `100.64.0.3:14210`
458///    and `127.0.0.1:14210` are different sockets.
459///
460/// The window is deliberately below Linux's default ephemeral range
461/// (32768-60999), which is where `pick_free_port`'s `bind(:0)` draws from — so
462/// a derived number cannot land on one the ledger is about to hand out even on
463/// the same interface.
464///
465/// The hash is FNV-1a written out here rather than `DefaultHasher`, whose
466/// output std explicitly does not promise to keep stable across releases. This
467/// number is written into a deployed door's environment and into the outer
468/// door's upstream list; a toolchain bump silently moving it would repoint one
469/// tier and not the other.
470pub fn listen_port(service: &str) -> u16 {
471    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
472    for byte in service.as_bytes() {
473        hash ^= u64::from(*byte);
474        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
475    }
476    let span = u64::from(INNER_DOOR_PORT_HIGH - INNER_DOOR_PORT_LOW) + 1;
477    INNER_DOOR_PORT_LOW + (hash % span) as u16
478}
479
480/// The mesh identity a [`DeployTier::Workload`] component registers its service
481/// record under.
482///
483/// **This is the naming rule, not a lookup**, and it is stated here because
484/// nothing else states it. A bundle's ident comes from the mirror
485/// (`BundleSlot::workload_name`, overridable by `name = "…"`), but a
486/// workload-tier component has no slot of its own — `[providers.*]` is
487/// per-kind, per-mirror, which is exactly the gap [`DeployTier`] was added to
488/// close. So the ident has to be derivable from the two names the service
489/// already declares, and this is that derivation.
490///
491/// Getting it wrong is a *loud* failure rather than a quiet one:
492/// [`InnerDoorPlan::routes_file`] refuses a mount whose unit resolved to no
493/// address, naming the unit, so a component that registered under some other
494/// ident fails the apply instead of falling through to the root mount.
495pub fn component_workload_ident(service: &str, component_id: &str) -> String {
496    crate::reconciler::native_support::sanitize_ident(&format!("{service}-{component_id}"))
497}
498
499impl InnerDoorPlan {
500    /// The workload name / mesh identity for this service's inner door.
501    pub fn workload_name(&self) -> String {
502        format!("passway-inner-{}", self.service)
503    }
504
505    /// Where this door's route table is materialized on the node.
506    pub fn routes_path(&self) -> PathBuf {
507        Path::new(ROUTES_DIR).join(format!("{}.routes.json", self.service))
508    }
509
510    /// This door's loopback port — [`listen_port`] of the service name.
511    pub fn listen_port(&self) -> u16 {
512        listen_port(&self.service)
513    }
514
515    /// The mesh identity whose ready service record carries `unit`'s address.
516    ///
517    /// The two arms come from different places on purpose, and neither is
518    /// derivable from the other. A bundle's ident is a *mirror* fact —
519    /// `BundleSlot::workload_name`, which a slot may rename with `name = "…"` —
520    /// so it is handed in. A workload-tier component has no slot to rename it,
521    /// so its ident is derived ([`component_workload_ident`]).
522    pub fn unit_ident(&self, unit: &DeployedUnit, bundle_ident: &str) -> String {
523        match unit {
524            DeployedUnit::Bundle => bundle_ident.to_string(),
525            DeployedUnit::Component(id) => component_workload_ident(&self.service, id),
526        }
527    }
528
529    /// Render the supervisable workload: a passway process serving this
530    /// service's mount table on loopback.
531    ///
532    /// ## Cleartext, and the invariant that makes it safe
533    ///
534    /// `PASSWAY_TLS_MODE=plaintext` (operator call, 2026-09-09 — see
535    /// `passway::tls::parse_listener_tls_mode` for the full argument). The
536    /// short version: no CA issues for `127.0.0.1`, so "TLS everywhere" here
537    /// means a self-signed leaf plus a way to switch OFF upstream certificate
538    /// verification on the *public* door — a real trust-boundary knob traded
539    /// for encrypting a hop that never leaves the loopback interface.
540    ///
541    /// This function cannot violate that invariant even if `listen_port` is
542    /// wrong, because it binds `127.0.0.1` literally and passway refuses the
543    /// mode on anything else. The bind is not a parameter.
544    ///
545    /// ## Why `listen_port` is an argument
546    ///
547    /// It is placement-time knowledge, exactly like the upstream addresses:
548    /// which port is free is a property of the node, not of the config. The
549    /// caller allocates and passes it, so this stays a pure function of
550    /// (plan, port, addresses) and is testable without a node.
551    ///
552    /// ## The route table travels IN the spec
553    ///
554    /// Not written beside it: [`WorkloadSpec::files`] makes the table and the
555    /// process that reads it one deploy rather than two, so a redeploy cannot
556    /// leave a door serving a stale table. Only kamaji's native backend
557    /// materializes those; every other backend refuses the spec by name rather
558    /// than starting the door against a file that is not there.
559    ///
560    /// ## Why `Workload::Container` and not a new `Workload` variant
561    ///
562    /// `TenantPasswayWorkload` is a typed variant, so the precedent for one
563    /// exists — but it earns that by carrying config kamaji itself must act on
564    /// (a domain to match, a PEM pair to re-read on every cold start, an idle
565    /// TTL to reap against). An inner door carries none of it: its entire
566    /// configuration is an argv, three env vars and one file, all of which
567    /// `WorkloadSpec` already expresses. A variant would buy nothing but
568    /// exhaustive-match churn in peer-owned `kamaji-proto`, which is the trade
569    /// R572-F1 already made and recorded.
570    pub fn workload(
571        &self,
572        listen_port: u16,
573        bundle_ident: &str,
574        yubaba: &[String],
575    ) -> Result<Workload> {
576        let routes_path = self.routes_path();
577        let name = self.workload_name();
578        let listen = format!("127.0.0.1:{listen_port}");
579
580        let env = vec![
581            literal_env("PASSWAY_TLS_MODE", "plaintext".to_string()),
582            literal_env("PASSWAY_LISTEN", listen),
583            literal_env(
584                "PASSWAY_PATH_ROUTES_FILE",
585                routes_path.display().to_string(),
586            ),
587            // R936-B12: every mount discovers its unit, so how fast the door
588            // notices a unit moving IS this interval. passway's 30s default
589            // would spend half of a one-minute re-home budget on noticing.
590            literal_env("PASSWAY_UPDATE_INTERVAL_SECS", DISCOVERY_INTERVAL_SECS.to_string()),
591            literal_env(
592                "PASSWAY_HEALTH_CHECK_INTERVAL_SECS",
593                DISCOVERY_INTERVAL_SECS.to_string(),
594            ),
595        ];
596
597        let mut annotations = HashMap::new();
598        // R931-B4: the marker kamaji's `deploy_container_backend` actually
599        // routes on (`WorkloadSpec::wants_native_exec`). Without it the spec
600        // above's empty-digest `ImageRef` — deliberately unpullable, per the
601        // comment below — falls through to the containerd arm instead of ever
602        // reaching kamaji's native backend, and containerd 500s asking to
603        // pre-pull an image that was never meant to exist. A kamaji with no
604        // native backend configured now refuses this by name
605        // (`deploy_native_exec`'s "native backend not configured" /
606        // "built without the native-exec feature" `BackendRefused`) instead of
607        // silently mis-routing to containerd.
608        annotations.insert(
609            NATIVE_EXEC_ANNOTATION.to_string(),
610            NATIVE_EXEC_VALUE.to_string(),
611        );
612        // R936-B11: survive a reboot. A native workload dies with every kamaji
613        // restart and nothing else on the node remembers a direct deploy, so
614        // until this the door was simply gone after one — and its outer door
615        // 503'd with it. Safe to replay here because an inner door is pinned
616        // to its front door by construction; see the annotation's docs for
617        // why a yubaba-placed appliance must never set it.
618        annotations.insert(
619            RESUME_AFTER_RESTART_ANNOTATION.to_string(),
620            RESUME_AFTER_RESTART_VALUE.to_string(),
621        );
622
623        let spec = WorkloadSpec {
624            name: name.clone(),
625            // Identity metadata only — the native backend pulls nothing.
626            image: ImageRef {
627                registry: "local".into(),
628                repository: "passway".into(),
629                tag: "inner-door".into(),
630                digest: String::new(),
631            },
632            tier: TierTag("infra".into()),
633            tenant: TenantId::singleton(),
634            namespace: NamespaceId::singleton(),
635            replicas: 1,
636            command: Some(vec![INNER_DOOR_BINARY.to_string()]),
637            entrypoint: None,
638            workdir: None,
639            user: None,
640            env,
641            secrets: vec![],
642            volumes: vec![],
643            resources: ResourceLimits {
644                memory_mb: 128,
645                cpu_millis: 256,
646                memory_request_mb: None,
647                cpu_limit_millis: None,
648                pids_max: None,
649                scratch_floor_mb: None,
650            },
651            depends_on: vec![],
652            requires: vec![],
653            healthcheck: Some(Healthcheck {
654                // A cleartext listener would answer an HttpGet probe, but a
655                // bare connect is the same liveness signal without asking the
656                // door to route a synthetic path through a mount table that
657                // may legitimately not have a catch-all for it.
658                probe: HealthProbe::TcpConnect { port: listen_port },
659                interval: Millis::from_secs(10),
660                timeout: Millis::from_secs(2),
661                initial_delay: Millis::from_secs(5),
662                failure_threshold: 3,
663            }),
664            restart_policy: RestartPolicy::Always,
665            // Pinned and non-drainable: the service's public door proxies to
666            // this on loopback, so moving it to another node does not relocate
667            // the thing that reaches it — it severs it.
668            archetype: Some(LifecycleArchetype::Appliance),
669            stop_policy: StopPolicy {
670                signal: 15,
671                grace_period: Millis::from_secs(5),
672            },
673            expose: ExposeSpec {
674                mesh: MeshExpose {
675                    identity: MeshIdent(name),
676                    ports: MeshExpose::anonymous_ports([listen_port]),
677                    allow_from: vec![],
678                },
679                // Loopback only. Nothing off this node reaches an inner door,
680                // which is the premise the cleartext listener rests on.
681                public: None,
682                operator: None,
683            },
684            labels: HashMap::new(),
685            durability: None,
686            annotations,
687            files: vec![InlineFile {
688                path: routes_path,
689                content: self.routes_file(bundle_ident, yubaba)?,
690                mode: Some(0o600),
691            }],
692        };
693
694        Ok(Workload::container(spec))
695    }
696}
697
698fn literal_env(name: &str, value: String) -> EnvVar {
699    EnvVar {
700        name: name.into(),
701        value: EnvValue::Literal { value },
702    }
703}
704
705#[cfg(test)]
706mod tests {
707    use super::*;
708    use crate::config::{DomainRoute, FrontDoor, RouteMode, ServiceComponent};
709    use crate::route_table::{CdnPlacement, RouteTable};
710
711    fn component(id: &str, mount: Option<&str>, deploy: DeployTier) -> ServiceComponent {
712        ServiceComponent {
713            id: id.to_string(),
714            kind: "mesofact-spa".to_string(),
715            path: format!("app/{id}"),
716            git: None,
717            role: "static".to_string(),
718            publishes: Some("static".to_string()),
719            mount: mount.map(str::to_string),
720            wave: 0,
721            deploy,
722        }
723    }
724
725    fn service(name: &str, components: Vec<ServiceComponent>) -> ServiceConfig {
726        ServiceConfig {
727            schema_version: 1,
728            name: name.to_string(),
729            address: crate::config::ServiceAddress::front_door(format!("{name}.test")),
730            description: None,
731            components,
732            db: Default::default(),
733        }
734    }
735
736    fn domains(service: &str, routes: &[(&str, &[(&str, &str)])]) -> BTreeMap<String, DomainConfig> {
737        let mut map = BTreeMap::new();
738        map.insert(
739            "test".to_string(),
740            DomainConfig {
741                schema_version: 1,
742                name: "test".to_string(),
743                domain: format!("{service}.test"),
744                front_door: FrontDoor::Passway,
745                cdn_bucket: "cdn".to_string(),
746                worker_bundle_path: None,
747                routes: routes
748                    .iter()
749                    .map(|(path, headers)| DomainRoute {
750                        path: path.to_string(),
751                        headers: headers
752                            .iter()
753                            .map(|(k, v)| (k.to_string(), v.to_string()))
754                            .collect(),
755                        mode: RouteMode::Static {
756                            component: format!("{service}/root"),
757                        },
758                    })
759                    .collect(),
760            },
761        );
762        map
763    }
764
765    /// Rule 1's negative, and the cheap half of this ticket's verify list: a
766    /// single-component service produces no plan at all, so there is no config
767    /// to write and no process to supervise.
768    #[test]
769    fn a_single_unit_service_gets_no_inner_door() {
770        let svc = service(
771            "yah-marketing",
772            vec![component("site", None, DeployTier::Bundle)],
773        );
774        assert_eq!(plan(&svc, &BTreeMap::new()).unwrap(), None);
775    }
776
777    /// The same negative one step further out, and the one that would be easy
778    /// to get wrong: THREE components still share one bundle, so they are one
779    /// unit and still earn no door.
780    #[test]
781    fn several_bundle_components_are_one_unit_and_still_get_no_door() {
782        let svc = service(
783            "noisetable",
784            vec![
785                component("site", None, DeployTier::Bundle),
786                component("app", Some("app"), DeployTier::Bundle),
787                component("docs", Some("docs"), DeployTier::Bundle),
788            ],
789        );
790        assert_eq!(plan(&svc, &BTreeMap::new()).unwrap(), None);
791    }
792
793    #[test]
794    fn one_bundle_component_plus_one_workload_component_is_two_units() {
795        let svc = service(
796            "noisetable",
797            vec![
798                component("site", None, DeployTier::Bundle),
799                component("account", Some("app"), DeployTier::Workload),
800            ],
801        );
802        let plan = plan(&svc, &BTreeMap::new()).unwrap().expect("two units");
803        assert_eq!(
804            plan.mounts.iter().map(|m| m.mount.as_str()).collect::<Vec<_>>(),
805            ["", "/app"]
806        );
807        assert_eq!(
808            plan.units(),
809            vec![
810                DeployedUnit::Bundle,
811                DeployedUnit::Component("account".into())
812            ]
813        );
814    }
815
816    /// The header half of the join: a mount picks up exactly the headers its
817    /// own route declares, and the root picks up none when its route declares
818    /// none. This is the config-side half of the ticket's live assertion that
819    /// `/app/` carries COOP/COEP while `/` carries neither.
820    ///
821    /// R898-F2 REORDERED THIS FIXTURE and changed nothing else. The assertions
822    /// and the property they pin are untouched; the route list now declares
823    /// `/app/*` ABOVE `/*`, which is what a legal manifest looks like under the
824    /// route table's first-match-wins contract (`yah-dev.toml:108`,
825    /// `noisetable-com.toml`). The old fixture declared the catch-all first,
826    /// which the previous prefix-equality join was blind to and the shared
827    /// matching rule is not — see [`headers_for`].
828    #[test]
829    fn each_mount_carries_only_its_own_routes_headers() {
830        let svc = service(
831            "noisetable",
832            vec![
833                component("site", None, DeployTier::Bundle),
834                component("account", Some("app"), DeployTier::Workload),
835            ],
836        );
837        let domains = domains(
838            "noisetable",
839            &[
840                (
841                    "/app/*",
842                    &[
843                        ("cross-origin-opener-policy", "same-origin"),
844                        ("cross-origin-embedder-policy", "require-corp"),
845                    ],
846                ),
847                ("/*", &[]),
848            ],
849        );
850        let plan = plan(&svc, &domains).unwrap().expect("two units");
851
852        let root = &plan.mounts[0];
853        assert_eq!(root.mount, "");
854        assert!(root.headers.is_empty(), "{:?}", root.headers);
855
856        let app = &plan.mounts[1];
857        assert_eq!(app.mount, "/app");
858        assert_eq!(
859            app.headers.get("cross-origin-opener-policy").map(String::as_str),
860            Some("same-origin")
861        );
862        assert_eq!(
863            app.headers
864                .get("cross-origin-embedder-policy")
865                .map(String::as_str),
866            Some("require-corp")
867        );
868    }
869
870    /// A bundle-tier component at a non-root mount keeps its own headers even
871    /// though it shares the bundle's upstream — the reason mounts are per
872    /// COMPONENT while units are per deployed thing.
873    #[test]
874    fn a_bundle_components_sub_mount_keeps_its_headers_and_the_bundle_upstream() {
875        let svc = service(
876            "noisetable",
877            vec![
878                component("site", None, DeployTier::Bundle),
879                component("docs", Some("docs"), DeployTier::Bundle),
880                component("account", Some("app"), DeployTier::Workload),
881            ],
882        );
883        let domains = domains(
884            "noisetable",
885            &[("/docs/*", &[("x-frame-options", "DENY")])],
886        );
887        let plan = plan(&svc, &domains).unwrap().expect("two units");
888
889        let docs = &plan.mounts[1];
890        assert_eq!(docs.mount, "/docs");
891        assert_eq!(docs.unit, DeployedUnit::Bundle);
892        assert_eq!(docs.headers.get("x-frame-options").map(String::as_str), Some("DENY"));
893        // Two units, three mounts.
894        assert_eq!(plan.units().len(), 2);
895        assert_eq!(plan.mounts.len(), 3);
896    }
897
898    #[test]
899    fn a_table_with_no_root_mount_is_refused_rather_than_written() {
900        let svc = service(
901            "noisetable",
902            vec![
903                component("app", Some("app"), DeployTier::Bundle),
904                component("account", Some("account"), DeployTier::Workload),
905            ],
906        );
907        let err = plan(&svc, &BTreeMap::new()).unwrap_err().to_string();
908        assert!(err.contains("no component at the service root"), "{err}");
909    }
910
911    #[test]
912    fn rendering_produces_the_exact_shape_passway_reads() {
913        let svc = service(
914            "noisetable",
915            vec![
916                component("site", None, DeployTier::Bundle),
917                component("account", Some("app"), DeployTier::Workload),
918            ],
919        );
920        let domains = domains(
921            "noisetable",
922            &[("/app/*", &[("cross-origin-opener-policy", "same-origin")])],
923        );
924        let plan = plan(&svc, &domains).unwrap().unwrap();
925
926        let yubaba = vec![
927            "http://100.64.0.1:7443".to_string(),
928            "http://100.64.0.3:7443".to_string(),
929        ];
930        let json = plan.routes_file("noisetable", &yubaba).unwrap();
931        let account = plan.unit_ident(&DeployedUnit::Component("account".into()), "noisetable");
932
933        assert_eq!(
934            json,
935            format!(
936                r#"{{"schema_version":1,"routes":[{{"mount":"","discover":{{"ident":"noisetable","yubaba":["http://100.64.0.1:7443","http://100.64.0.3:7443"]}}}},{{"mount":"/app","discover":{{"ident":"{account}","yubaba":["http://100.64.0.1:7443","http://100.64.0.3:7443"]}},"headers":{{"cross-origin-opener-policy":"same-origin"}}}}]}}"#
937            )
938        );
939        assert!(!json.contains("upstreams"), "R936-B12: no baked addresses: {json}");
940    }
941
942    /// With nowhere to discover from, every mount would 503; refuse instead.
943    #[test]
944    fn a_table_with_no_yubaba_to_poll_is_refused() {
945        let svc = service(
946            "noisetable",
947            vec![
948                component("site", None, DeployTier::Bundle),
949                component("account", Some("app"), DeployTier::Workload),
950            ],
951        );
952        let plan = plan(&svc, &BTreeMap::new()).unwrap().unwrap();
953        let err = plan.routes_file("noisetable", &[]).unwrap_err().to_string();
954        assert!(err.contains("at least one yubaba"), "{err}");
955        assert!(plan.workload(8443, "noisetable", &[]).is_err());
956    }
957
958    /// The rendered door, pinned on the four properties that are not
959    /// cosmetic: cleartext ONLY on loopback, the routes file travelling inside
960    /// the spec, and the env var passway selects path routing by.
961    #[test]
962    fn the_rendered_door_is_cleartext_on_loopback_and_carries_its_own_table() {
963        let svc = service(
964            "noisetable",
965            vec![
966                component("site", None, DeployTier::Bundle),
967                component("account", Some("app"), DeployTier::Workload),
968            ],
969        );
970        let plan = plan(&svc, &BTreeMap::new()).unwrap().unwrap();
971        let workload = plan
972            .workload(8443, "noisetable", &["http://100.64.0.3:7443".to_string()])
973            .unwrap();
974        let spec = workload.container_spec().expect("container-shaped");
975
976        let env: BTreeMap<&str, &str> = spec
977            .env
978            .iter()
979            .filter_map(|e| match &e.value {
980                EnvValue::Literal { value } => Some((e.name.as_str(), value.as_str())),
981                _ => None,
982            })
983            .collect();
984        assert_eq!(env.get("PASSWAY_TLS_MODE"), Some(&"plaintext"));
985        // The invariant: cleartext is bound to loopback by construction, not
986        // by whoever picked the port.
987        assert_eq!(env.get("PASSWAY_LISTEN"), Some(&"127.0.0.1:8443"));
988        assert!(spec.expose.public.is_none(), "an inner door is never public");
989
990        // The routes file rides the spec, and the env var points AT it.
991        assert_eq!(spec.files.len(), 1);
992        let file = &spec.files[0];
993        assert_eq!(
994            env.get("PASSWAY_PATH_ROUTES_FILE").map(|s| s.to_string()),
995            Some(file.path.display().to_string())
996        );
997        assert!(file.content.contains("\"schema_version\":1"), "{}", file.content);
998        assert!(file.content.contains("http://100.64.0.3:7443"), "{}", file.content);
999        assert_eq!(spec.command.as_deref(), Some(&[INNER_DOOR_BINARY.to_string()][..]));
1000        // R936-B12: the door notices a unit move within one short poll.
1001        assert_eq!(env.get("PASSWAY_UPDATE_INTERVAL_SECS"), Some(&"2"));
1002    }
1003
1004    /// R936-B11: the door is native AND asks its node's kamaji to replay it
1005    /// after a restart. Without the second marker a reboot of a front door
1006    /// took the door down for good and the outer door 503'd.
1007    #[test]
1008    fn the_rendered_door_is_native_and_survives_a_kamaji_restart() {
1009        let svc = service(
1010            "noisetable",
1011            vec![
1012                component("site", None, DeployTier::Bundle),
1013                component("account", Some("app"), DeployTier::Workload),
1014            ],
1015        );
1016        let plan = plan(&svc, &BTreeMap::new()).unwrap().unwrap();
1017        let workload = plan
1018            .workload(8443, "noisetable", &["http://100.64.0.3:7443".to_string()])
1019            .unwrap();
1020        let spec = workload.container_spec().expect("container-shaped");
1021        assert!(spec.wants_native_exec());
1022        assert!(spec.wants_resume_after_restart());
1023        assert!(!spec.wants_float(), "a door is pinned to its front door, never a floater");
1024    }
1025
1026    #[test]
1027    fn the_mount_spelling_matches_passways_convention_in_both_directions() {
1028        assert_eq!(passway_mount(None), "");
1029        assert_eq!(passway_mount(Some("")), "");
1030        assert_eq!(passway_mount(Some("/")), "");
1031        // Every spelling of one mount collapses to one string — the whole
1032        // reason this composes with `normalize_mount` instead of formatting.
1033        for raw in ["app", "/app", "app/", "/app/"] {
1034            assert_eq!(passway_mount(Some(raw)), "/app", "{raw}");
1035        }
1036        assert_eq!(passway_mount(Some("/a/b/")), "/a/b");
1037    }
1038
1039    // ── Phase 2: placement (R870-F23 steps 2 and 3) ─────────────────────────
1040
1041    /// The property the whole pin rests on: same service, same number, forever.
1042    /// The outer door's upstream list and the inner door's `PASSWAY_LISTEN` are
1043    /// rendered by two different call sites in two different apply phases; if
1044    /// this drifted, one tier would be repointed and the other would not.
1045    #[test]
1046    fn the_derived_port_is_stable_and_inside_its_declared_window() {
1047        assert_eq!(listen_port("noisetable"), listen_port("noisetable"));
1048        for service in ["noisetable", "yah-marketing", "", "a", "a-very-long-service-name"] {
1049            let port = listen_port(service);
1050            assert!(
1051                (INNER_DOOR_PORT_LOW..=INNER_DOOR_PORT_HIGH).contains(&port),
1052                "{service} -> {port}"
1053            );
1054            // Below the Linux default ephemeral floor, which is where
1055            // `kamaji::ports::pick_free_port`'s `bind(:0)` draws from. A number
1056            // inside that range could collide with a ledger allocation.
1057            assert!(port < 32_768, "{service} -> {port}");
1058        }
1059    }
1060
1061    /// Different services get different doors. Not a guarantee the hash can
1062    /// make in general — 10_000 slots, so a collision is possible — but two
1063    /// services co-tenant on one node colliding is what this is checked
1064    /// against, and the two real ones do not.
1065    #[test]
1066    fn two_services_do_not_share_a_door() {
1067        assert_ne!(listen_port("noisetable"), listen_port("yah-marketing"));
1068    }
1069
1070    /// Step 3's identity mapping. The two arms come from different places and
1071    /// the test says so: the bundle's ident is handed in (a mirror may rename
1072    /// it), a component's is derived from names the service already declares.
1073    #[test]
1074    fn each_unit_resolves_through_its_own_identity_rule() {
1075        let svc = service(
1076            "noisetable",
1077            vec![
1078                component("site", None, DeployTier::Bundle),
1079                component("account", Some("app"), DeployTier::Workload),
1080            ],
1081        );
1082        let plan = plan(&svc, &BTreeMap::new()).unwrap().unwrap();
1083
1084        assert_eq!(
1085            plan.unit_ident(&DeployedUnit::Bundle, "renamed-bundle"),
1086            "renamed-bundle",
1087            "a slot's `name = \"…\"` override has to win — it is what the record carries"
1088        );
1089        assert_eq!(
1090            plan.unit_ident(&DeployedUnit::Component("account".into()), "renamed-bundle"),
1091            "noisetable-account",
1092        );
1093    }
1094
1095    /// A component id that is not already a legal mesh ident is folded, not
1096    /// passed through — the ident travels into a service-record lookup and a
1097    /// `MeshIdent`, both of which are lowercase-and-dash.
1098    #[test]
1099    fn a_derived_component_ident_is_folded_like_every_other_mesh_ident() {
1100        assert_eq!(
1101            component_workload_ident("Noise_Table", "Account.API"),
1102            "noise-table-account-api"
1103        );
1104    }
1105
1106    /// Steps 2 and 3 joined: a two-unit service renders a door whose table
1107    /// names both resolved addresses and whose listener is the derived port.
1108    /// The positive half of the ticket's verify list, at the config tier.
1109    #[test]
1110    fn resolved_units_render_a_door_on_the_derived_port() {
1111        let svc = service(
1112            "noisetable",
1113            vec![
1114                component("site", None, DeployTier::Bundle),
1115                component("account", Some("app"), DeployTier::Workload),
1116            ],
1117        );
1118        let domains = domains(
1119            "noisetable",
1120            &[(
1121                "/app/*",
1122                &[
1123                    ("cross-origin-opener-policy", "same-origin"),
1124                    ("cross-origin-embedder-policy", "require-corp"),
1125                ],
1126            )],
1127        );
1128        let plan = plan(&svc, &domains).unwrap().unwrap();
1129
1130        let workload = plan
1131            .workload(plan.listen_port(), "noisetable", &["http://100.64.0.3:7443".to_string()])
1132            .unwrap();
1133        let spec = workload.container_spec().expect("container-shaped");
1134        let listen = spec
1135            .env
1136            .iter()
1137            .find(|e| e.name == "PASSWAY_LISTEN")
1138            .and_then(|e| match &e.value {
1139                EnvValue::Literal { value } => Some(value.clone()),
1140                _ => None,
1141            })
1142            .expect("a door always declares its listener");
1143        assert_eq!(listen, format!("127.0.0.1:{}", listen_port("noisetable")));
1144
1145        let table = &spec.files[0].content;
1146        assert!(table.contains(r#""ident":"noisetable""#), "{table}");
1147        assert!(table.contains(r#""ident":"noisetable-account""#), "{table}");
1148        assert!(table.contains("cross-origin-embedder-policy"), "{table}");
1149    }
1150
1151    // ── R898-F2: the inner door and the compiled table are one join ──────────
1152
1153    /// A placement that resolves the fixture's `static` routes. Nothing here
1154    /// asserts on origins — the point is that the HEADER answer the door plans
1155    /// and the header answer the compiled table carries come from one walk.
1156    fn placement() -> CdnPlacement {
1157        CdnPlacement {
1158            cdn_base: "https://cdn.test".to_string(),
1159            env: "prod".to_string(),
1160            ..Default::default()
1161        }
1162    }
1163
1164    fn compiled(domains: &BTreeMap<String, DomainConfig>) -> RouteTable {
1165        domains["test"]
1166            .route_table(&placement())
1167            .expect("the fixture's routes all resolve")
1168    }
1169
1170    /// passway spells the root mount `""`; the request that reaches it is `/`.
1171    fn mount_path(mount: &str) -> &str {
1172        if mount.is_empty() {
1173            "/"
1174        } else {
1175            mount
1176        }
1177    }
1178
1179    /// A two-unit service whose domain declares a headered `/app/*` above a
1180    /// headerless catch-all — a legal manifest under first-match-wins.
1181    fn seam_fixture() -> (ServiceConfig, BTreeMap<String, DomainConfig>) {
1182        let svc = service(
1183            "noisetable",
1184            vec![
1185                component("site", None, DeployTier::Bundle),
1186                component("account", Some("app"), DeployTier::Workload),
1187            ],
1188        );
1189        let domains = domains(
1190            "noisetable",
1191            &[
1192                (
1193                    "/app/*",
1194                    &[("cross-origin-opener-policy", "same-origin")],
1195                ),
1196                ("/*", &[("x-frame-options", "DENY")]),
1197            ],
1198        );
1199        (svc, domains)
1200    }
1201
1202    /// **THE SEAM (R898-F2).** Every mount's headers are the compiled route
1203    /// table's answer for that mount's path — not a second join that happens to
1204    /// agree. If the two ever diverge, the inner door serves headers the table
1205    /// says are served somewhere else.
1206    #[test]
1207    fn every_mounts_headers_are_the_compiled_route_tables_answer() {
1208        let (svc, domains) = seam_fixture();
1209        let table = compiled(&domains);
1210        let plan = plan(&svc, &domains).unwrap().expect("two units");
1211
1212        for m in &plan.mounts {
1213            let expected = table
1214                .match_path(mount_path(&m.mount))
1215                .map(|e| e.headers.clone())
1216                .unwrap_or_default();
1217            assert_eq!(m.headers, expected, "mount {:?}", m.mount);
1218        }
1219
1220        // Non-trivially: the fixture gives both mounts headers, and DIFFERENT
1221        // ones, so an implementation that returned `Default::default()` for
1222        // everything could not pass the loop above.
1223        assert_eq!(
1224            plan.mounts
1225                .iter()
1226                .map(|m| m.headers.keys().cloned().collect::<Vec<_>>())
1227                .collect::<Vec<_>>(),
1228            vec![
1229                vec!["x-frame-options".to_string()],
1230                vec!["cross-origin-opener-policy".to_string()],
1231            ]
1232        );
1233    }
1234
1235    /// The property the seam exists for: a header edited in the domain manifest
1236    /// reaches the inner door's table without a second join being touched, and
1237    /// both tiers move together.
1238    #[test]
1239    fn a_header_changed_in_the_manifest_moves_both_tiers_at_once() {
1240        let (svc, mut domains) = seam_fixture();
1241        let before = plan(&svc, &domains).unwrap().unwrap();
1242        assert_eq!(
1243            before.mounts[1]
1244                .headers
1245                .get("cross-origin-opener-policy")
1246                .map(String::as_str),
1247            Some("same-origin")
1248        );
1249
1250        // One edit, in the manifest, to the route that governs `/app`.
1251        let route = domains
1252            .get_mut("test")
1253            .unwrap()
1254            .routes
1255            .iter_mut()
1256            .find(|r| r.path == "/app/*")
1257            .unwrap();
1258        route.headers.insert(
1259            "cross-origin-embedder-policy".to_string(),
1260            "require-corp".to_string(),
1261        );
1262
1263        let after = plan(&svc, &domains).unwrap().unwrap();
1264        let table = compiled(&domains);
1265        assert_eq!(
1266            after.mounts[1].headers,
1267            table.match_path("/app").unwrap().headers,
1268            "the door's mount and the compiled entry must move together"
1269        );
1270        assert_eq!(
1271            after.mounts[1]
1272                .headers
1273                .get("cross-origin-embedder-policy")
1274                .map(String::as_str),
1275            Some("require-corp")
1276        );
1277        // And only that mount moved — no merging across rules.
1278        assert_eq!(before.mounts[0].headers, after.mounts[0].headers);
1279    }
1280
1281    /// The order-dependence the shared rule brings, stated as a test rather
1282    /// than left to be discovered: a catch-all declared ABOVE `/app/*` claims
1283    /// `/app` at every tier, and the inner door now agrees instead of quietly
1284    /// disagreeing. This is the manifest being wrong, not the door.
1285    #[test]
1286    fn a_catch_all_declared_first_claims_every_mount_at_both_tiers() {
1287        let svc = service(
1288            "noisetable",
1289            vec![
1290                component("site", None, DeployTier::Bundle),
1291                component("account", Some("app"), DeployTier::Workload),
1292            ],
1293        );
1294        let domains = domains(
1295            "noisetable",
1296            &[
1297                ("/*", &[("x-frame-options", "DENY")]),
1298                ("/app/*", &[("cross-origin-opener-policy", "same-origin")]),
1299            ],
1300        );
1301        let table = compiled(&domains);
1302        let plan = plan(&svc, &domains).unwrap().unwrap();
1303
1304        assert_eq!(
1305            table.match_path("/app").unwrap().path,
1306            "/*",
1307            "first match wins over the compiled table"
1308        );
1309        assert_eq!(plan.mounts[1].mount, "/app");
1310        assert_eq!(
1311            plan.mounts[1].headers.keys().cloned().collect::<Vec<_>>(),
1312            vec!["x-frame-options".to_string()],
1313            "and the inner door reports the same route's headers, not a second join's"
1314        );
1315    }
1316}