Skip to main content

forma_server/
response.rs

1//! The page response: HTML that never leaves without its policy.
2
3use crate::csp::{CspNonce, PagePolicy};
4use axum::http::{header, HeaderName, HeaderValue};
5use axum::response::{IntoResponse, Response};
6use std::time::Duration;
7
8#[cfg(feature = "compression")]
9mod compression;
10#[cfg(feature = "compression")]
11pub use compression::CompressedPageResponse;
12
13/// A rendered page, ready to send.
14///
15/// As axum's [`IntoResponse`] it always writes, together with the HTML:
16///
17/// - `Cache-Control: no-store`, because the HTML embeds a nonce minted for
18///   this one response; a cached copy would hand that nonce to every later
19///   reader, and another user's page with it;
20/// - `Content-Security-Policy`, the strict policy for that nonce
21///   ([`crate::csp::build_csp_header`]) with only the handler's typed
22///   [`crate::PolicyExtensions`] added;
23/// - Trusted Types enforcement in the strict policy, in every build and without
24///   a reporting endpoint. The named route relaxation moves only those two
25///   directives to `Content-Security-Policy-Report-Only`;
26/// - Optional reporting through [`crate::PolicyExtensions::report_to`] or
27///   [`crate::PolicyExtensions::report_uri`]. Strict pages also carry a diagnostic
28///   Report-Only policy in debug builds; a relaxed route always carries it;
29/// - `Cross-Origin-Opener-Policy: same-origin` (or `same-origin-allow-popups`
30///   when the extensions ask for it), `X-Content-Type-Options`,
31///   `Referrer-Policy` and `Permissions-Policy`;
32/// - `Content-Type: text/html; charset=utf-8`.
33///
34/// A handler cannot take the HTML out and send it some other way except
35/// through [`PageResponse::into_parts_unchecked`], the one named exit, which
36/// a consumer's CI can search for:
37///
38/// ```compile_fail,E0616
39/// # fn page() -> forma_server::PageResponse { unimplemented!() }
40/// let html = page().html; // private: the HTML leaves only with its headers
41/// ```
42///
43/// ```no_run
44/// # fn page() -> forma_server::PageResponse { unimplemented!() }
45/// let parts = page().into_parts_unchecked(); // the named, searchable exit
46/// # let _ = parts.html;
47/// ```
48///
49/// Verified by: crates/forma-server/tests/internal_renderer/page_response.rs > "page_response_writes_no_store_the_policy_and_the_document_headers"
50#[derive(Debug)]
51pub struct PageResponse {
52    html: String,
53    nonce: CspNonce,
54    policy: PagePolicy,
55    counts: RenderCounts,
56}
57
58/// What one render did, for the application's own logs and metrics.
59///
60/// On a [`crate::RenderError`] for a budget or a fault, the same counts say
61/// how far the walk got. For a page served without a walk (a browser
62/// shell) every count is zero. `nodes` and `list_iterations` are counted by
63/// [`crate::PageHandle::render`].
64///
65/// Walk time excludes checked props conversion and document assembly. Measure
66/// the complete handle call when deciding to move owned request data and a
67/// cloned handle into the application runtime's blocking pool.
68#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
69#[non_exhaustive]
70pub struct RenderCounts {
71    /// Elements and text nodes the walk wrote (hydration markers and
72    /// comments are not nodes).
73    pub nodes: usize,
74    /// Bytes of HTML the walk wrote into the page's root. State and document
75    /// markup are excluded from this work counter, but the complete response
76    /// is also checked against `WalkLimits::max_output_bytes` before allocation.
77    pub bytes: usize,
78    /// List rows the walk wrote, across every nesting depth, the quantity
79    /// `WalkLimits::max_list_iterations` bounds.
80    pub list_iterations: usize,
81    /// Time spent in the walk.
82    pub walk_time: Duration,
83}
84
85impl RenderCounts {
86    /// The walker's counts, with the time the walk took.
87    pub(crate) fn from_walk(counts: forma_ir::WalkCounts, walk_time: Duration) -> Self {
88        RenderCounts {
89            nodes: counts.nodes,
90            bytes: counts.bytes,
91            list_iterations: counts.list_iterations,
92            walk_time,
93        }
94    }
95}
96
97/// A page's raw parts, from [`PageResponse::into_parts_unchecked`].
98///
99/// Whoever sends these owns what [`PageResponse`] guaranteed: every header
100/// in `headers` goes out with `html`, and `html` is never cached or sent to a
101/// second request.
102#[derive(Debug)]
103#[non_exhaustive]
104pub struct PageParts {
105    /// The complete HTML document.
106    pub html: String,
107    /// The nonce `html` carries and the policy in `headers` blesses.
108    pub nonce: CspNonce,
109    /// Every header the response would have written, in its order.
110    pub headers: Vec<(HeaderName, HeaderValue)>,
111    /// What the render did.
112    pub counts: RenderCounts,
113}
114
115impl PageResponse {
116    /// Opt this response into Brotli/gzip negotiation (the `compression` feature).
117    ///
118    /// Only call this for a route whose response cannot put a secret such as a
119    /// CSRF token beside attacker-controlled text. Compression can expose secrets
120    /// through response length (BREACH); a fresh CSP nonce and `no-store` do not
121    /// protect other secrets. This method never enables compression globally.
122    ///
123    /// Preserves every page policy header and adds `Vary: Accept-Encoding`.
124    /// Bodies below 1 KiB stay uncompressed when identity is acceptable. Axum's
125    /// GET routing supplies the same headers for HEAD and removes its body.
126    #[cfg(feature = "compression")]
127    pub fn with_compression(
128        self,
129        request_headers: &axum::http::HeaderMap,
130    ) -> CompressedPageResponse {
131        CompressedPageResponse::new(self, request_headers)
132    }
133
134    /// Wrap a rendered document whose policy was built, from the same nonce,
135    /// before the walk (so an invalid extension costs no walk).
136    pub(crate) fn with_policy(
137        html: String,
138        nonce: CspNonce,
139        policy: PagePolicy,
140        counts: RenderCounts,
141    ) -> Self {
142        PageResponse {
143            html,
144            nonce,
145            policy,
146            counts,
147        }
148    }
149
150    /// What the render did: nodes, bytes and list rows walked, and time spent.
151    pub fn counts(&self) -> RenderCounts {
152        self.counts
153    }
154
155    /// The HTML, its nonce and every header, apart.
156    ///
157    /// The one way to reach the HTML without sending it as this response. It
158    /// exists for the rare handler that must assemble its own response (a
159    /// streaming body, a framework other than axum); each call site belongs
160    /// on the application's raw-entry allowlist (`forma-raw-lint`) with an
161    /// owner.
162    pub fn into_parts_unchecked(self) -> PageParts {
163        let headers = self.headers();
164        PageParts {
165            html: self.html,
166            nonce: self.nonce,
167            headers,
168            counts: self.counts,
169        }
170    }
171
172    /// The headers this response writes, in order.
173    fn headers(&self) -> Vec<(HeaderName, HeaderValue)> {
174        let mut headers = Vec::with_capacity(9);
175        headers.push((
176            header::CONTENT_TYPE,
177            HeaderValue::from_static("text/html; charset=utf-8"),
178        ));
179        headers.push((header::CACHE_CONTROL, HeaderValue::from_static("no-store")));
180        headers.push((header::CONTENT_SECURITY_POLICY, self.policy.csp().clone()));
181        if let Some(report_only) = self.policy.report_only() {
182            headers.push((
183                header::CONTENT_SECURITY_POLICY_REPORT_ONLY,
184                report_only.clone(),
185            ));
186        }
187        if let Some(endpoints) = self.policy.reporting_endpoints() {
188            headers.push((
189                HeaderName::from_static("reporting-endpoints"),
190                endpoints.clone(),
191            ));
192        }
193        for (name, value) in crate::types::document_security_headers() {
194            // The opener policy is the page's own: the extensions may ask for
195            // `same-origin-allow-popups`, and a second COOP header would leave
196            // the browser to pick one.
197            if name.as_str() != "cross-origin-opener-policy" {
198                headers.push((name.clone(), value.clone()));
199            }
200        }
201        headers.push((
202            HeaderName::from_static("cross-origin-opener-policy"),
203            self.policy.opener().clone(),
204        ));
205        headers
206    }
207}
208
209impl IntoResponse for PageResponse {
210    fn into_response(self) -> Response {
211        let headers = self.headers();
212        let mut response = Response::new(axum::body::Body::from(self.html));
213        let map = response.headers_mut();
214        for (name, value) in headers {
215            map.append(name, value);
216        }
217        response
218    }
219}