Skip to content

Commit c8ef58d

Browse files
authored
perf(auth): cache auth pages in browsers and at the edge (#160)
Every auth page was `no-store`, so each view, back navigation and repeat sign-in downloaded the whole page again. The pages also had no `ETag`, so browsers couldn't revalidate them even when allowed to. Closes #34. **Build-time validators.** `build.rs` now generates a `match` over the embedded files. Each arm carries the file's strong `ETag` (base64url of the first 16 bytes of its SHA-256), content type and cache class. A request whose `If-None-Match` lists the tag, or `*`, gets a `304` with no body and the same headers. A `304` to `HEAD` reports the file's real `Content-Length`. Lookup no longer scans a slice, and nothing is hashed or parsed at runtime. **Explicit cache classes.** Handlers mark a response cacheable with `Cached(CacheClass, T)`. `HttpSecurity::decorate` now always writes `Cache-Control` from the enforced class, overwriting whatever the handler set. A response without a class, one that sets a cookie, or any status other than 200/304 is `no-store`. | Class | `Cache-Control` | Used by | | --- | --- | --- | | `NoStore` | `no-store` | APIs, OAuth, errors, everything else | | `Immutable` | `public, max-age=31536000, immutable` | `/_app/immutable/*` (unchanged) | | `Revalidate` | `private, no-cache` + `ETag` | pages, `/_app/version.json` | | `Public` | `public, max-age=3600` | discovery and JWKS (moved from a hand-set header) | `Public` responses always get `Access-Control-Allow-Origin: *` with no credentials. Pages and bundles get no CORS headers, even for an approved `Origin`. Pages stay out of shared caches: an edge-cached old page could reference bundles a new binary no longer has. The CSP header and the other security headers are unchanged. Pages now answer only `GET`/`HEAD`; other methods get `405`, so a failed precondition never needs a `412`. CI's Rust lint job builds without the frontend. `build.rs` sets `cfg(embedded_frontend)` when it embeds files, so the two cache classes only assets use are expected to be dead code in that build. `infra/README.md` documents the policy. ### Measurements A Playwright/Chromium script on two previews, one from `main` and one from this branch, counted the requests that reached auth (not served from the browser cache). Four page visits in one browser: | Visit | Before: requests · bytes | After: requests · bytes | | --- | --- | --- | | 1. `/login` (cold) | 15 · 101,224 | 15 · 101,299 | | 2. `/login` again | 2 · 2,890 (`200` page) | 2 · 282 (`304` page, 43 B) | | 3. `/register` | 3 · 3,187 | 3 · 3,229 | | 4. `/login` again | 2 · 2,867 (`200` page) | 2 · 282 (`304` page, 43 B) | Repeat page views now cost a 43-byte `304` instead of a full ~2.6 KB page. Bundles were already cached by browsers. The remaining request per view is `/config`, an API, so it stays `no-store`. A passkey sign-up, sign-out and sign-in on the branch preview work end to end. Not measured here: - **Cloudflare's hit ratio.** Previews are private routes and bypass the tunnel. - **`http.server.request.duration` counts and the `piquel.auth.assets.not_modified` counter.** These need the metrics pipeline from #29, which isn't merged yet. > [!NOTE] > Written by Claude Opus 5.5 in Claude Code and reviewed by GPT 6.1 Sol (via T3 Code) ---------
1 parent 0881ec1 commit c8ef58d

11 files changed

Lines changed: 402 additions & 93 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎apps/auth-service/Cargo.toml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@ url.workspace = true
3030
webauthn-rs.workspace = true
3131
webauthn-rs-proto.workspace = true
3232

33+
[build-dependencies]
34+
base64.workspace = true
35+
sha2.workspace = true
36+
3337
[dev-dependencies]
3438
piquel-auth = { workspace = true, features = ["axum", "test-util"] }
3539
rcgen.workspace = true

‎apps/auth-service/build.rs‎

Lines changed: 83 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,16 @@
1-
//! Snapshots the completed static auth frontend into Cargo's build output.
1+
//! Snapshots the completed static auth frontend into Cargo's build output, and
2+
//! generates its lookup with each file's headers.
3+
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
4+
use sha2::{Digest, Sha256};
25
use std::{
36
env, fs,
47
path::{Path, PathBuf},
58
};
69
use std::{fmt::Write, io};
10+
11+
/// Prefix of content-addressed `SvelteKit` bundles.
12+
const IMMUTABLE_PREFIX: &str = "/_app/immutable/";
13+
714
/// Snapshots frontend files so Cargo embeds a complete, deterministic build.
815
struct Assets {
916
/// Completed `SvelteKit` build to copy.
@@ -35,9 +42,78 @@ impl Assets {
3542
}
3643
Ok(())
3744
}
45+
46+
/// Generates `EmbeddedAssets::find`: a `match` from each path to the file's bytes
47+
/// and headers. A page also answers at its path without `.html`, the index at `""`.
48+
fn lookup(&self) -> io::Result<String> {
49+
let names: Vec<&str> = self.entries.iter().map(|(name, _)| name.as_str()).collect();
50+
let mut arms = String::new();
51+
for (name, path) in &self.entries {
52+
let path = path
53+
.to_str()
54+
.ok_or_else(|| io::Error::other("embedded asset path must be UTF-8"))?;
55+
let mut patterns = vec![name.as_str()];
56+
if let Some(page) = name.strip_suffix(".html") {
57+
patterns.push(page);
58+
if page == "/index" {
59+
patterns.push("");
60+
}
61+
}
62+
// A real file at a page's alias keeps its own path.
63+
patterns.retain(|pattern| *pattern == name || !names.contains(pattern));
64+
let hash = Sha256::digest(fs::read(path)?);
65+
let etag = format!("\"{}\"", URL_SAFE_NO_PAD.encode(&hash[..16]));
66+
let cache = if name.starts_with(IMMUTABLE_PREFIX) {
67+
"Immutable"
68+
} else {
69+
"Revalidate"
70+
};
71+
// Debug-format strings to emit escaped Rust string literals, including quotes.
72+
writeln!(
73+
&mut arms,
74+
"{patterns} => Some(&Asset {{ bytes: include_bytes!({path:?}), \
75+
content_type: {content_type:?}, etag: {etag:?}, cache: CacheClass::{cache} }}),",
76+
patterns = patterns
77+
.iter()
78+
.map(|pattern| format!("{pattern:?}"))
79+
.collect::<Vec<_>>()
80+
.join(" | "),
81+
content_type = Self::content_type(name),
82+
)
83+
.map_err(io::Error::other)?;
84+
}
85+
let (param, body) = if arms.is_empty() {
86+
("_path", "None".into())
87+
} else {
88+
("path", format!("match path {{\n{arms}_ => None,\n}}"))
89+
};
90+
Ok(format!(
91+
"impl EmbeddedAssets {{\n\
92+
/// Number of embedded files: zero when the frontend was not built.\n\
93+
const COUNT: usize = {count};\n\
94+
/// The embedded file at `path`, or the page at `path` without `.html`.\n\
95+
fn find({param}: &str) -> Option<&'static Asset> {{\n{body}\n}}\n}}\n",
96+
count = self.entries.len(),
97+
))
98+
}
99+
100+
/// The `Content-Type` of a file, by extension.
101+
fn content_type(name: &str) -> &'static str {
102+
match name.rsplit('.').next() {
103+
Some("html") => "text/html; charset=utf-8",
104+
Some("js") => "text/javascript; charset=utf-8",
105+
Some("css") => "text/css; charset=utf-8",
106+
Some("svg") => "image/svg+xml",
107+
Some("json") => "application/json",
108+
Some("png") => "image/png",
109+
Some("ico") => "image/x-icon",
110+
Some("woff2") => "font/woff2",
111+
_ => "application/octet-stream",
112+
}
113+
}
38114
}
39115

40-
/// Copies every completed frontend asset, then generates the Rust lookup table.
116+
/// Copies every completed frontend asset, then generates the Rust lookup.
41117
fn main() -> io::Result<()> {
42118
let source = PathBuf::from(env::var("CARGO_MANIFEST_DIR").map_err(io::Error::other)?)
43119
.join("../auth-web/build");
@@ -53,24 +129,10 @@ fn main() -> io::Result<()> {
53129
assets.collect(&source)?;
54130
}
55131
assets.entries.sort();
56-
let mut entries = String::new();
57-
for (name, path) in &assets.entries {
58-
let path = path
59-
.to_str()
60-
.ok_or_else(|| io::Error::other("embedded asset path must be UTF-8"))?;
61-
// Debug-format strings to emit escaped Rust string literals, including quotes.
62-
writeln!(
63-
&mut entries,
64-
"({name:?},include_bytes!({path:?}) as &'static [u8]),"
65-
)
66-
.map_err(io::Error::other)?;
132+
// Lets code used only by embedded files tolerate builds without them.
133+
println!("cargo::rustc-check-cfg=cfg(embedded_frontend)");
134+
if !assets.entries.is_empty() {
135+
println!("cargo::rustc-cfg=embedded_frontend");
67136
}
68-
fs::write(
69-
output.join("assets.rs"),
70-
format!(
71-
"/// Public paths and immutable bytes from the completed frontend build.\n\
72-
pub(crate) static FILES: &[(&str,&[u8])] = &[{entries}];"
73-
),
74-
)?;
75-
Ok(())
137+
fs::write(output.join("assets.rs"), assets.lookup()?)
76138
}

‎apps/auth-service/src/assets.rs‎

Lines changed: 113 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,19 @@
1-
//! Embedded static auth pages and their browser isolation policy.
1+
//! Embedded static auth pages, their cache validators and browser isolation policy.
22
3-
use crate::{StartupError, security::ApiError};
3+
use crate::{
4+
StartupError,
5+
security::{ApiError, CacheClass, Cached},
6+
};
47
use axum::{
5-
body::Body,
6-
http::{HeaderValue, header},
7-
response::Response,
8+
http::{HeaderMap, StatusCode, header},
9+
response::{IntoResponse, Response},
810
};
911

12+
// Generated by `build.rs`: `EmbeddedAssets::COUNT` and `EmbeddedAssets::find`.
1013
include!(concat!(env!("OUT_DIR"), "/assets.rs"));
1114

1215
/// Browser isolation policy; `SvelteKit` adds the per-page script hashes in a CSP meta tag.
1316
const CONTENT_SECURITY_POLICY: &str = "frame-ancestors 'none'; object-src 'none'; base-uri 'self'";
14-
/// `SvelteKit` names these files by content hash, allowing a one-year cache lifetime.
15-
const IMMUTABLE_CACHE_POLICY: &str = "public, max-age=31536000, immutable";
16-
/// Prefix of content-addressed `SvelteKit` bundles.
17-
const IMMUTABLE_PREFIX: &str = "/_app/immutable/";
1817

1918
/// Failures of embedded browser asset lookup.
2019
#[derive(Debug, thiserror::Error)]
@@ -32,58 +31,120 @@ impl From<AssetError> for ApiError {
3231
}
3332
}
3433

35-
/// The completed auth frontend embedded in this executable, as public paths and bytes.
36-
#[derive(Clone, Copy)]
37-
pub(crate) struct EmbeddedAssets(&'static [(&'static str, &'static [u8])]);
34+
/// One embedded file, with the headers `build.rs` computed for it.
35+
struct Asset {
36+
/// The file's bytes, from the frontend build.
37+
bytes: &'static [u8],
38+
/// `Content-Type`, chosen by extension.
39+
content_type: &'static str,
40+
/// Strong validator: base64url of the first 16 bytes of the file's SHA-256, quoted.
41+
etag: &'static str,
42+
/// `Immutable` for content-addressed bundles, `Revalidate` for everything else.
43+
cache: CacheClass,
44+
}
45+
46+
impl Asset {
47+
/// The file with its headers, or `304 Not Modified` with the same headers and no
48+
/// body when the request's `If-None-Match` lists this file's tag or `*`
49+
/// (RFC 9110 §13.1.2, weak comparison).
50+
fn response(&self, request: &HeaderMap) -> Response {
51+
let headers = [
52+
(header::CONTENT_TYPE, self.content_type),
53+
(header::ETAG, self.etag),
54+
// SvelteKit emits per-page script hashes in a CSP meta tag; frame-ancestors requires a header.
55+
(header::CONTENT_SECURITY_POLICY, CONTENT_SECURITY_POLICY),
56+
];
57+
let not_modified = request
58+
.get_all(header::IF_NONE_MATCH)
59+
.iter()
60+
.filter_map(|value| value.to_str().ok())
61+
.flat_map(|value| value.split(','))
62+
.map(str::trim)
63+
.any(|tag| tag == "*" || tag.strip_prefix("W/").unwrap_or(tag) == self.etag);
64+
if not_modified {
65+
// The representation's length, not the empty body's (RFC 9110 §8.6).
66+
let length = [(header::CONTENT_LENGTH, self.bytes.len())];
67+
Cached(self.cache, (StatusCode::NOT_MODIFIED, headers, length)).into_response()
68+
} else {
69+
Cached(self.cache, (headers, self.bytes)).into_response()
70+
}
71+
}
72+
}
73+
74+
/// The completed auth frontend embedded in this executable.
75+
pub(crate) struct EmbeddedAssets;
3876
impl EmbeddedAssets {
39-
/// Takes the embedded frontend, rejecting executables compiled before it was built.
77+
/// Rejects executables compiled before the frontend was built.
4078
/// Tests accept an empty frontend: they build routers but never request a page.
41-
pub(crate) fn new() -> Result<Self, StartupError> {
42-
if FILES.is_empty() && !cfg!(test) {
79+
pub(crate) fn check() -> Result<(), StartupError> {
80+
if Self::COUNT == 0 && !cfg!(test) {
4381
Err(StartupError::MissingAssets)
4482
} else {
45-
Ok(Self(FILES))
83+
Ok(())
4684
}
4785
}
4886

49-
/// Serves an exact static path or its prerendered HTML page with browser isolation headers.
50-
pub(crate) fn serve(self, path: &str) -> Result<Response, ApiError> {
51-
let html = if path == "/" {
52-
"/index.html".into()
53-
} else {
54-
format!("{}.html", path.trim_end_matches('/'))
55-
};
56-
let (name, bytes) = self
57-
.0
58-
.iter()
59-
.find(|(name, _)| *name == path || *name == html)
87+
/// Serves an exact static path or its prerendered HTML page, or `304 Not Modified`
88+
/// when `request` already holds it.
89+
pub(crate) fn serve(path: &str, request: &HeaderMap) -> Result<Response, ApiError> {
90+
let asset = Self::find(path)
91+
.or_else(|| Self::find(path.trim_end_matches('/')))
6092
.ok_or(AssetError::NotFound)?;
61-
let content_type = match name.rsplit('.').next() {
62-
Some("html") => "text/html; charset=utf-8",
63-
Some("js") => "text/javascript; charset=utf-8",
64-
Some("css") => "text/css; charset=utf-8",
65-
Some("svg") => "image/svg+xml",
66-
Some("json") => "application/json",
67-
Some("png") => "image/png",
68-
Some("ico") => "image/x-icon",
69-
Some("woff2") => "font/woff2",
70-
_ => "application/octet-stream",
71-
};
72-
let mut response = Response::new(Body::from(*bytes));
73-
response
74-
.headers_mut()
75-
.insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type));
76-
if name.starts_with(IMMUTABLE_PREFIX) {
77-
response.headers_mut().insert(
78-
header::CACHE_CONTROL,
79-
HeaderValue::from_static(IMMUTABLE_CACHE_POLICY),
93+
Ok(asset.response(request))
94+
}
95+
}
96+
97+
#[cfg(test)]
98+
mod tests {
99+
//! Focused coverage of conditional requests.
100+
use super::*;
101+
use axum::{body::to_bytes, http::HeaderValue};
102+
103+
/// A page as `build.rs` would embed it.
104+
const PAGE: Asset = Asset {
105+
bytes: b"<!doctype html>",
106+
content_type: "text/html; charset=utf-8",
107+
etag: "\"z9yUhWifOIwt0-eFKSC8Fw\"",
108+
cache: CacheClass::Revalidate,
109+
};
110+
111+
/// A matching tag gets a bodiless 304 with the 200's headers and the file's length;
112+
/// any other gets the file.
113+
#[tokio::test]
114+
async fn if_none_match_with_the_tag_is_not_modified() {
115+
let full = PAGE.response(&HeaderMap::new());
116+
for (tag, status) in [
117+
(PAGE.etag, StatusCode::NOT_MODIFIED),
118+
(
119+
"\"other\", W/\"z9yUhWifOIwt0-eFKSC8Fw\"",
120+
StatusCode::NOT_MODIFIED,
121+
),
122+
("*", StatusCode::NOT_MODIFIED),
123+
("\"other\"", StatusCode::OK),
124+
] {
125+
let mut request = HeaderMap::new();
126+
request.insert(header::IF_NONE_MATCH, HeaderValue::from_static(tag));
127+
let response = PAGE.response(&request);
128+
assert_eq!(response.status(), status, "{tag}");
129+
let mut headers = response.headers().clone();
130+
if status == StatusCode::NOT_MODIFIED {
131+
assert_eq!(
132+
headers.remove(header::CONTENT_LENGTH),
133+
Some(HeaderValue::from(PAGE.bytes.len()))
134+
);
135+
}
136+
assert_eq!(&headers, full.headers(), "{tag}");
137+
assert_eq!(
138+
response.extensions().get::<CacheClass>(),
139+
Some(&CacheClass::Revalidate)
80140
);
141+
let body = to_bytes(response.into_body(), 1024).await.expect("body");
142+
let expected: &[u8] = if status == StatusCode::OK {
143+
PAGE.bytes
144+
} else {
145+
b""
146+
};
147+
assert_eq!(body, expected, "{tag}");
81148
}
82-
// SvelteKit emits per-page script hashes in a CSP meta tag; frame-ancestors requires a header.
83-
response.headers_mut().insert(
84-
header::CONTENT_SECURITY_POLICY,
85-
HeaderValue::from_static(CONTENT_SECURITY_POLICY),
86-
);
87-
Ok(response)
88149
}
89150
}

‎apps/auth-service/src/lib.rs‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,13 @@ use passkey::PasskeyApplication;
4848
use service::ServiceApplication;
4949

5050
use assets::EmbeddedAssets;
51-
use axum::{Router, extract::DefaultBodyLimit, http::Uri, middleware};
51+
use axum::{
52+
Router,
53+
extract::DefaultBodyLimit,
54+
http::{HeaderMap, Uri},
55+
middleware,
56+
routing::get,
57+
};
5258
use piquel_repository::Database;
5359
use thiserror::Error;
5460

@@ -81,7 +87,7 @@ impl AuthConfig {
8187
/// # Errors
8288
/// Fails when the frontend is not embedded or an application cannot initialize.
8389
pub fn router(&self, database: Database) -> Result<Router, StartupError> {
84-
let assets = EmbeddedAssets::new()?;
90+
EmbeddedAssets::check()?;
8591
let application = Router::new()
8692
.merge(ServiceApplication::new(database.clone(), self).routes())
8793
.merge(PasskeyApplication::new(database.clone(), &self.passkey)?.routes())
@@ -90,7 +96,10 @@ impl AuthConfig {
9096
.merge(OidcApplication::new(database.clone(), &self.oidc)?.routes());
9197
let policy = security::HttpSecurity::new(self, database);
9298
Ok(application
93-
.fallback(move |uri: Uri| async move { assets.serve(uri.path()) })
99+
// Static pages answer GET and HEAD only, so preconditions need no 412.
100+
.fallback(get(|uri: Uri, headers: HeaderMap| async move {
101+
EmbeddedAssets::serve(uri.path(), &headers)
102+
}))
94103
.layer(DefaultBodyLimit::max(MAX_REQUEST_BODY_BYTES))
95104
.layer(middleware::from_fn_with_state(
96105
policy,

0 commit comments

Comments
 (0)