From bf2e05477e1cf1a04e509c5f40a89c797af1fa4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 6 Sep 2026 00:41:13 +0300 Subject: [PATCH] =?UTF-8?q?A=20photoless=20profile=20answers=20the=20defau?= =?UTF-8?q?lt=20face:=20the=20photo=20route=20renders=20the=20name's=20fir?= =?UTF-8?q?st=20letter=20on=20a=20quiet=20tile=20as=20SVG=20instead=20of?= =?UTF-8?q?=20the=20not-found,=20so=20an=20app's=20=20never=20shows?= =?UTF-8?q?=20the=20broken-image=20glyph=20=E2=80=94=20an=20unknown=20id?= =?UTF-8?q?=20gets=20the=20same=20tile=20with=20a=20=3F,=20keeping=20a=20m?= =?UTF-8?q?issing=20person=20indistinguishable=20from=20a=20missing=20phot?= =?UTF-8?q?o,=20and=20the=20tile=20revalidates=20on=20its=20ETag=20where?= =?UTF-8?q?=20the=20photo=20caches=20immutable,=20so=20a=20later=20upload?= =?UTF-8?q?=20still=20replaces=20it?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/im-web/src/photo.rs | 160 +++++++++++++++++++++++++------------ 1 file changed, 110 insertions(+), 50 deletions(-) diff --git a/crates/im-web/src/photo.rs b/crates/im-web/src/photo.rs index fa7e44a..04c26a2 100644 --- a/crates/im-web/src/photo.rs +++ b/crates/im-web/src/photo.rs @@ -167,60 +167,110 @@ fn not_found() -> (StatusCode, HeaderMap, Vec) { (StatusCode::NOT_FOUND, HeaderMap::new(), Vec::new()) } -/// Serves one person's photo. Signed-in only — either through the session -/// cookie or as a registered OIDC app presenting HTTP Basic over -/// `client_id:client_secret` — and a missing photo reads exactly like a -/// missing person: the not-found, never a `403`. -/// -/// Apps count as signed-in viewers because registration is the trust: im -/// hands the client secret out exactly once, keeps only its digest, and the -/// app presents it on every fetch. Unknown clients, wrong secrets, unknown -/// users and missing photos all answer the same not-found, so no failure -/// is distinguishable on the wire. -#[route(GET "/photo/{user_id}")] -async fn serve(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> { - if server::current_user(cx).await.is_none() && !server::valid_app(cx).await { - return Ok(not_found()); - } - let target = im_core::model::UserId::from(path_param::(cx).to_string()); - let store = server::app(cx).store.clone(); - let Ok(Some((bytes, mime))) = photos::photo(&store, &target).await else { - return Ok(not_found()); - }; - +/// The response for served bytes: the ETag and cache policy, the 304 when +/// the caller's copy is already this one. +fn bytes_response( + cx: &Cx, + bytes: Vec, + content_type: &str, + cache: &'static str, +) -> (StatusCode, HeaderMap, Vec) { let etag = format!("\"{:x}\"", fnv1a(&bytes)); let mut headers = HeaderMap::new(); headers.insert(header::ETAG, HeaderValue::from_str(&etag).unwrap()); - // The stamp in the URL is the other half of this caching: `upload` - // bumps it whenever the bytes change, so a year of `immutable` never - // shows an old photo — a changed photo is a changed URL. `private` - // because the route is session-gated. - headers.insert( - header::CACHE_CONTROL, - HeaderValue::from_static("private, max-age=31536000, immutable"), - ); - + headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(cache)); let if_none_match = request_headers(cx) .get(header::IF_NONE_MATCH) .and_then(|v| v.to_str().ok()); if if_none_match == Some(etag.as_str()) { - return Ok((StatusCode::NOT_MODIFIED, headers, Vec::new())); + return (StatusCode::NOT_MODIFIED, headers, Vec::new()); } - headers.insert( header::CONTENT_TYPE, - HeaderValue::from_str(&mime) + HeaderValue::from_str(content_type) .unwrap_or(HeaderValue::from_static("application/octet-stream")), ); - Ok((StatusCode::OK, headers, bytes)) + (StatusCode::OK, headers, bytes) } +/// The default face, as an image: the name's first letter on a quiet tile — +/// the same answer im's own pages give a photoless profile (the initial span +/// in `layout::avatar`), rendered to SVG so an app's `` can carry it. +/// The colors are fixed (mid tile, light letter) because the tile ships to +/// apps whose themes im does not know. +fn default_avatar(initial: &str) -> Vec { + // The initial is one character off a name, but escape anyway: nothing + // stops a name from starting with `&`, `<`, or `>`. + let escaped = initial + .replace('&', "&") + .replace('<', "<") + .replace('>', ">"); + format!( + "\ + \ + {escaped}" + ) + .into_bytes() +} + +/// Serves one person's photo. Signed-in only — either through the session +/// cookie or as a registered OIDC app presenting HTTP Basic over +/// `client_id:client_secret`. +/// +/// A person with no photo gets the default face — the name's first letter +/// on a quiet tile, the same face im's own pages render — so an app's +/// `` shows a person, never a broken-image glyph. An unknown id gets +/// the same tile with a `?`, so an authenticated fetch still cannot tell a +/// missing person from a missing photo; only the missing credential reads +/// as the not-found. The tile answers `no-cache` (revalidating on its +/// ETag) where the photo answers `immutable`: apps fetch this URL without +/// the stamp im's own pages add, so a photo uploaded later must replace +/// the tile, and a year of `immutable` would pin the letter forever. +#[route(GET "/photo/{user_id}")] +async fn serve(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> { + if server::current_user(cx).await.is_none() && !server::valid_app(cx).await { + return Ok(not_found()); + } + let target = im_core::model::UserId::from(path_param::(cx).to_string()); + let store = server::app(cx).store.clone(); + if let Ok(Some((bytes, mime))) = photos::photo(&store, &target).await { + // The stamp in the URL is the other half of this caching: `upload` + // bumps it whenever the bytes change, so a year of `immutable` + // never shows an old photo — a changed photo is a changed URL. + // `private` because the route is session-gated. + return Ok(bytes_response( + cx, + bytes, + &mime, + "private, max-age=31536000, immutable", + )); + } + let initial = match im_core::accounts::user_by_id(&store, &target).await { + Ok(Some(user)) => user + .name + .chars() + .next() + .unwrap_or('?') + .to_uppercase() + .to_string(), + _ => "?".to_string(), + }; + Ok(bytes_response( + cx, + default_avatar(&initial), + "image/svg+xml", + "private, no-cache", + )) +} #[cfg(test)] mod tests { use std::path::Path; use std::sync::Arc; + use super::PhotoStamps; use im_core::accounts::{create_invite, create_user_from_invite}; use im_core::model::UserId; use im_core::oidc::create_client; @@ -230,7 +280,6 @@ mod tests { use topcoat::cookie::RouterBuilderCookieExt as _; use topcoat::router::{Body, HeaderMap, Router, RouterBuilderDiscoverExt as _, StatusCode}; use topcoat::router::{header, to_bytes}; - use super::PhotoStamps; use crate::config::Config; use crate::server::{self, SESSION_COOKIE}; @@ -248,9 +297,10 @@ mod tests { async fn setup() -> Setup { let store = Store::open(Path::new(":memory:")).await.unwrap(); - let (client_id, secret) = create_client(&store, "drive", vec!["http://app/callback".into()]) - .await - .unwrap(); + let (client_id, secret) = + create_client(&store, "drive", vec!["http://app/callback".into()]) + .await + .unwrap(); let invite = create_invite(&store, "ann@example.com", None, false) .await .unwrap(); @@ -334,10 +384,7 @@ mod tests { .await; assert_eq!(status, StatusCode::OK); assert_eq!(bytes, PHOTO); - assert_eq!( - headers.get(header::CONTENT_TYPE).unwrap(), - "image/png" - ); + assert_eq!(headers.get(header::CONTENT_TYPE).unwrap(), "image/png"); } #[tokio::test] @@ -390,31 +437,44 @@ mod tests { } #[tokio::test] - async fn app_credentials_unknown_user_is_not_found() { + async fn app_credentials_unknown_user_gets_the_unknown_avatar() { let setup = setup().await; - let (status, _, bytes) = get( + let (status, headers, bytes) = get( &setup.router, "no-such-user", Some(basic(&setup.client_id, &setup.secret)), None, ) .await; - assert_eq!(status, StatusCode::NOT_FOUND); - assert!(bytes.is_empty()); + assert_eq!(status, StatusCode::OK); + assert_eq!(headers.get(header::CONTENT_TYPE).unwrap(), "image/svg+xml"); + let body = String::from_utf8(bytes).unwrap(); + assert!(body.contains(">?<"), "unknown user gets the ? tile: {body}"); } #[tokio::test] - async fn app_credentials_missing_photo_is_not_found() { + async fn app_credentials_missing_photo_gets_the_initial_avatar() { let setup = setup().await; - let (status, _, bytes) = get( + let (status, headers, bytes) = get( &setup.router, setup.plain_id.as_str(), Some(basic(&setup.client_id, &setup.secret)), None, ) .await; - assert_eq!(status, StatusCode::NOT_FOUND); - assert!(bytes.is_empty()); + assert_eq!(status, StatusCode::OK); + assert_eq!(headers.get(header::CONTENT_TYPE).unwrap(), "image/svg+xml"); + // The tile revalidates instead of caching immutably: a photo + // uploaded later has to be able to replace it. + assert_eq!( + headers.get(header::CACHE_CONTROL).unwrap(), + "private, no-cache" + ); + let body = String::from_utf8(bytes).unwrap(); + assert!( + body.contains(">B<"), + "photoless Ben gets his initial: {body}" + ); } #[tokio::test]