Skip to main content

holger_front/
lib.rs

1//! **holger.rs's front page** — the whole public door, as one pure function.
2//!
3//! holger-server is a hand-rolled `hyper` dispatcher with no router, no
4//! template engine and no static-asset tree; until now `GET /` answered `404
5//! Unknown repository`. So this crate is not a framework and does not try to
6//! be one: it is [`route`], a function from a method and a path to a
7//! [`Reply`], and mounting it in `server/lib/src/exposed/http.rs` is four
8//! lines next to the `/-/search` arm.
9//!
10//! That shape is the point. Everything the page *is* — the bytes, the JSON,
11//! the cache headers, the refusals — is decided here, where it can be tested
12//! in a crate that builds in seconds, rather than inside a request handler
13//! that needs the whole server to compile.
14//!
15//! ## The two doors
16//!
17//! | path | what it answers |
18//! |---|---|
19//! | `GET /` | the page (one self-contained HTML file) |
20//! | `GET /holger.webp` | the picture on its left half |
21//! | `GET /-/front` | who this server is, and whether it has a browser login |
22//! | `GET /-/releases` | the catalogue: the public repositories, and the latest version of each package |
23//!
24//! ## ★ The one rule about version numbers
25//!
26//! **This crate never decides which version is newest.** [`latest_by`] groups
27//! and folds, but the comparison is a function the caller passes in, and the
28//! caller is `server/lib`, which passes `retention::cmp_version` — the
29//! comparator holger already uses to decide which artifact a retention sweep
30//! must not delete.
31//!
32//! That is not indirection for its own sake. A front page that ranked versions
33//! with its own comparator would be a SECOND source of truth for "the latest
34//! release", and the first time somebody published `1.10.0` beside `1.9.0` the
35//! page and `holger retention` would name different artifacts as the newest —
36//! with no way to tell which of them was wrong.
37
38use serde::{Deserialize, Serialize};
39use std::cmp::Ordering;
40use std::collections::BTreeMap;
41
42use holger_errcode as ec;
43
44/// The page, as served. One file: holger-server has nowhere to serve a second
45/// one from.
46pub const PAGE: &str = include_str!("../assets/front.html");
47
48/// The picture on the left half.
49///
50/// Produced from the repository's OWN `.nornir/assets/holger-znippy-logo.png`
51/// by `holger-ops logo` — the same file the readme shows, converted once, in
52/// Rust, to lossless WebP. Compiled in rather than read from disk, because a
53/// front page whose picture depends on a deploy having copied a file is a
54/// front page with a half-drawn state nobody tests.
55pub const PICTURE: &[u8] = include_bytes!("../assets/holger.webp");
56
57/// Where the picture is served, named once here and once in the page's
58/// `--backdrop-image`. A test asserts they agree.
59pub const PICTURE_PATH: &str = "/holger.webp";
60
61/// **The makers' marks, compiled in for the same reason the picture is** — and
62/// served from THIS origin rather than hotlinked. An avatar fetched off a third
63/// party's CDN would need a hole in this page's policy and would hand every
64/// visitor's address to that third party for two files under 4 kB. Copied from
65/// gunnar-ui, so the estate's two fronts credit their makers identically.
66pub const VETRA_MARK: &[u8] = include_bytes!("../assets/vetra.svg");
67/// Where the Vetra wordmark is served. A WORDMARK, so the page sizes it by
68/// height only (96x18 from its own 1380x260 viewBox); forcing it square would
69/// squash five letters.
70pub const VETRA_PATH: &str = "/vetra.svg";
71pub const IGNALINA_MARK: &[u8] = include_bytes!("../assets/ignalina.png");
72/// Where the Ignalina mark is served — a square avatar, 18x18.
73pub const IGNALINA_PATH: &str = "/ignalina.png";
74pub const FRONT_PATH: &str = "/-/front";
75pub const RELEASES_PATH: &str = "/-/releases";
76
77// ─────────────────────────────────────────────────────────────────────────────
78// The three columns
79// ─────────────────────────────────────────────────────────────────────────────
80
81/// **One row of the front page's table, and there is no fourth field.**
82///
83/// Size, content type, checksum, upload time and namespace all exist on
84/// [`holger_traits::ArtifactEntry`](https://codeberg.org/nordisk/holger) and
85/// none of them is here. The page a stranger reads first answers one question
86/// — what is in this server and how new is it — and every further column is
87/// noise around the answer. The console has the rest.
88#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
89pub struct Release {
90    /// The holger repository the artifact lives in (`crates-mirror`, `bundles`).
91    pub repository: String,
92    /// The artifact's name. A namespaced coordinate (maven `groupId`, npm
93    /// scope) is rendered `namespace/name` by [`artifact_name`] — one string,
94    /// because the column is one column.
95    pub artifact: String,
96    /// The version, verbatim. Never parsed, never normalised, never
97    /// re-rendered: whatever was published is what is shown.
98    pub version: String,
99}
100
101/// **One public repository, as a stranger may see it.**
102///
103/// ★ Why this exists beside [`Release`]: a repository with nothing in it
104/// produced NO rows, so a freshly installed holger — or one whose store is
105/// still empty, which is what holger.rs is today — answered `/-/releases` with
106/// `[]` and the front page said "Nothing published yet." and named nothing at
107/// all. That is a true sentence about the artifacts and a useless page about
108/// the server: the repositories are configured, they are public, and they are
109/// the first thing a visitor needs in order to point a package manager
110/// anywhere.
111///
112/// So the roster is listed whether or not anything has been published into it.
113#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
114pub struct Repository {
115    /// The repository's name, which is also its first path segment on this
116    /// server.
117    pub name: String,
118    /// The format it speaks — `cargo`, `maven`, `npm`, `generic`. Verbatim from
119    /// the server; never mapped to a prettier word here, because the word the
120    /// server uses is the word the operator configured.
121    pub format: String,
122    /// How many distinct packages the listing found in it. `0` is an answer and
123    /// is printed as one — an empty repository is a normal state.
124    pub packages: usize,
125}
126
127/// **What `/-/releases` answers: the roster and the rows, in one document.**
128///
129/// One fetch, because it is one question — *what is in this server* — and two
130/// fetches would be two chances for the page to render half an answer.
131///
132/// It is an object and not an array, and that is a wire change with a reason:
133/// the array could only ever carry artifacts, so a server with repositories and
134/// no artifacts had no way to say so.
135#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
136pub struct Catalogue {
137    /// Every repository a stranger may list. Already ordered by the caller.
138    pub repositories: Vec<Repository>,
139    /// The newest version of each package, already ranked and ordered by the
140    /// caller. See the module note on why this crate ranks nothing.
141    pub releases: Vec<Release>,
142}
143
144/// How a namespaced coordinate becomes the single string in the middle column.
145///
146/// `Some("org.apache.arrow") + "arrow-vector"` -> `org.apache.arrow/arrow-vector`;
147/// `None + "serde"` -> `serde`. An empty namespace is the same as none — some
148/// backends hand back `Some("")` and a leading `/` in the column would be a
149/// visible bug for an invisible cause.
150pub fn artifact_name(namespace: Option<&str>, name: &str) -> String {
151    match namespace {
152        Some(ns) if !ns.is_empty() => format!("{ns}/{name}"),
153        _ => name.to_string(),
154    }
155}
156
157/// Fold every `(repository, artifact, version)` down to the newest version of
158/// each `(repository, artifact)`, using `newer` to compare.
159///
160/// `newer(a, b)` must answer the ordering of `a` against `b` as VERSIONS. Pass
161/// `retention::cmp_version`; do not pass `str::cmp`, which puts `1.9.0` after
162/// `1.10.0` and is the whole reason this is a parameter.
163///
164/// The result is sorted by repository, then artifact — a stable order, so the
165/// page does not reshuffle between two loads of an unchanged server.
166pub fn latest_by<F>(rows: impl IntoIterator<Item = Release>, newer: F) -> Vec<Release>
167where
168    F: Fn(&str, &str) -> Ordering,
169{
170    // A BTreeMap, not a HashMap: the key order IS the output order, so the
171    // sort is free and cannot be forgotten.
172    let mut best: BTreeMap<(String, String), String> = BTreeMap::new();
173    for r in rows {
174        let key = (r.repository, r.artifact);
175        match best.get(&key) {
176            // `Greater` only — a tie keeps the FIRST one seen, so a repository
177            // that somehow lists one version twice does not flap between loads.
178            Some(have) if newer(&r.version, have) != Ordering::Greater => {}
179            _ => {
180                best.insert(key, r.version);
181            }
182        }
183    }
184    best.into_iter()
185        .map(|((repository, artifact), version)| Release { repository, artifact, version })
186        .collect()
187}
188
189// ─────────────────────────────────────────────────────────────────────────────
190// Who this server is
191// ─────────────────────────────────────────────────────────────────────────────
192
193/// ★ **WHICH OF THE THREE STATES the door is in — the third one is new.**
194///
195/// There were two: no login at all ([`Front::login`] is `None`), and a login
196/// somewhere else on this origin (a link the button follows). Neither of them
197/// is what holger.rs needs, because on holger.rs the console IS this origin:
198/// the link sent a visitor to `/login`, a second page with the same button on
199/// it, and the reader pressed the same thing twice to reach one ceremony.
200///
201/// So there is a third: the ceremony runs **on this page**. The page holds the
202/// WebAuthn call itself — `navigator.credentials.get` against the paths the
203/// server names — and there is no navigation until it has succeeded.
204///
205/// It is a field and not a separate type because the airgapped appliance
206/// serves this same crate with `/auth/*` absent entirely. The appliance
207/// answers [`Door::Link`] or `None` and the ceremony code on the page is never
208/// reached; nothing about the ceremony is compiled into the appliance's
209/// choices, it is markup and script that a server has to opt into by naming
210/// three paths.
211#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
212#[serde(rename_all = "lowercase")]
213pub enum Door {
214    /// The button is a link: press it and the browser goes to `start`.
215    ///
216    /// The default, and it is the default on purpose: a `/-/front` document
217    /// written before this field existed deserialises as a link, which is what
218    /// it was.
219    #[default]
220    Link,
221    /// The ceremony is HERE. `start`, `finish` and `next` are all rooted paths
222    /// on this origin and the page never leaves until `finish` said yes.
223    Here,
224}
225
226/// The door a browser can actually walk through, if there is one.
227#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
228pub struct Login {
229    /// What the button says. **The server's word, not the page's.**
230    pub label: String,
231    /// Where the button goes. A same-site rooted path; the page refuses
232    /// anything else, so a misconfigured server cannot turn the button into an
233    /// open redirect.
234    ///
235    /// For [`Door::Here`] this is the ceremony's START path, fetched rather
236    /// than navigated to.
237    pub start: String,
238    /// Which of the two doors this is. Defaulted, so an older document still
239    /// reads.
240    #[serde(default)]
241    pub door: Door,
242    /// [`Door::Here`] only: where the signed assertion is POSTed. `None` for a
243    /// link, and the page treats a `Here` with no `finish` as a link, because
244    /// a ceremony with nowhere to finish is not a ceremony.
245    #[serde(default, skip_serializing_if = "Option::is_none")]
246    pub finish: Option<String>,
247    /// [`Door::Here`] only: where the browser goes once the session cookie is
248    /// set. A same-site rooted path like the others; `None` means `/`.
249    #[serde(default, skip_serializing_if = "Option::is_none")]
250    pub next: Option<String>,
251}
252
253/// What the button says when the door is the console.
254///
255/// Here rather than in the server for the reason [`Front::no_login_refusal`] is
256/// here: the page prints it verbatim, so it exists in one place and a test can
257/// hold the page to it.
258pub const CONSOLE_LABEL: &str = "Open the console";
259
260/// ★ **What the button says when the ceremony is on this page, and it is the
261/// estate's word.**
262///
263/// Byte-for-byte gunnar's button
264/// (`gunnar-ui/crates/gunnar-ui-server/src/auth/login.html`): the two fronts in
265/// one estate name the same act the same way. "Open the console" describes a
266/// navigation, and there is no navigation any more — the label has to say what
267/// pressing it actually does.
268pub const PASSKEY_LABEL: &str = "Log in with passkey";
269
270/// ★ **The console door, or `None` — and `None` is the answer for anything the
271/// PAGE would refuse to follow.**
272///
273/// The page's button follows only a same-site rooted path (see the `btn.onclick`
274/// guard in `assets/front.html`), which is the open-redirect defence and is not
275/// negotiable. So an operator who points this at `https://console.example.com`
276/// would get a button that is enabled, labelled, and does **nothing at all** on
277/// click — strictly worse than the honest dead button
278/// [`Front::no_login_refusal`] explains, because there is no sentence anywhere
279/// saying why.
280///
281/// This constructor therefore applies the page's own rule **server-side**, and
282/// answers `None` for every value the page would silently drop. The two rules
283/// are asserted equal by
284/// [`the_rust_rule_and_the_pages_rule_refuse_the_same_values`] — one rule, two
285/// languages, held together the way this crate holds its sentences together.
286///
287/// Note what this means for a deployment, because it is a real constraint and
288/// not a detail: **the console must be reachable at a path on THIS server's
289/// origin.** A console on its own host has no rooted path from here, and the
290/// honest answer for it is the one the page already gives.
291pub fn console_login(path: &str) -> Option<Login> {
292    if !same_site_rooted_path(path) {
293        return None;
294    }
295    Some(Login {
296        label: CONSOLE_LABEL.to_string(),
297        start: path.to_string(),
298        door: Door::Link,
299        finish: None,
300        next: None,
301    })
302}
303
304/// ★ **The third state: the passkey ceremony, on this page.**
305///
306/// `start` and `finish` are the server's own ceremony doors and `next` is where
307/// a successful login lands. All three go through `same_site_rooted_path`,
308/// the same rule [`console_login`] applies, and **any one of them failing it
309/// answers `None`** — not a partly-wired ceremony. A page that fetched a
310/// ceremony from one origin and posted the assertion to another is not a door
311/// with a bug in it, it is a different thing entirely.
312///
313/// The label is [`PASSKEY_LABEL`] and the server does not get to choose it: the
314/// button's words and the button's behaviour are one decision, and a server
315/// that could say "Open the console" over a ceremony that never navigates would
316/// be lying to the reader in the one place the reader is looking.
317pub fn passkey_login_here(start: &str, finish: &str, next: &str) -> Option<Login> {
318    if !same_site_rooted_path(start)
319        || !same_site_rooted_path(finish)
320        || !same_site_rooted_path(next)
321    {
322        return None;
323    }
324    Some(Login {
325        label: PASSKEY_LABEL.to_string(),
326        start: start.to_string(),
327        door: Door::Here,
328        finish: Some(finish.to_string()),
329        next: Some(next.to_string()),
330    })
331}
332
333/// The page's `btn.onclick` rule, in Rust.
334///
335/// One leading slash, no authority, and no character the URL parser strips
336/// before it decides what the value even is: `//host` and `/\host` are off-site
337/// in every engine, and a value carrying a space, a tab, a newline or a NUL is
338/// one whose meaning is settled after those are removed.
339fn same_site_rooted_path(path: &str) -> bool {
340    !path.is_empty()
341        && path.starts_with('/')
342        && !path.starts_with("//")
343        && !path.starts_with("/\\")
344        // The page's class is `[\x00-\x20\x7f]` — written in `assets/front.html`
345        // as literal control bytes, which is why that file reads as binary.
346        // `is_ascii_whitespace` is NOT this set (it omits NUL, the other C0
347        // controls and DEL), so the range is spelled out rather than borrowed.
348        && !path.chars().any(|c| (c as u32) <= 0x20 || c as u32 == 0x7f)
349}
350
351/// What `/-/front` answers: everything on the page that is a fact about THIS
352/// server rather than about holger.
353#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
354pub struct Front {
355    /// The base URL a package manager is pointed at. `None` when the server
356    /// was not told its own public name — printed by the server or not at all,
357    /// because a page that guessed it from `location.origin` would print the
358    /// proxy's address on any deployment behind one.
359    #[serde(skip_serializing_if = "Option::is_none")]
360    pub base_url: Option<String>,
361    /// ★ **`None` is an ANSWER, and it is the honest one today.**
362    ///
363    /// holger-server authenticates with mTLS, OIDC and bearer tokens — doors
364    /// for `cargo`, `pip`, `docker` and the native console. There is no
365    /// browser session, so there is no button, and the page says
366    /// [`ec::FRONT_NO_BROWSER_LOGIN`] by name rather than offering one.
367    ///
368    /// It is serialised even when null (no `skip_serializing_if`) precisely so
369    /// the page can tell a server with no login from a server too old to have
370    /// the field.
371    pub login: Option<Login>,
372}
373
374impl Front {
375    /// A server that has told us nothing but its own address.
376    pub fn anonymous(base_url: Option<String>) -> Self {
377        Front { base_url, login: None }
378    }
379
380    /// The refusal the page prints when [`Front::login`] is `None`, by name
381    /// and with its code. Kept here rather than only in the page's JavaScript
382    /// so the words exist in one place and a test can hold them to it.
383    pub fn no_login_refusal() -> String {
384        format!(
385            "{}: this server offers no browser login. Its doors are mTLS, OIDC and bearer — \
386             for cargo, pip, docker and the console, not for a tab.",
387            ec::FRONT_NO_BROWSER_LOGIN.code
388        )
389    }
390}
391
392/// ★ **The three sentences the PAGE prints on its own.**
393///
394/// They are raised in JavaScript, where no Rust compiler can see them and the
395/// frozen registry cannot be consulted — which is exactly how a page ends up
396/// showing a code nobody allocated, or the same failure worded two ways in two
397/// places. So each one is built HERE, from the registry row, and the tests
398/// assert the page carries the string this produces. Change the sentence here
399/// and the test tells you the page has drifted; change it in the page and the
400/// test tells you the same thing.
401///
402/// This is also what makes the rows honest to the wiring guard: a code marked
403/// `wired` must be referenced from the file it claims, and these are the
404/// references.
405pub fn page_refusals() -> [(&'static ec::ErrCode, String); 3] {
406    [
407        (&ec::FRONT_NO_BROWSER_LOGIN, Front::no_login_refusal()),
408        (
409            &ec::FRONT_READS_GATED,
410            format!(
411                "{}: this server gates reads behind a credential, so its front page cannot name \
412                 itself. Configure `require_auth_for_reads: false`, or read the console instead.",
413                ec::FRONT_READS_GATED.code
414            ),
415        ),
416        (
417            &ec::FRONT_DOOR_ABSENT,
418            format!(
419                "{}: this build of holger-server has no `/-/front` door. The page is newer than \
420                 the server behind it.",
421                ec::FRONT_DOOR_ABSENT.code
422            ),
423        ),
424    ]
425}
426
427// ─────────────────────────────────────────────────────────────────────────────
428// The door
429// ─────────────────────────────────────────────────────────────────────────────
430
431/// One answer: a status, a content type, headers that matter, and the bytes.
432#[derive(Debug, Clone, PartialEq)]
433pub struct Reply {
434    pub status: u16,
435    pub content_type: &'static str,
436    /// `Cache-Control`. Named rather than implied: the page and the JSON must
437    /// NOT be cached (a stale release table is a lie about what is published)
438    /// and the picture must be, because it is 300 kB that never changes
439    /// without a redeploy.
440    pub cache_control: &'static str,
441    pub body: Vec<u8>,
442}
443
444impl Reply {
445    fn html(body: &str) -> Reply {
446        Reply {
447            status: 200,
448            content_type: "text/html; charset=utf-8",
449            cache_control: "no-store",
450            body: body.as_bytes().to_vec(),
451        }
452    }
453    fn json(body: String) -> Reply {
454        Reply {
455            status: 200,
456            content_type: "application/json",
457            cache_control: "no-store",
458            body: body.into_bytes(),
459        }
460    }
461    fn webp(bytes: &'static [u8]) -> Reply {
462        Reply {
463            status: 200,
464            content_type: "image/webp",
465            // A year, and immutable: the file's content is compiled into the
466            // binary, so it cannot change without a new binary, and a new
467            // binary is a new deploy.
468            cache_control: "public, max-age=31536000, immutable",
469            body: bytes.to_vec(),
470        }
471    }
472    /// A mark, cached like the picture: compiled into the binary, so it cannot
473    /// change without a new deploy.
474    fn mark(bytes: &'static [u8], content_type: &'static str) -> Reply {
475        Reply {
476            status: 200,
477            content_type,
478            cache_control: "public, max-age=31536000, immutable",
479            body: bytes.to_vec(),
480        }
481    }
482    fn refused(status: u16, code: &ec::ErrCode, detail: &str) -> Reply {
483        Reply {
484            status,
485            content_type: "application/json",
486            cache_control: "no-store",
487            body: serde_json::json!({ "code": code.code, "error": detail }).to_string().into_bytes(),
488        }
489    }
490}
491
492/// What the server must hand the door to answer it.
493///
494/// It is a struct and not four arguments so that adding a fact to the front
495/// page is a field here and a line in the caller, never a new function.
496pub struct Doors<'a> {
497    pub front: &'a Front,
498    /// The roster and the rows. Already the latest, already ordered. The door
499    /// does not rank — see the module note on why.
500    pub catalogue: &'a Catalogue,
501}
502
503/// ★ **The whole public surface, as a pure function.**
504///
505/// `None` means "not mine" — the caller falls through to its own routing, so
506/// mounting this cannot shadow a repository. Every path it DOES own is under
507/// `/` or the already-reserved `/-/` namespace, which can never route into a
508/// repository.
509pub fn route(method: &str, path: &str, doors: &Doors<'_>) -> Option<Reply> {
510    let owned = matches!(
511        path,
512        "/" | PICTURE_PATH | VETRA_PATH | IGNALINA_PATH | FRONT_PATH | RELEASES_PATH
513    );
514    if !owned {
515        return None;
516    }
517
518    // ★ Read-only, and the refusal is by name. A `POST /` that fell through to
519    // the repository router would be a write attempt against a repository
520    // called "" — a 404 that looks like a typo instead of a method that is not
521    // allowed here.
522    if method != "GET" && method != "HEAD" {
523        return Some(Reply::refused(
524            405,
525            &ec::FRONT_METHOD_NOT_ALLOWED,
526            "the front door answers GET and HEAD only",
527        ));
528    }
529
530    let mut reply = match path {
531        "/" => Reply::html(PAGE),
532        PICTURE_PATH => Reply::webp(PICTURE),
533        VETRA_PATH => Reply::mark(VETRA_MARK, "image/svg+xml"),
534        IGNALINA_PATH => Reply::mark(IGNALINA_MARK, "image/png"),
535        FRONT_PATH => Reply::json(
536            serde_json::to_string(doors.front).unwrap_or_else(|_| "{}".to_string()),
537        ),
538        RELEASES_PATH => Reply::json(
539            serde_json::to_string(doors.catalogue)
540                .unwrap_or_else(|_| r#"{"repositories":[],"releases":[]}"#.to_string()),
541        ),
542        _ => unreachable!("`owned` above is the same list"),
543    };
544    // HEAD is the same answer without the bytes. Written here rather than left
545    // to the caller, because a HEAD that returned the body would be the kind
546    // of thing nothing notices until a health check downloads the picture
547    // every thirty seconds.
548    if method == "HEAD" {
549        reply.body.clear();
550    }
551    Some(reply)
552}
553
554/// The refusal for a server whose reads are gated, so `/-/front` cannot be
555/// read at all. Produced by the CALLER, which is the half that knows about
556/// `require_auth_for_reads`; it lives here so the code and the words are in
557/// the same place as the page that prints them.
558pub fn reads_gated() -> Reply {
559    Reply::refused(
560        403,
561        &ec::FRONT_READS_GATED,
562        "this server gates reads behind a credential, so its front page cannot name itself",
563    )
564}
565
566#[cfg(test)]
567mod tests {
568    use super::*;
569
570    /// A comparator that is WRONG on purpose — plain string order, which puts
571    /// `1.9.0` above `1.10.0`. Used to prove the fold asks the comparator it
572    /// was given and holds no opinion of its own.
573    fn lexicographic(a: &str, b: &str) -> Ordering {
574        a.cmp(b)
575    }
576
577    /// A toy numeric comparator standing in for `retention::cmp_version`, so
578    /// the grouping can be tested without depending on `server/lib`.
579    fn numeric(a: &str, b: &str) -> Ordering {
580        let parts = |v: &str| v.split('.').map(|p| p.parse::<u64>().unwrap_or(0)).collect::<Vec<_>>();
581        parts(a).cmp(&parts(b))
582    }
583
584    fn rel(repo: &str, art: &str, ver: &str) -> Release {
585        Release { repository: repo.into(), artifact: art.into(), version: ver.into() }
586    }
587
588    // ── The console door ─────────────────────────────────────────────────────
589
590    /// A path the page will follow becomes a button, labelled in the server's
591    /// own word.
592    #[test]
593    fn a_rooted_path_becomes_the_console_button() {
594        let login = console_login("/console").expect("a rooted path is a door");
595        assert_eq!(login.start, "/console");
596        assert_eq!(login.label, CONSOLE_LABEL);
597    }
598
599    /// ★ **The Rust rule and the PAGE's rule refuse exactly the same values.**
600    ///
601    /// This is the test the whole constructor exists for. The page's
602    /// `btn.onclick` drops a value it will not follow **silently** — no
603    /// sentence, no code, just a button that does nothing — so a server that
604    /// answered with one would produce the one failure state the front page's
605    /// design is otherwise free of. Rather than trust two prose descriptions of
606    /// one rule, the page's own class is read out of [`PAGE`] and applied here.
607    ///
608    /// It is spelled `\x00-\x20` plus `\x7f`, and since 2026-09-20 it is
609    /// written in the HTML as JS ESCAPES and not as literal control bytes.
610    /// That is not a style preference, it is the fix for a page that hung:
611    /// the literal NUL made `assets/front.html` read as binary to `file(1)`,
612    /// and in a browser the HTML tokenizer's script-data state replaces a
613    /// U+0000 with U+FFFD, so the engine parsed `/[\u{fffd}-\u{20}\u{7f}]/`,
614    /// refused it as "range out of order in character class", and threw away
615    /// the WHOLE inline script — the `/-/front` fetch with it. The page then
616    /// sat on its literal `reading the server …` with the button still
617    /// `disabled` for ever. [`the_page_carries_no_raw_control_bytes`] is the
618    /// guard that keeps a literal from coming back.
619    #[test]
620    fn the_rust_rule_and_the_pages_rule_refuse_the_same_values() {
621        // The page still carries the guard this mirrors. If the button's
622        // handler is rewritten, this test must be re-read, not re-blessed.
623        assert!(
624            PAGE.contains("if (!start.startsWith('/') || start.startsWith('//') || start.startsWith('/\\\\')) return false;"),
625            "the page's same-site guard has moved; console_login may no longer mirror it"
626        );
627        assert!(
628            PAGE.contains(r"if (/[\x00-\x20\x7f]/.test(start)) return false;"),
629            "the page's control-character class has changed; same_site_rooted_path is now a second opinion"
630        );
631
632        for refused in [
633            "",                            // the page returns early on empty
634            "https://console.example.com", // an off-site URL — the tempting mistake
635            "console",                     // a relative path is not rooted
636            "//evil.example.com",          // protocol-relative: off-site everywhere
637            "/\\evil.example.com",         // backslash authority: off-site everywhere
638            "/console\u{0}",               // NUL
639            "/console\u{9}",               // tab
640            "/console\u{a}",               // newline
641            "/con sole",                   // space
642            "/console\u{7f}",              // DEL — the one the first draft missed
643        ] {
644            assert!(
645                console_login(refused).is_none(),
646                "{refused:?} must not become a button: the page would drop it in silence"
647            );
648        }
649    }
650
651    /// An unconfigured console leaves the page exactly as it is today — the
652    /// named refusal, not a button to nowhere. A self-hoster who runs no
653    /// console must not be offered one.
654    #[test]
655    fn no_console_configured_is_still_the_named_refusal() {
656        let f = Front { base_url: None, login: None };
657        let body = serde_json::to_string(&f).unwrap();
658        assert!(body.contains("\"login\":null"), "{body}");
659        assert!(Front::no_login_refusal().starts_with(ec::FRONT_NO_BROWSER_LOGIN.code));
660    }
661
662    /// ★ **The fold has no opinion about versions.** The same input with two
663    /// comparators gives two different answers — which is the proof that the
664    /// ranking comes from the caller and not from this crate.
665    #[test]
666    fn the_comparator_decides_and_this_crate_does_not() {
667        let rows = vec![rel("crates", "serde", "1.9.0"), rel("crates", "serde", "1.10.0")];
668        assert_eq!(latest_by(rows.clone(), numeric)[0].version, "1.10.0");
669        assert_eq!(latest_by(rows, lexicographic)[0].version, "1.9.0");
670    }
671
672    /// One row per `(repository, artifact)`, and the same artifact name in two
673    /// repositories is two rows — a mirror and a local store legitimately hold
674    /// different versions of `serde`, and collapsing them would hide it.
675    #[test]
676    fn one_row_per_repository_and_artifact() {
677        let out = latest_by(
678            vec![
679                rel("crates", "serde", "1.0.1"),
680                rel("crates", "serde", "1.0.9"),
681                rel("mirror", "serde", "1.0.4"),
682                rel("crates", "tokio", "1.2.0"),
683            ],
684            numeric,
685        );
686        assert_eq!(out.len(), 3);
687        assert_eq!(
688            out.iter().map(|r| (r.repository.as_str(), r.artifact.as_str(), r.version.as_str())).collect::<Vec<_>>(),
689            vec![("crates", "serde", "1.0.9"), ("crates", "tokio", "1.2.0"), ("mirror", "serde", "1.0.4")]
690        );
691    }
692
693    /// The order is stable and does not depend on the order rows arrived in.
694    /// A page that reshuffled between two loads of an unchanged server would
695    /// read as a server that is changing.
696    #[test]
697    fn the_order_does_not_depend_on_the_input_order() {
698        let a = vec![rel("b", "y", "1"), rel("a", "z", "1"), rel("a", "y", "1")];
699        let mut b = a.clone();
700        b.reverse();
701        assert_eq!(latest_by(a, numeric), latest_by(b, numeric));
702    }
703
704    #[test]
705    fn a_namespace_joins_the_name_with_one_slash_and_an_empty_one_does_not() {
706        assert_eq!(artifact_name(Some("org.apache.arrow"), "arrow-vector"), "org.apache.arrow/arrow-vector");
707        assert_eq!(artifact_name(Some("@scope"), "pkg"), "@scope/pkg");
708        assert_eq!(artifact_name(None, "serde"), "serde");
709        assert_eq!(artifact_name(Some(""), "serde"), "serde", "an empty namespace put a slash on the front");
710    }
711
712    // ── the door ─────────────────────────────────────────────────────────────
713
714    fn doors() -> (Front, Catalogue) {
715        (
716            Front::anonymous(Some("https://holger.rs".into())),
717            Catalogue {
718                repositories: vec![Repository {
719                    name: "bundles".into(),
720                    format: "generic".into(),
721                    packages: 1,
722                }],
723                releases: vec![rel("bundles", "site-a", "3")],
724            },
725        )
726    }
727
728    #[test]
729    fn the_page_is_served_at_the_root_and_is_not_cached() {
730        let (f, r) = doors();
731        let d = Doors { front: &f, catalogue: &r };
732        let reply = route("GET", "/", &d).expect("the root is this door's");
733        assert_eq!(reply.status, 200);
734        assert_eq!(reply.content_type, "text/html; charset=utf-8");
735        assert_eq!(reply.cache_control, "no-store", "the page must not be cached");
736        assert_eq!(reply.body, PAGE.as_bytes());
737    }
738
739    /// The picture is cached hard, because it cannot change without a new
740    /// binary — and the JSON is not, because it changes whenever anybody
741    /// publishes.
742    #[test]
743    fn the_picture_is_cached_forever_and_the_json_never() {
744        let (f, r) = doors();
745        let d = Doors { front: &f, catalogue: &r };
746        let pic = route("GET", PICTURE_PATH, &d).unwrap();
747        assert_eq!(pic.content_type, "image/webp");
748        assert!(pic.cache_control.contains("immutable"), "{}", pic.cache_control);
749        for p in [FRONT_PATH, RELEASES_PATH] {
750            assert_eq!(route("GET", p, &d).unwrap().cache_control, "no-store", "{p} was cacheable");
751        }
752    }
753
754    /// ★ **The picture the page names is the picture the door serves.** The
755    /// path is written twice — once in CSS, once as a constant — and this is
756    /// what keeps the two from drifting into a broken left half that nobody
757    /// notices because the layout still works.
758    #[test]
759    fn the_page_asks_for_the_picture_this_door_serves() {
760        assert!(
761            PAGE.contains(&format!("url(\"{PICTURE_PATH}\")")),
762            "the page's --backdrop-image does not name {PICTURE_PATH}"
763        );
764        assert!(PAGE.contains(RELEASES_PATH), "the page does not fetch {RELEASES_PATH}");
765        assert!(PAGE.contains(FRONT_PATH), "the page does not fetch {FRONT_PATH}");
766    }
767
768    /// ★ **The page carries no raw control byte, because one of them silently
769    /// deleted the whole inline script.**
770    ///
771    /// MEASURED 2026-09-20 on the live holger.rs: `assets/front.html` held a
772    /// literal U+0000 inside the `btn.onclick` guard's regex. `curl` saw a
773    /// perfectly good 23 115-byte document and `/-/front` answered 200; a
774    /// browser did not. The HTML tokenizer's script-data state turns U+0000
775    /// into U+FFFD before the JS engine ever sees it, so the engine was handed
776    /// `/[\u{fffd}-\u{20}\u{7f}]/`, whose range runs backwards. That is an
777    /// early SyntaxError, which kills the ENTIRE `<script>` element — the
778    /// `/-/front` fetch, the button's label, the button's `disabled = false`,
779    /// all of it — and leaves the page showing its own literal placeholder
780    /// `reading the server …` next to a grey button that cannot be pressed.
781    ///
782    /// The class is therefore spelled with escapes now, and this test is the
783    /// reason a literal cannot come back. `\t`, `\n` and `\r` are the three
784    /// bytes a text document is allowed to contain.
785    #[test]
786    fn the_page_carries_no_raw_control_bytes() {
787        for (i, b) in PAGE.bytes().enumerate() {
788            let allowed = matches!(b, b'\t' | b'\n' | b'\r');
789            assert!(
790                allowed || !(b.is_ascii_control() || b == 0x7f),
791                "assets/front.html carries a raw control byte {b:#04x} at offset {i}; \
792                 a browser replaces U+0000 with U+FFFD in script data and throws the whole \
793                 inline script away. Write it as a JS escape."
794            );
795        }
796    }
797
798    /// The picture really is a WebP, and really is the one that was converted
799    /// — not a PNG somebody renamed.
800    #[test]
801    fn the_compiled_in_picture_is_a_webp() {
802        assert!(PICTURE.len() > 12, "the picture is empty — run `holger-ops logo`");
803        assert_eq!(&PICTURE[0..4], b"RIFF", "not a RIFF container");
804        assert_eq!(&PICTURE[8..12], b"WEBP", "not a WebP");
805    }
806
807    /// ★ **Nothing but this door's own four paths is claimed.** A door that
808    /// answered `/crates-mirror` would shadow a repository, and it would do it
809    /// silently — the repository would simply stop existing.
810    #[test]
811    fn a_repository_path_is_never_this_doors() {
812        let (f, r) = doors();
813        let d = Doors { front: &f, catalogue: &r };
814        for p in ["/crates-mirror", "/v2/alpine/manifests/latest", "/-/search", "/healthz", "/bundles/x", ""] {
815            assert!(route("GET", p, &d).is_none(), "{p} was claimed by the front door");
816        }
817    }
818
819    /// A write against the front door is refused BY NAME with a code, not
820    /// dropped into the repository router where it becomes a confusing 404.
821    #[test]
822    fn a_write_is_refused_by_name_with_its_code() {
823        let (f, r) = doors();
824        let d = Doors { front: &f, catalogue: &r };
825        for m in ["POST", "PUT", "DELETE", "PATCH"] {
826            let reply = route(m, "/", &d).unwrap();
827            assert_eq!(reply.status, 405, "{m}");
828            let body = String::from_utf8(reply.body).unwrap();
829            assert!(body.contains(ec::FRONT_METHOD_NOT_ALLOWED.code), "{m}: {body}");
830        }
831    }
832
833    #[test]
834    fn head_answers_the_same_thing_without_the_bytes() {
835        let (f, r) = doors();
836        let d = Doors { front: &f, catalogue: &r };
837        for p in ["/", PICTURE_PATH, FRONT_PATH, RELEASES_PATH] {
838            let get = route("GET", p, &d).unwrap();
839            let head = route("HEAD", p, &d).unwrap();
840            assert_eq!(head.status, get.status);
841            assert_eq!(head.content_type, get.content_type);
842            assert!(head.body.is_empty(), "HEAD {p} carried a body");
843        }
844    }
845
846    /// The three columns go over the wire under the names the page reads, and
847    /// there is no fourth.
848    #[test]
849    fn the_wire_carries_exactly_three_columns() {
850        let (f, r) = doors();
851        let d = Doors { front: &f, catalogue: &r };
852        let body = String::from_utf8(route("GET", RELEASES_PATH, &d).unwrap().body).unwrap();
853        let doc: serde_json::Value = serde_json::from_str(&body).unwrap();
854        let rows: Vec<serde_json::Map<String, serde_json::Value>> =
855            serde_json::from_value(doc["releases"].clone()).unwrap();
856        assert_eq!(rows.len(), 1);
857        // A SET, not a sequence: `serde_json::Map` is a BTreeMap without the
858        // `preserve_order` feature, so the wire order is alphabetical and
859        // asserting declaration order here would only be asserting serde's
860        // build configuration. The COLUMN order is the page's, and it is
861        // checked where it lives — in `the_page_is_holgers`, against the
862        // `<th>` headings a reader actually sees.
863        let mut keys: Vec<&str> = rows[0].keys().map(|k| k.as_str()).collect();
864        keys.sort_unstable();
865        assert_eq!(keys, vec!["artifact", "repository", "version"], "the row grew or lost a column");
866    }
867
868    /// ★ **`login: null` is sent, not omitted.** The page must be able to tell
869    /// a server that HAS no browser login from a server too old to have the
870    /// field — they need different sentences, and a skipped field makes them
871    /// the same byte sequence.
872    #[test]
873    fn a_server_with_no_login_says_so_rather_than_saying_nothing() {
874        let f = Front::anonymous(None);
875        let body = serde_json::to_string(&f).unwrap();
876        assert!(body.contains("\"login\":null"), "{body}");
877        assert!(!body.contains("base_url"), "an absent base URL should not be sent at all: {body}");
878    }
879
880    /// The refusal the page prints carries the registry's code, and the page
881    /// and the Rust say the same words — one sentence, two places, held
882    /// together by this.
883    #[test]
884    fn the_no_login_refusal_is_the_same_sentence_in_the_page_and_in_the_code() {
885        let r = Front::no_login_refusal();
886        assert!(r.starts_with(ec::FRONT_NO_BROWSER_LOGIN.code), "{r}");
887        assert!(PAGE.contains(&r), "the page's sentence has drifted from Front::no_login_refusal():\n{r}");
888    }
889
890    /// Every code this door and its page can show is a row in the FROZEN
891    /// registry. A refusal with a number nobody allocated is a refusal nobody
892    /// can look up.
893    #[test]
894    fn every_code_the_page_prints_is_in_the_registry() {
895        for code in [
896            ec::FRONT_METHOD_NOT_ALLOWED,
897            ec::FRONT_NO_BROWSER_LOGIN,
898            ec::FRONT_READS_GATED,
899            ec::FRONT_DOOR_ABSENT,
900        ] {
901            assert_eq!(code.subsystem, "front");
902            assert!(holger_errcode::ALL.iter().any(|c| c.code == code.code), "{} is not in ALL", code.code);
903        }
904    }
905
906    /// ★ **Every sentence the page prints is the sentence this crate builds.**
907    /// The page raises three refusals in JavaScript, where nothing checks
908    /// them; this is the check. A word changed on either side fails here,
909    /// naming which.
910    #[test]
911    fn the_pages_refusals_are_the_ones_this_crate_words() {
912        for (code, sentence) in page_refusals() {
913            assert!(sentence.starts_with(code.code), "{sentence}");
914            assert!(
915                PAGE.contains(&sentence),
916                "the page has drifted from the wording of {}:\n  expected: {sentence}",
917                code.code
918            );
919        }
920    }
921
922    /// ★ **No gunnar sentence survived the copy.** The page's shape is
923    /// gunnar's login page and its words must be holger's; a page that says
924    /// gunnar's sentences under holger's logo is worse than one that says
925    /// nothing. This is the test that catches a paste.
926    ///
927    /// `vetra` and `ignalina` were on this list until 2026-09-17 and are
928    /// DELIBERATELY off it now. They were never gunnar's words — they are the
929    /// two companies that make both products, and the credit line is now
930    /// gunnar's block verbatim BY INSTRUCTION, marks and all, so the estate's
931    /// two fronts credit their makers identically instead of one crediting
932    /// companies and the other listing two people and a repository URL. What
933    /// this test exists to catch is a gunnar SENTENCE arriving under holger's
934    /// logo; a shared maker is not that, and keeping them here would make the
935    /// guard fail on the one paste that was asked for.
936    #[test]
937    ///
938    /// `passkey` and `webauthn` were on this list until 2026-09-20 and are off
939    /// it now for a reason that is not a relaxation: they were banned because
940    /// holger-server HAD no browser session, so either word on this page could
941    /// only have arrived by paste. The console's ceremony now runs ON this page
942    /// ([`Door::Here`]), so "passkey" is holger's own word for holger's own
943    /// door. `gunnar`, `badger` and `git server` stay: those describe a
944    /// different product and can still only arrive by paste.
945    #[test]
946    fn the_page_says_nothing_about_gunnar() {
947        let lower = PAGE.to_lowercase();
948        for word in ["gunnar", "badger", "git server"] {
949            assert!(!lower.contains(word), "the page still says `{word}`");
950        }
951    }
952
953    /// ★ **The credit names the makers and serves their marks from HERE.** The
954    /// page carried "Rickard Lundin & Henrik Torp · codeberg.org/nordisk/holger"
955    /// until 2026-09-17; it now carries gunnar's block. Both marks are compiled
956    /// in and routed by this door, because a credit whose images 404 is worse
957    /// than a credit in plain text.
958    #[test]
959    fn the_credit_names_both_makers_and_this_door_serves_their_marks() {
960        assert!(PAGE.contains("Vetra AB"), "the credit does not name Vetra AB");
961        assert!(PAGE.contains("Ignalina ApS"), "the credit does not name Ignalina ApS");
962        assert!(!PAGE.contains("Rickard"), "the old people-and-repo credit is still here");
963        assert!(!PAGE.contains("codeberg.org/nordisk/holger"), "the old repo link is still here");
964        for path in [VETRA_PATH, IGNALINA_PATH] {
965            assert!(PAGE.contains(path), "the page does not reference {path}");
966            let (f, rel) = doors();
967            let d = Doors { front: &f, catalogue: &rel };
968            let r = route("GET", path, &d).unwrap_or_else(|| panic!("{path} is not served"));
969            assert_eq!(r.status, 200, "{path} answered {}", r.status);
970            assert!(!r.body.is_empty(), "{path} served an empty body");
971        }
972    }
973
974    /// ★ **No price, no currency, no amount.** The console's discipline,
975    /// carried over: holger's front page states what is published, and every
976    /// number on it came from the server.
977    #[test]
978    fn the_page_names_no_price_and_no_currency() {
979        for token in ["€", "$", "£", "kr", "SEK", "EUR", "USD", "/month", "per month", "free tier", "pricing"] {
980            assert!(!PAGE.contains(token), "the page carries `{token}`");
981        }
982    }
983
984    /// The page says what holger is, in the repository's own words, and names
985    /// the product it is a front for.
986    #[test]
987    fn the_page_is_holgers() {
988        assert!(PAGE.contains("<h1>Holger</h1>"), "the page does not name the product");
989        assert!(PAGE.contains("Immutable artifact repository"), "the tagline is not the readme's");
990        assert!(PAGE.contains("Latest releases"), "the list is not named");
991        // ★ The three columns, in the order a reader sees them. The JSON is
992        // alphabetical and says nothing about this; the markup is where the
993        // order lives, so the markup is where it is checked.
994        let mut at = 0usize;
995        for col in ["Repository", "Artifact", "Version"] {
996            let head = format!(">{col}</th>");
997            let found = PAGE.find(&head).unwrap_or_else(|| panic!("the `{col}` column heading is missing"));
998            assert!(found > at, "the columns are out of order at `{col}`");
999            at = found;
1000        }
1001        // …and the script fills them in that same order, so the heading and
1002        // the cell under it are the same field.
1003        let script = PAGE.split("<script>").nth(1).unwrap_or("");
1004        assert!(
1005            script.contains("[['repository', ''], ['artifact', ''], ['version', 'version']]"),
1006            "the script no longer fills the columns in the order the headings promise"
1007        );
1008    }
1009
1010    /// The picture is on the LEFT: `.art` is the first child of `<body>` and
1011    /// takes the first half of a row. A `flex-direction: row-reverse` or a
1012    /// reordered body would move it, and it is one line either way — so it is
1013    /// asserted rather than trusted.
1014    #[test]
1015    fn the_picture_is_on_the_left() {
1016        let body = PAGE.split("<body>").nth(1).expect("the page has a body");
1017        let art = body.find("class=\"art\"").expect("the page has the picture half");
1018        let side = body.find("class=\"side\"").expect("the page has the column");
1019        assert!(art < side, "the picture is not the first half of the page");
1020        assert!(!PAGE.contains("row-reverse"), "something reversed the row and put the picture on the right");
1021        assert!(PAGE.contains(".art {\n    flex: 0 0 50%;"), "the picture no longer owns a half");
1022    }
1023
1024    /// ★ **The page computes no version ordering.** The one rule of this
1025    /// crate, checked against the page's own script: no sort, no compare, no
1026    /// localeCompare. The server ranks; the page prints.
1027    #[test]
1028    fn the_page_does_not_rank_anything() {
1029        let script = PAGE.split("<script>").nth(1).unwrap_or("");
1030        for banned in [".sort(", "localeCompare", "parseFloat", "parseInt"] {
1031            assert!(!script.contains(banned), "the page's script carries `{banned}` — it is deciding something");
1032        }
1033    }
1034
1035    /// Nothing is fetched from a third party. This server runs airgapped by
1036    /// design; a font or a script from a CDN would be a front page that is
1037    /// blank in exactly the deployment holger exists for.
1038    #[test]
1039    fn the_page_fetches_nothing_from_outside() {
1040        for scheme in ["http://", "//cdn", "googleapis", "cdnjs", "jsdelivr", "unpkg"] {
1041            assert!(!PAGE.contains(scheme), "the page reaches out to `{scheme}`");
1042        }
1043        // The one external link is the forge the source is published from, and
1044        // it is a link a reader clicks — not something the page loads.
1045        assert_eq!(PAGE.matches("https://").count(), 1, "the page names more than one external URL");
1046    }
1047
1048    // ── the third state ──────────────────────────────────────────────────────
1049
1050    /// ★★ **THE BUTTON SAYS "Log in with passkey" AND THE CEREMONY IS HERE.**
1051    ///
1052    /// The owner's words, twice: the same label as gunnar's, and no second page
1053    /// that shows the same thing again. Both halves are asserted, because
1054    /// either one alone is the bug that was shipped — a label over a
1055    /// navigation, or a ceremony behind a button that says "Open the console".
1056    #[test]
1057    fn the_ceremony_door_is_labelled_and_wired_to_this_page() {
1058        let login = passkey_login_here(
1059            "/auth/passkey/login/start",
1060            "/auth/passkey/login/finish",
1061            "/overview",
1062        )
1063        .expect("three rooted paths are a ceremony");
1064        assert_eq!(login.label, PASSKEY_LABEL);
1065        assert_eq!(login.label, "Log in with passkey");
1066        assert_eq!(login.door, Door::Here);
1067        assert_eq!(login.finish.as_deref(), Some("/auth/passkey/login/finish"));
1068        assert_eq!(login.next.as_deref(), Some("/overview"));
1069
1070        // …and it goes over the wire naming its own state, because the page
1071        // branches on that word and nothing else.
1072        let body = serde_json::to_string(&Front {
1073            base_url: None,
1074            login: Some(login),
1075        })
1076        .unwrap();
1077        assert!(body.contains(r#""door":"here""#), "{body}");
1078    }
1079
1080    /// The link door is unchanged and still says so on the wire. The appliance
1081    /// and any self-hoster with a console elsewhere on the origin keep exactly
1082    /// the page they had.
1083    #[test]
1084    fn a_link_door_still_says_link_and_carries_no_ceremony() {
1085        let login = console_login("/login?next=/overview").unwrap();
1086        assert_eq!(login.door, Door::Link);
1087        assert_eq!(login.label, CONSOLE_LABEL);
1088        assert!(login.finish.is_none() && login.next.is_none());
1089        let body = serde_json::to_string(&login).unwrap();
1090        assert!(body.contains(r#""door":"link""#), "{body}");
1091        assert!(!body.contains("finish"), "a link door sent a ceremony field: {body}");
1092    }
1093
1094    /// A `/-/front` document written before `door` existed still reads, and
1095    /// reads as the link it was. The field defaults rather than failing, which
1096    /// is the whole reason it is a field on a struct and not a tag on an enum.
1097    #[test]
1098    fn a_document_from_before_this_field_is_still_a_link() {
1099        let old = r#"{"label":"Open the console","start":"/login"}"#;
1100        let login: Login = serde_json::from_str(old).unwrap();
1101        assert_eq!(login.door, Door::Link);
1102    }
1103
1104    /// ★ **All three paths go through one rule, and one bad path is no door.**
1105    ///
1106    /// A half-wired ceremony — a start on this origin and a finish somewhere
1107    /// else — is not a door with a bug in it. It is the assertion being posted
1108    /// to a stranger.
1109    #[test]
1110    fn one_off_site_path_refuses_the_whole_ceremony() {
1111        let good = ("/auth/passkey/login/start", "/auth/passkey/login/finish", "/overview");
1112        assert!(passkey_login_here(good.0, good.1, good.2).is_some());
1113        for bad in ["https://evil.example.com/finish", "//evil.example.com", "/\\evil", "", "relative"] {
1114            assert!(passkey_login_here(bad, good.1, good.2).is_none(), "start {bad:?}");
1115            assert!(passkey_login_here(good.0, bad, good.2).is_none(), "finish {bad:?}");
1116            assert!(passkey_login_here(good.0, good.1, bad).is_none(), "next {bad:?}");
1117        }
1118    }
1119
1120    /// ★ **The page holds the ceremony itself.** The three calls a WebAuthn
1121    /// login is made of are in the document, so the button cannot be a
1122    /// navigation dressed up as one.
1123    #[test]
1124    fn the_page_carries_the_ceremony_and_not_a_second_page() {
1125        let script = PAGE.split("<script>").nth(1).unwrap_or("");
1126        assert!(
1127            script.contains("navigator.credentials.get"),
1128            "the page does not call the authenticator — the button is still a link"
1129        );
1130        assert!(script.contains("allowCredentials"), "the page does not decode the challenge list");
1131        assert!(script.contains("clientDataJSON"), "the page does not send the assertion");
1132        // The LABEL is deliberately not in the page. It is the server's word —
1133        // `/-/front` names it and the page prints what it is handed — which is
1134        // why the button could say "Open the console" over a ceremony if the
1135        // two halves were decided in two places. They are decided in one:
1136        // `PASSKEY_LABEL` is set by `passkey_login_here` and by nothing else,
1137        // and `the_ceremony_door_is_labelled_and_wired_to_this_page` is where
1138        // the words are held.
1139        assert!(
1140            !PAGE.contains("Open the console"),
1141            "the page hard-codes a label; the server names the button"
1142        );
1143    }
1144
1145    // ── the roster ───────────────────────────────────────────────────────────
1146
1147    /// ★ **A server with repositories and nothing published still has a
1148    /// catalogue.** The state holger.rs is in: an empty array said "nothing
1149    /// here" about a server that has repositories a stranger can use.
1150    #[test]
1151    fn an_empty_store_still_names_its_repositories() {
1152        let f = Front::anonymous(None);
1153        let c = Catalogue {
1154            repositories: vec![
1155                Repository { name: "crates-mirror".into(), format: "cargo".into(), packages: 0 },
1156            ],
1157            releases: vec![],
1158        };
1159        let d = Doors { front: &f, catalogue: &c };
1160        let body = String::from_utf8(route("GET", RELEASES_PATH, &d).unwrap().body).unwrap();
1161        let doc: serde_json::Value = serde_json::from_str(&body).unwrap();
1162        assert_eq!(doc["repositories"].as_array().unwrap().len(), 1);
1163        assert_eq!(doc["repositories"][0]["name"], "crates-mirror");
1164        assert_eq!(doc["repositories"][0]["format"], "cargo");
1165        assert_eq!(doc["repositories"][0]["packages"], 0);
1166        assert!(doc["releases"].as_array().unwrap().is_empty());
1167    }
1168
1169    /// The page reads the two lists by the names the wire uses, and names the
1170    /// roster for a reader.
1171    #[test]
1172    fn the_page_reads_both_halves_of_the_catalogue() {
1173        let script = PAGE.split("<script>").nth(1).unwrap_or("");
1174        assert!(script.contains("doc.repositories"), "the page ignores the roster");
1175        assert!(script.contains("doc.releases"), "the page ignores the rows");
1176        assert!(PAGE.contains("Public repositories"), "the roster has no heading");
1177    }
1178
1179    /// No `innerHTML` anywhere: a repository name, an artifact name and a
1180    /// version are operator-supplied text arriving over a socket.
1181    #[test]
1182    fn nothing_on_the_page_turns_text_into_markup() {
1183        assert!(!PAGE.contains("innerHTML"), "the page writes markup from data");
1184        assert!(!PAGE.contains("document.write"), "the page uses document.write");
1185    }
1186}