Skip to main content

ledgeline_shell/
security.rs

1//! Access control and response hardening for the local HTTP server: a
2//! per-process bearer token, a `Host`-header guard, an exact-origin CORS
3//! allowlist, and the security headers (CSP included) every response carries.
4//!
5//! # Threat model — stated honestly
6//!
7//! Ledgeline serves a complete financial journal, readable *and writable*, over
8//! plain HTTP on loopback. Until this module existed the only thing between that
9//! journal and every web page the user had open was the port number, and
10//! `CorsLayer::permissive()` gave even that away: any origin could read
11//! `/transactions` and `POST`/`DELETE` `/api/transactions` (SEC-1).
12//!
13//! ## What the controls here genuinely stop
14//!
15//! * **A web page sweeping loopback ports.** With no CORS layer on the default
16//!   path a page on `https://evil.example` (or `file://`, or another
17//!   `http://localhost:*` app) still gets its request *sent*, but cannot read
18//!   any reply — and because every wire and `/api` route now demands the token,
19//!   it cannot land a blind write either. The token is a 256-bit random value it
20//!   has no way to guess and, absent CORS, no way to read.
21//! * **A page on an ALLOWLISTED origin reading the token.** `--allow-origin`
22//!   opens the API to a named dev origin, and for a while it opened the SPA
23//!   shell too, because the CORS layer was installed over the whole router
24//!   including the fallback. The shell then carried the token in its body, so one
25//!   `fetch("http://127.0.0.1:<port>/")` from any page on that origin — another
26//!   Vite project, a malicious dev dependency — read it and had full read/write
27//!   on the journal with no interaction (SEC-12). The layer is now a
28//!   `route_layer` over the explicit routes only; see [`protect`].
29//! * **DNS rebinding.** [`host_guard`] rejects any request whose `Host` is not a
30//!   loopback name on the port we actually bound, so re-pointing
31//!   `attacker.example.com` at `127.0.0.1` buys nothing.
32//! * **Silent exfiltration if an XSS sink ever appears.** The `connect-src
33//!   'self'` CSP means injected script cannot post the journal anywhere.
34//!
35//! ## What they do NOT stop — do not claim otherwise
36//!
37//! * **A malicious process running as the SAME user.** It can read (and rewrite)
38//!   the journal file directly; no HTTP control is relevant.
39//! * **Anyone who can read the `--server` terminal.** Headless mode prints the
40//!   launch URL, token included, because something else has to drive it.
41//! * **Anything at all once `--host` is pointed off loopback.** That path is
42//!   gated on an explicitly configured token (`$LEDGELINE_TOKEN` for Ledgeline,
43//!   [`AppIdentity::token_env`] in general) and turns the `Host` guard off,
44//!   because the legitimate `Host` values are then unknowable.
45//!
46//! ## Closed: another local process scraping the token from `GET /`
47//!
48//! The SPA shell is served without a token (the browser has nothing to present
49//! before it has loaded the page), and HTTP gives us no way to tell the user's
50//! own WebView from someone else's `curl`. The shell used to carry the token in
51//! its body for the browser to bootstrap, so any process that could reach
52//! loopback — another local user's included — could `GET /` and read it. The
53//! token now appears in no response body at all:
54//!
55//! * the GUI hands it to its WebView out of band, with wry's initialization
56//!   script, guarded to our exact origin ([`token_init_script`]);
57//! * `--server` prints a launch URL with the token in its `#token=` fragment,
58//!   which a browser never puts on the wire; the SPA moves it into
59//!   `sessionStorage` and strips it from the address bar.
60//!
61//! That exposure is what made the following worth writing down. This threat
62//! model used to bound the worst case by "the journal file's own permissions",
63//! which was **wrong** — wrong enough to be a finding in its own right, because
64//! it is not bounded at all. Whoever holds the token holds `PUT /api/prefs`, and
65//! `hledgerPath` there names the binary spawned on every import. So a token
66//! scraped once bought arbitrary CODE EXECUTION as the user, surviving restarts,
67//! from which the journal's permissions follow trivially (SEC-14).
68//! Ledgeline's `prefs::check_storable` refuses a group- or world-writable binary and runs
69//! the candidate before persisting it. Read that narrowly:
70//!
71//! * it removes the PERSISTENT half for anything that is not plausibly hledger
72//!   — a script that prints nothing recognisable is refused and never written
73//!   down, so it does not run on every import forever after;
74//! * it does **not** remove execution. The probe *is* an `exec`, so
75//!   `PUT /api/prefs` still runs whatever the caller names, exactly once (it
76//!   used to be twice), before refusing it. Bounding that would mean not probing
77//!   at all, and then a bad path is discovered at import time instead — which is
78//!   the failure mode `prefs.rs` exists to prevent;
79//! * and an attacker who owns a binary that DOES print an hledger version banner
80//!   walks through all of it unchanged.
81//!
82//! So it is defence in depth for whoever already holds the token, and keeping
83//! the token out of `GET /` is what keeps everyone else from holding it.
84//!
85//! The token is per-process and never persisted: restarting the app invalidates
86//! it, and no other process is told what it is.
87//!
88//! # Shared by every app on the shell
89//!
90//! Nothing here is Ledgeline's alone. An app names its token variable and its
91//! SPA's globals in an [`AppIdentity`], adds any request headers its uploads
92//! carry to the CORS allowlist ([`Security::cors_layer`]), and puts the whole
93//! posture on its router with [`protect`] (the explicit routes) and [`harden`]
94//! (everything).
95
96use std::net::IpAddr;
97use std::sync::Arc;
98use std::time::Duration;
99
100use axum::Router;
101use axum::extract::{Request, State};
102use axum::http::{HeaderName, HeaderValue, Method, StatusCode, header};
103use axum::middleware::{self, Next};
104use axum::response::{IntoResponse, Response};
105use base64::Engine as _;
106use sha2::{Digest, Sha256};
107use tower_http::catch_panic::CatchPanicLayer;
108use tower_http::cors::{AllowOrigin, CorsLayer};
109use tower_http::set_header::SetResponseHeaderLayer;
110
111use crate::AppIdentity;
112
113/// Entropy in a generated token: 256 bits, hex-encoded to 64 characters.
114const TOKEN_BYTES: usize = 32;
115
116/// Bounds on an externally supplied token. The lower bound keeps a careless
117/// `LEDGELINE_TOKEN=dev` from being treated as a real control.
118const MIN_TOKEN_LEN: usize = 16;
119const MAX_TOKEN_LEN: usize = 128;
120
121/// How long a browser may cache a CORS preflight for an allowlisted origin.
122const PREFLIGHT_MAX_AGE: Duration = Duration::from_secs(600);
123
124/// Policy up to and including the `script-src` allowlist's `'self'`; per-response
125/// inline-script hashes are appended to this.
126const CSP_HEAD: &str = "default-src 'self'; script-src 'self'";
127
128/// Everything after `script-src`, shared by the shell and by every other
129/// response. `connect-src 'self'` is the directive that neutralises the whole
130/// exfiltration class; `style-src` needs `'unsafe-inline'` for the shell's
131/// `style="display: contents"` attribute, and for the `<style>` element
132/// CodeMirror's style-mod writes at run time in a document (the invoicer's
133/// template editor; it uses `adoptedStyleSheets` only in a shadow root).
134/// Dropping it would need a per-response nonce passed to `EditorView.cspNonce`.
135const CSP_TAIL: &str = "; style-src 'self' 'unsafe-inline'; img-src 'self' data:; \
136connect-src 'self'; font-src 'self'; object-src 'none'; base-uri 'none'; \
137form-action 'none'; frame-ancestors 'none'";
138
139/// Used only if the composed policy somehow will not fit in a header value —
140/// strictly *tighter* than the real one, so a bug here fails closed.
141const FALLBACK_CSP: &str =
142    "default-src 'none'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'";
143
144/// Failures building the security configuration.
145#[derive(Debug, thiserror::Error)]
146pub enum SecurityError {
147    #[error("generating an access token: {0}")]
148    Random(#[from] getrandom::Error),
149    #[error(
150        "an access token must be {MIN_TOKEN_LEN}–{MAX_TOKEN_LEN} characters of [A-Za-z0-9._-] (it is embedded in a script and a URL, so the character set is restricted)"
151    )]
152    MalformedToken,
153    /// [`MalformedToken`](Self::MalformedToken), from the environment
154    /// variable `var` ([`token_from_env_or_random`]).
155    #[error(
156        "${var} must be {MIN_TOKEN_LEN}–{MAX_TOKEN_LEN} characters of [A-Za-z0-9._-] (it is embedded in a script and a URL, so the character set is restricted)"
157    )]
158    MalformedEnvToken { var: &'static str },
159    #[error("--allow-origin {origin}: not a usable origin (expected e.g. http://localhost:5173)")]
160    BadOrigin { origin: String },
161}
162
163/// A per-process bearer token. Never persisted, never logged except by explicit
164/// request in `--server` mode, and compared in (best-effort) constant time.
165#[derive(Clone)]
166pub struct AccessToken(Arc<str>);
167
168impl AccessToken {
169    /// A fresh 256-bit token from the OS CSPRNG.
170    ///
171    /// # Errors
172    /// [`SecurityError::Random`] if the platform entropy source fails.
173    pub fn generate() -> Result<Self, SecurityError> {
174        let mut bytes = [0u8; TOKEN_BYTES];
175        getrandom::fill(&mut bytes)?;
176        Ok(Self(hex(&bytes).into()))
177    }
178
179    /// Adopt a caller-supplied token, rejecting anything outside
180    /// `[A-Za-z0-9._-]{16,128}`. The character set matters: the token is
181    /// placed in the GUI's initialization script and in the `--server` launch
182    /// URL's fragment, and a quote, `</script>` or `&` in either would be an
183    /// injection or a mangled credential.
184    ///
185    /// # Errors
186    /// [`SecurityError::MalformedToken`] if `raw` is too short, too long, or
187    /// contains a character outside the allowed set.
188    pub fn parse(raw: &str) -> Result<Self, SecurityError> {
189        let well_formed = (MIN_TOKEN_LEN..=MAX_TOKEN_LEN).contains(&raw.len())
190            && raw
191                .chars()
192                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'));
193        well_formed
194            .then(|| Self(raw.into()))
195            .ok_or(SecurityError::MalformedToken)
196    }
197
198    #[must_use]
199    pub fn as_str(&self) -> &str {
200        &self.0
201    }
202
203    /// Best-effort constant-time comparison. The values are 256-bit random, so a
204    /// timing oracle over loopback HTTP is not a practical attack; this only
205    /// avoids handing one out for free. (Rust makes no formal guarantee that the
206    /// optimiser preserves this; a dedicated crate would.)
207    ///
208    /// Public for an app that accepts the token (or a second secret of its
209    /// own) somewhere [`token_guard`] does not reach: the invoicer's gate over
210    /// MBR's pages, which a browser loads by navigation, with a cookie.
211    #[must_use]
212    pub fn matches(&self, presented: &str) -> bool {
213        let (expected, actual) = (self.0.as_bytes(), presented.as_bytes());
214        expected.len() == actual.len()
215            && expected
216                .iter()
217                .zip(actual)
218                .fold(0u8, |acc, (a, b)| acc | (a ^ b))
219                == 0
220    }
221}
222
223/// The same-origin stand-in for a link a sandboxed frame may not follow
224/// itself: `<origin>/.ledgeline/open?url=<the link, percent-encoded>`.
225///
226/// WebKit refuses every custom-protocol load (`mailto:`) from a frame
227/// sandboxed without `allow-scripts`, and runs no script there, not even the
228/// parent's listeners. So the invoicer's SPA rewrites such a link in its
229/// note and invoice frames to this path (`invoicer/web/src/lib/frameLinks.ts`
230/// carries the same string), a same-origin navigation WebKit allows. The
231/// desktop window's navigation handler recognises it
232/// (`gui::handoff_target`), hands the target to the app's own
233/// allowlist and keeps the frame where it is. A plain browser (`--server`)
234/// has no such handler: the server answers the path with `204 No Content`,
235/// so the frame stays put and nothing opens.
236///
237/// Under a dotted prefix no books folder is served from by MBR's router.
238pub const HANDOFF_PATH: &str = "/.ledgeline/open";
239
240/// `raw` re-serialized when it is a plain https URL: no port, no credentials.
241/// The first test an app's "open this in the system browser" allowlist
242/// applies, before its own hosts. The one judge of such URLs, for the
243/// window's navigation and an app's links alike (not `gui`-only, so a
244/// server-only build vets them the same way).
245#[must_use]
246pub fn plain_https(raw: &str) -> Option<url::Url> {
247    let url = url::Url::parse(raw.trim()).ok()?;
248    let plain = url.scheme() == "https"
249        && url.host_str().is_some()
250        && url.port().is_none()
251        && url.username().is_empty()
252        && url.password().is_none();
253    plain.then_some(url)
254}
255
256/// `raw` re-serialized when it is a `mailto:` URL with an address, such as
257/// `mailto:ap@example.com?subject=Invoice%20108`. Headers (`subject`, `body`,
258/// …) are fine; a bare `mailto:` or one with only headers is refused. The
259/// sibling of [`plain_https`] for an app's "open this in the mail app" links.
260#[must_use]
261pub fn plain_mailto(raw: &str) -> Option<url::Url> {
262    let url = url::Url::parse(raw.trim()).ok()?;
263    let addressed = url.scheme() == "mailto" && !url.path().trim().is_empty();
264    addressed.then_some(url)
265}
266
267/// The process's token together with where it came from. `from_env` is what
268/// SEC-9 keys on: a non-loopback bind is only allowed when the operator chose
269/// the token deliberately.
270pub struct ProcessToken {
271    pub token: AccessToken,
272    /// `true` when the value came from the app's token variable
273    /// ([`AppIdentity::token_env`]) rather than the CSPRNG.
274    pub from_env: bool,
275}
276
277/// `$<var>` when set and non-empty, otherwise a fresh random token. `var` is
278/// the app's [`AppIdentity::token_env`]: set it when a cross-origin client
279/// (vite dev, the Playwright e2e harness) has to know the token before the
280/// server starts.
281///
282/// # Errors
283/// [`SecurityError::MalformedEnvToken`] if the environment value is not a
284/// well-formed token, or [`SecurityError::Random`] if entropy is unavailable.
285pub fn token_from_env_or_random(var: &'static str) -> Result<ProcessToken, SecurityError> {
286    match std::env::var(var).ok().filter(|raw| !raw.is_empty()) {
287        Some(raw) => Ok(ProcessToken {
288            token: AccessToken::parse(&raw)
289                .map_err(|_| SecurityError::MalformedEnvToken { var })?,
290            from_env: true,
291        }),
292        None => Ok(ProcessToken {
293            token: AccessToken::generate()?,
294            from_env: false,
295        }),
296    }
297}
298
299/// The access-control posture a router enforces. Cheaply cloneable (the lists
300/// are shared), because both the middleware state and the SPA handler hold one.
301#[derive(Clone)]
302pub struct Security {
303    /// Required on every wire and `/api` route; `None` disables the token guard.
304    token: Option<AccessToken>,
305    /// Acceptable `Host` values; `None` disables the guard (non-loopback binds).
306    hosts: Option<Arc<[String]>>,
307    /// Exact origins allowed cross-origin; empty means no CORS layer at all.
308    origins: Arc<[HeaderValue]>,
309}
310
311impl Security {
312    /// No token, no `Host` guard, no CORS.
313    ///
314    /// This is the shape an app's in-process test router uses (Ledgeline's
315    /// `app` and `router_with_state`) so the `tower::oneshot` harnesses can
316    /// drive routes directly. **Never use it for a socket-bound server** — see
317    /// [`protect`] and [`harden`].
318    #[must_use]
319    pub fn open() -> Self {
320        Self {
321            token: None,
322            hosts: None,
323            origins: Arc::from([]),
324        }
325    }
326
327    /// The loopback posture: require `token` on every wire and `/api` route, and
328    /// reject any `Host` that is not a loopback name on `port`.
329    #[must_use]
330    pub fn local(token: AccessToken, port: u16) -> Self {
331        let hosts = ["127.0.0.1", "localhost", "[::1]"]
332            .into_iter()
333            .map(|host| format!("{host}:{port}"))
334            .collect::<Vec<_>>();
335        Self {
336            token: Some(token),
337            hosts: Some(hosts.into()),
338            origins: Arc::from([]),
339        }
340    }
341
342    /// The posture for IN-PROCESS dispatch — a mobile host's custom-scheme
343    /// handler feeding requests to the router with `Router::oneshot`, no socket
344    /// at all (`ledgeline-ffi`).
345    ///
346    /// * **The token is still required.** A scheme handler receives every
347    ///   request its web view makes, including one from a foreign page that
348    ///   somehow got loaded into it (a link followed, an injected frame): the
349    ///   browser enforces CORS on the *response*, not on whether the request is
350    ///   delivered, so a blind write would land without it. The host hands the
351    ///   token to its own pages out of band ([`token_init_script`]), as the
352    ///   desktop WebView gets it.
353    /// * **No `Host` guard.** It exists against DNS rebinding, which needs a
354    ///   socket to rebind to. There is none, and the authority a custom scheme
355    ///   presents is whatever the host chose.
356    /// * **No CORS**, as on every default posture.
357    #[must_use]
358    pub fn in_process(token: AccessToken) -> Self {
359        Self::any_host(token)
360    }
361
362    /// Require `token` but accept any `Host`. Only for an explicitly requested
363    /// non-loopback bind, where the legitimate `Host` values are unknowable —
364    /// which also means this posture has NO anti-DNS-rebinding control.
365    #[must_use]
366    pub fn any_host(token: AccessToken) -> Self {
367        Self {
368            token: Some(token),
369            hosts: None,
370            origins: Arc::from([]),
371        }
372    }
373
374    /// Permit these EXACT origins to read responses cross-origin (`--allow-origin`).
375    /// Never a wildcard: each entry is matched literally by the browser.
376    ///
377    /// # Errors
378    /// [`SecurityError::BadOrigin`] if an entry is not a valid header value or
379    /// does not look like a scheme-qualified origin.
380    pub fn allow_origins<S: AsRef<str>>(self, origins: &[S]) -> Result<Self, SecurityError> {
381        let parsed = origins
382            .iter()
383            .map(|origin| {
384                let origin = origin.as_ref().trim_end_matches('/');
385                let usable = origin.starts_with("http://") || origin.starts_with("https://");
386                HeaderValue::from_str(origin)
387                    .ok()
388                    .filter(|_| usable)
389                    .ok_or_else(|| SecurityError::BadOrigin {
390                        origin: origin.to_string(),
391                    })
392            })
393            .collect::<Result<Vec<_>, _>>()?;
394        Ok(Self {
395            origins: parsed.into(),
396            ..self
397        })
398    }
399
400    /// The CORS layer for the allowlisted origins, or `None` (the default) when
401    /// there are none — in which case no CORS layer is installed at all and the
402    /// server is same-origin only.
403    ///
404    /// `extra_headers` are request headers beyond `Authorization`,
405    /// `Content-Type` and `Accept` that the app's own client sends (Ledgeline's
406    /// statement upload names its file in one); an allowlisted origin's
407    /// preflight for any other header is refused.
408    #[must_use]
409    pub fn cors_layer(&self, extra_headers: &[HeaderName]) -> Option<CorsLayer> {
410        if self.origins.is_empty() {
411            return None;
412        }
413        Some(
414            CorsLayer::new()
415                .allow_origin(AllowOrigin::list(self.origins.iter().cloned()))
416                .allow_methods([
417                    Method::GET,
418                    Method::POST,
419                    Method::PUT,
420                    Method::PATCH,
421                    Method::DELETE,
422                ])
423                // The token travels in `Authorization`, not a cookie, so the
424                // browser never needs to attach credentials — and leaving this
425                // false keeps an allowlisted dev origin from riding along on any
426                // ambient authority.
427                .allow_credentials(false)
428                .allow_headers(
429                    [header::AUTHORIZATION, header::CONTENT_TYPE, header::ACCEPT]
430                        .into_iter()
431                        .chain(extra_headers.iter().cloned())
432                        .collect::<Vec<_>>(),
433                )
434                .max_age(PREFLIGHT_MAX_AGE),
435        )
436    }
437}
438
439/// Is `candidate` a document of the app's own SPA: on `origin` exactly
440/// (`http://127.0.0.1:<port>`, no trailing slash) and under `spa_base`
441/// ([`AppIdentity::spa_base`])?
442///
443/// The test the desktop window applies to every page its main frame commits
444/// to. `candidate` is parsed the way the WebView parses it (WHATWG URL rules,
445/// via `url`), so dot segments are resolved first, `%2e%2e` included, and
446/// `/app/../note.md` is judged as `/note.md`. A percent-encoded slash stays
447/// encoded, so `/app%2f..` is not under `/app/`; the server routes on the
448/// same encoded path, so whatever this accepts, the server hands to the SPA.
449/// The comparison is case-sensitive, as the server's routes are.
450///
451/// Refused: any other scheme, host or port (credentials in the URL change the
452/// host, not the origin, so they cannot smuggle one in), `about:`, `data:`
453/// and `javascript:` URLs (their origins are opaque), `blob:` URLs (even our
454/// own: a blob document is not the SPA), and on our own
455/// origin any path outside `spa_base`, except the base itself without its
456/// trailing slash (`/app`, which the invoicer's router also serves the SPA
457/// on).
458#[must_use]
459pub fn in_spa(origin: &str, spa_base: &str, candidate: &str) -> bool {
460    let Ok(url) = url::Url::parse(candidate) else {
461        return false;
462    };
463    // `blob:http://…` has its creator's (tuple) origin, so the scheme is
464    // checked too: only an http(s) document is ever the SPA.
465    let candidate_origin = url.origin();
466    matches!(url.scheme(), "http" | "https")
467        && candidate_origin.is_tuple()
468        && candidate_origin.ascii_serialization() == origin
469        && path_in_spa(spa_base, url.path())
470}
471
472/// Is the (already normalized) `path` under `spa_base`? `/` covers every path.
473fn path_in_spa(spa_base: &str, path: &str) -> bool {
474    spa_base == "/" || path.starts_with(spa_base) || path == spa_base.trim_end_matches('/')
475}
476
477/// The initialization script that hands the WebView its access token, as the
478/// `window` global the app's SPA reads ([`AppIdentity::token_global`]).
479///
480/// Shared by the desktop GUI (wry's initialization script, the `gui` module) and
481/// a mobile host (a `WKUserScript` at document start — see `ledgeline-ffi`).
482///
483/// This is how the token reaches the SPA WITHOUT appearing in any response body:
484/// the shell is served unauthenticated, so anything that can reach loopback can
485/// read it, and it used to carry the token for exactly that reason. wry runs this
486/// at document start, before the page's own scripts, outside the page's CSP —
487/// but on EVERY document the main frame loads, whatever it is. So the script
488/// checks two things before it hands anything over:
489///
490/// * `location.origin` is ours exactly. The navigation handler already keeps
491///   the WebView on our origin; this means a document from anywhere else would
492///   still get nothing, should one ever load.
493/// * `location.pathname` is under the app's SPA base
494///   ([`AppIdentity::spa_base`], the same rule as [`in_spa`]), so a page that
495///   shares the origin but is not the SPA (the invoicer's MBR pages) gets
496///   nothing either, even if it reached the main frame. An app whose SPA is
497///   the whole origin (`/`) gets the origin check alone, which keeps its
498///   script, the iOS host's included, exactly as it was.
499///
500/// The values are serialized as JSON string literals rather than interpolated
501/// raw. [`AccessToken::parse`] already restricts the token to a safe character
502/// set, and the origin and base are ours, so this is belt and braces — but it
503/// costs nothing and does not depend on any of them staying true.
504#[must_use]
505pub fn token_init_script(app: &AppIdentity, origin: &str, token: &AccessToken) -> String {
506    let literal = |value: &str| serde_json::Value::from(value).to_string();
507    let path_guard = if app.spa_base == "/" {
508        String::new()
509    } else {
510        format!(
511            " && (window.location.pathname === {bare} \
512             || window.location.pathname.startsWith({base}))",
513            bare = literal(app.spa_base.trim_end_matches('/')),
514            base = literal(app.spa_base),
515        )
516    };
517    format!(
518        "if (window.location.origin === {origin}{path_guard}) {{ window.{global} = {token}; }}",
519        origin = literal(origin),
520        global = app.token_global,
521        token = literal(token.as_str()),
522    )
523}
524
525/// Reject any request whose `Host` is not one this server answers to.
526///
527/// This is the anti-DNS-rebinding control: an attacker page on
528/// `attacker.example.com` whose DNS has been re-pointed at `127.0.0.1` still
529/// sends `Host: attacker.example.com`, which never matches. Applied to the WHOLE
530/// router (the SPA shell included) so a rebound page cannot even fetch the
531/// shell.
532pub async fn host_guard(
533    State(security): State<Security>,
534    request: Request,
535    next: Next,
536) -> Response {
537    let Some(allowed) = security.hosts.clone() else {
538        return next.run(request).await;
539    };
540    // HTTP/1.1 carries the authority in `Host`; HTTP/2's `:authority` pseudo
541    // header lands in the URI instead.
542    let presented = request
543        .headers()
544        .get(header::HOST)
545        .and_then(|value| value.to_str().ok())
546        .map(str::to_owned)
547        .or_else(|| {
548            request
549                .uri()
550                .authority()
551                .map(|authority| authority.as_str().to_owned())
552        });
553    match presented {
554        Some(host) if allowed.iter().any(|ok| ok.eq_ignore_ascii_case(&host)) => {
555            next.run(request).await
556        }
557        _ => (
558            StatusCode::FORBIDDEN,
559            "Rejected: this server only answers to a loopback Host.\n",
560        )
561            .into_response(),
562    }
563}
564
565/// Require `Authorization: Bearer <token>` on every route this wraps.
566///
567/// Installed with `route_layer`, so it covers exactly the wire and `/api` routes
568/// and never the SPA shell or its static assets — which must stay reachable for
569/// the browser to bootstrap at all.
570pub async fn token_guard(
571    State(security): State<Security>,
572    request: Request,
573    next: Next,
574) -> Response {
575    let Some(expected) = security.token.clone() else {
576        return next.run(request).await;
577    };
578    let presented = request
579        .headers()
580        .get(header::AUTHORIZATION)
581        .and_then(|value| value.to_str().ok())
582        .and_then(bearer_token);
583    match presented {
584        Some(token) if expected.matches(token) => next.run(request).await,
585        _ => (
586            StatusCode::UNAUTHORIZED,
587            [(header::WWW_AUTHENTICATE, "Bearer")],
588            "Missing or invalid access token.\n",
589        )
590            .into_response(),
591    }
592}
593
594/// The credential from an `Authorization: Bearer <token>` value (scheme matched
595/// case-insensitively, per RFC 7235).
596#[must_use]
597pub fn bearer_token(value: &str) -> Option<&str> {
598    let (scheme, token) = value.split_once(' ')?;
599    scheme
600        .eq_ignore_ascii_case("Bearer")
601        .then(|| token.trim())
602        .filter(|token| !token.is_empty())
603}
604
605/// `Cache-Control: no-store` — "do not write this anywhere".
606///
607/// The canonical spelling for every app on the shell. JSON routes go through
608/// [`no_store_json`]; anything that needs the header and is not returning
609/// `Json` (e.g. the HTML shell in [`spa`](crate::spa)) uses this value
610/// directly rather than a fresh copy of the literal.
611#[must_use]
612pub fn no_store() -> HeaderValue {
613    HeaderValue::from_static("no-store")
614}
615
616/// A JSON response marked [`no_store`], with no `ETag` — the one helper every
617/// Ledgeline `*_api` module uses for reads that are not derived from the
618/// journal snapshot (import, rules, aliases, budget, prices, projections,
619/// accounts, QB-journal, profiles, benchmarks).
620///
621/// The `ETag` is a single per-journal generation counter shared by every read
622/// route, so there is no third option for these: tagging them would either
623/// invalidate the SPA's cached `/transactions` body for a change that affects
624/// no transaction, or hand out a stale document under a fresh tag.
625pub fn no_store_json<T: serde::Serialize>(body: T) -> Response {
626    ([(header::CACHE_CONTROL, no_store())], axum::Json(body)).into_response()
627}
628
629/// The Content-Security-Policy for every response that carries no inline script
630/// (JSON, static assets, errors).
631#[must_use]
632pub fn base_csp() -> HeaderValue {
633    csp_value(CSP_TAIL)
634}
635
636/// The policy for one rendering of the SPA shell: the base policy plus a
637/// `'sha256-…'` source for each inline `<script>` the shell actually contains,
638/// and the app's `frame-src` when it has one ([`AppIdentity::spa_frame_src`]).
639///
640/// Computed from the served bytes rather than baked in, so it stays correct
641/// across SPA rebuilds (SvelteKit's bootstrap script changes every build) and
642/// across the token we inject into it.
643#[must_use]
644pub fn shell_csp(app: &AppIdentity, html: &str) -> HeaderValue {
645    let hashes = inline_script_hashes(html)
646        .iter()
647        .map(|hash| format!(" '{hash}'"))
648        .collect::<String>();
649    let frames = app
650        .spa_frame_src
651        .map(|sources| format!("; frame-src {sources}"))
652        .unwrap_or_default();
653    csp_value(&format!("{hashes}{CSP_TAIL}{frames}"))
654}
655
656/// [`CSP_HEAD`] followed by `rest` (the script hashes, [`CSP_TAIL`], and any
657/// per-app directives), or [`FALLBACK_CSP`] if that is no header value.
658fn csp_value(rest: &str) -> HeaderValue {
659    HeaderValue::from_str(&format!("{CSP_HEAD}{rest}"))
660        .unwrap_or_else(|_| HeaderValue::from_static(FALLBACK_CSP))
661}
662
663/// `sha256-<base64>` CSP source expressions for every inline `<script>` in
664/// `html`, in document order (elements with a `src` attribute are external and
665/// covered by `'self'` instead).
666///
667/// A deliberately small scanner: the only HTML this ever sees is our own
668/// generated shell, whose script tags have no attributes containing `>`.
669fn inline_script_hashes(html: &str) -> Vec<String> {
670    let mut hashes = Vec::new();
671    let mut rest = html;
672    while let Some(open) = rest.find("<script") {
673        let Some(open_len) = rest[open..].find('>') else {
674            break;
675        };
676        let body_start = open + open_len + 1;
677        let Some(close) = rest[body_start..].find("</script>") else {
678            break;
679        };
680        let body_end = body_start + close;
681        if !rest[open..body_start].contains("src=") {
682            hashes.push(csp_sha256(&rest[body_start..body_end]));
683        }
684        rest = &rest[body_end + "</script>".len()..];
685    }
686    hashes
687}
688
689/// The `sha256-<base64>` source expression for one inline script's exact text.
690#[must_use]
691pub fn csp_sha256(script: &str) -> String {
692    let digest = Sha256::digest(script.as_bytes());
693    format!(
694        "sha256-{}",
695        base64::engine::general_purpose::STANDARD.encode(digest)
696    )
697}
698
699/// Is `host` a loopback address (or the `localhost` name)? Anything else — a LAN
700/// address, or the `0.0.0.0` / `::` wildcards — publishes the app's data beyond
701/// this machine.
702#[must_use]
703pub fn is_loopback_host(host: &str) -> bool {
704    let bare = host.trim_start_matches('[').trim_end_matches(']');
705    bare.eq_ignore_ascii_case("localhost")
706        || bare
707            .parse::<IpAddr>()
708            .is_ok_and(|address| address.is_loopback())
709}
710
711/// The access-control decisions taken at startup, before the socket is bound.
712///
713/// Split from [`Security`] itself because the `Host` guard has to name the port
714/// we ACTUALLY bound, and `--port 0` (the GUI's default) only reveals that at
715/// bind time — so the plan is made early and [`SecurityPlan::build`] finishes it.
716pub struct SecurityPlan {
717    token: AccessToken,
718    /// Whether the bind host resolved to loopback; drives the `Host` guard.
719    loopback: bool,
720    /// Exact origins from `--allow-origin`, validated by [`build`](Self::build).
721    origins: Vec<String>,
722}
723
724impl SecurityPlan {
725    /// A plan for serving `token` on `host`, opening the API to `origins`.
726    #[must_use]
727    pub fn new(token: AccessToken, host: &str, origins: Vec<String>) -> Self {
728        Self {
729            token,
730            loopback: is_loopback_host(host),
731            origins,
732        }
733    }
734
735    /// Whether the bind host is loopback. Anything else should be refused
736    /// unless the operator chose the token deliberately (SEC-9).
737    #[must_use]
738    pub fn is_loopback(&self) -> bool {
739        self.loopback
740    }
741
742    /// Finish the plan now that `port` is known.
743    ///
744    /// # Errors
745    /// [`SecurityError::BadOrigin`] for an unusable `--allow-origin` entry.
746    pub fn build(&self, port: u16) -> Result<Security, SecurityError> {
747        let base = if self.loopback {
748            Security::local(self.token.clone(), port)
749        } else {
750            Security::any_host(self.token.clone())
751        };
752        base.allow_origins(&self.origins)
753    }
754}
755
756/// Put the token guard and the CORS allowlist on every route registered on
757/// `router` so far — call it after the last API route and BEFORE the SPA
758/// fallback, which must stay reachable without a token.
759///
760/// Both are `route_layer`s, never `layer`s: they reach exactly the explicit
761/// routes, so the fallback (the SPA shell, its assets, deep links) is served
762/// same-origin only and never carries a CORS header (SEC-12). The CORS layer
763/// wraps the token guard, which is required: a preflight carries no
764/// `Authorization` and must be answered rather than refused. The default
765/// posture is no CORS layer at all, so a browser refuses to hand any
766/// cross-origin page the responses (SEC-1). `cors_headers` are the app's extra
767/// request headers ([`Security::cors_layer`]).
768pub fn protect<S>(router: Router<S>, security: &Security, cors_headers: &[HeaderName]) -> Router<S>
769where
770    S: Clone + Send + Sync + 'static,
771{
772    let router = router.route_layer(middleware::from_fn_with_state(
773        security.clone(),
774        token_guard,
775    ));
776    match security.cors_layer(cors_headers) {
777        Some(cors) => router.route_layer(cors),
778        None => router,
779    }
780}
781
782/// The layers every response passes through, applied to the WHOLE router (the
783/// SPA shell included): the `Host` guard (anti-DNS-rebinding), a handler panic
784/// as a `500` rather than a dropped connection (SEC-2), `nosniff`,
785/// `no-referrer`, and the base CSP for any response without its own (SEC-7) —
786/// `if_not_present`, so the SPA shell's policy, which additionally hashes the
787/// inline scripts it just rendered, is left alone.
788///
789/// Call it last, after the fallback and any app-specific layers that belong
790/// inside the guard (Ledgeline's compression).
791pub fn harden<S>(router: Router<S>, security: Security) -> Router<S>
792where
793    S: Clone + Send + Sync + 'static,
794{
795    router
796        .layer(middleware::from_fn_with_state(security, host_guard))
797        .layer(CatchPanicLayer::new())
798        .layer(SetResponseHeaderLayer::overriding(
799            header::X_CONTENT_TYPE_OPTIONS,
800            HeaderValue::from_static("nosniff"),
801        ))
802        .layer(SetResponseHeaderLayer::overriding(
803            header::REFERRER_POLICY,
804            HeaderValue::from_static("no-referrer"),
805        ))
806        .layer(SetResponseHeaderLayer::if_not_present(
807            header::CONTENT_SECURITY_POLICY,
808            base_csp(),
809        ))
810}
811
812fn hex(bytes: &[u8]) -> String {
813    bytes.iter().map(|byte| format!("{byte:02x}")).collect()
814}
815
816#[cfg(test)]
817mod tests {
818    use super::*;
819
820    #[test]
821    fn plain_mailto_needs_an_address() {
822        for allowed in [
823            " mailto:ap@example.com ",
824            "mailto:ap@example.com?subject=Invoice%20108&body=Hello",
825            "MAILTO:ap@example.com",
826        ] {
827            assert!(plain_mailto(allowed).is_some(), "{allowed}");
828        }
829        assert_eq!(
830            plain_mailto("mailto:ap@example.com?subject=Invoice 108")
831                .map(String::from)
832                .as_deref(),
833            Some("mailto:ap@example.com?subject=Invoice%20108"),
834            "answered re-serialized"
835        );
836        for refused in [
837            "mailto:",
838            "mailto:?subject=hi",
839            "https://example.com/",
840            "tel:+15551234567",
841            "javascript:alert(1)",
842            "not a url",
843        ] {
844            assert!(plain_mailto(refused).is_none(), "{refused}");
845        }
846    }
847
848    #[test]
849    fn generated_tokens_are_long_and_unique() {
850        let first = AccessToken::generate().expect("entropy available");
851        let second = AccessToken::generate().expect("entropy available");
852        assert_eq!(first.as_str().len(), TOKEN_BYTES * 2);
853        assert!(first.as_str().chars().all(|c| c.is_ascii_hexdigit()));
854        assert_ne!(
855            first.as_str(),
856            second.as_str(),
857            "two generated tokens must differ"
858        );
859    }
860
861    #[test]
862    fn parse_rejects_short_and_unsafe_tokens() {
863        assert!(AccessToken::parse("dev").is_err(), "too short");
864        assert!(
865            AccessToken::parse(&"x".repeat(MAX_TOKEN_LEN + 1)).is_err(),
866            "too long"
867        );
868        // The token is interpolated into a <script> string literal, so anything
869        // that could break out of it must be refused.
870        assert!(AccessToken::parse("abcdefghijklmnop\"").is_err());
871        assert!(AccessToken::parse("abcdefghij</script>klmno").is_err());
872        assert!(AccessToken::parse("dev-token_for.e2e").is_ok());
873    }
874
875    #[test]
876    fn token_matches_only_itself() {
877        let token = AccessToken::parse("dev-token_for.e2e").expect("well-formed");
878        assert!(token.matches("dev-token_for.e2e"));
879        assert!(!token.matches("dev-token_for.e2f"));
880        assert!(!token.matches("dev-token_for.e2"), "prefix must not match");
881        assert!(!token.matches(""));
882    }
883
884    #[test]
885    fn bearer_token_parses_case_insensitively() {
886        assert_eq!(bearer_token("Bearer abc"), Some("abc"));
887        assert_eq!(bearer_token("bearer abc"), Some("abc"));
888        assert_eq!(bearer_token("Basic abc"), None);
889        assert_eq!(bearer_token("abc"), None);
890        assert_eq!(bearer_token("Bearer "), None);
891    }
892
893    #[test]
894    fn allow_origins_rejects_wildcards_and_bare_hosts() {
895        assert!(Security::open().allow_origins(&["*"]).is_err());
896        assert!(Security::open().allow_origins(&["localhost:5173"]).is_err());
897        assert!(
898            Security::open()
899                .allow_origins(&["http://localhost:5173"])
900                .is_ok()
901        );
902    }
903
904    #[test]
905    fn no_allowed_origins_means_no_cors_layer() {
906        assert!(
907            Security::local(sample_token(), 5000)
908                .cors_layer(&[])
909                .is_none()
910        );
911        assert!(
912            Security::local(sample_token(), 5000)
913                .allow_origins(&["http://localhost:4173"])
914                .expect("valid origin")
915                .cors_layer(&[])
916                .is_some()
917        );
918    }
919
920    #[test]
921    fn loopback_hosts_are_recognised_and_nothing_else_is() {
922        for host in [
923            "127.0.0.1",
924            "localhost",
925            "LOCALHOST",
926            "::1",
927            "[::1]",
928            "127.0.0.2",
929        ] {
930            assert!(is_loopback_host(host), "{host}");
931        }
932        for host in [
933            "0.0.0.0",
934            "::",
935            "192.168.1.5",
936            "example.com",
937            "localhost.evil",
938        ] {
939            assert!(!is_loopback_host(host), "{host}");
940        }
941    }
942
943    #[test]
944    fn an_env_token_names_its_variable_when_malformed() {
945        let error = SecurityError::MalformedEnvToken {
946            var: "LEDGELINE_TOKEN",
947        };
948        assert!(
949            error
950                .to_string()
951                .starts_with("$LEDGELINE_TOKEN must be 16–128 characters"),
952            "{error}"
953        );
954    }
955
956    /// The token goes to the WebView by initialization script, and only to a
957    /// document on our exact origin — the script itself runs on every document
958    /// the main frame loads.
959    const WHOLE_ORIGIN: AppIdentity = AppIdentity {
960        name: "Ledgeline",
961        bundle_id: "com.zmre.ledgeline",
962        log_prefix: "ledgeline",
963        token_env: "LEDGELINE_TOKEN",
964        token_global: "__LEDGELINE_TOKEN__",
965        embedded_global: "__LEDGELINE_EMBEDDED__",
966        spa_base: "/",
967        spa_frame_src: None,
968    };
969
970    const UNDER_APP: AppIdentity = AppIdentity {
971        name: "Ledgeline Invoicer",
972        bundle_id: "com.zmre.ledgeline.invoicer",
973        log_prefix: "ledgeline-invoicer",
974        token_env: "LEDGELINE_INVOICER_TOKEN",
975        token_global: "__LEDGELINE_TOKEN__",
976        embedded_global: "__LEDGELINE_EMBEDDED__",
977        spa_base: "/app/",
978        spa_frame_src: Some("'self' https:"),
979    };
980
981    #[test]
982    fn the_token_script_is_guarded_by_our_exact_origin() {
983        // A SPA that is the whole origin: the origin check alone, unchanged
984        // from before the path guard (the iOS host relies on this).
985        let script = token_init_script(&WHOLE_ORIGIN, "http://127.0.0.1:5000", &sample_token());
986        assert_eq!(
987            script,
988            "if (window.location.origin === \"http://127.0.0.1:5000\") \
989             { window.__LEDGELINE_TOKEN__ = \"token-for-unit-tests\"; }"
990        );
991    }
992
993    /// SEC-6: a SPA under a base hands the token only to documents under it,
994    /// not to every page that shares the origin.
995    #[test]
996    fn the_token_script_is_guarded_by_the_spa_base_too() {
997        let script = token_init_script(&UNDER_APP, "http://127.0.0.1:5000", &sample_token());
998        assert_eq!(
999            script,
1000            "if (window.location.origin === \"http://127.0.0.1:5000\" \
1001             && (window.location.pathname === \"/app\" \
1002             || window.location.pathname.startsWith(\"/app/\"))) \
1003             { window.__LEDGELINE_TOKEN__ = \"token-for-unit-tests\"; }"
1004        );
1005    }
1006
1007    /// The script's guard and [`in_spa`] are one rule: evaluate the guard
1008    /// against what `location` would hold for each URL (`url` parses as WebKit
1009    /// does) and compare.
1010    #[test]
1011    fn the_token_scripts_path_guard_agrees_with_in_spa() {
1012        let origin = "http://127.0.0.1:5000";
1013        for candidate in [
1014            "http://127.0.0.1:5000/app",
1015            "http://127.0.0.1:5000/app/",
1016            "http://127.0.0.1:5000/app/invoices/7?x=1#y",
1017            "http://127.0.0.1:5000/app/../notes/x.md",
1018            "http://127.0.0.1:5000/app/%2e%2e/notes/x.md",
1019            "http://127.0.0.1:5000/app%2f../notes/x.md",
1020            "http://127.0.0.1:5000/apps/",
1021            "http://127.0.0.1:5000/App/",
1022            "http://127.0.0.1:5000/customers/contracts/sow.html",
1023            "http://127.0.0.1:5000/",
1024        ] {
1025            let url = url::Url::parse(candidate).expect("test URL parses");
1026            let pathname = url.path();
1027            let guard = pathname == "/app" || pathname.starts_with("/app/");
1028            assert_eq!(
1029                guard,
1030                in_spa(origin, UNDER_APP.spa_base, candidate),
1031                "{candidate}"
1032            );
1033        }
1034    }
1035
1036    #[test]
1037    fn in_spa_allows_only_documents_under_the_base_on_our_origin() {
1038        let origin = "http://127.0.0.1:5000";
1039        let base = UNDER_APP.spa_base;
1040        for allowed in [
1041            "http://127.0.0.1:5000/app",
1042            "http://127.0.0.1:5000/app/",
1043            "http://127.0.0.1:5000/app/new",
1044            "http://127.0.0.1:5000/app/invoices/2026-001?tab=pdf#top",
1045            "http://127.0.0.1:5000/app/customers/a%20b",
1046            // Dot segments that stay inside the base.
1047            "http://127.0.0.1:5000/app/x/../y",
1048            "http://127.0.0.1:5000/./app/",
1049            // An encoded slash is not a separator: the server routes this
1050            // under `/app/` too, to the SPA.
1051            "http://127.0.0.1:5000/app/..%2fnotes",
1052            // The host is case-insensitive and `url` lowercases it.
1053            "HTTP://127.0.0.1:5000/app/",
1054        ] {
1055            assert!(in_spa(origin, base, allowed), "{allowed}");
1056        }
1057        for refused in [
1058            // Our origin, but not the SPA: MBR's notes, files, UI and the API.
1059            "http://127.0.0.1:5000/",
1060            "http://127.0.0.1:5000",
1061            "http://127.0.0.1:5000/customers/contracts/sow.html",
1062            "http://127.0.0.1:5000/notes/acme.md",
1063            "http://127.0.0.1:5000/.mbr/notes",
1064            "http://127.0.0.1:5000/.ledgeline-invoicer/preview",
1065            "http://127.0.0.1:5000/api/books",
1066            // Prefix and case tricks.
1067            "http://127.0.0.1:5000/apps",
1068            "http://127.0.0.1:5000/app.html",
1069            "http://127.0.0.1:5000/application/",
1070            "http://127.0.0.1:5000/App/",
1071            "http://127.0.0.1:5000/APP/",
1072            "http://127.0.0.1:5000//app/",
1073            // Dot segments that climb out, plain and encoded.
1074            "http://127.0.0.1:5000/app/../notes/acme.md",
1075            "http://127.0.0.1:5000/app/%2e%2e/notes/acme.md",
1076            "http://127.0.0.1:5000/app/%2E%2E/notes/acme.md",
1077            "http://127.0.0.1:5000/app/.%2e/notes/acme.md",
1078            "http://127.0.0.1:5000/app/..\\notes/acme.md",
1079            "http://127.0.0.1:5000/app%2f../notes/acme.md",
1080            "http://127.0.0.1:5000/%61pp/",
1081            // Other ports, hosts and schemes.
1082            "http://127.0.0.1:5001/app/",
1083            "http://127.0.0.1:50000/app/",
1084            "http://127.0.0.1/app/",
1085            "https://127.0.0.1:5000/app/",
1086            "http://localhost:5000/app/",
1087            "http://[::1]:5000/app/",
1088            "http://127.0.0.1:5000.evil.example/app/",
1089            "http://127.0.0.1:5000@evil.example/app/",
1090            "http://evil.example/app/",
1091            "https://evil.example/app/",
1092            "file:///app/",
1093            "ws://127.0.0.1:5000/app/",
1094            // Opaque origins.
1095            "about:blank",
1096            "about:srcdoc",
1097            "data:text/html,<script>alert(1)</script>",
1098            "javascript:alert(1)",
1099            "blob:http://127.0.0.1:5000/0b0e6a4c-0000-4000-8000-000000000000",
1100            // Not URLs at all.
1101            "",
1102            "/app/",
1103            "not a url",
1104        ] {
1105            assert!(!in_spa(origin, base, refused), "{refused}");
1106        }
1107    }
1108
1109    #[test]
1110    fn a_whole_origin_spa_allows_every_path_on_our_origin_and_nothing_else() {
1111        let origin = "http://127.0.0.1:5000";
1112        let base = WHOLE_ORIGIN.spa_base;
1113        for allowed in [
1114            "http://127.0.0.1:5000/",
1115            "http://127.0.0.1:5000",
1116            "http://127.0.0.1:5000/reports?tab=1",
1117            "http://127.0.0.1:5000/new",
1118            "http://127.0.0.1:5000/settings?rule=x",
1119        ] {
1120            assert!(in_spa(origin, base, allowed), "{allowed}");
1121        }
1122        for refused in [
1123            "http://127.0.0.1:5001/",
1124            "http://127.0.0.1:5000@evil.example/",
1125            "https://evil.example/",
1126            "about:blank",
1127            "data:text/html,x",
1128            "javascript:alert(1)",
1129            "blob:http://127.0.0.1:5000/0b0e6a4c-0000-4000-8000-000000000000",
1130        ] {
1131            assert!(!in_spa(origin, base, refused), "{refused}");
1132        }
1133    }
1134
1135    #[test]
1136    fn inline_script_hashes_skips_external_scripts() {
1137        // Known-answer: sha256("") is the empty-string digest, base64-encoded.
1138        let html = "<head><script>window.x=1</script><script src=\"/a.js\"></script></head>";
1139        let hashes = inline_script_hashes(html);
1140        assert_eq!(hashes.len(), 1, "only the inline script is hashed");
1141        assert_eq!(hashes[0], csp_sha256("window.x=1"));
1142    }
1143
1144    #[test]
1145    fn csp_sha256_matches_the_known_answer_for_the_empty_script() {
1146        // sha256 of the empty string, base64 — the standard test vector.
1147        assert_eq!(
1148            csp_sha256(""),
1149            "sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="
1150        );
1151    }
1152
1153    #[test]
1154    fn shell_csp_carries_every_inline_hash_and_the_exfiltration_guard() {
1155        let html = "<head><script>a</script></head><body><script>b</script></body>";
1156        for app in [&WHOLE_ORIGIN, &UNDER_APP] {
1157            let csp = shell_csp(app, html);
1158            let csp = csp.to_str().expect("ascii");
1159            assert!(csp.contains(&format!("'{}'", csp_sha256("a"))));
1160            assert!(csp.contains(&format!("'{}'", csp_sha256("b"))));
1161            assert!(csp.contains("connect-src 'self'"));
1162            assert!(csp.contains("frame-ancestors 'none'"));
1163            assert!(!csp.contains("unsafe-eval"));
1164        }
1165    }
1166
1167    /// An app without `spa_frame_src` (Ledgeline) gets exactly the shared
1168    /// policy, byte for byte: no `frame-src`, so `default-src 'self'` rules.
1169    #[test]
1170    fn shell_csp_has_no_frame_src_unless_the_app_asks() {
1171        let html = "<script>a</script>";
1172        let hash = csp_sha256("a");
1173        assert_eq!(
1174            shell_csp(&WHOLE_ORIGIN, html).to_str().expect("ascii"),
1175            format!(
1176                "default-src 'self'; script-src 'self' '{hash}'; \
1177                 style-src 'self' 'unsafe-inline'; img-src 'self' data:; \
1178                 connect-src 'self'; font-src 'self'; object-src 'none'; \
1179                 base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
1180            )
1181        );
1182        assert_eq!(
1183            base_csp().to_str().expect("ascii"),
1184            "default-src 'self'; script-src 'self'; \
1185             style-src 'self' 'unsafe-inline'; img-src 'self' data:; \
1186             connect-src 'self'; font-src 'self'; object-src 'none'; \
1187             base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
1188        );
1189    }
1190
1191    #[test]
1192    fn shell_csp_appends_the_apps_frame_src() {
1193        let html = "<script>a</script>";
1194        let with = shell_csp(&UNDER_APP, html);
1195        let without = shell_csp(&WHOLE_ORIGIN, html);
1196        assert_eq!(
1197            with.to_str().expect("ascii"),
1198            format!(
1199                "{}; frame-src 'self' https:",
1200                without.to_str().expect("ascii")
1201            )
1202        );
1203        assert!(
1204            !base_csp().to_str().expect("ascii").contains("frame-src"),
1205            "only the shell carries the app's frame-src"
1206        );
1207    }
1208
1209    /// A per-app directive that cannot be a header value fails closed.
1210    #[test]
1211    fn a_bad_frame_src_falls_back_to_the_tighter_policy() {
1212        let broken = AppIdentity {
1213            spa_frame_src: Some("'self'\n"),
1214            ..UNDER_APP
1215        };
1216        assert_eq!(
1217            shell_csp(&broken, "").to_str().expect("ascii"),
1218            FALLBACK_CSP
1219        );
1220    }
1221
1222    fn sample_token() -> AccessToken {
1223        AccessToken::parse("token-for-unit-tests").expect("well-formed")
1224    }
1225}