diff --git a/crates/in-client/src/lib.rs b/crates/in-client/src/lib.rs index 7d14240..7b55400 100644 --- a/crates/in-client/src/lib.rs +++ b/crates/in-client/src/lib.rs @@ -117,6 +117,36 @@ pub async fn current_user(cx: &Cx) -> Option { } } +/// The person's profile photo from im, if im has one. `None` on 404 and on +/// anything else that is not the bytes — a dropped connection, a body that +/// will not read, a reply without a mime — because a missing face must never +/// fail the page around it: the caller renders its initials instead. +/// +/// Authenticated as the app, not the browser: `Authorization: Basic +/// base64(client_id ":" client_secret)` against im's `/photo/{user_id}`, +/// the same credentials the introspection round-trip posts with. +pub async fn photo_for(cx: &Cx, user_id: &str) -> Option<(Vec, String)> { + let state = client(cx); + let reply = state + .http + .get(format!("{}/photo/{user_id}", state.config.issuer)) + .basic_auth(&state.config.client_id, Some(&state.config.client_secret)) + .send() + .await + .ok()?; + if !reply.status().is_success() { + return None; + } + let mime = reply + .headers() + .get(reqwest::header::CONTENT_TYPE)? + .to_str() + .ok()? + .to_string(); + let bytes = reply.bytes().await.ok()?.to_vec(); + Some((bytes, mime)) +} + /// Path of im's RFC 7662 introspection endpoint, relative to the issuer. const INTROSPECT_PATH: &str = "/introspect"; diff --git a/crates/in-web/src/avatar.rs b/crates/in-web/src/avatar.rs new file mode 100644 index 0000000..eaddb34 --- /dev/null +++ b/crates/in-web/src/avatar.rs @@ -0,0 +1,69 @@ +//! The signed-in person's face, proxied from im. +//! +//! `GET /avatar/{user_id}` answers with im's photo bytes for the caller's own +//! id — anything else (another id, no photo, im unreachable) is the same 404, +//! and a browser without a session is refused outright. Served with the same +//! fnv1a ETag + immutable cache as im's own photo route, so the topbar's +//! `` revalidates rather than refetches. + +use topcoat::context::Cx; +use topcoat::router::request::headers as request_headers; +use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, path_param, route}; +use crate::server::require_user; + +path_param!(user_id); + +fn not_found() -> (StatusCode, HeaderMap, Vec) { + (StatusCode::NOT_FOUND, HeaderMap::new(), Vec::new()) +} + +/// `GET /avatar/{user_id}`: im's photo for the caller, or the same not-found +/// a stranger would see — never a `403`, which would confirm the id belongs +/// to somebody else's account. +#[route(GET "/avatar/{user_id}")] +async fn avatar(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> { + let target: &str = path_param::(cx); + + let user = match require_user(cx).await { + Ok(user) => user, + // An `` has no page to carry a refusal on; 401 names the fix + // the way the live channel's does. + Err(_) => return Ok((StatusCode::UNAUTHORIZED, HeaderMap::new(), Vec::new())), + }; + // v1: one's own face only — anyone else's id reads exactly like no + // photo, so one account's face can never be probed through another's. + if target != user.id { + return Ok(not_found()); + } + let Some((bytes, mime)) = in_client::photo_for(cx, target).await else { + return Ok(not_found()); + }; + + let etag = format!("\"{:x}\"", crate::files::fnv1a(&bytes)); + let mut headers = HeaderMap::new(); + headers.insert( + header::ETAG, + HeaderValue::from_str(&etag).unwrap_or(HeaderValue::from_static("\"0\"")), + ); + // The bytes are im's to version and this URL carries no stamp of its + // own, so a changed photo may take up to a year to show — the price of + // proxying without a stamp channel, and the same trade the thumbnail + // route already makes. `private` because the route is gated and a shared + // proxy must not answer a stranger from another account's entry. + headers.insert( + header::CACHE_CONTROL, + HeaderValue::from_static("private, max-age=31536000, immutable"), + ); + headers.insert( + header::CONTENT_TYPE, + HeaderValue::from_str(&mime).unwrap_or(HeaderValue::from_static("application/octet-stream")), + ); + + let if_none_match = request_headers(cx) + .get(header::IF_NONE_MATCH) + .and_then(|value| value.to_str().ok()); + if if_none_match == Some(etag.as_str()) { + return Ok((StatusCode::NOT_MODIFIED, headers, Vec::new())); + } + Ok((StatusCode::OK, headers, bytes)) +} diff --git a/crates/in-web/src/drive.rs b/crates/in-web/src/drive.rs index 65b2183..c4ec3c8 100644 --- a/crates/in-web/src/drive.rs +++ b/crates/in-web/src/drive.rs @@ -149,7 +149,7 @@ fn human_size(bytes: u64) -> String { } } fn page_refusal(cx: &Cx) -> Option { - ["create", "rename", "move", "delete", "upload"] + ["rename", "move", "delete", "upload"] .iter() .find_map(|call| refusal_of(cx, call)) } @@ -204,6 +204,10 @@ async fn drive(cx: &Cx) -> Result { }; let destinations = folder_tree(store.as_ref(), &user.id).await; let refusal = page_refusal(cx); + // The create-folder answer belongs to the modal, not the page line: a + // refused create reopens it with the sentence inside, iz's confirm idiom. + let create_refusal = refusal_of(cx, "create"); + let create_open = create_refusal.is_some(); // A link minted from this surface redirects back here with the plaintext // token on `?created=` — rendered once, like the settings page does. let created = created_token(uri(cx).query().unwrap_or("")); @@ -247,14 +251,26 @@ async fn drive(cx: &Cx) -> Result { aria-label=(t(language, Key::SearchPlaceholder)) > -
- (t(language, Key::NewFolder)) -
- - - -
+
+ "+ "(t(language, Key::NewFolder)) +
+
(t(language, Key::NewFolder))
+
+ + +
+
+ +
+ if let Some(refusal) = create_refusal { + + } +
+
if let Some(refusal) = refusal { diff --git a/crates/in-web/src/layout.rs b/crates/in-web/src/layout.rs index 60bc52b..a300fc5 100644 --- a/crates/in-web/src/layout.rs +++ b/crates/in-web/src/layout.rs @@ -75,8 +75,12 @@ pub(crate) async fn wordmark(cx: &Cx) -> Result { } /// A person as a circle (or, on the Instrument skin, a square): the initials, -/// toned by the id so every account has its own colour. Shared by the -/// topbar user menu on every signed-in page. +/// toned by the id so every account has its own colour, with the im photo +/// over it when im has one. Whether im has one is not known cheaply — the +/// photo is the app's credentialed fetch, not the browser's — so the `` +/// always renders and hides itself on error (see `avatar_script`), leaving +/// the initials beneath as the fallback. Shared by the topbar user menu on +/// every signed-in page. pub(crate) async fn avatar(cx: &Cx, user: &User, extra: &str) -> Result { let tone = user .id @@ -86,12 +90,44 @@ pub(crate) async fn avatar(cx: &Cx, user: &User, extra: &str) -> Result { let class = format!("avatar avatar-tone-{tone} {extra}"); let name = user.display_name.clone(); let initials = initials_of(&user.display_name); + let src = format!("/avatar/{}", user.id); view! { cx => - (initials) + + (initials) + + } } +/// The photo half's client half: a missing photo must fall back to the +/// initials beneath it, and a bare `` to a 404 shows the broken-image +/// box instead. One document-level capture `error` listener hides every +/// `img.avatar-photo` that fails, plus a sweep for the ones already failed +/// before it ran; hiding is registered through `__inOwn` so the live morph +/// — which owns no names, only what the client declares — does not strip it +/// back off on the next refresh. +pub async fn avatar_script(cx: &Cx) -> Result { + use topcoat::view::Unescaped; + const JS: &str = "\ + (function () { \ + if (window.__inAvatar) { return; } \ + window.__inAvatar = true; \ + function hide(img) { \ + if (window.__inOwn) { window.__inOwn(img, [], ['style']); } \ + img.style.display = 'none'; \ + } \ + document.addEventListener('error', function (e) { \ + var img = e.target && e.target.closest ? e.target.closest('img.avatar-photo') : null; \ + if (img) { hide(img); } \ + }, true); \ + document.querySelectorAll('img.avatar-photo').forEach(function (img) { \ + if (img.complete && img.naturalWidth === 0) { hide(img); } \ + }); \ + })();"; + view! { cx => } +} + /// The first letters of the first two words, uppercased — "Ada Lovelace" /// wears "AL", a bare address wears its first letter. fn initials_of(name: &str) -> String { @@ -195,6 +231,7 @@ pub async fn topbar(cx: &Cx, active: NavPage, user: &User, lang: Lang) -> Result (topbar_nav(cx, active, lang).await?) (user_menu(cx, user, lang).await?) + (avatar_script(cx).await?) } } diff --git a/crates/in-web/src/lib.rs b/crates/in-web/src/lib.rs index 8013183..78115a5 100644 --- a/crates/in-web/src/lib.rs +++ b/crates/in-web/src/lib.rs @@ -3,6 +3,7 @@ // first overflow. #![recursion_limit = "256"] +pub mod avatar; pub mod drive; pub mod dropdown; pub mod files; diff --git a/crates/in-web/tests/http.rs b/crates/in-web/tests/http.rs index 3049d4f..b6cfe2d 100644 --- a/crates/in-web/tests/http.rs +++ b/crates/in-web/tests/http.rs @@ -41,6 +41,7 @@ fn asset_dir() -> PathBuf { struct FakeIm { addr: std::net::SocketAddr, tokens: Arc>>, + photos: Arc, String)>>>, } impl FakeIm { @@ -49,13 +50,17 @@ impl FakeIm { let addr = listener.local_addr().unwrap(); let tokens: Arc>> = Arc::new(Mutex::new(HashMap::new())); + let photos: Arc, String)>>> = + Arc::new(Mutex::new(HashMap::new())); let map = tokens.clone(); + let pmap = photos.clone(); tokio::spawn(async move { loop { let Ok((socket, _)) = listener.accept().await else { return; }; let map = map.clone(); + let pmap = pmap.clone(); tokio::spawn(async move { use tokio::io::{AsyncReadExt, AsyncWriteExt}; let mut socket = socket; @@ -92,10 +97,22 @@ impl FakeIm { let len = content_length(&head); let body: Vec = req[body_start..body_start + len].to_vec(); req.drain(..body_start + len); - let answer = answer_for(&map, &first, &body); - let payload = serde_json::to_vec(&answer).unwrap(); + let (status, content_type, payload) = match photo_answer(&pmap, &head, &first) { + Some(photo) => photo, + None => match answer_for(&map, &first, &body) { + Some(answer) => ( + "200 OK", + "application/json".to_string(), + serde_json::to_vec(&answer).unwrap(), + ), + // Anything but the introspection route is + // nothing at all, the way the real im 404s + // unknown paths rather than answering them. + None => ("404 Not Found", "text/plain".to_string(), Vec::new()), + }, + }; let response = format!( - "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\r\n", + "HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\n\r\n", payload.len() ); if socket.write_all(response.as_bytes()).await.is_err() { @@ -108,12 +125,57 @@ impl FakeIm { }); } }); - Self { addr, tokens } + Self { addr, tokens, photos } } fn url(&self) -> String { format!("http://{}", self.addr) } + + /// Stores the photo `GET /photo/{user_id}` answers with — the bytes and + /// the mime im would serve for this account. + fn set_photo(&self, user_id: &str, bytes: Vec, mime: &str) { + self.photos + .lock() + .unwrap() + .insert(user_id.to_string(), (bytes, mime.to_string())); + } +} + +/// The Basic credential the app presents for `GET /photo/*`: `in-test:s3cr3t`. +const PHOTO_BASIC: &str = "Basic aW4tdGVzdDpzM2NyM3Q="; + +/// Answers `GET /photo/{id}` from the photo map — the app's Basic credential +/// or nothing, a missing photo exactly like a missing person. `None` for +/// anything else, which stays the introspection JSON. +fn photo_answer( + photos: &Arc, String)>>>, + head: &str, + request_line: &str, +) -> Option<(&'static str, String, Vec)> { + let mut parts = request_line.split_whitespace(); + if parts.next() != Some("GET") { + return None; + } + let target = parts.next().unwrap_or(""); + let path = target.split_once('?').map(|(path, _)| path).unwrap_or(target); + let id = path.strip_prefix("/photo/")?; + if id.is_empty() || id.contains('/') { + return None; + } + let authed = head + .lines() + .filter_map(|line| line.split_once(':')) + .any(|(name, value)| { + name.trim().eq_ignore_ascii_case("authorization") && value.trim() == PHOTO_BASIC + }); + if !authed { + return Some(("404 Not Found", "text/plain".to_string(), Vec::new())); + } + match photos.lock().unwrap().get(id) { + Some((bytes, mime)) => Some(("200 OK", mime.clone(), bytes.clone())), + None => Some(("404 Not Found", "text/plain".to_string(), Vec::new())), + } } fn headers_end(req: &[u8]) -> Option { @@ -150,16 +212,15 @@ fn decode(raw: &str) -> String { } out } - fn answer_for( map: &Arc>>, request_line: &str, body: &[u8], -) -> serde_json::Value { +) -> Option { let mut head = request_line.split_whitespace(); let is_introspect = head.next() == Some("POST") && head.next() == Some(in_client::introspect_path()); if !is_introspect { - return serde_json::json!({"active": false}); + return None; } let text = String::from_utf8_lossy(body).to_string(); let token = text @@ -168,8 +229,8 @@ fn answer_for( .find(|(name, _)| *name == "token") .map(|(_, value)| decode(value)); match token.and_then(|token| map.lock().unwrap().get(&token).cloned()) { - Some(claims) => claims, - None => serde_json::json!({"active": false}), + Some(claims) => Some(claims), + None => Some(serde_json::json!({"active": false})), } } @@ -2421,3 +2482,135 @@ async fn settings_lives_in_the_user_menu_not_the_topbar() { let issuer = format!("href=\"{}/\"", app.config.oidc.issuer); assert!(menu.contains(&issuer), "no profile link to the issuer: {menu}"); } + +#[tokio::test] +async fn avatar_serves_own_photo_with_etag() { + let app = TestApp::build().await; + let cookie = app.sign_in("sub-face", "face@in.test", "Face").await; + let me = owner_of(&app, "sub-face").await; + app.fake.set_photo(&me, tiny_png(), "image/png"); + + let face = app.get(&format!("/avatar/{me}"), Some(&cookie)).await; + assert_eq!(face.status, StatusCode::OK); + assert_eq!(face.content_type.as_deref(), Some("image/png")); + assert_eq!( + face.cache_control.as_deref(), + Some("private, max-age=31536000, immutable") + ); + assert_eq!(face.bytes, tiny_png()); + + let etag = face.etag.clone().expect("no etag on the avatar"); + let cached = app + .get_with_if_none_match(&format!("/avatar/{me}"), Some(&cookie), &etag) + .await; + assert_eq!(cached.status, StatusCode::NOT_MODIFIED); + assert!(cached.bytes.is_empty()); + + // The user menu wears the photo over the initials, with the fallback script. + let page = app.get("/drive", Some(&cookie)).await; + assert_eq!(page.status, StatusCode::OK); + let body = page.text(); + assert!( + body.contains(&format!("src=\"/avatar/{me}\"")), + "menu wears no photo img" + ); + assert!(body.contains("avatar-stack"), "no initials stack under the photo"); + assert!(body.contains("__inAvatar"), "no avatar fallback script"); +} + +#[tokio::test] +async fn avatar_without_photo_is_not_found() { + let app = TestApp::build().await; + let cookie = app.sign_in("sub-noface", "noface@in.test", "NoFace").await; + let me = owner_of(&app, "sub-noface").await; + + let face = app.get(&format!("/avatar/{me}"), Some(&cookie)).await; + assert_eq!(face.status, StatusCode::NOT_FOUND); + assert!(face.bytes.is_empty()); +} + +#[tokio::test] +async fn avatar_for_someone_else_is_not_found() { + let app = TestApp::build().await; + let alice = app.sign_in("sub-alice-face", "alice@in.test", "Alice").await; + let bob = app.sign_in("sub-bob-face", "bob@in.test", "Bob").await; + let bob_id = owner_of(&app, "sub-bob-face").await; + app.fake.set_photo(&bob_id, tiny_png(), "image/png"); + + // Bob's face through Alice's session: the same 404 as no photo at all, + // never a hint that Bob has one. + let face = app.get(&format!("/avatar/{bob_id}"), Some(&alice)).await; + assert_eq!(face.status, StatusCode::NOT_FOUND); + assert!(face.bytes.is_empty()); + + // And an id that names nobody at all. + let ghost = app + .get("/avatar/00000000000000000000000000", Some(&alice)) + .await; + assert_eq!(ghost.status, StatusCode::NOT_FOUND); + + // Bob himself still sees his own. + let own = app.get(&format!("/avatar/{bob_id}"), Some(&bob)).await; + assert_eq!(own.status, StatusCode::OK); + assert_eq!(own.bytes, tiny_png()); +} + +#[tokio::test] +async fn avatar_without_session_is_unauthorized() { + let app = TestApp::build().await; + let face = app.get("/avatar/anyone", None).await; + assert_eq!(face.status, StatusCode::UNAUTHORIZED); +} + +#[tokio::test] +async fn drive_new_folder_rides_a_confirm_modal() { + let app = TestApp::build().await; + let cookie = app.sign_in("sub-newfolder", "newfolder@in.test", "NewFolder").await; + + let page = app.get("/drive", Some(&cookie)).await; + assert_eq!(page.status, StatusCode::OK); + let body = page.text(); + + // The filterbar carries the confirm modal, not the old disclosure box. + assert!(body.contains("confirm-details"), "no confirm modal on the drive"); + assert!(!body.contains("tag-new"), "old disclosure box still rendered"); + let details_at = body.find("confirm-details").expect("no confirm modal"); + let details_end = body[details_at..].find("
").expect("modal never closes"); + let details = &body[details_at..details_at + details_end]; + assert!( + details.contains("action=\"/api/folder/create\""), + "create form escapes the modal: {details}" + ); + assert!(details.contains("name=\"parent_id\""), "no parent field: {details}"); + assert!(details.contains("name=\"name\""), "no name field: {details}"); + assert!(details.contains("Create folder"), "no submit: {details}"); + + // Creating through the POST still lands. + let answer = app + .post("/api/folder/create", Some(&cookie), &[("parent_id", ""), ("name", "dup")]) + .await; + assert!(answer.accepted(), "clean create refused: {:?}", answer.location); + + // A refused create reopens the modal with the sentence inside — and only there. + let answer = app + .post("/api/folder/create", Some(&cookie), &[("parent_id", ""), ("name", "dup")]) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER); + assert!( + answer.body.contains("NameTaken"), + "dupe was not refused: {}", + answer.body + ); + let page = app.get("/drive?refusal=name-taken&on=create", Some(&cookie)).await; + assert_eq!(page.status, StatusCode::OK); + let body = page.text(); + assert!( + body.contains("
* { grid-area: 1 / 1; } + > .avatar + .avatar { margin-left: 0; } +} + // The avatar leads the profile panel. Without a photo it is itself the // upload control — the file input rides its `form` attribute to a hidden // sibling form, so nothing nests inside the profile form. With one, the