forge
Explore
Log in

Don't you dare go Hollow

in_old

Clone
★ 0

0 watching0 forksRustGPL-3.01.1 MiB218b775Tahinli2 months ago90 commits

server.rs850 lines, 35.8 KiBHistoryRawDownload
1//! Server-side plumbing: the application context, the person behind the
2//! current request, and the role guards.
3//!
4//! Every guard here is the real one. The UI hides what a role may not do, but
5//! the answer that matters is the one given in this module, on the server.
6//!
7//! There are no local passwords in v1 — im holds the central session over
8//! OIDC and `in-client` (vendored from `im-client`) holds this app's side of
9//! it. This module's `current_user` maps im's claims onto the local user row,
10//! provisioning it on first sight.
11
12use std::collections::HashMap;
13
14use std::sync::{Arc, LazyLock, PoisonError};
15
16use in_core::Config;
17use in_core::store::{Store, StoreError, User};
18use serde::{Deserialize, Serialize};
19use sha2::Digest;
20use topcoat::asset::AssetBundle;
21use topcoat::context::{Cx, app_context, memoize};
22use topcoat::router::request::{client_ip, headers};
23use topcoat::router::{Body, HeaderValue, Next, StatusCode, header, response::{IntoResponse, Response}, route, to_bytes};
24
25/// The whole application context, put into the router by `main.rs`. One
26/// struct rather than three separate contexts so a route needing two of them
27/// reads both off the same value. The OIDC client state lives in the router
28/// separately — `in_client::mount` puts it there — because its login routes
29/// read it without going through this struct.
30#[derive(Clone)]
31pub struct App {
32 /// The drive store. `Arc` over the trait so tests can hand a router a
33 /// rehearsal double without touching Turso.
34 pub store: Arc<dyn Store>,
35 /// The loaded `config/in.toml` — every tunable wave 2 reads.
36 pub config: Config,
37 /// Told when the process is stopping, so the live streams end instead of
38 /// being waited out.
39 pub shutdown: crate::live::Shutdown,
40 /// The `in.key` loaded at boot — the same key that seals the session
41 /// cookies. Share-link creation seals the minted token with it onto a
42 /// setting row, so the full link address can be re-shown later; a
43 /// database copy without the key file carries links that open but can
44 /// no longer be re-viewed.
45 pub link_key: in_core::store::secret::Key,
46 /// im's identity directory — the roster, the photo bytes and the live
47 /// change feed — authenticated with the same client pair the OIDC side
48 /// holds. Built once at boot; cheap to clone.
49 pub directory: im_client::directory::DirectoryClient,
50 /// Whether the directory's live stream is up, read by the settings
51 /// page's Connection card. Atomics, not locks: the sync task writes
52 /// from its own loop, every settings render reads, neither ever blocks.
53 pub health: DirectoryHealth,
54}
55
56/// The live state of the identity-directory connection, as the Connection
57/// card displays it. Cloned freely; every clone sees the same atomics.
58#[derive(Clone, Debug)]
59pub struct DirectoryHealth {
60 /// 1 while `/directory/live` is open, 0 while connecting or
61 /// re-connecting — the boot default is 0, and every stream end or
62 /// error returns it there until the next open.
63 stream: Arc<std::sync::atomic::AtomicU8>,
64 /// Unix seconds of the last roster event the stream delivered; 0 is
65 /// never. The age a card shows is derived at read time, so a stale
66 /// moment ages honestly without a ticking task behind it.
67 last_event: Arc<std::sync::atomic::AtomicI64>,
68 /// Unix seconds of the last full `/directory` pass that committed —
69 /// the healer's heartbeat. It ticks slowly (boot, every stream end),
70 /// which is why a card shows it: a feed gone quiet and a mirror
71 /// stopped healing are two different silences.
72 last_pass: Arc<std::sync::atomic::AtomicI64>,
73}
74
75impl Default for DirectoryHealth {
76 fn default() -> Self {
77 Self {
78 stream: Arc::new(std::sync::atomic::AtomicU8::new(0)),
79 last_event: Arc::new(std::sync::atomic::AtomicI64::new(0)),
80 last_pass: Arc::new(std::sync::atomic::AtomicI64::new(0)),
81 }
82 }
83}
84impl DirectoryHealth {
85 pub fn new() -> Self {
86 Self::default()
87 }
88
89 /// The stream opened.
90 pub fn connected(&self) {
91 use std::sync::atomic::Ordering::Relaxed;
92 self.stream.store(1, Relaxed);
93 }
94
95 /// The stream ended or failed; the task will dial again.
96 pub fn reconnecting(&self) {
97 use std::sync::atomic::Ordering::Relaxed;
98 self.stream.store(0, Relaxed);
99 }
100
101 /// A roster event came through the live stream: it is connected, and
102 /// this is the moment it last said anything.
103 pub fn note_event(&self) {
104 use std::sync::atomic::Ordering::Relaxed;
105 self.stream.store(1, Relaxed);
106 self.last_event.store(now_unix(), Relaxed);
107 }
108
109 /// A full roster pass committed: the mirror healed (or was already
110 /// true), however quiet the live feed has been.
111 pub fn note_pass(&self) {
112 use std::sync::atomic::Ordering::Relaxed;
113 self.last_pass.store(now_unix(), Relaxed);
114 }
115
116 /// Whether the card shows the green dot.
117 pub fn stream_connected(&self) -> bool {
118 use std::sync::atomic::Ordering::Relaxed;
119 self.stream.load(Relaxed) == 1
120 }
121
122 /// Seconds since the last roster event, or `None` before the first one.
123 pub fn last_event_age_secs(&self) -> Option<i64> {
124 use std::sync::atomic::Ordering::Relaxed;
125 let at = self.last_event.load(Relaxed);
126 (at > 0).then(|| (now_unix() - at).max(0))
127 }
128
129 /// Seconds since the last full roster pass, or `None` before the
130 /// first one — a boot whose pass has not landed yet.
131 pub fn last_pass_age_secs(&self) -> Option<i64> {
132 use std::sync::atomic::Ordering::Relaxed;
133 let at = self.last_pass.load(Relaxed);
134 (at > 0).then(|| (now_unix() - at).max(0))
135 }
136}
137
138fn now_unix() -> i64 {
139 time::OffsetDateTime::now_utc().unix_timestamp()
140}
141
142/// The application context this request runs under.
143pub fn app(cx: &Cx) -> App {
144 app_context::<App>(cx).clone()
145}
146
147/// The origin the public links carry: the `base_url` an admin saved on the
148/// running install when one is set, else the config chain — the file's
149/// `base_url`, else the address bound. Every public URL construction (the
150/// share links and their copy-once banners) asks this; the settings
151/// server-address panel is what edits the setting the lookup reads.
152pub async fn share_origin(cx: &Cx) -> String {
153 match app(cx).store.get_setting("base_url").await {
154 Ok(Some(base)) if !base.trim().is_empty() => base.trim().to_string(),
155 _ => app(cx).config.public_origin(),
156 }
157}
158
159/// The full public address of a share link — `{origin}/s/{token}` —
160/// re-derived from the token its creation sealed onto the
161/// `share_token:{id}` setting row.
162///
163/// `None` when the address cannot be told again: a link minted before the
164/// sealing carries no row, and a key lost since minting opens nothing. Both
165/// callers degrade the same way — the masked value plus the legacy note —
166/// so the option is the whole contract.
167pub async fn share_link_url(cx: &Cx, link: &in_core::store::ShareLink) -> Option<String> {
168 let app = app(cx);
169 let sealed = app
170 .store
171 .get_setting(&format!("share_token:{}", link.id))
172 .await
173 .ok()??;
174 let token = in_core::store::secret::open(&app.link_key, &sealed)?;
175 Some(format!("{}/s/{token}", share_origin(cx).await))
176}
177
178/// One proxy hop in front of the process. `in` is reached through that hop,
179/// so [`client_ip`] reads the address it appended rather than the hop's own.
180/// A direct connection, with no hop in front, is its own address.
181pub fn trusted_proxies() -> topcoat::router::TrustedProxies {
182 topcoat::router::TrustedProxies::new().nearest(1)
183}
184
185/// A stable-enough label for the client.
186///
187/// [`client_ip`] under [`trusted_proxies`]: the address the one trusted hop
188/// reported, or the peer when the request did not come through it. `unknown`
189/// when neither is there. A client-supplied `x-forwarded-for` is not read
190/// unless that hop appended it.
191pub fn client_label(cx: &Cx) -> String {
192 client_ip(cx)
193 .map(|ip| ip.to_string())
194 .unwrap_or_else(|| "unknown".to_string())
195}
196
197/// The stylesheet this binary serves must be the one compiled into it.
198///
199/// `asset!` embeds an asset's declaration — its id and source path — into
200/// the binary, but the served bytes live in the bundle directory beside the
201/// executable, and topcoat loads whatever manifest it finds there. A bundle
202/// left behind by another deploy sits beside a newer binary without a word
203/// of complaint, and the pages then reference a stylesheet whose bytes are
204/// from another generation — the mixed generation a browser once caught on
205/// production. `build.rs` stamps the compiled stylesheet's SHA-256 into the
206/// binary; this hashes the bundle's bytes against it, so a foreign bundle
207/// refuses the boot instead of serving under it.
208///
209/// Returns the startup log line naming the served fingerprint, or the
210/// reason the boot must not proceed.
211pub fn stylesheet_guard(bundle: &AssetBundle) -> Result<String, String> {
212 let expected = env!("IN_STYLE_FINGERPRINT");
213 let stylesheet = bundle
214 .catalog()
215 .assets()
216 .find(|asset| {
217 let name = asset.name();
218 name.starts_with("main-") && name.ends_with(".css")
219 })
220 .ok_or_else(|| {
221 format!(
222 "the asset bundle at {} carries no stylesheet",
223 bundle.dir().display()
224 )
225 })?;
226 let bytes = std::fs::read(bundle.dir().join(stylesheet.name())).map_err(|err| {
227 format!(
228 "the bundled stylesheet {} could not be read: {err}",
229 stylesheet.name()
230 )
231 })?;
232 let digest = sha2::Sha256::digest(&bytes);
233 let actual = format!(
234 "sha256:{}",
235 digest
236 .as_slice()
237 .iter()
238 .map(|b| format!("{b:02x}"))
239 .collect::<String>()
240 );
241 if actual != expected {
242 return Err(format!(
243 "the asset bundle at {} is from another build: stylesheet {} is {actual} but this binary was compiled against {expected}; run `topcoat asset bundle` and redeploy",
244 bundle.dir().display(),
245 stylesheet.name()
246 ));
247 }
248 Ok(format!(
249 "assets stylesheet {} ({actual})",
250 stylesheet.name()
251 ))
252}
253
254/// The person behind this request, or nobody, or the store failing to say.
255///
256/// im is asked on every request — the cookie holds an opaque session token,
257/// introspected per call — so an admin revoking the person in im signs them
258/// out here at once. The first sight of a `sub` inserts the local row (and
259/// the first user ever becomes the admin); every later sight refreshes the
260/// address and name and stamps the last-seen time.
261///
262/// A store error is not "nobody" — a busy database mid-drag is a fact about
263/// the database, not about whether this browser is signed in, and a caller
264/// that folded the two together would send a signed-in person to a sign-in
265/// screen because a write elsewhere held a lock for a moment.
266///
267/// A disabled account reads as nobody: the cookie is im's business and is
268/// left untouched, but every guard below refuses as if signed out.
269#[memoize(as_ref)]
270pub async fn current_user(cx: &Cx) -> Result<Option<User>, StoreError> {
271 let Some(claims) = in_client::current_user(cx).await else {
272 return Ok(None);
273 };
274 let app = app(cx);
275 let user = app
276 .store
277 .provision_user(
278 &claims.sub,
279 &claims.email,
280 &claims.name,
281 None,
282 claims.photo_version,
283 app.config.default_quota_bytes,
284 )
285 .await?;
286 if user.disabled {
287 return Ok(None);
288 }
289 Ok(Some(user))
290}
291
292/// The person behind this request, or a refusal the caller can return as-is.
293///
294/// A store error becomes `Refusal::Unavailable` rather than `SignInFirst`,
295/// which would tell a signed-in person to sign in again over what was only
296/// a database hiccup.
297pub async fn require_user(cx: &Cx) -> Result<User, Refusal> {
298 match current_user(cx).await {
299 Ok(Some(user)) => Ok(user.clone()),
300 Ok(None) => Err(Refusal::SignInFirst),
301 Err(_) => Err(Refusal::Unavailable),
302 }
303}
304
305/// The sign-in probe the live channel's error path polls: 204 while this
306/// browser carries a live session, 401 the moment it does not — no HTML,
307/// no body, nothing but the answer. It exists for the one question an open
308/// tab can ask mid-flight ("am I still signed in?") without dragging a
309/// page render behind it. A store failure answers 500 rather than 401:
310/// the probe's whole contract is that only a real sign-out draws the 401,
311/// and a broken database must never fake one.
312#[route(GET "/api/me")]
313pub async fn me(cx: &Cx) -> topcoat::Result<Response> {
314 match current_user(cx).await {
315 Ok(Some(_)) => (StatusCode::NO_CONTENT, "").into_response(cx),
316 Ok(None) => (StatusCode::UNAUTHORIZED, "").into_response(cx),
317 Err(_) => (StatusCode::INTERNAL_SERVER_ERROR, "").into_response(cx),
318 }
319}
320
321/// The admin behind this request. Anyone else is refused *here*, not
322/// merely hidden from in the UI.
323pub async fn require_admin(cx: &Cx) -> Result<User, Refusal> {
324 let user = require_user(cx).await?;
325 if user.admin {
326 Ok(user)
327 } else {
328 Err(Refusal::Forbidden)
329 }
330}
331
332/// The service behind this request, by bearer key — the machine half of the
333/// auth surface. A human browser's session cookie means nothing here and a
334/// service key means nothing to [`current_user`]: the two never meet. A
335/// disabled account reads as no key at all, the same way a disabled person
336/// reads as signed out.
337pub async fn service_client(cx: &Cx) -> Option<User> {
338 let presented = headers(cx)
339 .get(header::AUTHORIZATION)
340 .and_then(|value| value.to_str().ok())?;
341 let token = presented.strip_prefix("Bearer ")?.trim();
342 if token.is_empty() {
343 return None;
344 }
345 let user = app(cx).store.service_account_by_token(token).await.ok()??;
346 (!user.disabled).then_some(user)
347}
348
349/// How long a freshly minted service key waits on the shelf for its one
350/// showing: ten minutes, im's own ticket lifetime.
351const SHOWN_TTL: std::time::Duration = std::time::Duration::from_secs(10 * 60);
352
353/// Where a freshly minted service key waits between its POST and the one
354/// GET that shows it. The panel's write answers a 303 — the house idiom —
355/// but the key itself must never ride a URL or a log line, so the query
356/// carries only a random claim ticket: the shelf holds the plaintext, the
357/// page's read takes it out ([`take_shown_secret`]), and a replayed or
358/// reloaded URL finds the shelf empty and renders no key at all. A restart
359/// drops the shelf — the admin mints another.
360static SHOWN_SECRETS: LazyLock<std::sync::Mutex<HashMap<String, (String, std::time::Instant)>>> =
361 LazyLock::new(|| std::sync::Mutex::new(HashMap::new()));
362
363/// Parks a fresh service key on the shelf and returns the claim ticket for
364/// its URL.
365pub fn stash_shown_secret(secret: String) -> String {
366 let ticket = format!("{}", ulid::Ulid::generate());
367 let mut shelf = SHOWN_SECRETS.lock().unwrap_or_else(PoisonError::into_inner);
368 shelf.retain(|_, (_, parked)| parked.elapsed() < SHOWN_TTL);
369 shelf.insert(ticket.clone(), (secret, std::time::Instant::now()));
370 ticket
371}
372
373/// Takes a stashed key out — exactly once; the second reader of the same
374/// ticket gets nothing.
375pub fn take_shown_secret(ticket: &str) -> Option<String> {
376 SHOWN_SECRETS
377 .lock()
378 .unwrap_or_else(PoisonError::into_inner)
379 .remove(ticket)
380 .map(|(secret, _)| secret)
381}
382
383impl From<StoreError> for Refusal {
384 fn from(_: StoreError) -> Refusal {
385 Refusal::Unavailable
386 }
387}
388
389/// Everything a refused call is allowed to say.
390///
391/// The codes are the contract's: a browser without script only ever sees
392/// them through the address bar, so each one has a short word form
393/// ([`Refusal::code`]) beside its sentence.
394#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
395pub enum Refusal {
396 /// No session, a revoked one, or a disabled account — deliberately one
397 /// answer for all three.
398 SignInFirst,
399 /// Signed in, but not an admin (or not the owner). Cross-owner reads are
400 /// answered with [`Refusal::NotFound`] instead — a 404, never a 403 —
401 /// so this is only for surfaces whose existence is no secret.
402 Forbidden,
403 /// No such file or folder — or none this account may see. Deliberately
404 /// one answer for both.
405 NotFound,
406 /// The bytes would not fit the remaining quota.
407 QuotaExceeded,
408 /// A folder with children stays until it is emptied.
409 FolderNotEmpty,
410 /// The target belongs to somebody else. Answered like [`Refusal::NotFound`]
411 /// on the wire; a distinct code so the carry still names what happened.
412 CrossOwner,
413 /// A share link spent, expired, revoked, or never real.
414 ShareRevoked,
415 /// The upload session expired or was aborted before the finish landed.
416 UploadExpired,
417 /// A chunk arrived out of order, twice, or the wrong size.
418 BadChunk,
419 /// A restore was asked for while an ancestor folder is still trashed —
420 /// restore the ancestor first.
421 AncestorTrashed,
422 /// The store failed to say. Never a sign-in prompt — see `require_user`.
423 Unavailable,
424 /// The ui field was not one of the values the form offers.
425 BadUi,
426 /// The theme field was not one of the values the form offers.
427 BadTheme,
428 /// The language field was not one of the values the form offers.
429 BadLanguage,
430 /// The admin's quota form named something unusable — unparseable, or a
431 /// unit the form does not offer.
432 BadLimit,
433 /// The admin's server-address form named something no public link can
434 /// be built on — no `http`/`https` scheme, or a trailing slash.
435 BadBaseUrl,
436 /// A quota form named a service account: the ceiling is im's to set,
437 /// and the family beat carries it.
438 ServiceQuota,
439 /// A Service keys form named a service that cannot take the action —
440 /// not mintable, not keyed, or an empty name.
441 BadServiceKey,
442}
443
444impl Refusal {
445 /// The refusal in words.
446 pub fn message(&self) -> String {
447 match self {
448 Refusal::SignInFirst => "Sign in first.".to_string(),
449 Refusal::Forbidden => "Not permitted.".to_string(),
450 Refusal::NotFound => "No such file or folder.".to_string(),
451 Refusal::QuotaExceeded => "Over quota.".to_string(),
452 Refusal::FolderNotEmpty => "That folder still has files in it.".to_string(),
453 // Same sentence as NotFound: a cross-owner probe must not learn
454 // the target exists.
455 Refusal::CrossOwner => "No such file or folder.".to_string(),
456 Refusal::ShareRevoked => "This link no longer works.".to_string(),
457 Refusal::UploadExpired => "This upload expired. Start it again.".to_string(),
458 Refusal::BadChunk => "That piece arrived damaged. Send it again.".to_string(),
459 Refusal::AncestorTrashed => "Restore the folder it is in first.".to_string(),
460 Refusal::Unavailable => "Something went wrong.".to_string(),
461 Refusal::BadUi => "That interface choice is not offered.".to_string(),
462 Refusal::BadTheme => "That is not a theme.".to_string(),
463 Refusal::BadLanguage => "That is not a language.".to_string(),
464 Refusal::BadLimit => "That limit is not usable.".to_string(),
465 Refusal::BadBaseUrl => {
466 "That address is not an origin links can be built on.".to_string()
467 }
468 Refusal::ServiceQuota => "The limit is im's to set.".to_string(),
469 Refusal::BadServiceKey => "That key is not usable.".to_string(),
470 }
471 }
472
473 /// `message()`, in the reader's language.
474 pub fn message_in(&self, lang: crate::i18n::Lang) -> String {
475 use crate::i18n::Lang::Tr;
476 if lang != Tr {
477 return self.message();
478 }
479 match self {
480 Refusal::SignInFirst => "Önce oturum aç.".to_string(),
481 Refusal::Forbidden => "İzin verilmiyor.".to_string(),
482 Refusal::NotFound => "Böyle bir dosya ya da klasör yok.".to_string(),
483 Refusal::QuotaExceeded => "Kota doldu.".to_string(),
484 Refusal::FolderNotEmpty => "Bu klasörde hâlâ dosyalar var.".to_string(),
485 Refusal::CrossOwner => "Böyle bir dosya ya da klasör yok.".to_string(),
486 Refusal::ShareRevoked => "Bu bağlantı artık çalışmıyor.".to_string(),
487 Refusal::UploadExpired => "Bu yüklemenin süresi doldu. Yeniden başlat.".to_string(),
488 Refusal::BadChunk => "Bu parça bozuk geldi. Yeniden gönder.".to_string(),
489 Refusal::Unavailable => "Bir şeyler ters gitti.".to_string(),
490 Refusal::AncestorTrashed => "Önce içinde olduğu klasörü geri yükle.".to_string(),
491 Refusal::BadUi => "Bu arayüz seçeneği sunulmuyor.".to_string(),
492 Refusal::BadTheme => "Bu bir tema değil.".to_string(),
493 Refusal::BadLanguage => "Bu bir dil değil.".to_string(),
494 Refusal::BadLimit => "Bu sınır kullanılamaz.".to_string(),
495 Refusal::BadBaseUrl => {
496 "Bu adres, bağlantı kurulabilecek bir kök adres değil.".to_string()
497 }
498 Refusal::ServiceQuota => "Limit im'de belirlenir.".to_string(),
499 Refusal::BadServiceKey => "Bu anahtar kullanılamaz.".to_string(),
500 }
501 }
502
503 /// The refusal a `code` names, or nothing. Nothing for an unknown word: the
504 /// query is whatever the address bar holds, so a code that is not one of
505 /// ours says nothing at all rather than something invented.
506 pub fn from_code(code: &str) -> Option<Refusal> {
507 Some(match code {
508 "sign-in-first" => Refusal::SignInFirst,
509 "forbidden" => Refusal::Forbidden,
510 "not-found" => Refusal::NotFound,
511 "quota-exceeded" => Refusal::QuotaExceeded,
512 "folder-not-empty" => Refusal::FolderNotEmpty,
513 "cross-owner" => Refusal::CrossOwner,
514 "share-revoked" => Refusal::ShareRevoked,
515 "upload-expired" => Refusal::UploadExpired,
516 "bad-chunk" => Refusal::BadChunk,
517 "ancestor-trashed" => Refusal::AncestorTrashed,
518 "unavailable" => Refusal::Unavailable,
519 "bad-ui" => Refusal::BadUi,
520 "bad-theme" => Refusal::BadTheme,
521 "bad-language" => Refusal::BadLanguage,
522 "bad-limit" => Refusal::BadLimit,
523 "bad-base-url" => Refusal::BadBaseUrl,
524 "service-quota" => Refusal::ServiceQuota,
525 "bad-service-key" => Refusal::BadServiceKey,
526 _ => return None,
527 })
528 }
529
530 /// The refusal as a short word, for the address bar.
531 ///
532 /// A browser without script never sees a call's return value: it posts the
533 /// form, follows the redirect, and the page it lands on has to be told what
534 /// happened. That telling goes through the query, so every refusal needs a
535 /// name that survives a round trip through a URL.
536 pub fn code(&self) -> &'static str {
537 match self {
538 Refusal::SignInFirst => "sign-in-first",
539 Refusal::Forbidden => "forbidden",
540 Refusal::NotFound => "not-found",
541 Refusal::QuotaExceeded => "quota-exceeded",
542 Refusal::FolderNotEmpty => "folder-not-empty",
543 Refusal::CrossOwner => "cross-owner",
544 Refusal::ShareRevoked => "share-revoked",
545 Refusal::UploadExpired => "upload-expired",
546 Refusal::BadChunk => "bad-chunk",
547 Refusal::AncestorTrashed => "ancestor-trashed",
548 Refusal::Unavailable => "unavailable",
549 Refusal::BadUi => "bad-ui",
550 Refusal::BadTheme => "bad-theme",
551 Refusal::BadLanguage => "bad-language",
552 Refusal::BadLimit => "bad-limit",
553 Refusal::BadBaseUrl => "bad-base-url",
554 Refusal::ServiceQuota => "service-quota",
555 Refusal::BadServiceKey => "bad-service-key",
556 }
557 }
558}
559
560/// Which call a carried refusal belongs to. Two forms on one page must not both
561/// claim the same sentence, so the redirect names the call and this is the name:
562/// the last piece of the server function's path, with anything that is not a
563/// plain word dropped so it can only ever be compared, never rendered.
564pub fn call_id(path: &str) -> String {
565 path.rsplit('/')
566 .next()
567 .unwrap_or(path)
568 .chars()
569 .filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-')
570 .collect()
571}
572
573/// What a call refused with, however the browser without script carried it
574/// back — read straight off the query, since there is no client-side action
575/// value to check first the way a hydrated page in the old UI had.
576///
577/// Every topcoat page is rendered server-side on every request, so there is
578/// only ever the query to read.
579pub fn refusal_of(cx: &Cx, call: &str) -> Option<Refusal> {
580 let query = topcoat::router::request::uri(cx).query()?;
581 let mut code = None;
582 let mut on = None;
583 for pair in query.split('&') {
584 if let Some((key, value)) = pair.split_once('=') {
585 match key {
586 "refusal" => code = Some(value),
587 "on" => on = Some(value),
588 _ => {}
589 }
590 }
591 }
592 if on? != call {
593 return None;
594 }
595 Refusal::from_code(code?)
596}
597
598/// The page a form was posted from: the `Referer`, with the answer any
599/// earlier post left on its query dropped, or `nowhere` when no `Referer`
600/// came with the request.
601///
602/// The feedback pairs — `refusal=`, `on=`, `why=`, `saved=` — are how a page
603/// renders what the last post did, and `move=` opens the drive's one-shot
604/// destination picker, which no post should return to. Sending the browser
605/// on the query re-renders that old answer under the new post's own: a change
606/// that succeeded right after one that was refused announces the refusal
607/// again, and reads as having failed. The answer this redirect carries — the
608/// pairs it was built with, or the body [`carry_refusal_on_redirect`] copies
609/// onto the query — is the one that shows; an earlier one never survives the
610/// trip.
611pub fn back_to(cx: &Cx, nowhere: &str) -> String {
612 let referer = headers(cx)
613 .get(header::REFERER)
614 .and_then(|value| value.to_str().ok())
615 .unwrap_or(nowhere);
616 // The Referer is attacker-influenceable input on its way into a
617 // Location header: only a local path rides it — an absolute URL, a
618 // protocol-relative `//`, or a backslash (browsers normalize it to a
619 // slash) all fall back to the caller's safe target.
620 let referer = match referer {
621 r if r.starts_with('/') && !r.starts_with("//") && !r.contains('\\') => r,
622 _ => nowhere,
623 };
624 let (path, query) = referer.split_once('?').unwrap_or((referer, ""));
625 let pairs: Vec<&str> = query
626 .split('&')
627 .filter(|pair| {
628 !pair.is_empty()
629 && !["refusal", "on", "why", "saved", "move"].iter().any(|key| {
630 pair.strip_prefix(*key)
631 .is_some_and(|rest| rest.starts_with('='))
632 })
633 })
634 .collect();
635 if pairs.is_empty() {
636 return path.to_string();
637 }
638 format!("{path}?{}", pairs.join("&"))
639}
640
641/// Puts a refusal on the redirect a browser without script follows.
642///
643/// A hydrated page reads the call's return value straight off the action. A
644/// browser without script has no such thing: it posts the form, the server
645/// function handler answers with a redirect back to the page it came from, and
646/// the value — the whole refusal — sits in a body nobody will ever look at.
647/// The click then looks like nothing happening, which is the worst answer
648/// in can give.
649///
650/// So the refusal is copied onto the `Location`, as `?refusal=<code>&on=<call>`,
651/// and the page renders it from the query. This is one place rather than a
652/// dozen because the shape is the same for every refusing call, present
653/// and future: nothing here knows what any of them do.
654///
655/// Requests carrying script are untouched — they are answered with the value
656/// itself and never see a redirect.
657///
658/// Ported from axum's `middleware::from_fn` onto a topcoat `#[layer]`. topcoat's
659/// Post/Redirect/Get helper (`error::see_other`) answers with `303 See Other`,
660/// not the `302 Found` axum's server-function redirect used, so the status this
661/// checks for is `SEE_OTHER` — the guard's three conditions are otherwise
662/// unchanged.
663#[topcoat::router::layer("/api")]
664async fn carry_refusal_on_redirect(
665 cx: &Cx,
666 body: Body,
667 next: Next<'_>,
668) -> topcoat::Result<Response> {
669 // A form post from a browser asks for a page back. A server-function call
670 // from the hydrated bundle does not.
671 let wants_page = headers(cx)
672 .get(header::ACCEPT)
673 .and_then(|value| value.to_str().ok())
674 .is_some_and(|value| value.contains("text/html"));
675 let called = call_id(topcoat::router::request::uri(cx).path());
676 let has_referer = headers(cx).contains_key(header::REFERER);
677 let response = next.run(cx, body).await?;
678 if !wants_page || !has_referer || response.status() != StatusCode::SEE_OTHER {
679 return Ok(response);
680 }
681
682 let (mut parts, body) = response.into_parts();
683 // The body of one of these redirects is a serialised `Option<Refusal>` and
684 // nothing else; the cap is there so a response that is something else
685 // entirely cannot be read into memory whole. A body that fails to parse —
686 // an empty one included, the shape a route with nothing to say back sends
687 // — is read as "no refusal", never as "leave the Location alone": the
688 // Referer sanitization below has to run on every redirect this layer
689 // sees, not only the ones that happen to carry a refusal.
690 let Ok(bytes) = to_bytes(body, 64 * 1024).await else {
691 return Ok(Response::from_parts(parts, Body::empty()));
692 };
693 let refusal = serde_json::from_slice::<Option<Refusal>>(&bytes)
694 .ok()
695 .flatten();
696 if let Some(location) = parts
697 .headers
698 .get(header::LOCATION)
699 .and_then(|v| v.to_str().ok())
700 {
701 let rewritten = match refusal {
702 Some(refusal) => carrying(location, refusal.code(), &called),
703 None => Some(same_origin(location).to_string()),
704 };
705 if let Some(carried) = rewritten
706 && let Ok(value) = HeaderValue::from_str(&carried)
707 {
708 parts.headers.insert(header::LOCATION, value);
709 }
710 }
711 Ok(Response::from_parts(parts, Body::from(bytes)))
712}
713
714/// `location` with the refusal in its query.
715///
716/// The redirect goes back to the page the form was posted from, and that page
717/// may already carry a query — `?folder=<id>` is how a browser without script
718/// opens a folder at all — so the two pairs are merged in, and the pair from
719/// any earlier refusal is dropped rather than stacked on top of.
720fn carrying(location: &str, code: &str, called: &str) -> Option<String> {
721 if called.is_empty() {
722 return None;
723 }
724 // The Location we are rewriting came from the form post's Referer, and on a
725 // cross-origin post the Referer is whatever the other site is. Sending the
726 // browser back there would make in an open redirect, so the address is
727 // rebuilt from its path and query alone and anything that is not a plain
728 // absolute path is answered with the drive.
729 let here = same_origin(location);
730 let (path, query) = match here.split_once('?') {
731 Some((path, query)) => (path, query),
732 None => (here, ""),
733 };
734 let mut pairs: Vec<String> = query
735 .split('&')
736 .filter(|pair| {
737 !pair.is_empty() && !pair.starts_with("refusal=") && !pair.starts_with("on=")
738 })
739 .map(str::to_string)
740 .collect();
741 pairs.push(format!("refusal={code}&on={called}"));
742 Some(format!("{path}?{}", pairs.join("&")))
743}
744
745/// The path and query of `location`, with scheme and authority dropped. A
746/// protocol-relative address (`//elsewhere.example/`) is another host wearing a
747/// path's clothes, and a browser reads a backslash there as a slash, so both
748/// are answered with the drive rather than trusted.
749fn same_origin(location: &str) -> &str {
750 let rest = match location.split_once("://") {
751 Some((_scheme, rest)) => match rest.find(['/', '?']) {
752 Some(at) => &rest[at..],
753 None => "/",
754 },
755 None => location,
756 };
757 let mut characters = rest.chars();
758 match (characters.next(), characters.next()) {
759 (Some('/'), Some('/' | '\\')) => "/",
760 (Some('/'), _) => rest,
761 _ => "/",
762 }
763}
764
765/// The cache directives a response cannot choose for itself.
766///
767/// HTML is revalidated on every load: a page the browser kept from before a
768/// deploy is the old app answering under the new one's address, which is how a
769/// fixed bug once came back after shipping. So every response whose body is a
770/// document gets `no-cache`. Responses that already carry a directive keep it —
771/// topcoat stamps the fingerprinted assets under `/_topcoat/assets` with a year
772/// of `immutable` and the live stream with `no-cache`, and the file and
773/// thumbnail handlers stamp their own — and everything else (redirects, JSON
774/// answers) ships none, the idiom they already ride on: no directive, nothing
775/// cached. One layer at `/`, because the decision is about what the bytes are,
776/// not which route built them.
777#[topcoat::router::layer("/")]
778async fn cache_directives(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result<Response> {
779 let response = next.run(cx, body).await?;
780 let (mut parts, body) = response.into_parts();
781 let is_html = parts
782 .headers
783 .get(header::CONTENT_TYPE)
784 .and_then(|value| value.to_str().ok())
785 .is_some_and(|value| value.starts_with("text/html"));
786 if !is_html || parts.headers.contains_key(header::CACHE_CONTROL) {
787 return Ok(Response::from_parts(parts, body));
788 }
789 parts
790 .headers
791 .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
792 Ok(Response::from_parts(parts, body))
793}
794
795#[cfg(test)]
796mod client_label_tests {
797 use std::net::SocketAddr;
798
799 use topcoat::router::response::IntoResponse;
800 use topcoat::router::{
801 Body, Method, RemoteAddr, RouteFn, RouteFuture, Router, request::Request, to_bytes,
802 };
803
804 use super::{client_label, trusted_proxies};
805
806 fn echo(cx: &topcoat::context::Cx, _body: Body) -> RouteFuture<'_> {
807 Box::pin(async move { client_label(cx).into_response(cx) })
808 }
809
810 fn router(trust_one_hop: bool) -> Router {
811 let builder = Router::builder().route(RouteFn::new(Method::GET, "/label", echo));
812 if trust_one_hop {
813 builder.trusted_proxies(trusted_proxies()).build()
814 } else {
815 builder.build()
816 }
817 }
818
819 async fn label(trust_one_hop: bool, peer: &str, forwarded: Option<&str>) -> String {
820 let mut builder = Request::builder()
821 .method(Method::GET)
822 .uri("/label")
823 .extension(RemoteAddr(peer.parse::<SocketAddr>().unwrap()));
824 if let Some(value) = forwarded {
825 builder = builder.header("x-forwarded-for", value);
826 }
827 let response = router(trust_one_hop)
828 .handle(builder.body(Body::empty()).unwrap())
829 .await;
830 String::from_utf8(to_bytes(response.into_body(), 64).await.unwrap().to_vec()).unwrap()
831 }
832
833 #[tokio::test]
834 async fn one_trusted_hop_reports_the_client_not_the_proxy() {
835 let got = label(true, "10.0.0.1:4242", Some("198.51.100.1")).await;
836 assert_eq!(got, "198.51.100.1");
837 }
838
839 #[tokio::test]
840 async fn a_missing_header_falls_back_to_the_peer() {
841 let got = label(true, "203.0.113.9:4242", None).await;
842 assert_eq!(got, "203.0.113.9");
843 }
844
845 #[tokio::test]
846 async fn an_untrusted_peer_cannot_spoof_the_forwarded_header() {
847 let got = label(false, "203.0.113.9:4242", Some("198.51.100.1")).await;
848 assert_eq!(got, "203.0.113.9");
849 }
850}