Skip to main content

glacier/
response.rs

1//! HTTP responses and the `IntoResponse` conversion trait.
2
3use bytes::Bytes;
4use http::{Extensions, HeaderMap, HeaderName, HeaderValue, StatusCode, header};
5use http_body_util::Full;
6use serde::Serialize;
7
8use crate::error::Error;
9
10/// Marks a [`Response::head`] response.
11#[derive(Debug, Clone, Copy)]
12struct Head;
13
14/// A fully buffered HTTP response.
15#[derive(Debug, Clone)]
16pub struct Response {
17    status: StatusCode,
18    headers: HeaderMap,
19    body: Bytes,
20    extensions: Extensions,
21}
22
23impl Default for Response {
24    fn default() -> Self {
25        Self::new(StatusCode::OK)
26    }
27}
28
29impl Response {
30    /// An empty response with the given status.
31    pub fn new(status: StatusCode) -> Self {
32        Self {
33            status,
34            headers: HeaderMap::new(),
35            body: Bytes::new(),
36            extensions: Extensions::new(),
37        }
38    }
39
40    pub fn text(body: impl Into<String>) -> Self {
41        Self::with_body(body.into(), "text/plain; charset=utf-8")
42    }
43
44    pub fn html(body: impl Into<String>) -> Self {
45        let mut body = body.into();
46        // Under `glacier server`, a page reloads itself when files change.
47        if crate::view::reload::enabled()
48            && let Some(at) = body.rfind("</body>")
49        {
50            body.insert_str(at, &crate::view::reload::script());
51        }
52        Self::with_body(body, "text/html; charset=utf-8")
53    }
54
55    /// Serializes `value` as JSON. Serialization failures become a 500.
56    /// With [`escape_html_entities_in_json`] on, `<`, `>` and `&` are
57    /// written `\u003c`, `\u003e` and `\u0026`, as Rails writes them.
58    pub fn json<T: Serialize + ?Sized>(value: &T) -> Self {
59        match serde_json::to_vec(value) {
60            Ok(body) if ESCAPE_HTML.load(std::sync::atomic::Ordering::Relaxed) => {
61                Self::with_body(escape_html(&body), "application/json; charset=utf-8")
62            }
63            Ok(body) => Self::with_body(body, "application/json; charset=utf-8"),
64            Err(err) => Error::from(err).into_response(),
65        }
66    }
67
68    /// A `303 See Other` redirect, the right status after a form submission.
69    pub fn redirect(location: &str) -> Self {
70        Self::new(StatusCode::SEE_OTHER).with_header(header::LOCATION, location)
71    }
72
73    /// A file for the browser to save, as Rails' `send_data`: its type
74    /// from the name's extension (`application/octet-stream` if unknown)
75    /// and a `Content-Disposition: attachment` naming it.
76    pub fn download(bytes: impl Into<Bytes>, filename: &str) -> Self {
77        Self::send_data(bytes, filename, "attachment")
78    }
79
80    /// A file for the browser to show, such as a PDF in its viewer, as
81    /// Rails' `send_data …, disposition: "inline"`.
82    pub fn inline(bytes: impl Into<Bytes>, filename: &str) -> Self {
83        Self::send_data(bytes, filename, "inline")
84    }
85
86    fn send_data(bytes: impl Into<Bytes>, filename: &str, disposition: &str) -> Self {
87        let extension = filename
88            .rsplit_once('.')
89            .map(|(_, ext)| ext.to_ascii_lowercase());
90        let content_type = extension
91            .as_deref()
92            .and_then(crate::mime::for_format)
93            .unwrap_or("application/octet-stream");
94        // An ASCII fallback and the exact name, as Rails writes it.
95        let ascii: String = filename
96            .chars()
97            .map(|c| {
98                if c.is_ascii_graphic() && c != '"' && c != '\\' || c == ' ' {
99                    c
100                } else {
101                    '_'
102                }
103            })
104            .collect();
105        const UNRESERVED: &percent_encoding::AsciiSet = &percent_encoding::NON_ALPHANUMERIC
106            .remove(b'-')
107            .remove(b'.')
108            .remove(b'_')
109            .remove(b'~');
110        let exact = percent_encoding::utf8_percent_encode(filename, UNRESERVED);
111        Self::new(StatusCode::OK)
112            .with_body_bytes(bytes)
113            .with_header(header::CONTENT_TYPE, content_type)
114            .with_header(
115                header::CONTENT_DISPOSITION,
116                format!("{disposition}; filename=\"{ascii}\"; filename*=UTF-8''{exact}"),
117            )
118    }
119
120    /// A response with only a status and no body, as Rails' `head :ok`.
121    /// Error statuses stay empty too: `Pipeline::api` leaves them be.
122    pub fn head(status: StatusCode) -> Self {
123        let mut response = Self::new(status);
124        response.extensions.insert(Head);
125        response
126    }
127
128    pub fn no_content() -> Self {
129        Self::new(StatusCode::NO_CONTENT)
130    }
131
132    fn with_body(body: impl Into<Bytes>, content_type: &'static str) -> Self {
133        let mut res = Self::new(StatusCode::OK);
134        res.body = body.into();
135        res.headers
136            .insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type));
137        res
138    }
139
140    /// Replaces the body, leaving headers untouched.
141    pub fn with_body_bytes(mut self, body: impl Into<Bytes>) -> Self {
142        self.body = body.into();
143        self
144    }
145
146    pub fn with_status(mut self, status: StatusCode) -> Self {
147        self.status = status;
148        self
149    }
150
151    /// Sets a header, replacing any existing value. Invalid names or values
152    /// are dropped with a warning rather than panicking mid-request.
153    pub fn with_header<K, V>(mut self, name: K, value: V) -> Self
154    where
155        K: TryInto<HeaderName>,
156        V: TryInto<HeaderValue>,
157    {
158        match (name.try_into(), value.try_into()) {
159            (Ok(name), Ok(value)) => {
160                self.headers.insert(name, value);
161            }
162            _ => tracing::warn!("ignoring invalid response header"),
163        }
164        self
165    }
166
167    pub fn status(&self) -> StatusCode {
168        self.status
169    }
170
171    pub fn headers(&self) -> &HeaderMap {
172        &self.headers
173    }
174
175    pub fn headers_mut(&mut self) -> &mut HeaderMap {
176        &mut self.headers
177    }
178
179    pub fn header(&self, name: impl http::header::AsHeaderName) -> Option<&str> {
180        self.headers.get(name).and_then(|v| v.to_str().ok())
181    }
182
183    /// Data attached for middleware further up the stack; never sent to
184    /// the client.
185    pub fn extensions(&self) -> &Extensions {
186        &self.extensions
187    }
188
189    pub fn extensions_mut(&mut self) -> &mut Extensions {
190        &mut self.extensions
191    }
192
193    pub fn body(&self) -> &Bytes {
194        &self.body
195    }
196
197    /// This response for a conditional GET, as Rails' `stale?`/`fresh_when`:
198    /// it gets `Last-Modified` and a weak `ETag` of its body, and becomes an
199    /// empty `304 Not Modified` when the request's `If-None-Match` matches
200    /// the ETag, or (without one) its `If-Modified-Since` isn't older than
201    /// `last_modified`.
202    ///
203    /// ```ignore
204    /// Response::json(&action).fresh_when(&ctx, action.updated_at.and_utc())
205    /// ```
206    pub fn fresh_when(
207        mut self,
208        ctx: &crate::Context,
209        last_modified: chrono::DateTime<chrono::Utc>,
210    ) -> Self {
211        use sha2::Digest;
212        let modified = last_modified
213            .format("%a, %d %b %Y %H:%M:%S GMT")
214            .to_string();
215        let digest = sha2::Sha256::digest(&self.body);
216        let etag = format!(
217            "W/\"{}\"",
218            digest[..16]
219                .iter()
220                .map(|b| format!("{b:02x}"))
221                .collect::<String>()
222        );
223        let fresh = match ctx.header(header::IF_NONE_MATCH) {
224            Some(tags) => tags.split(',').any(|tag| {
225                // Weakly: `W/"x"` matches `"x"`, as RFC 9110 has it for GETs.
226                let tag = tag.trim();
227                tag == "*" || tag.trim_start_matches("W/") == etag.trim_start_matches("W/")
228            }),
229            None => ctx
230                .header(header::IF_MODIFIED_SINCE)
231                .and_then(crate::time::parse_http_date)
232                .is_some_and(|since| since.timestamp() >= last_modified.timestamp()),
233        };
234        if let Ok(value) = HeaderValue::from_str(&modified) {
235            self.headers.insert(header::LAST_MODIFIED, value);
236        }
237        if let Ok(value) = HeaderValue::from_str(&etag) {
238            self.headers.insert(header::ETAG, value);
239        }
240        if fresh && self.status == StatusCode::OK {
241            self.status = StatusCode::NOT_MODIFIED;
242            self.body = Bytes::new();
243            self.headers.remove(header::CONTENT_TYPE);
244        }
245        self
246    }
247
248    /// Whether this is a [`head`](Self::head) response, meant to be empty.
249    pub fn is_head(&self) -> bool {
250        self.extensions.get::<Head>().is_some()
251    }
252
253    /// The body decoded as UTF-8 (lossily). Mostly useful in tests.
254    pub fn body_text(&self) -> String {
255        String::from_utf8_lossy(&self.body).into_owned()
256    }
257
258    /// The body parsed as JSON (`null` if it isn't). Mostly useful in
259    /// tests: `res.body_json()["id"]`.
260    pub fn body_json(&self) -> serde_json::Value {
261        serde_json::from_slice(&self.body).unwrap_or_default()
262    }
263
264    pub(crate) fn into_http(self) -> http::Response<Full<Bytes>> {
265        let mut res = http::Response::new(Full::new(self.body));
266        *res.status_mut() = self.status;
267        *res.headers_mut() = self.headers;
268        res
269    }
270}
271
272/// Anything a handler can return.
273pub trait IntoResponse {
274    fn into_response(self) -> Response;
275}
276
277static ESCAPE_HTML: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
278
279/// Writes `<`, `>`, `&`, U+2028 and U+2029 in JSON responses as `\u` escapes,
280/// as Rails does by default (`escape_html_entities_in_json`), so JSON put
281/// into a page can't close a `<script>`. Call it once at startup.
282pub fn escape_html_entities_in_json(on: bool) {
283    ESCAPE_HTML.store(on, std::sync::atomic::Ordering::Relaxed);
284}
285
286/// The escaping itself. These characters only appear inside JSON strings,
287/// so replacing them anywhere is safe.
288fn escape_html(json: &[u8]) -> Vec<u8> {
289    let text = String::from_utf8_lossy(json);
290    let mut out = String::with_capacity(text.len());
291    for c in text.chars() {
292        match c {
293            '<' => out.push_str("\\u003c"),
294            '>' => out.push_str("\\u003e"),
295            '&' => out.push_str("\\u0026"),
296            '\u{2028}' => out.push_str("\\u2028"),
297            '\u{2029}' => out.push_str("\\u2029"),
298            c => out.push(c),
299        }
300    }
301    out.into_bytes()
302}
303
304#[cfg(test)]
305mod escape_tests {
306    #[test]
307    fn escapes_as_rails_does() {
308        let json = br#"{"url":"/a?b=1&c=<x>"}"#;
309        assert_eq!(
310            String::from_utf8(super::escape_html(json)).unwrap(),
311            r#"{"url":"/a?b=1\u0026c=\u003cx\u003e"}"#
312        );
313    }
314}
315
316impl IntoResponse for Response {
317    fn into_response(self) -> Response {
318        self
319    }
320}
321
322impl IntoResponse for &'static str {
323    fn into_response(self) -> Response {
324        Response::text(self)
325    }
326}
327
328impl IntoResponse for String {
329    fn into_response(self) -> Response {
330        Response::text(self)
331    }
332}
333
334impl IntoResponse for StatusCode {
335    fn into_response(self) -> Response {
336        Response::new(self)
337    }
338}
339
340impl<R: IntoResponse> IntoResponse for (StatusCode, R) {
341    fn into_response(self) -> Response {
342        self.1.into_response().with_status(self.0)
343    }
344}
345
346impl<R: IntoResponse, E: IntoResponse> IntoResponse for Result<R, E> {
347    fn into_response(self) -> Response {
348        match self {
349            Ok(r) => r.into_response(),
350            Err(e) => e.into_response(),
351        }
352    }
353}
354
355/// An HTML response body.
356#[derive(Debug, Clone)]
357pub struct Html<T>(pub T);
358
359impl<T: Into<String>> IntoResponse for Html<T> {
360    fn into_response(self) -> Response {
361        Response::html(self.0)
362    }
363}
364
365/// A JSON response body.
366#[derive(Debug, Clone)]
367pub struct Json<T>(pub T);
368
369impl Json<()> {
370    /// A JSON object to build field by field: `Json.object()` in
371    /// `.glacier`, then `.field("name", value)`; see
372    /// [`Object`](crate::serialize::Object).
373    pub fn object() -> crate::serialize::Object {
374        crate::serialize::Object::new()
375    }
376}
377
378impl<T: Serialize> IntoResponse for Json<T> {
379    fn into_response(self) -> Response {
380        Response::json(&self.0)
381    }
382}
383
384/// What an action may give back, as it is: a [`Response`] or anything that
385/// becomes one, an [`Error`](crate::Error) (the request fails with it), or
386/// a [`Result`](crate::Result) of either. In `.glacier`, `return error` and
387/// an action's last value use it, so neither needs an `Ok(…)`.
388pub trait Returned {
389    /// As the action's `Result`.
390    fn returned(self) -> crate::Result;
391}
392
393/// `x` as an action's `Result`; see [`Returned`].
394#[doc(hidden)]
395pub fn returned(value: impl Returned) -> crate::Result {
396    value.returned()
397}
398
399impl<R: IntoResponse> Returned for crate::Result<R> {
400    fn returned(self) -> crate::Result {
401        self.map(IntoResponse::into_response)
402    }
403}
404
405impl Returned for crate::Error {
406    fn returned(self) -> crate::Result {
407        Err(self)
408    }
409}
410
411macro_rules! returned_as_response {
412    ($($ty:ty),* $(,)?) => {$(
413        impl Returned for $ty {
414            fn returned(self) -> crate::Result {
415                Ok(self.into_response())
416            }
417        }
418    )*};
419}
420
421returned_as_response!(
422    Response,
423    &'static str,
424    String,
425    StatusCode,
426    crate::view::Rendered
427);
428
429impl<R: IntoResponse> Returned for (StatusCode, R) {
430    fn returned(self) -> crate::Result {
431        Ok(self.into_response())
432    }
433}
434
435impl<T: Into<String>> Returned for Html<T> {
436    fn returned(self) -> crate::Result {
437        Ok(self.into_response())
438    }
439}
440
441impl<T: Serialize> Returned for Json<T> {
442    fn returned(self) -> crate::Result {
443        Ok(self.into_response())
444    }
445}
446
447/// One `key: value` of `redirect!`: `status: :found` (a name, number or
448/// [`StatusCode`]) sets the redirect's status, as Rails' `redirect_to …,
449/// status: :found`; any other key is a flash (`notice: "Saved."`).
450#[doc(hidden)]
451pub trait RedirectOption {
452    fn apply(self, key: &str, status: &mut StatusCode);
453}
454
455macro_rules! redirect_text {
456    ($($ty:ty),*) => {$(
457        impl RedirectOption for $ty {
458            #[track_caller]
459            fn apply(self, key: &str, status: &mut StatusCode) {
460                if key == "status" {
461                    *status = IntoStatus::into_status(AsRef::<str>::as_ref(&self));
462                } else {
463                    crate::request::put_flash(key, AsRef::<str>::as_ref(&self));
464                }
465            }
466        }
467    )*};
468}
469redirect_text!(&str, String, &String);
470
471macro_rules! redirect_status {
472    ($($ty:ty),*) => {$(
473        impl RedirectOption for $ty {
474            #[track_caller]
475            fn apply(self, key: &str, status: &mut StatusCode) {
476                assert!(key == "status", "a flash (`{key}:`) is text");
477                *status = self.into_status();
478            }
479        }
480    )*};
481}
482redirect_status!(StatusCode, u16, i32);
483
484/// A response status from a number (`201`), a [`StatusCode`] or a
485/// snake_case name (`"created"`, `"unprocessable_entity"`), for
486/// `json!(…, status = …)` and `.glacier`'s `status: :created`.
487pub trait IntoStatus {
488    fn into_status(self) -> StatusCode;
489}
490
491impl IntoStatus for StatusCode {
492    fn into_status(self) -> StatusCode {
493        self
494    }
495}
496
497impl IntoStatus for u16 {
498    #[track_caller]
499    fn into_status(self) -> StatusCode {
500        StatusCode::from_u16(self).unwrap_or_else(|_| panic!("{self} isn't an HTTP status"))
501    }
502}
503
504impl IntoStatus for i32 {
505    #[track_caller]
506    fn into_status(self) -> StatusCode {
507        u16::try_from(self)
508            .ok()
509            .and_then(|code| StatusCode::from_u16(code).ok())
510            .unwrap_or_else(|| panic!("{self} isn't an HTTP status"))
511    }
512}
513
514impl IntoStatus for &str {
515    /// # Panics
516    ///
517    /// On a name no status has, so a typo fails loudly.
518    #[track_caller]
519    fn into_status(self) -> StatusCode {
520        status_named(self).unwrap_or_else(|| panic!("no HTTP status is called `:{self}`"))
521    }
522}
523
524/// The snake_case name of a status: `see_other`, `unprocessable_entity`.
525pub fn status_name(status: StatusCode) -> String {
526    let reason = status.canonical_reason().unwrap_or(status.as_str());
527    reason
528        .to_ascii_lowercase()
529        .replace(['-', '\''], "")
530        .split(|c: char| !c.is_ascii_alphanumeric())
531        .filter(|word| !word.is_empty())
532        .collect::<Vec<_>>()
533        .join("_")
534}
535
536/// The status with this snake_case name, if any.
537pub fn status_named(name: &str) -> Option<StatusCode> {
538    (100..600)
539        .filter_map(|code| StatusCode::from_u16(code).ok())
540        .find(|status| status_name(*status) == name)
541}