Skip to main content

Module security

Module security 

Source
Expand description

Access control and response hardening for the local HTTP server: a per-process bearer token, a Host-header guard, an exact-origin CORS allowlist, and the security headers (CSP included) every response carries.

§Threat model — stated honestly

Ledgeline serves a complete financial journal, readable and writable, over plain HTTP on loopback. Until this module existed the only thing between that journal and every web page the user had open was the port number, and CorsLayer::permissive() gave even that away: any origin could read /transactions and POST/DELETE /api/transactions (SEC-1).

§What the controls here genuinely stop

  • A web page sweeping loopback ports. With no CORS layer on the default path a page on https://evil.example (or file://, or another http://localhost:* app) still gets its request sent, but cannot read any reply — and because every wire and /api route now demands the token, it cannot land a blind write either. The token is a 256-bit random value it has no way to guess and, absent CORS, no way to read.
  • A page on an ALLOWLISTED origin reading the token. --allow-origin opens the API to a named dev origin, and for a while it opened the SPA shell too, because the CORS layer was installed over the whole router including the fallback. The shell then carried the token in its body, so one fetch("http://127.0.0.1:<port>/") from any page on that origin — another Vite project, a malicious dev dependency — read it and had full read/write on the journal with no interaction (SEC-12). The layer is now a route_layer over the explicit routes only; see protect.
  • DNS rebinding. host_guard rejects any request whose Host is not a loopback name on the port we actually bound, so re-pointing attacker.example.com at 127.0.0.1 buys nothing.
  • Silent exfiltration if an XSS sink ever appears. The connect-src 'self' CSP means injected script cannot post the journal anywhere.

§What they do NOT stop — do not claim otherwise

  • A malicious process running as the SAME user. It can read (and rewrite) the journal file directly; no HTTP control is relevant.
  • Anyone who can read the --server terminal. Headless mode prints the launch URL, token included, because something else has to drive it.
  • Anything at all once --host is pointed off loopback. That path is gated on an explicitly configured token ($LEDGELINE_TOKEN for Ledgeline, AppIdentity::token_env in general) and turns the Host guard off, because the legitimate Host values are then unknowable.

§Closed: another local process scraping the token from GET /

The SPA shell is served without a token (the browser has nothing to present before it has loaded the page), and HTTP gives us no way to tell the user’s own WebView from someone else’s curl. The shell used to carry the token in its body for the browser to bootstrap, so any process that could reach loopback — another local user’s included — could GET / and read it. The token now appears in no response body at all:

  • the GUI hands it to its WebView out of band, with wry’s initialization script, guarded to our exact origin (token_init_script);
  • --server prints a launch URL with the token in its #token= fragment, which a browser never puts on the wire; the SPA moves it into sessionStorage and strips it from the address bar.

That exposure is what made the following worth writing down. This threat model used to bound the worst case by “the journal file’s own permissions”, which was wrong — wrong enough to be a finding in its own right, because it is not bounded at all. Whoever holds the token holds PUT /api/prefs, and hledgerPath there names the binary spawned on every import. So a token scraped once bought arbitrary CODE EXECUTION as the user, surviving restarts, from which the journal’s permissions follow trivially (SEC-14). Ledgeline’s prefs::check_storable refuses a group- or world-writable binary and runs the candidate before persisting it. Read that narrowly:

  • it removes the PERSISTENT half for anything that is not plausibly hledger — a script that prints nothing recognisable is refused and never written down, so it does not run on every import forever after;
  • it does not remove execution. The probe is an exec, so PUT /api/prefs still runs whatever the caller names, exactly once (it used to be twice), before refusing it. Bounding that would mean not probing at all, and then a bad path is discovered at import time instead — which is the failure mode prefs.rs exists to prevent;
  • and an attacker who owns a binary that DOES print an hledger version banner walks through all of it unchanged.

So it is defence in depth for whoever already holds the token, and keeping the token out of GET / is what keeps everyone else from holding it.

The token is per-process and never persisted: restarting the app invalidates it, and no other process is told what it is.

§Shared by every app on the shell

Nothing here is Ledgeline’s alone. An app names its token variable and its SPA’s globals in an AppIdentity, adds any request headers its uploads carry to the CORS allowlist (Security::cors_layer), and puts the whole posture on its router with protect (the explicit routes) and harden (everything).

Structs§

AccessToken
A per-process bearer token. Never persisted, never logged except by explicit request in --server mode, and compared in (best-effort) constant time.
ProcessToken
The process’s token together with where it came from. from_env is what SEC-9 keys on: a non-loopback bind is only allowed when the operator chose the token deliberately.
Security
The access-control posture a router enforces. Cheaply cloneable (the lists are shared), because both the middleware state and the SPA handler hold one.
SecurityPlan
The access-control decisions taken at startup, before the socket is bound.

Enums§

SecurityError
Failures building the security configuration.

Constants§

HANDOFF_PATH
The same-origin stand-in for a link a sandboxed frame may not follow itself: <origin>/.ledgeline/open?url=<the link, percent-encoded>.

Functions§

base_csp
The Content-Security-Policy for every response that carries no inline script (JSON, static assets, errors).
bearer_token
The credential from an Authorization: Bearer <token> value (scheme matched case-insensitively, per RFC 7235).
csp_sha256
The sha256-<base64> source expression for one inline script’s exact text.
harden
The layers every response passes through, applied to the WHOLE router (the SPA shell included): the Host guard (anti-DNS-rebinding), a handler panic as a 500 rather than a dropped connection (SEC-2), nosniff, no-referrer, and the base CSP for any response without its own (SEC-7) — if_not_present, so the SPA shell’s policy, which additionally hashes the inline scripts it just rendered, is left alone.
host_guard
Reject any request whose Host is not one this server answers to.
in_spa
Is candidate a document of the app’s own SPA: on origin exactly (http://127.0.0.1:<port>, no trailing slash) and under spa_base (AppIdentity::spa_base)?
is_loopback_host
Is host a loopback address (or the localhost name)? Anything else — a LAN address, or the 0.0.0.0 / :: wildcards — publishes the app’s data beyond this machine.
no_store
Cache-Control: no-store — “do not write this anywhere”.
no_store_json
A JSON response marked no_store, with no ETag — the one helper every Ledgeline *_api module uses for reads that are not derived from the journal snapshot (import, rules, aliases, budget, prices, projections, accounts, QB-journal, profiles, benchmarks).
plain_https
raw re-serialized when it is a plain https URL: no port, no credentials. The first test an app’s “open this in the system browser” allowlist applies, before its own hosts. The one judge of such URLs, for the window’s navigation and an app’s links alike (not gui-only, so a server-only build vets them the same way).
plain_mailto
raw re-serialized when it is a mailto: URL with an address, such as mailto:ap@example.com?subject=Invoice%20108. Headers (subject, body, …) are fine; a bare mailto: or one with only headers is refused. The sibling of plain_https for an app’s “open this in the mail app” links.
protect
Put the token guard and the CORS allowlist on every route registered on router so far — call it after the last API route and BEFORE the SPA fallback, which must stay reachable without a token.
shell_csp
The policy for one rendering of the SPA shell: the base policy plus a 'sha256-…' source for each inline <script> the shell actually contains, and the app’s frame-src when it has one (AppIdentity::spa_frame_src).
token_from_env_or_random
$<var> when set and non-empty, otherwise a fresh random token. var is the app’s AppIdentity::token_env: set it when a cross-origin client (vite dev, the Playwright e2e harness) has to know the token before the server starts.
token_guard
Require Authorization: Bearer <token> on every route this wraps.
token_init_script
The initialization script that hands the WebView its access token, as the window global the app’s SPA reads (AppIdentity::token_global).