//! `GET /api/v1/people/{sub}/photo` (`docs/contracts.md` section 3.2): a person's profile photo, as bytes. //! //! The `sub` must be a ULID, else `404`. A person with no photo, an unknown or deleted person, and a photo //! whose stored type is not on the allowlist are all `404`, so the answer does not say which it was. There //! is no initials picture for a machine. The bytes go with `nosniff` and a `"p"` ETag. With //! `?v=` equal to the current version the answer may be cached for a year (the URL names the version); //! otherwise it may be kept but must be checked again. `If-None-Match` gets a `304`. use http::header::{CACHE_CONTROL, CONTENT_TYPE, ETAG, IF_NONE_MATCH, X_CONTENT_TYPE_OPTIONS}; use im_core::photo::read_photo; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::request::{headers, uri}; use topcoat::router::response::Response; use topcoat::router::{Body, HeaderValue, StatusCode, raw_path_params, route}; use super::machine_auth::{DIRECTORY_READ, require}; use super::{api_error, not_found}; use crate::oidc::{Single, parse_pairs, single}; use crate::state::AppState; /// The image types a photo may be served as. Anything else stored is not served. pub const ALLOWED_TYPES: [&str; 4] = ["image/png", "image/jpeg", "image/webp", "image/gif"]; /// Caching when `?v=` names the current version: the URL is unique to this picture. const IMMUTABLE_CACHE: &str = "private, max-age=31536000, immutable"; /// Caching otherwise: keep it, but ask again before use. const REVALIDATE_CACHE: &str = "private, no-cache"; /// `GET /api/v1/people/{sub}/photo`. #[route(GET "/api/v1/people/{sub}/photo")] async fn photo(cx: &Cx) -> Result { let app = app_context::(cx); let machine = match require(app, cx, DIRECTORY_READ).await? { Ok(machine) => machine, Err(refusal) => return Ok(refusal), }; tracing::debug!(caller = %machine.caller, "photo: request"); let Some(sub) = path_sub(cx) else { return Ok(not_found()); }; if !is_ulid(&sub) { return Ok(not_found()); } let Some(person) = app.store.user_by_id(&sub).await? else { return Ok(not_found()); }; let Some(mime) = person.photo_mime.as_deref().and_then(allowed_type) else { return Ok(not_found()); }; let etag = format!("\"p{}\"", person.picture_version); let cache = if requested_version(cx) == Some(person.picture_version) { IMMUTABLE_CACHE } else { REVALIDATE_CACHE }; if none_match(cx, &etag) { return Ok(answer( StatusCode::NOT_MODIFIED, &etag, mime, cache, Vec::new(), )); } let dir = app.config.data_dir.clone(); let read_sub = sub.clone(); let stored = match tokio::task::spawn_blocking(move || read_photo(&dir, &read_sub)).await { Ok(Ok(stored)) => stored, Ok(Err(error)) => { tracing::error!(error = %error, "photo: the stored picture could not be read"); return Ok(api_error( StatusCode::INTERNAL_SERVER_ERROR, "internal", "The photo could not be read.", None, )); } Err(error) => { tracing::error!(error = %error, "photo: the read task failed"); return Ok(api_error( StatusCode::INTERNAL_SERVER_ERROR, "internal", "The photo could not be read.", None, )); } }; match stored { Some(bytes) => Ok(answer(StatusCode::OK, &etag, mime, cache, bytes)), // The row names a photo whose file is gone: there is no picture to send. None => Ok(not_found()), } } /// The `{sub}` of the matched route, or `None`. fn path_sub(cx: &Cx) -> Option { raw_path_params(cx) .find(|(name, _)| *name == "sub") .map(|(_, value)| value.as_str().to_owned()) } /// The `v` query parameter as a version, when it is exactly one integer. fn requested_version(cx: &Cx) -> Option { let query = uri(cx).query()?; let pairs = parse_pairs(query.as_bytes())?; match single(&pairs, "v") { Single::One(value) => value.parse().ok(), _ => None, } } /// True when `If-None-Match` names `etag`. fn none_match(cx: &Cx, etag: &str) -> bool { headers(cx) .get_all(IF_NONE_MATCH) .iter() .filter_map(|value| value.to_str().ok()) .flat_map(|value| value.split(',')) .any(|tag| tag.trim() == etag) } /// The stored type, when it is on the allowlist. fn allowed_type(stored: &str) -> Option<&'static str> { ALLOWED_TYPES.into_iter().find(|allowed| *allowed == stored) } /// A user id is a ULID: 26 characters of Crockford base32, the first at most `7`. Anything else (a path /// fragment, an encoded slash, a dot segment) is refused before it reaches the disk. pub fn is_ulid(sub: &str) -> bool { sub.len() == 26 && ulid::Ulid::from_string(sub).is_ok() } /// One photo answer with its headers. fn answer( status: StatusCode, etag: &str, mime: &str, cache: &'static str, body: Vec, ) -> Response { let mut response = Response::new(Body::from(body)); *response.status_mut() = status; let headers = response.headers_mut(); headers.insert( CONTENT_TYPE, HeaderValue::from_str(mime).unwrap_or(HeaderValue::from_static("application/octet-stream")), ); headers.insert(CACHE_CONTROL, HeaderValue::from_static(cache)); headers.insert( ETAG, HeaderValue::from_str(etag).unwrap_or(HeaderValue::from_static("\"\"")), ); headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")); response }