Skip to content

Commit 3dc0dc3

Browse files
PiquelChipsclaude
andcommitted
feat(auth): server-rendered consent and logout pages
auth-service serves its consent and logout pages itself, as Topcoat pages with plain forms, instead of SvelteKit pages calling JSON endpoints. - piquel-ui (crates/ui): Topcoat components and layouts that render plain data and take URLs as props. - web/: thin page handlers, mounted with route_service on the paths routes.rs declares. They call the consent and logout logic in-process and answer 303, or render why they cannot. - A page security class: forms only from auth's own pages (the shared same-origin rule), its own rate budget, a per-page CSP whose form-action names the redirect target (or a link onwards when no policy can), and Topcoat's body limit set to 64 KiB. - The shared stylesheet and the SDK, which gains a tsc build step, are embedded under content-addressed /assets/ paths and cached forever. The SDK keeps the consent form from posting twice. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent aa4dc60 commit 3dc0dc3

41 files changed

Lines changed: 1546 additions & 485 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎Cargo.lock‎

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

‎Cargo.toml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ members = [
99
"crates/crypto",
1010
"crates/database",
1111
"crates/telemetry",
12+
"crates/ui",
1213
]
1314

1415
[workspace.package]
@@ -33,6 +34,7 @@ piquel-repository = { path = "crates/database" }
3334
piquel-telemetry = { path = "crates/telemetry" }
3435
piquel-auth = { path = "crates/auth-sdk" }
3536
piquel-admin-api = { path = "crates/admin-api" }
37+
piquel-ui = { path = "crates/ui" }
3638

3739
# External crates
3840
async-trait = "0.1"
@@ -56,6 +58,9 @@ sha2 = "0.10"
5658
rand = "0.8"
5759
sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio-rustls", "postgres", "chrono", "uuid", "json", "ipnet", "migrate", "macros"] }
5860
thiserror = "2.0"
61+
# Server-rendered pages: the router, `view!` and the tower service only. Its
62+
# defaults add a browser runtime, `asset!` and discovery, which auth's pages avoid.
63+
topcoat = { version = "0.10", default-features = false }
5964
tokio = { version = "1.48", features = ["macros", "rt-multi-thread", "signal", "net", "sync", "time"] }
6065
tower = { version = "0.5", features = ["util"] }
6166
tower-http = { version = "0.6", features = ["trace"] }

‎README.md‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,9 @@ just build
2222
```
2323

2424
The executable is `target/release/auth-service`. Auth assets are embedded at compile
25-
time; rebuild Rust after changing `apps/auth-web`. piquel.fr's settings server builds to
26-
`apps/piquel-web/build` and runs on Node (see its README). Auth needs Node only
27-
to build its pages.
25+
time; rebuild Rust after changing `apps/auth-web` or `packages/auth-sdk`. piquel.fr's
26+
settings server builds to `apps/piquel-web/build` and runs on Node (see its README).
27+
Auth needs Node only to build its sign-in pages and the SDK script.
2828

2929
## Development
3030

@@ -422,8 +422,10 @@ explains how to choose a requirement and handle the challenge.
422422
- Browser state and opaque secrets are random, hashed where lookup is needed, and
423423
bound to the initiating browser. Auth cookies are host-only, Secure and HttpOnly.
424424
Mutations require an exact allowed origin and CSRF header; OIDC back-channel
425-
endpoints instead validate their protocol credentials.
426-
- Request throttling and expiring-state cleanup use PostgreSQL. Throttling uses separate login, token, userinfo and account budgets per client IP, and covers every API route except health probes and discovery.
425+
endpoints instead validate their protocol credentials. A form posted to one of
426+
auth's server-rendered pages must come from auth's own pages: `Sec-Fetch-Site:
427+
same-origin`, or the auth origin when the browser sends no `Sec-Fetch-Site`.
428+
- Request throttling and expiring-state cleanup use PostgreSQL. Throttling uses separate login, token, userinfo, account and page budgets per client IP, and covers every API route except health probes and discovery.
427429
By default it uses the direct peer IP; only peers in `AUTH_TRUSTED_PROXIES`
428430
may supply a single overwritten `X-Forwarded-For`. Configure this when terminating TLS
429431
at a reverse proxy so users do not share the proxy’s budget. Untrusted headers

‎apps/auth-service/Cargo.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ piquel-crypto.workspace = true
1212
piquel-repository.workspace = true
1313
piquel-telemetry.workspace = true
1414
piquel-auth.workspace = true
15+
piquel-ui.workspace = true
1516

1617
askama.workspace = true
1718
axum.workspace = true
@@ -27,6 +28,7 @@ serde.workspace = true
2728
serde_json.workspace = true
2829
thiserror.workspace = true
2930
tokio.workspace = true
31+
topcoat = { workspace = true, features = ["router", "view", "tower"] }
3032
tracing.workspace = true
3133
url.workspace = true
3234
webauthn-rs.workspace = true

‎apps/auth-service/build.rs‎

Lines changed: 66 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
//! Snapshots the completed static auth frontend into Cargo's build output, and
2-
//! generates its lookup with each file's headers.
1+
//! Snapshots the completed static auth frontend into Cargo's build output, names the
2+
//! stylesheet and SDK script of auth's server-rendered pages by their content, and
3+
//! generates their lookup with each file's headers.
34
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
45
use sha2::{Digest, Sha256};
56
use std::{
@@ -10,6 +11,8 @@ use std::{fmt::Write, io};
1011

1112
/// Prefix of content-addressed `SvelteKit` bundles.
1213
const IMMUTABLE_PREFIX: &str = "/_app/immutable/";
14+
/// Where the files of auth's server-rendered pages are served, named by their content.
15+
const PAGE_ASSETS_PREFIX: &str = "/assets/";
1316

1417
/// Snapshots frontend files so Cargo embeds a complete, deterministic build.
1518
struct Assets {
@@ -19,6 +22,8 @@ struct Assets {
1922
snapshot: PathBuf,
2023
/// Public paths paired with their copied file paths.
2124
entries: Vec<(String, PathBuf)>,
25+
/// The pages' files, by the content-addressed public path each is served at.
26+
named: Vec<(String, PathBuf)>,
2227
}
2328
impl Assets {
2429
/// Copies static files recursively and records their browser paths.
@@ -43,12 +48,35 @@ impl Assets {
4348
Ok(())
4449
}
4550

51+
/// Copies `file` and names it by its content under [`PAGE_ASSETS_PREFIX`], as
52+
/// `{stem}.{hash}.{extension}`, so it can be cached forever. Returns that path.
53+
fn name(&mut self, stem: &str, extension: &str, file: &Path) -> io::Result<String> {
54+
let bytes = fs::read(file)?;
55+
let hash = Sha256::digest(&bytes);
56+
let hex = hash[..8].iter().fold(String::new(), |mut hex, byte| {
57+
let _ = write!(hex, "{byte:02x}");
58+
hex
59+
});
60+
let path = format!("{PAGE_ASSETS_PREFIX}{stem}.{hex}.{extension}");
61+
// Copied under its public path, as the frontend's files are.
62+
let snapshot = self.snapshot.join(path.trim_start_matches('/'));
63+
fs::create_dir_all(
64+
snapshot
65+
.parent()
66+
.ok_or_else(|| io::Error::other("asset snapshot has no parent directory"))?,
67+
)?;
68+
fs::write(&snapshot, bytes)?;
69+
self.named.push((path.clone(), snapshot));
70+
Ok(path)
71+
}
72+
4673
/// Generates `EmbeddedAssets::find`: a `match` from each path to the file's bytes
4774
/// and headers. A page also answers at its path without `.html`, the index at `""`.
48-
fn lookup(&self) -> io::Result<String> {
75+
/// The pages' named files are content-addressed, so immutable.
76+
fn lookup(&self, stylesheet: &str, script: Option<&str>) -> io::Result<String> {
4977
let names: Vec<&str> = self.entries.iter().map(|(name, _)| name.as_str()).collect();
5078
let mut arms = String::new();
51-
for (name, path) in &self.entries {
79+
for (name, path) in self.entries.iter().chain(&self.named) {
5280
let path = path
5381
.to_str()
5482
.ok_or_else(|| io::Error::other("embedded asset path must be UTF-8"))?;
@@ -63,11 +91,12 @@ impl Assets {
6391
patterns.retain(|pattern| *pattern == name || !names.contains(pattern));
6492
let hash = Sha256::digest(fs::read(path)?);
6593
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-
};
94+
let cache =
95+
if name.starts_with(IMMUTABLE_PREFIX) || name.starts_with(PAGE_ASSETS_PREFIX) {
96+
"Immutable"
97+
} else {
98+
"Revalidate"
99+
};
71100
// Debug-format strings to emit escaped Rust string literals, including quotes.
72101
writeln!(
73102
&mut arms,
@@ -82,17 +111,17 @@ impl Assets {
82111
)
83112
.map_err(io::Error::other)?;
84113
}
85-
let (param, body) = if arms.is_empty() {
86-
("_path", "None".into())
87-
} else {
88-
("path", format!("match path {{\n{arms}_ => None,\n}}"))
89-
};
90114
Ok(format!(
91115
"impl EmbeddedAssets {{\n\
92-
/// Number of embedded files: zero when the frontend was not built.\n\
116+
/// Number of embedded frontend files: zero when the frontend was not built.\n\
93117
const COUNT: usize = {count};\n\
118+
/// Path of the stylesheet of auth's own pages.\n\
119+
pub(crate) const STYLESHEET: &str = {stylesheet:?};\n\
120+
/// Path of the SDK's script, or `None` when the SDK was not built.\n\
121+
pub(crate) const SCRIPT: Option<&str> = {script:?};\n\
94122
/// 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",
123+
fn find(path: &str) -> Option<&'static Asset> {{\n\
124+
match path {{\n{arms}_ => None,\n}}\n}}\n}}\n",
96125
count = self.entries.len(),
97126
))
98127
}
@@ -113,26 +142,42 @@ impl Assets {
113142
}
114143
}
115144

116-
/// Copies every completed frontend asset, then generates the Rust lookup.
145+
/// Copies every completed frontend asset, names the pages' stylesheet and the SDK's
146+
/// script by their content, then generates the Rust lookup.
117147
fn main() -> io::Result<()> {
118-
let source = PathBuf::from(env::var("CARGO_MANIFEST_DIR").map_err(io::Error::other)?)
119-
.join("../auth-web/build");
148+
let manifest = PathBuf::from(env::var("CARGO_MANIFEST_DIR").map_err(io::Error::other)?);
149+
let source = manifest.join("../auth-web/build");
150+
let stylesheet = manifest.join("../../packages/auth-sdk/src/style.css");
151+
let script = manifest.join("../../packages/auth-sdk/build/index.js");
120152
let output = PathBuf::from(env::var("OUT_DIR").map_err(io::Error::other)?);
121-
println!("cargo:rerun-if-changed={}", source.display());
153+
for input in [&source, &stylesheet, &script] {
154+
println!("cargo:rerun-if-changed={}", input.display());
155+
}
122156
let mut assets = Assets {
123157
source: source.clone(),
124158
snapshot: output.join("auth-assets"),
125159
entries: Vec::new(),
160+
named: Vec::new(),
126161
};
127162
// A missing build embeds nothing; the service then refuses to start.
128163
if source.exists() {
129164
assets.collect(&source)?;
130165
}
131166
assets.entries.sort();
167+
let stylesheet = assets.name("style", "css", &stylesheet)?;
168+
// Like the frontend, a missing SDK build is only refused at startup.
169+
let script = if script.exists() {
170+
Some(assets.name("auth-sdk", "js", &script)?)
171+
} else {
172+
None
173+
};
132174
// Lets code used only by embedded files tolerate builds without them.
133175
println!("cargo::rustc-check-cfg=cfg(embedded_frontend)");
134176
if !assets.entries.is_empty() {
135177
println!("cargo::rustc-cfg=embedded_frontend");
136178
}
137-
fs::write(output.join("assets.rs"), assets.lookup()?)
179+
fs::write(
180+
output.join("assets.rs"),
181+
assets.lookup(&stylesheet, script.as_deref())?,
182+
)
138183
}

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

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
//! Embedded static auth pages, their cache validators and browser isolation policy.
1+
//! Embedded static auth pages, the stylesheet and SDK script of the server-rendered
2+
//! pages, their cache validators and browser isolation policy.
23
34
use crate::{
45
StartupError,
@@ -9,7 +10,7 @@ use axum::{
910
response::{IntoResponse, Response},
1011
};
1112

12-
// Generated by `build.rs`: `EmbeddedAssets::COUNT` and `EmbeddedAssets::find`.
13+
// Generated by `build.rs`: `EmbeddedAssets::COUNT`, `STYLESHEET`, `SCRIPT` and `find`.
1314
include!(concat!(env!("OUT_DIR"), "/assets.rs"));
1415

1516
/// Browser isolation policy; `SvelteKit` adds the per-page script hashes in a CSP meta tag.
@@ -33,13 +34,13 @@ impl From<AssetError> for ApiError {
3334

3435
/// One embedded file, with the headers `build.rs` computed for it.
3536
struct Asset {
36-
/// The file's bytes, from the frontend build.
37+
/// The file's bytes, from the frontend or SDK build.
3738
bytes: &'static [u8],
3839
/// `Content-Type`, chosen by extension.
3940
content_type: &'static str,
4041
/// Strong validator: base64url of the first 16 bytes of the file's SHA-256, quoted.
4142
etag: &'static str,
42-
/// `Immutable` for content-addressed bundles, `Revalidate` for everything else.
43+
/// `Immutable` for content-addressed files, `Revalidate` for everything else.
4344
cache: CacheClass,
4445
}
4546

@@ -71,13 +72,15 @@ impl Asset {
7172
}
7273
}
7374

74-
/// The completed auth frontend embedded in this executable.
75+
/// The completed auth frontend, and the files of the server-rendered pages, embedded
76+
/// in this executable.
7577
pub(crate) struct EmbeddedAssets;
7678
impl EmbeddedAssets {
77-
/// Rejects executables compiled before the frontend was built.
78-
/// Tests accept an empty frontend: they build routers but never request a page.
79+
/// Rejects executables compiled before the frontend or the SDK was built.
80+
/// Tests accept neither: they build routers but never request a frontend page or
81+
/// the SDK's script.
7982
pub(crate) fn check() -> Result<(), StartupError> {
80-
if Self::COUNT == 0 && !cfg!(test) {
83+
if (Self::COUNT == 0 || Self::SCRIPT.is_none()) && !cfg!(test) {
8184
Err(StartupError::MissingAssets)
8285
} else {
8386
Ok(())
@@ -147,4 +150,20 @@ mod tests {
147150
assert_eq!(body, expected, "{tag}");
148151
}
149152
}
153+
154+
/// The pages' stylesheet is served at the path naming its content, so it is
155+
/// cached forever.
156+
#[test]
157+
fn the_stylesheet_is_immutable() {
158+
let response =
159+
EmbeddedAssets::serve(EmbeddedAssets::STYLESHEET, &HeaderMap::new()).expect("found");
160+
assert_eq!(
161+
response.headers()[header::CONTENT_TYPE],
162+
"text/css; charset=utf-8"
163+
);
164+
assert_eq!(
165+
response.extensions().get::<CacheClass>(),
166+
Some(&CacheClass::Immutable)
167+
);
168+
}
150169
}

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

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ mod sessions;
4040
/// Fixtures shared by the applications' tests.
4141
#[cfg(test)]
4242
mod tests;
43+
/// auth.piquel.fr's server-rendered pages.
44+
mod web;
4345

4446
pub use admin::{
4547
AdminError, AdminService, GracePeriod, HandleIssue, HandleProblem, InviteExpiry, Operator,
@@ -59,6 +61,7 @@ pub use jobs::Jobs;
5961
use oidc::OidcApplication;
6062
use passkey::PasskeyApplication;
6163
use service::ServiceApplication;
64+
use web::WebApplication;
6265

6366
use account::AccountApplication;
6467
use assets::EmbeddedAssets;
@@ -99,7 +102,7 @@ pub enum StartupError {
99102
Outbound(#[source] reqwest::Error),
100103
/// The executable lacks the required browser assets.
101104
#[error(
102-
"build the auth frontend with pnpm --filter @piquel/auth-web build before compiling auth-service"
105+
"build the auth frontend and SDK with pnpm --filter \"@piquel/auth-web...\" build before compiling auth-service"
103106
)]
104107
MissingAssets,
105108
}
@@ -112,6 +115,7 @@ impl AuthConfig {
112115
/// Fails when the frontend is not embedded or an application cannot initialize.
113116
pub fn router(&self, database: Database) -> Result<Router, StartupError> {
114117
EmbeddedAssets::check()?;
118+
let oidc = OidcApplication::new(database.clone(), &self.oidc)?;
115119
let application = Router::new()
116120
.merge(ServiceApplication::new(database.clone(), self).routes())
117121
.merge(PasskeyApplication::new(database.clone(), &self.passkey)?.routes())
@@ -120,7 +124,8 @@ impl AuthConfig {
120124
.merge(AccountApplication::new(database.clone()).routes())
121125
.merge(ClientApplication::new(database.clone()).routes())
122126
.merge(EmailApplication::new(database.clone(), &self.email).routes())
123-
.merge(OidcApplication::new(database.clone(), &self.oidc)?.routes());
127+
.merge(WebApplication::new(oidc.clone(), &self.oidc.origin).routes())
128+
.merge(oidc.routes());
124129
let policy = security::HttpSecurity::new(self, database);
125130
let protected = application
126131
// Static pages answer GET and HEAD only, so preconditions need no 412.

0 commit comments

Comments
 (0)