A photoless profile answers the default face: the photo route renders the name's first letter on a quiet tile as SVG instead of the not-found, so an app's <img> never shows the broken-image glyph — an unknown id gets the same tile with a ?, keeping a missing person indistinguishable from a missing photo, and the tile revalidates on its ETag where the photo caches immutable, so a later upload still replaces it
Browse files at this commitbf2e05477e1cf1a04e509c5f40a89c797af1fa4aParent: 2f25e2c1 changed file +110 -50
- crates/im-web/src/photo.rs +110 -50
crates/im-web/src/photo.rsmodified+110 -50
| @@ -167,60 +167,110 @@ fn not_found() -> (StatusCode, HeaderMap, Vec<u8>) { | |||
| 167 | (StatusCode::NOT_FOUND, HeaderMap::new(), Vec::new()) | 167 | (StatusCode::NOT_FOUND, HeaderMap::new(), Vec::new()) |
| 168 | } | 168 | } |
| 169 | 169 | ||
| 170 | -/// Serves one person's photo. Signed-in only — either through the session | 170 | +/// The response for served bytes: the ETag and cache policy, the 304 when |
| 171 | -/// cookie or as a registered OIDC app presenting HTTP Basic over | 171 | +/// the caller's copy is already this one. |
| 172 | -/// `client_id:client_secret` — and a missing photo reads exactly like a | 172 | +fn bytes_response( |
| 173 | -/// missing person: the not-found, never a `403`. | 173 | + cx: &Cx, |
| 174 | -/// | 174 | + bytes: Vec<u8>, |
| 175 | -/// Apps count as signed-in viewers because registration is the trust: im | 175 | + content_type: &str, |
| 176 | -/// hands the client secret out exactly once, keeps only its digest, and the | 176 | + cache: &'static str, |
| 177 | -/// app presents it on every fetch. Unknown clients, wrong secrets, unknown | 177 | +) -> (StatusCode, HeaderMap, Vec<u8>) { |
| 178 | -/// users and missing photos all answer the same not-found, so no failure | ||
| 179 | -/// is distinguishable on the wire. | ||
| 180 | -#[route(GET "/photo/{user_id}")] | ||
| 181 | -async fn serve(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> { | ||
| 182 | - if server::current_user(cx).await.is_none() && !server::valid_app(cx).await { | ||
| 183 | - return Ok(not_found()); | ||
| 184 | - } | ||
| 185 | - let target = im_core::model::UserId::from(path_param::<UserId>(cx).to_string()); | ||
| 186 | - let store = server::app(cx).store.clone(); | ||
| 187 | - let Ok(Some((bytes, mime))) = photos::photo(&store, &target).await else { | ||
| 188 | - return Ok(not_found()); | ||
| 189 | - }; | ||
| 190 | - | ||
| 191 | let etag = format!("\"{:x}\"", fnv1a(&bytes)); | 178 | let etag = format!("\"{:x}\"", fnv1a(&bytes)); |
| 192 | let mut headers = HeaderMap::new(); | 179 | let mut headers = HeaderMap::new(); |
| 193 | headers.insert(header::ETAG, HeaderValue::from_str(&etag).unwrap()); | 180 | headers.insert(header::ETAG, HeaderValue::from_str(&etag).unwrap()); |
| 194 | - // The stamp in the URL is the other half of this caching: `upload` | 181 | + headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(cache)); |
| 195 | - // bumps it whenever the bytes change, so a year of `immutable` never | ||
| 196 | - // shows an old photo — a changed photo is a changed URL. `private` | ||
| 197 | - // because the route is session-gated. | ||
| 198 | - headers.insert( | ||
| 199 | - header::CACHE_CONTROL, | ||
| 200 | - HeaderValue::from_static("private, max-age=31536000, immutable"), | ||
| 201 | - ); | ||
| 202 | - | ||
| 203 | let if_none_match = request_headers(cx) | 182 | let if_none_match = request_headers(cx) |
| 204 | .get(header::IF_NONE_MATCH) | 183 | .get(header::IF_NONE_MATCH) |
| 205 | .and_then(|v| v.to_str().ok()); | 184 | .and_then(|v| v.to_str().ok()); |
| 206 | if if_none_match == Some(etag.as_str()) { | 185 | if if_none_match == Some(etag.as_str()) { |
| 207 | - return Ok((StatusCode::NOT_MODIFIED, headers, Vec::new())); | 186 | + return (StatusCode::NOT_MODIFIED, headers, Vec::new()); |
| 208 | } | 187 | } |
| 209 | - | ||
| 210 | headers.insert( | 188 | headers.insert( |
| 211 | header::CONTENT_TYPE, | 189 | header::CONTENT_TYPE, |
| 212 | - HeaderValue::from_str(&mime) | 190 | + HeaderValue::from_str(content_type) |
| 213 | .unwrap_or(HeaderValue::from_static("application/octet-stream")), | 191 | .unwrap_or(HeaderValue::from_static("application/octet-stream")), |
| 214 | ); | 192 | ); |
| 215 | - Ok((StatusCode::OK, headers, bytes)) | 193 | + (StatusCode::OK, headers, bytes) |
| 216 | } | 194 | } |
| 217 | 195 | ||
| 196 | +/// The default face, as an image: the name's first letter on a quiet tile — | ||
| 197 | +/// the same answer im's own pages give a photoless profile (the initial span | ||
| 198 | +/// in `layout::avatar`), rendered to SVG so an app's `<img>` can carry it. | ||
| 199 | +/// The colors are fixed (mid tile, light letter) because the tile ships to | ||
| 200 | +/// apps whose themes im does not know. | ||
| 201 | +fn default_avatar(initial: &str) -> Vec<u8> { | ||
| 202 | + // The initial is one character off a name, but escape anyway: nothing | ||
| 203 | + // stops a name from starting with `&`, `<`, or `>`. | ||
| 204 | + let escaped = initial | ||
| 205 | + .replace('&', "&") | ||
| 206 | + .replace('<', "<") | ||
| 207 | + .replace('>', ">"); | ||
| 208 | + format!( | ||
| 209 | + "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 96 96\">\ | ||
| 210 | + <rect width=\"96\" height=\"96\" rx=\"6\" fill=\"#3a3f47\"/>\ | ||
| 211 | + <text x=\"48\" y=\"48\" dy=\"0.35em\" text-anchor=\"middle\" \ | ||
| 212 | + font-family=\"ui-monospace, monospace\" font-size=\"40\" \ | ||
| 213 | + fill=\"#9aa1ab\">{escaped}</text></svg>" | ||
| 214 | + ) | ||
| 215 | + .into_bytes() | ||
| 216 | +} | ||
| 217 | + | ||
| 218 | +/// Serves one person's photo. Signed-in only — either through the session | ||
| 219 | +/// cookie or as a registered OIDC app presenting HTTP Basic over | ||
| 220 | +/// `client_id:client_secret`. | ||
| 221 | +/// | ||
| 222 | +/// A person with no photo gets the default face — the name's first letter | ||
| 223 | +/// on a quiet tile, the same face im's own pages render — so an app's | ||
| 224 | +/// `<img>` shows a person, never a broken-image glyph. An unknown id gets | ||
| 225 | +/// the same tile with a `?`, so an authenticated fetch still cannot tell a | ||
| 226 | +/// missing person from a missing photo; only the missing credential reads | ||
| 227 | +/// as the not-found. The tile answers `no-cache` (revalidating on its | ||
| 228 | +/// ETag) where the photo answers `immutable`: apps fetch this URL without | ||
| 229 | +/// the stamp im's own pages add, so a photo uploaded later must replace | ||
| 230 | +/// the tile, and a year of `immutable` would pin the letter forever. | ||
| 231 | +#[route(GET "/photo/{user_id}")] | ||
| 232 | +async fn serve(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> { | ||
| 233 | + if server::current_user(cx).await.is_none() && !server::valid_app(cx).await { | ||
| 234 | + return Ok(not_found()); | ||
| 235 | + } | ||
| 236 | + let target = im_core::model::UserId::from(path_param::<UserId>(cx).to_string()); | ||
| 237 | + let store = server::app(cx).store.clone(); | ||
| 238 | + if let Ok(Some((bytes, mime))) = photos::photo(&store, &target).await { | ||
| 239 | + // The stamp in the URL is the other half of this caching: `upload` | ||
| 240 | + // bumps it whenever the bytes change, so a year of `immutable` | ||
| 241 | + // never shows an old photo — a changed photo is a changed URL. | ||
| 242 | + // `private` because the route is session-gated. | ||
| 243 | + return Ok(bytes_response( | ||
| 244 | + cx, | ||
| 245 | + bytes, | ||
| 246 | + &mime, | ||
| 247 | + "private, max-age=31536000, immutable", | ||
| 248 | + )); | ||
| 249 | + } | ||
| 250 | + let initial = match im_core::accounts::user_by_id(&store, &target).await { | ||
| 251 | + Ok(Some(user)) => user | ||
| 252 | + .name | ||
| 253 | + .chars() | ||
| 254 | + .next() | ||
| 255 | + .unwrap_or('?') | ||
| 256 | + .to_uppercase() | ||
| 257 | + .to_string(), | ||
| 258 | + _ => "?".to_string(), | ||
| 259 | + }; | ||
| 260 | + Ok(bytes_response( | ||
| 261 | + cx, | ||
| 262 | + default_avatar(&initial), | ||
| 263 | + "image/svg+xml", | ||
| 264 | + "private, no-cache", | ||
| 265 | + )) | ||
| 266 | +} | ||
| 218 | 267 | ||
| 219 | #[cfg(test)] | 268 | #[cfg(test)] |
| 220 | mod tests { | 269 | mod tests { |
| 221 | use std::path::Path; | 270 | use std::path::Path; |
| 222 | use std::sync::Arc; | 271 | use std::sync::Arc; |
| 223 | 272 | ||
| 273 | + use super::PhotoStamps; | ||
| 224 | use im_core::accounts::{create_invite, create_user_from_invite}; | 274 | use im_core::accounts::{create_invite, create_user_from_invite}; |
| 225 | use im_core::model::UserId; | 275 | use im_core::model::UserId; |
| 226 | use im_core::oidc::create_client; | 276 | use im_core::oidc::create_client; |
| @@ -230,7 +280,6 @@ mod tests { | |||
| 230 | use topcoat::cookie::RouterBuilderCookieExt as _; | 280 | use topcoat::cookie::RouterBuilderCookieExt as _; |
| 231 | use topcoat::router::{Body, HeaderMap, Router, RouterBuilderDiscoverExt as _, StatusCode}; | 281 | use topcoat::router::{Body, HeaderMap, Router, RouterBuilderDiscoverExt as _, StatusCode}; |
| 232 | use topcoat::router::{header, to_bytes}; | 282 | use topcoat::router::{header, to_bytes}; |
| 233 | - use super::PhotoStamps; | ||
| 234 | 283 | ||
| 235 | use crate::config::Config; | 284 | use crate::config::Config; |
| 236 | use crate::server::{self, SESSION_COOKIE}; | 285 | use crate::server::{self, SESSION_COOKIE}; |
| @@ -248,9 +297,10 @@ mod tests { | |||
| 248 | 297 | ||
| 249 | async fn setup() -> Setup { | 298 | async fn setup() -> Setup { |
| 250 | let store = Store::open(Path::new(":memory:")).await.unwrap(); | 299 | let store = Store::open(Path::new(":memory:")).await.unwrap(); |
| 251 | - let (client_id, secret) = create_client(&store, "drive", vec!["http://app/callback".into()]) | 300 | + let (client_id, secret) = |
| 252 | - .await | 301 | + create_client(&store, "drive", vec!["http://app/callback".into()]) |
| 253 | - .unwrap(); | 302 | + .await |
| 303 | + .unwrap(); | ||
| 254 | let invite = create_invite(&store, "ann@example.com", None, false) | 304 | let invite = create_invite(&store, "ann@example.com", None, false) |
| 255 | .await | 305 | .await |
| 256 | .unwrap(); | 306 | .unwrap(); |
| @@ -334,10 +384,7 @@ mod tests { | |||
| 334 | .await; | 384 | .await; |
| 335 | assert_eq!(status, StatusCode::OK); | 385 | assert_eq!(status, StatusCode::OK); |
| 336 | assert_eq!(bytes, PHOTO); | 386 | assert_eq!(bytes, PHOTO); |
| 337 | - assert_eq!( | 387 | + assert_eq!(headers.get(header::CONTENT_TYPE).unwrap(), "image/png"); |
| 338 | - headers.get(header::CONTENT_TYPE).unwrap(), | ||
| 339 | - "image/png" | ||
| 340 | - ); | ||
| 341 | } | 388 | } |
| 342 | 389 | ||
| 343 | #[tokio::test] | 390 | #[tokio::test] |
| @@ -390,31 +437,44 @@ mod tests { | |||
| 390 | } | 437 | } |
| 391 | 438 | ||
| 392 | #[tokio::test] | 439 | #[tokio::test] |
| 393 | - async fn app_credentials_unknown_user_is_not_found() { | 440 | + async fn app_credentials_unknown_user_gets_the_unknown_avatar() { |
| 394 | let setup = setup().await; | 441 | let setup = setup().await; |
| 395 | - let (status, _, bytes) = get( | 442 | + let (status, headers, bytes) = get( |
| 396 | &setup.router, | 443 | &setup.router, |
| 397 | "no-such-user", | 444 | "no-such-user", |
| 398 | Some(basic(&setup.client_id, &setup.secret)), | 445 | Some(basic(&setup.client_id, &setup.secret)), |
| 399 | None, | 446 | None, |
| 400 | ) | 447 | ) |
| 401 | .await; | 448 | .await; |
| 402 | - assert_eq!(status, StatusCode::NOT_FOUND); | 449 | + assert_eq!(status, StatusCode::OK); |
| 403 | - assert!(bytes.is_empty()); | 450 | + assert_eq!(headers.get(header::CONTENT_TYPE).unwrap(), "image/svg+xml"); |
| 451 | + let body = String::from_utf8(bytes).unwrap(); | ||
| 452 | + assert!(body.contains(">?<"), "unknown user gets the ? tile: {body}"); | ||
| 404 | } | 453 | } |
| 405 | 454 | ||
| 406 | #[tokio::test] | 455 | #[tokio::test] |
| 407 | - async fn app_credentials_missing_photo_is_not_found() { | 456 | + async fn app_credentials_missing_photo_gets_the_initial_avatar() { |
| 408 | let setup = setup().await; | 457 | let setup = setup().await; |
| 409 | - let (status, _, bytes) = get( | 458 | + let (status, headers, bytes) = get( |
| 410 | &setup.router, | 459 | &setup.router, |
| 411 | setup.plain_id.as_str(), | 460 | setup.plain_id.as_str(), |
| 412 | Some(basic(&setup.client_id, &setup.secret)), | 461 | Some(basic(&setup.client_id, &setup.secret)), |
| 413 | None, | 462 | None, |
| 414 | ) | 463 | ) |
| 415 | .await; | 464 | .await; |
| 416 | - assert_eq!(status, StatusCode::NOT_FOUND); | 465 | + assert_eq!(status, StatusCode::OK); |
| 417 | - assert!(bytes.is_empty()); | 466 | + assert_eq!(headers.get(header::CONTENT_TYPE).unwrap(), "image/svg+xml"); |
| 467 | + // The tile revalidates instead of caching immutably: a photo | ||
| 468 | + // uploaded later has to be able to replace it. | ||
| 469 | + assert_eq!( | ||
| 470 | + headers.get(header::CACHE_CONTROL).unwrap(), | ||
| 471 | + "private, no-cache" | ||
| 472 | + ); | ||
| 473 | + let body = String::from_utf8(bytes).unwrap(); | ||
| 474 | + assert!( | ||
| 475 | + body.contains(">B<"), | ||
| 476 | + "photoless Ben gets his initial: {body}" | ||
| 477 | + ); | ||
| 418 | } | 478 | } |
| 419 | 479 | ||
| 420 | #[tokio::test] | 480 | #[tokio::test] |