//! Page: profile (`/settings/profile`). Username capitalization, avatar upload and removal, //! the "about" text and the timezone. Every POST checks the CSRF token first. use forge_core::AuditAction; use forge_core::names::capitalization_change; use forge_core::tz::{all_timezones, validate_timezone}; use forge_core::{Session, Store, User, avatar::MAX_UPLOAD_BYTES, avatar::process_avatar}; use serde::Deserialize; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; use topcoat::router::content::multipart::Multipart; use topcoat::router::error::{SeeOther, see_other}; use topcoat::router::{BodyLimit, page, query_params, route}; use topcoat::view::{View, component, view}; use crate::audit::{self, Actor, Target}; use crate::auth::{require_csrf, require_user}; use crate::i18n::{self, Key, Lang, about_too_long, t}; use crate::state::AppState; use crate::views::{alert, avatar_url, shell, user_facing_message}; /// Longest "about" text, in characters. pub const MAX_ABOUT_CHARS: usize = 2000; /// Multipart framing overhead allowed on top of the image itself. const MULTIPART_OVERHEAD: usize = 64 * 1024; /// Body limit for the avatar upload route. The default 2 MiB is too small for a 5 MiB image. pub fn avatar_body_limit() -> BodyLimit { BodyLimit::max(MAX_UPLOAD_BYTES + MULTIPART_OVERHEAD).at("/settings/profile/avatar") } #[query_params(error = bad_request)] struct ProfileQuery { saved: Option, } #[derive(Deserialize)] struct ProfileForm { #[serde(default)] csrf: String, #[serde(default)] username: String, } #[derive(Deserialize)] struct DetailsForm { #[serde(default)] csrf: String, #[serde(default)] about: String, #[serde(default)] timezone: String, } #[derive(Deserialize)] struct CsrfForm { #[serde(default)] csrf: String, } /// Values shown in the forms. On a failed POST these are what the user typed. struct Draft { username: String, about: String, timezone: String, } impl Draft { fn from_user(user: &User) -> Self { Self { username: user.username.clone(), about: user.about.clone(), timezone: user.timezone.clone(), } } } /// Per-section error messages. #[derive(Default)] struct Errors { username: Option, avatar: Option, details: Option, } struct Zone { name: String, selected: bool, } struct ProfilePage { lang: Lang, csrf: String, current: String, draft: Draft, errors: Errors, notice: Option<&'static str>, avatar_src: String, has_avatar: bool, zones: Vec, } #[component] async fn profile_body(page: ProfilePage) -> Result { let ProfilePage { lang, csrf, current, draft, errors, notice, avatar_src, has_avatar, zones, } = page; Ok(view! {

(t(lang, Key::Profile))

if let Some(message) = notice {

(message)

}

(t(lang, Key::Username))

(t(lang, Key::CurrentUsername)) (current.as_str())

if let Some(message) = errors.username { alert(message: message.as_str()) }

(t(lang, Key::Avatar))

(t(lang,
if let Some(message) = errors.avatar { alert(message: message.as_str()) }
if has_avatar {
}

(t(lang, Key::AboutAndTimezone))

if let Some(message) = errors.details { alert(message: message.as_str()) }
}) } /// Collects what the profile page shows. `draft` fills the forms; `errors` shows under each section. async fn page_data( viewer: &(User, Session), lang: Lang, draft: Draft, errors: Errors, notice: Option<&'static str>, ) -> Result { let hash = viewer.0.avatar_hash.clone(); let zones = all_timezones() .into_iter() .map(|name| { let selected = name == draft.timezone; Zone { name, selected } }) .collect(); Ok(ProfilePage { lang, csrf: viewer.1.csrf_token.clone(), current: viewer.0.username.clone(), draft, errors, notice, avatar_src: avatar_url(&viewer.0.username, hash.as_deref()), has_avatar: hash.is_some(), zones, }) } fn notice_for(lang: Lang, saved: Option<&str>) -> Option<&'static str> { match saved { Some("1") => Some(t(lang, Key::OkUsernameUpdated)), Some("avatar") => Some(t(lang, Key::OkAvatarUpdated)), Some("avatar-removed") => Some(t(lang, Key::OkAvatarRemoved)), Some("details") => Some(t(lang, Key::OkProfileSaved)), _ => None, } } /// Checks the "about" length and the timezone name. Returns the message-carrying error. fn check_details(lang: Lang, about: &str, timezone: &str) -> forge_core::Result<()> { if about.chars().count() > MAX_ABOUT_CHARS { return Err(forge_core::Error::Invalid(about_too_long( lang, MAX_ABOUT_CHARS, ))); } validate_timezone(timezone) } /// Stores a processed avatar, or removes it if no image was sent. async fn store_avatar( store: &Store, user_id: &str, image: Option>, lang: Lang, ) -> forge_core::Result<()> { let Some(bytes) = image else { return Err(forge_core::Error::Invalid( t(lang, Key::ErrChooseImage).into(), )); }; // Decoding and resizing are CPU-bound; keep them off the async workers. let joined = tokio::task::spawn_blocking(move || process_avatar(&bytes)).await; let processed = joined.map_err(std::io::Error::other)??; store .set_avatar(user_id, &processed.png, &processed.hash) .await } #[page("/settings/profile")] async fn profile_page(cx: &Cx) -> Result { let viewer = require_user(cx).await?; let lang = i18n::lang(cx, Some(&viewer.0)); let saved = query_params::(cx)?.saved.clone(); let draft = Draft::from_user(&viewer.0); let page = page_data( &viewer, lang, draft, Errors::default(), notice_for(lang, saved.as_deref()), ) .await?; Ok(view! { shell(title: "Profile", viewer: Some(&viewer), profile_body(page: page)) }) } #[page(POST "/settings/profile")] async fn profile_save(cx: &Cx, Form(form): Form) -> Result { let viewer = require_csrf(cx, &form.csrf).await?; let lang = i18n::lang(cx, Some(&viewer.0)); let store = &app_context::(cx).store; let result = match capitalization_change(&viewer.0.username, &form.username) { Ok(display) => store.set_username_display(&viewer.0.id, &display).await, Err(e) => Err(e), }; let message = match result { Ok(()) => { audit::record( store, Some(cx), Actor::User(&viewer.0), AuditAction::UsernameChanged, Target { kind: "user", id: &viewer.0.id, name: form.username.trim(), }, serde_json::json!({ "from": viewer.0.username }), ) .await; return Err(see_other("/settings/profile?saved=1").into()); } Err(e) => match user_facing_message(&e) { Some(message) => message, None => return Err(e.into()), }, }; let draft = Draft { username: form.username, ..Draft::from_user(&viewer.0) }; let errors = Errors { username: Some(message), ..Errors::default() }; let page = page_data(&viewer, lang, draft, errors, None).await?; Ok(view! { shell(title: "Profile", viewer: Some(&viewer), profile_body(page: page)) }) } #[page(POST "/settings/profile/details")] async fn details_save(cx: &Cx, Form(form): Form) -> Result { let viewer = require_csrf(cx, &form.csrf).await?; let store = &app_context::(cx).store; let lang = i18n::lang(cx, Some(&viewer.0)); let about = form.about.replace("\r\n", "\n"); let result = match check_details(lang, &about, &form.timezone) { Ok(()) => { store .set_profile(&viewer.0.id, &about, &form.timezone) .await } Err(e) => Err(e), }; let message = match result { Ok(()) => return Err(see_other("/settings/profile?saved=details").into()), Err(e) => match user_facing_message(&e) { Some(message) => message, None => return Err(e.into()), }, }; let draft = Draft { username: viewer.0.username.clone(), about, timezone: form.timezone, }; let errors = Errors { details: Some(message), ..Errors::default() }; let page = page_data(&viewer, lang, draft, errors, None).await?; Ok(view! { shell(title: "Profile", viewer: Some(&viewer), profile_body(page: page)) }) } /// Reads the multipart body. The CSRF field is checked before the image is decoded. #[page(POST "/settings/profile/avatar")] async fn avatar_upload(cx: &Cx, mut multipart: Multipart) -> Result { let mut csrf = String::new(); let mut image = None; while let Some(field) = multipart.next_field().await? { let name = field.name().map(str::to_owned); match name.as_deref() { Some("csrf") => csrf = field.text().await?, Some("avatar") => image = Some(field.bytes().await?.to_vec()), _ => {} } } let viewer = require_csrf(cx, &csrf).await?; let lang = i18n::lang(cx, Some(&viewer.0)); let store = &app_context::(cx).store; let message = match store_avatar(store, &viewer.0.id, image, lang).await { Ok(()) => return Err(see_other("/settings/profile?saved=avatar").into()), Err(e) => match user_facing_message(&e) { Some(message) => message, None => return Err(e.into()), }, }; let errors = Errors { avatar: Some(message), ..Errors::default() }; let page = page_data(&viewer, lang, Draft::from_user(&viewer.0), errors, None).await?; Ok(view! { shell(title: "Profile", viewer: Some(&viewer), profile_body(page: page)) }) } #[route(POST "/settings/profile/avatar/delete")] async fn avatar_remove(cx: &Cx, Form(form): Form) -> Result { let viewer = require_csrf(cx, &form.csrf).await?; app_context::(cx) .store .delete_avatar(&viewer.0.id) .await?; Ok(see_other("/settings/profile?saved=avatar-removed")) } #[cfg(test)] pub(crate) mod tests { use forge_core::{Store, User}; use topcoat::router::request::Request; use topcoat::router::{Body, Router, to_bytes}; use crate::auth::SESSION_COOKIE; pub(crate) const TOKEN: &str = "profile-test-session"; pub(crate) const CSRF: &str = "profile-test-csrf"; pub(crate) struct Fixture { pub router: Router, pub store: Store, pub user: User, _dir: tempfile::TempDir, } pub(crate) async fn fixture() -> Fixture { let dir = tempfile::tempdir().expect("tempdir"); let path = dir.path().to_path_buf(); let state = crate::test_support::test_state(&path).await; let store = state.store.clone(); let router = crate::test_support::app_router(state); let user = store .create_user("tahinli", None, "not-a-real-hash", false) .await .unwrap(); crate::test_support::create_session(&store, &user.id, TOKEN, CSRF).await; Fixture { router, store, user, _dir: dir, } } /// A response with its status, headers and raw body. pub(crate) struct Reply { pub status: u16, pub headers: http::HeaderMap, pub body: Vec, } impl Reply { pub fn header(&self, name: &str) -> Option { self.headers .get(name) .and_then(|v| v.to_str().ok()) .map(str::to_owned) } pub fn text(&self) -> String { String::from_utf8_lossy(&self.body).into_owned() } } /// Sends one request with an optional session cookie and an explicit content type. pub(crate) async fn send_full( router: &Router, method: &str, uri: &str, signed_in: bool, content_type: Option<&str>, body: Vec, ) -> Reply { let mut builder = Request::builder().method(method).uri(uri); if signed_in { builder = builder.header("cookie", format!("__Host-{SESSION_COOKIE}={TOKEN}")); } if let Some(content_type) = content_type { builder = builder.header("content-type", content_type); } let res = router.handle(builder.body(Body::from(body)).unwrap()).await; let status = res.status().as_u16(); let headers = res.headers().clone(); let body = to_bytes(res.into_body(), usize::MAX) .await .unwrap() .to_vec(); Reply { status, headers, body, } } /// Sends one request with an optional session cookie. Returns `(status, location, body)`. pub(crate) async fn send( router: &Router, method: &str, uri: &str, signed_in: bool, form: Option<&str>, ) -> (u16, Option, String) { let reply = match form { Some(form) => { send_full( router, method, uri, signed_in, Some("application/x-www-form-urlencoded"), form.as_bytes().to_vec(), ) .await } None => send_full(router, method, uri, signed_in, None, Vec::new()).await, }; let location = reply.header("location"); (reply.status, location, reply.text()) } /// Builds a `multipart/form-data` body. Each field is `(name, Some((filename, type)) for /// files, bytes)`. Returns the content type and the body. /// One multipart field: name, optional `(filename, content type)` and the bytes. pub(crate) type Field<'a> = (&'a str, Option<(&'a str, &'a str)>, &'a [u8]); pub(crate) fn multipart(fields: &[Field<'_>]) -> (String, Vec) { const BOUNDARY: &str = "forgeTestBoundary7MA4YWxkTrZu0gW"; let mut body = Vec::new(); for (name, file, data) in fields { body.extend_from_slice( format!("--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"{name}\"") .as_bytes(), ); if let Some((filename, content_type)) = file { body.extend_from_slice( format!("; filename=\"{filename}\"\r\nContent-Type: {content_type}").as_bytes(), ); } body.extend_from_slice(b"\r\n\r\n"); body.extend_from_slice(data); body.extend_from_slice(b"\r\n"); } body.extend_from_slice(format!("--{BOUNDARY}--\r\n").as_bytes()); (format!("multipart/form-data; boundary={BOUNDARY}"), body) } /// A 64x48 PNG generated with the `image` crate. pub(crate) fn png_bytes() -> Vec { let img = image::RgbImage::from_fn(64, 48, |x, y| { image::Rgb([(x * 4) as u8, (y * 5) as u8, 128]) }); let mut out = Vec::new(); image::DynamicImage::ImageRgb8(img) .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) .expect("encode png"); out } /// Uploads `file` as the avatar of the signed-in test user, with `csrf` as the token. pub(crate) async fn upload_avatar(router: &Router, csrf: &str, file: &[u8]) -> Reply { let csrf_field = csrf.as_bytes(); let (content_type, body) = multipart(&[ ("csrf", None, csrf_field), ("avatar", Some(("avatar.png", "image/png")), file), ]); send_full( router, "POST", "/settings/profile/avatar", true, Some(&content_type), body, ) .await } #[tokio::test] async fn tahinli_to_capitalized_succeeds_and_dashboard_shows_it() { let fx = fixture().await; let form = format!("csrf={CSRF}&username=Tahinli"); let (status, location, _) = send(&fx.router, "POST", "/settings/profile", true, Some(&form)).await; assert_eq!(status, 303); assert_eq!(location.as_deref(), Some("/settings/profile?saved=1")); let stored = fx.store.user_by_id(&fx.user.id).await.unwrap().unwrap(); assert_eq!(stored.username, "Tahinli"); let (status, _, body) = send(&fx.router, "GET", "/", true, None).await; assert_eq!(status, 200); assert!(body.contains(""), "{body}"); let (status, _, body) = send(&fx.router, "GET", "/settings/profile?saved=1", true, None).await; assert_eq!(status, 200); assert!(body.contains("Username updated."), "{body}"); } #[tokio::test] async fn a_different_name_is_rejected_and_nothing_is_saved() { let fx = fixture().await; let form = format!("csrf={CSRF}&username=other"); let (status, _, body) = send(&fx.router, "POST", "/settings/profile", true, Some(&form)).await; assert_eq!(status, 200); assert!( body.contains("Only the capitalization can be changed."), "{body}" ); let stored = fx.store.user_by_id(&fx.user.id).await.unwrap().unwrap(); assert_eq!(stored.username, "tahinli"); } #[tokio::test] async fn post_without_a_valid_csrf_token_is_rejected() { let fx = fixture().await; let forged = "csrf=wrong&username=Tahinli"; let (status, _, _) = send(&fx.router, "POST", "/settings/profile", true, Some(forged)).await; assert_eq!(status, 403); let missing = "username=Tahinli"; let (status, _, _) = send(&fx.router, "POST", "/settings/profile", true, Some(missing)).await; assert_eq!(status, 403); let stored = fx.store.user_by_id(&fx.user.id).await.unwrap().unwrap(); assert_eq!(stored.username, "tahinli"); } #[tokio::test] async fn anonymous_requests_are_sent_to_login() { let fx = fixture().await; let (status, location, _) = send(&fx.router, "GET", "/settings/profile", false, None).await; assert_eq!(status, 303); assert!(location.unwrap_or_default().starts_with("/login?next=")); let form = format!("csrf={CSRF}&username=Tahinli"); let (status, location, _) = send(&fx.router, "POST", "/settings/profile", false, Some(&form)).await; assert_eq!(status, 303); assert!(location.unwrap_or_default().starts_with("/login?next=")); let stored = fx.store.user_by_id(&fx.user.id).await.unwrap().unwrap(); assert_eq!(stored.username, "tahinli"); } #[tokio::test] async fn about_and_timezone_round_trip() { let fx = fixture().await; let form = format!("csrf={CSRF}&about=Hello+*world*&timezone=Europe%2FIstanbul"); let (status, location, _) = send( &fx.router, "POST", "/settings/profile/details", true, Some(&form), ) .await; assert_eq!(status, 303); assert_eq!(location.as_deref(), Some("/settings/profile?saved=details")); let stored = fx.store.user_by_id(&fx.user.id).await.unwrap().unwrap(); assert_eq!(stored.about, "Hello *world*"); assert_eq!(stored.timezone, "Europe/Istanbul"); let (status, _, body) = send(&fx.router, "GET", "/settings/profile", true, None).await; assert_eq!(status, 200); assert!(body.contains("Hello *world*"), "{body}"); assert!( body.contains(r#"value="Europe/Istanbul" selected"#), "{body}" ); } #[tokio::test] async fn a_bad_timezone_is_rejected_and_nothing_is_saved() { let fx = fixture().await; let form = format!("csrf={CSRF}&about=kept&timezone=Mars%2FOlympus"); let (status, location, body) = send( &fx.router, "POST", "/settings/profile/details", true, Some(&form), ) .await; assert_eq!(status, 200); assert!(location.is_none()); assert!(body.contains(r#"role="alert""#), "{body}"); let stored = fx.store.user_by_id(&fx.user.id).await.unwrap().unwrap(); assert_eq!(stored.timezone, "UTC"); assert_eq!(stored.about, ""); } #[tokio::test] async fn details_post_without_csrf_is_rejected() { let fx = fixture().await; let form = "about=x&timezone=UTC"; let (status, _, _) = send( &fx.router, "POST", "/settings/profile/details", true, Some(form), ) .await; assert_eq!(status, 403); } #[tokio::test] async fn avatar_upload_without_csrf_is_rejected() { let fx = fixture().await; let png = png_bytes(); let (content_type, body) = multipart(&[("avatar", Some(("a.png", "image/png")), &png[..])]); let reply = send_full( &fx.router, "POST", "/settings/profile/avatar", true, Some(&content_type), body, ) .await; assert_eq!(reply.status, 403); assert!(fx.store.avatar_hash(&fx.user.id).await.unwrap().is_none()); } #[tokio::test] async fn svg_upload_is_rejected_and_nothing_is_stored() { let fx = fixture().await; let svg = br#""#; let (content_type, body) = multipart(&[ ("csrf", None, CSRF.as_bytes()), ("avatar", Some(("evil.svg", "image/svg+xml")), &svg[..]), ]); let reply = send_full( &fx.router, "POST", "/settings/profile/avatar", true, Some(&content_type), body, ) .await; assert_eq!(reply.status, 200); assert!(reply.text().contains(r#"role="alert""#)); assert!(fx.store.avatar_hash(&fx.user.id).await.unwrap().is_none()); } #[tokio::test] async fn avatar_upload_then_remove_is_served_correctly() { let fx = fixture().await; let png = png_bytes(); let reply = upload_avatar(&fx.router, CSRF, &png).await; assert_eq!(reply.status, 303); assert_eq!( reply.header("location").as_deref(), Some("/settings/profile?saved=avatar") ); let stored_hash = fx.store.avatar_hash(&fx.user.id).await.unwrap().unwrap(); assert_eq!(stored_hash.len(), 16); // The page shows the new avatar with the hash as its version. let (_, _, body) = send(&fx.router, "GET", "/settings/profile", true, None).await; assert!(body.contains(&format!("?v={stored_hash}")), "{body}"); // The top-nav avatar uses the real hash too, not the default URL. let (_, _, body) = send(&fx.router, "GET", "/", true, None).await; let nav_src = format!(r#"src="/avatars/tahinli?v={stored_hash}""#); assert!(body.contains(&nav_src), "{body}"); // Served as a stored PNG with a hash ETag, and 304 on a match. let served = send_full( &fx.router, "GET", "/avatars/tahinli", false, None, Vec::new(), ) .await; assert_eq!(served.status, 200); assert_eq!(served.header("content-type").as_deref(), Some("image/png")); assert_eq!(served.header("etag"), Some(format!("\"{stored_hash}\""))); assert_eq!( served.header("x-content-type-options").as_deref(), Some("nosniff") ); assert!(served.body.starts_with(&[0x89, b'P', b'N', b'G'])); let uri = format!("/avatars/tahinli?v={stored_hash}"); let immutable = send_full(&fx.router, "GET", &uri, false, None, Vec::new()).await; assert_eq!( immutable.header("cache-control").as_deref(), Some("public, max-age=31536000, immutable") ); let etag = format!("\"{stored_hash}\""); let mut request = Request::builder().method("GET").uri(&uri); request = request.header("if-none-match", etag.as_str()); let not_modified = fx.router.handle(request.body(Body::empty()).unwrap()).await; assert_eq!(not_modified.status().as_u16(), 304); // Removing gives the generated default SVG. let form = format!("csrf={CSRF}"); let (status, location, _) = send( &fx.router, "POST", "/settings/profile/avatar/delete", true, Some(&form), ) .await; assert_eq!(status, 303); assert_eq!( location.as_deref(), Some("/settings/profile?saved=avatar-removed") ); assert!(fx.store.avatar_hash(&fx.user.id).await.unwrap().is_none()); let (_, _, body) = send(&fx.router, "GET", "/", true, None).await; assert!( body.contains(r#"src="/avatars/tahinli?v=default""#), "{body}" ); let default = send_full( &fx.router, "GET", "/avatars/tahinli", false, None, Vec::new(), ) .await; assert_eq!(default.status, 200); assert_eq!( default.header("content-type").as_deref(), Some("image/svg+xml") ); assert_eq!( default.header("x-content-type-options").as_deref(), Some("nosniff") ); assert!(default.text().starts_with("