forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

photo.rs157 lines, 5.7 KiBHistoryRawDownload
1//! `GET /api/v1/people/{sub}/photo` (`docs/contracts.md` section 3.2): a person's profile photo, as bytes.
2//!
3//! The `sub` must be a ULID, else `404`. A person with no photo, an unknown or deleted person, and a photo
4//! whose stored type is not on the allowlist are all `404`, so the answer does not say which it was. There
5//! is no initials picture for a machine. The bytes go with `nosniff` and a `"p<picture_version>"` ETag. With
6//! `?v=` equal to the current version the answer may be cached for a year (the URL names the version);
7//! otherwise it may be kept but must be checked again. `If-None-Match` gets a `304`.
8
9use http::header::{CACHE_CONTROL, CONTENT_TYPE, ETAG, IF_NONE_MATCH, X_CONTENT_TYPE_OPTIONS};
10use im_core::photo::read_photo;
11use topcoat::Result;
12use topcoat::context::{Cx, app_context};
13use topcoat::router::request::{headers, uri};
14use topcoat::router::response::Response;
15use topcoat::router::{Body, HeaderValue, StatusCode, raw_path_params, route};
16
17use super::machine_auth::{DIRECTORY_READ, require};
18use super::{api_error, not_found};
19use crate::oidc::{Single, parse_pairs, single};
20use crate::state::AppState;
21
22/// The image types a photo may be served as. Anything else stored is not served.
23pub const ALLOWED_TYPES: [&str; 4] = ["image/png", "image/jpeg", "image/webp", "image/gif"];
24
25/// Caching when `?v=` names the current version: the URL is unique to this picture.
26const IMMUTABLE_CACHE: &str = "private, max-age=31536000, immutable";
27
28/// Caching otherwise: keep it, but ask again before use.
29const REVALIDATE_CACHE: &str = "private, no-cache";
30
31/// `GET /api/v1/people/{sub}/photo`.
32#[route(GET "/api/v1/people/{sub}/photo")]
33async fn photo(cx: &Cx) -> Result<Response> {
34 let app = app_context::<AppState>(cx);
35 let machine = match require(app, cx, DIRECTORY_READ).await? {
36 Ok(machine) => machine,
37 Err(refusal) => return Ok(refusal),
38 };
39 tracing::debug!(caller = %machine.caller, "photo: request");
40 let Some(sub) = path_sub(cx) else {
41 return Ok(not_found());
42 };
43 if !is_ulid(&sub) {
44 return Ok(not_found());
45 }
46 let Some(person) = app.store.user_by_id(&sub).await? else {
47 return Ok(not_found());
48 };
49 let Some(mime) = person.photo_mime.as_deref().and_then(allowed_type) else {
50 return Ok(not_found());
51 };
52 let etag = format!("\"p{}\"", person.picture_version);
53 let cache = if requested_version(cx) == Some(person.picture_version) {
54 IMMUTABLE_CACHE
55 } else {
56 REVALIDATE_CACHE
57 };
58 if none_match(cx, &etag) {
59 return Ok(answer(
60 StatusCode::NOT_MODIFIED,
61 &etag,
62 mime,
63 cache,
64 Vec::new(),
65 ));
66 }
67 let dir = app.config.data_dir.clone();
68 let read_sub = sub.clone();
69 let stored = match tokio::task::spawn_blocking(move || read_photo(&dir, &read_sub)).await {
70 Ok(Ok(stored)) => stored,
71 Ok(Err(error)) => {
72 tracing::error!(error = %error, "photo: the stored picture could not be read");
73 return Ok(api_error(
74 StatusCode::INTERNAL_SERVER_ERROR,
75 "internal",
76 "The photo could not be read.",
77 None,
78 ));
79 }
80 Err(error) => {
81 tracing::error!(error = %error, "photo: the read task failed");
82 return Ok(api_error(
83 StatusCode::INTERNAL_SERVER_ERROR,
84 "internal",
85 "The photo could not be read.",
86 None,
87 ));
88 }
89 };
90 match stored {
91 Some(bytes) => Ok(answer(StatusCode::OK, &etag, mime, cache, bytes)),
92 // The row names a photo whose file is gone: there is no picture to send.
93 None => Ok(not_found()),
94 }
95}
96
97/// The `{sub}` of the matched route, or `None`.
98fn path_sub(cx: &Cx) -> Option<String> {
99 raw_path_params(cx)
100 .find(|(name, _)| *name == "sub")
101 .map(|(_, value)| value.as_str().to_owned())
102}
103
104/// The `v` query parameter as a version, when it is exactly one integer.
105fn requested_version(cx: &Cx) -> Option<i64> {
106 let query = uri(cx).query()?;
107 let pairs = parse_pairs(query.as_bytes())?;
108 match single(&pairs, "v") {
109 Single::One(value) => value.parse().ok(),
110 _ => None,
111 }
112}
113
114/// True when `If-None-Match` names `etag`.
115fn none_match(cx: &Cx, etag: &str) -> bool {
116 headers(cx)
117 .get_all(IF_NONE_MATCH)
118 .iter()
119 .filter_map(|value| value.to_str().ok())
120 .flat_map(|value| value.split(','))
121 .any(|tag| tag.trim() == etag)
122}
123
124/// The stored type, when it is on the allowlist.
125fn allowed_type(stored: &str) -> Option<&'static str> {
126 ALLOWED_TYPES.into_iter().find(|allowed| *allowed == stored)
127}
128
129/// A user id is a ULID: 26 characters of Crockford base32, the first at most `7`. Anything else (a path
130/// fragment, an encoded slash, a dot segment) is refused before it reaches the disk.
131pub fn is_ulid(sub: &str) -> bool {
132 sub.len() == 26 && ulid::Ulid::from_string(sub).is_ok()
133}
134
135/// One photo answer with its headers.
136fn answer(
137 status: StatusCode,
138 etag: &str,
139 mime: &str,
140 cache: &'static str,
141 body: Vec<u8>,
142) -> Response {
143 let mut response = Response::new(Body::from(body));
144 *response.status_mut() = status;
145 let headers = response.headers_mut();
146 headers.insert(
147 CONTENT_TYPE,
148 HeaderValue::from_str(mime).unwrap_or(HeaderValue::from_static("application/octet-stream")),
149 );
150 headers.insert(CACHE_CONTROL, HeaderValue::from_static(cache));
151 headers.insert(
152 ETAG,
153 HeaderValue::from_str(etag).unwrap_or(HeaderValue::from_static("\"\"")),
154 );
155 headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
156 response
157}