arcature 0.1.0

Arcature: an opinionated full-stack Rust web framework. One package, batteries included.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
//! The handler-facing Inertia entry point, the Axum extractor, and the
//! Inertia middleware layer.

use std::convert::Infallible;
use std::sync::Arc;

use axum::body::Body;
use axum::body::HttpBody;
use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use axum::http::{HeaderMap, HeaderValue, Method, Request, StatusCode};
use axum::response::{IntoResponse, Response};
use tower::{Layer, Service};

use super::config::InertiaConfig;
use super::error::InertiaError;
use super::headers::Headers;
use super::page::{Component, Page, PageOptions};
use super::props::Props;
use super::request::InertiaRequest;
use super::response::{ensure_vary_x_inertia, html, json_response, serialize};
use crate::http::security::CspNonce;

/// The Inertia adapter entry point extracted in a handler. Carries the
/// request context, the resolved configuration, and this request's
/// Content-Security-Policy nonce when one was minted.
#[derive(Clone)]
pub struct Inertia {
    request: Arc<InertiaRequest>,
    config: InertiaConfig,
    nonce: Option<CspNonce>,
}

impl Inertia {
    /// The parsed Inertia request context.
    pub fn request(&self) -> &InertiaRequest {
        &self.request
    }

    /// The resolved Inertia configuration.
    pub fn config(&self) -> &InertiaConfig {
        &self.config
    }

    /// This request's Content-Security-Policy nonce, if
    /// [`SecurityHeaders::with_csp_nonce`] is installed.
    ///
    /// The renderer already puts it on the payload script; this is for a
    /// handler that renders something else of its own.
    ///
    /// [`SecurityHeaders::with_csp_nonce`]: crate::http::security::SecurityHeaders::with_csp_nonce
    pub fn nonce(&self) -> Option<&CspNonce> {
        self.nonce.as_ref()
    }

    /// Render a page from any serializable props. The normal path: serializes
    /// `props` to a JSON object and renders the page. On a first visit
    /// (non-Inertia request) returns the initial HTML; on an Inertia visit
    /// returns the JSON page object.
    pub async fn render(
        &self,
        component: impl Into<Component>,
        props: impl serde::Serialize,
    ) -> Result<Response, InertiaError> {
        self.render_with_options(component, props, PageOptions::new())
            .await
    }

    /// Render a page behind the Client Exposure Firewall.
    ///
    /// Identical to [`render`](Self::render) except for the bound: `P` must
    /// implement [`ClientData`](crate::inertia::contracts::ClientData), the
    /// explicit browser-safety opt-in the `#[page]` macro generates. A type
    /// that merely derives `Serialize` -- an internal domain model, say --
    /// does not compile here, so it cannot reach the browser by accident.
    ///
    /// `render` stays available for ad-hoc JSON props (the `inertia!()`
    /// macro path); `render_page` is the typed path a `#[page]` prop struct
    /// travels.
    pub async fn render_page<P>(
        &self,
        contract: crate::inertia::contracts::PageContract<P>,
        props: P,
    ) -> Result<Response, InertiaError>
    where
        P: crate::inertia::contracts::ClientData,
    {
        self.render(contract.name(), props).await
    }

    /// Render with page-level options (history flags, flash data).
    pub async fn render_with_options(
        &self,
        component: impl Into<Component>,
        props: impl serde::Serialize,
        options: PageOptions,
    ) -> Result<Response, InertiaError> {
        let page_props = serde_json::to_value(&props)?;
        let props = Props::from_serialized(page_props)?;
        self.render_advanced_with_options(component, props, options)
            .await
    }

    /// Render with advanced per-prop behavior (deferred, optional, merge).
    pub async fn render_advanced(
        &self,
        component: impl Into<Component>,
        props: Props,
    ) -> Result<Response, InertiaError> {
        self.render_advanced_with_options(component, props, PageOptions::new())
            .await
    }

    /// The single sink: resolve props, build the page object, dispatch JSON or
    /// HTML based on whether this is an Inertia request.
    pub async fn render_advanced_with_options(
        &self,
        component: impl Into<Component>,
        props: Props,
        options: PageOptions,
    ) -> Result<Response, InertiaError> {
        let component = component.into();
        let resolved = super::props::resolve(
            props,
            self.config.shared_props(),
            &self.request,
            component.as_str(),
        )
        .await?;
        let status = options.resolved_status();
        let mut metadata = resolved.metadata;
        metadata.apply_options(options);
        let page = Page {
            component: component.to_string(),
            props: serde_json::Value::Object(resolved.props),
            url: self.request.url().to_string(),
            version: self.config.version().map(|v| v.as_str().to_string()),
            metadata,
        };
        self.respond(page, status)
    }

    fn respond(&self, page: Page, status: StatusCode) -> Result<Response, InertiaError> {
        if self.request.is_inertia() {
            let json = serialize(&page)?;
            Ok(json_response(json, status))
        } else {
            html(&page, &self.config, self.nonce.clone(), status)
        }
    }

    /// Build a standard redirect (302/303) selecting the status from the
    /// request method.
    pub fn redirect(&self, location: impl Into<String>) -> super::redirect::Redirect {
        super::redirect::Redirect::to(location, self.request.method().clone())
    }
}

impl<S> FromRequestParts<S> for Inertia
where
    S: Send + Sync,
{
    type Rejection = Response;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        let Some(config) = parts.extensions.get::<InertiaConfig>().cloned() else {
            return Err(InertiaError::ConfigMissing.into_response());
        };
        let request = parts
            .extensions
            .get::<InertiaRequest>()
            .cloned()
            .map(Arc::new)
            .unwrap_or_else(|| {
                Arc::new(InertiaRequest::parse(
                    &parts.headers,
                    &parts.method,
                    &parts.uri,
                ))
            });
        // Put there by `SecurityHeaders` (pipeline stage 6) on the way down,
        // long before this extractor runs. Absent whenever the application did
        // not ask for a nonce, which is the common case.
        let nonce = parts.extensions.get::<CspNonce>().cloned();
        Ok(Inertia {
            request,
            config,
            nonce,
        })
    }
}

// --- The Inertia middleware layer -------------------------------------------

/// A Tower layer that installs the Inertia protocol behavior on a router.
#[derive(Clone)]
pub struct InertiaLayer {
    config: InertiaConfig,
}

impl InertiaLayer {
    /// Create a layer with the given Inertia configuration.
    pub fn new(config: InertiaConfig) -> Self {
        InertiaLayer { config }
    }
}

impl<S> Layer<S> for InertiaLayer {
    type Service = InertiaMiddleware<S>;

    fn layer(&self, inner: S) -> Self::Service {
        InertiaMiddleware {
            inner,
            config: self.config.clone(),
        }
    }
}

/// The service produced by [`InertiaLayer`].
#[derive(Clone)]
pub struct InertiaMiddleware<S> {
    inner: S,
    config: InertiaConfig,
}

impl<S, ReqBody> Service<Request<ReqBody>> for InertiaMiddleware<S>
where
    S: Service<Request<ReqBody>, Response = Response, Error = Infallible> + Clone + Send + 'static,
    S::Future: Send + 'static,
    ReqBody: Send + 'static,
{
    type Response = Response;
    type Error = Infallible;
    type Future = std::pin::Pin<
        Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>> + Send>,
    >;

    fn poll_ready(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, mut req: Request<ReqBody>) -> Self::Future {
        let config = self.config.clone();
        let (mut parts, body) = req.into_parts();
        let request_context = InertiaRequest::parse(&parts.headers, &parts.method, &parts.uri);

        // GET-only asset-version mismatch short-circuit.
        if let Some(short_circuit) = version_mismatch_response(&config, &request_context) {
            drop(body);
            return Box::pin(async move { Ok(short_circuit) });
        }

        parts.extensions.insert(config.clone());
        parts.extensions.insert(request_context.clone());
        // Read, not inserted: `SecurityHeaders` (stage 6) minted it well
        // outside this layer. A deferred `Page<T>` render happens below,
        // after the request has been consumed, so the value has to be taken
        // out while the parts are still in hand.
        let nonce = parts.extensions.get::<CspNonce>().cloned();
        req = Request::from_parts(parts, body);

        let mut inner = self.inner.clone();
        Box::pin(async move {
            let resp = inner.call(req).await?;
            // Deferred renders first: a `Page<T>` handler could only record
            // what to render, because `IntoResponse` never sees the request.
            // This is the first point that holds both halves. It must happen
            // before `post_process`, whose empty-body rule would otherwise
            // read the placeholder as "handler returned nothing".
            let resp = render_pending(resp, &request_context, &config, nonce).await;
            Ok(post_process(resp, &request_context))
        })
    }
}

/// Perform a render a `Page<T>` deferred to this layer, if there is one.
///
/// Responses without a [`PendingPage`](super::pending::PendingPage) pass
/// through untouched -- a handler that built its own response, a redirect, an
/// error, a static file.
async fn render_pending(
    mut resp: Response,
    request: &InertiaRequest,
    config: &InertiaConfig,
    nonce: Option<CspNonce>,
) -> Response {
    let Some(pending) = resp
        .extensions_mut()
        .remove::<super::pending::PendingPage>()
    else {
        return resp;
    };
    let (component, props) = pending.into_parts();
    let inertia = Inertia {
        request: Arc::new(request.clone()),
        config: config.clone(),
        nonce,
    };
    let mut rendered = match inertia.render(component, props).await {
        Ok(rendered) => rendered,
        Err(error) => return error.into_response(),
    };

    // The status belongs to the render -- the placeholder's was a stand-in
    // for "nobody rendered this". Headers the handler set are its own
    // (`Set-Cookie` from a flash, a `Cache-Control`), so they carry over,
    // except the two that describe the body that was just replaced.
    for (name, value) in resp.headers() {
        if name == axum::http::header::CONTENT_TYPE
            || name == axum::http::header::CONTENT_LENGTH
            || rendered.headers().contains_key(name)
        {
            continue;
        }
        rendered.headers_mut().append(name.clone(), value.clone());
    }
    rendered
}

fn version_mismatch_response(config: &InertiaConfig, request: &InertiaRequest) -> Option<Response> {
    if request.method() != Method::GET || !request.is_inertia() {
        return None;
    }
    // Absent on both sides is a match: an application with no build step
    // has no version to compare, and the client sends none back.
    let current = config.version_str();
    if request.request_version().unwrap_or_default() == current {
        return None;
    }
    let mut headers = HeaderMap::new();
    if let Ok(v) = HeaderValue::from_str(request.url()) {
        headers.insert(Headers::LOCATION, v);
    } else {
        return None;
    }
    if let Ok(v) = HeaderValue::from_str(current) {
        headers.insert(Headers::VERSION, v);
    } else {
        return None;
    }
    ensure_vary_x_inertia(&mut headers);
    Some((StatusCode::CONFLICT, headers, Body::empty()).into_response())
}

fn post_process(mut resp: Response, request: &InertiaRequest) -> Response {
    ensure_vary_x_inertia(resp.headers_mut());

    // Empty-response fallback: Inertia request with 200 + empty body -> 302
    // to referer (or request URL).
    if request.is_inertia()
        && resp.status() == StatusCode::OK
        && resp.body().size_hint().exact() == Some(0)
    {
        let destination = request.referer().unwrap_or_else(|| request.url());
        if let Ok(location) = HeaderValue::from_str(destination) {
            *resp.status_mut() = StatusCode::FOUND;
            resp.headers_mut()
                .insert(axum::http::header::LOCATION, location);
        }
    }

    // Convert bare 302 after PUT/PATCH/DELETE to 303.
    //
    // Only 302, and deliberately so. 302 is the ambiguous one -- the spec
    // says preserve the method, every browser turns it into a GET -- so the
    // protocol pins it down. 307 and 308 are unambiguous: a handler that
    // returned one asked for the method to be repeated, and overriding that
    // would be Arcature inventing a rule the official adapters do not have.
    if request.is_inertia()
        && matches!(
            request.method(),
            &Method::PUT | &Method::PATCH | &Method::DELETE
        )
        && resp.status() == StatusCode::FOUND
    {
        *resp.status_mut() = StatusCode::SEE_OTHER;
    }

    // Fragment redirect: 3xx with a `#` in Location -> 409 + X-Inertia-Redirect.
    if request.is_inertia() && !request.is_prefetch() {
        let is_redirect = matches!(resp.status().as_u16(), 301 | 302 | 303 | 307 | 308);
        if is_redirect
            && let Some(location) = resp.headers().get(axum::http::header::LOCATION).cloned()
            && let Ok(loc_str) = location.to_str()
            && loc_str.contains('#')
        {
            let mut headers = HeaderMap::new();
            headers.insert(Headers::REDIRECT, location);
            ensure_vary_x_inertia(&mut headers);
            *resp.status_mut() = StatusCode::CONFLICT;
            resp.headers_mut().remove(axum::http::header::LOCATION);
            for (k, v) in headers {
                if let Some(k) = k {
                    resp.headers_mut().append(k, v);
                }
            }
        }
    }

    resp
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::http::header::{CONTENT_TYPE, LOCATION, REFERER};
    use axum::http::{HeaderName, Uri};

    fn config(version: Option<&str>) -> InertiaConfig {
        let document = super::super::config::default_root_document("Test");
        match version {
            Some(version) => InertiaConfig::new(version, document).expect("config"),
            None => InertiaConfig::versionless(document),
        }
    }

    fn request(method: Method, pairs: &[(&'static str, &str)]) -> InertiaRequest {
        let mut headers = HeaderMap::new();
        for (name, value) in pairs {
            headers.insert(
                HeaderName::from_static(name),
                HeaderValue::from_str(value).expect("header value"),
            );
        }
        InertiaRequest::parse(&headers, &method, &Uri::from_static("/users"))
    }

    fn inertia_get() -> InertiaRequest {
        request(Method::GET, &[("x-inertia", "true")])
    }

    fn empty(status: StatusCode) -> Response {
        Response::builder()
            .status(status)
            .body(Body::empty())
            .expect("response")
    }

    fn redirect_to(status: StatusCode, location: &'static str) -> Response {
        let mut response = empty(status);
        response
            .headers_mut()
            .insert(LOCATION, HeaderValue::from_static(location));
        response
    }

    async fn render(request: InertiaRequest, options: PageOptions) -> Response {
        Inertia {
            request: Arc::new(request),
            config: config(Some("v1")),
            nonce: None,
        }
        .render_advanced_with_options("users/index", Props::new(), options)
        .await
        .expect("render succeeds")
    }

    async fn body_of(response: Response) -> String {
        let bytes = axum::body::to_bytes(response.into_body(), 1 << 20)
            .await
            .expect("body");
        String::from_utf8(bytes.to_vec()).expect("utf-8")
    }

    #[test]
    fn a_stale_asset_version_turns_a_get_into_a_conflict() {
        let response = version_mismatch_response(
            &config(Some("v2")),
            &request(
                Method::GET,
                &[("x-inertia", "true"), ("x-inertia-version", "v1")],
            ),
        )
        .expect("a mismatch must short-circuit");
        assert_eq!(response.status(), StatusCode::CONFLICT);
        assert_eq!(response.headers()[Headers::LOCATION], "/users");
        assert_eq!(response.headers()[Headers::VERSION], "v2");
        assert_eq!(response.headers()[Headers::VARY], "X-Inertia");
    }

    #[test]
    fn only_an_inertia_get_is_short_circuited() {
        // A stale POST still reaches the handler. The client resolves a
        // mismatch by reloading the location it is given, and a reload cannot
        // replay a form submission -- so short-circuiting one would lose it.
        let stale = &[("x-inertia", "true"), ("x-inertia-version", "v1")];
        assert!(
            version_mismatch_response(&config(Some("v2")), &request(Method::POST, stale)).is_none()
        );
        // Not an Inertia request at all: a plain browser navigation has no
        // version to be stale, and answering it with a 409 would show the
        // user an error page instead of the site.
        assert!(
            version_mismatch_response(
                &config(Some("v2")),
                &request(Method::GET, &[("x-inertia-version", "v1")])
            )
            .is_none()
        );
    }

    #[test]
    fn an_application_without_an_asset_version_never_forces_a_reload() {
        assert!(version_mismatch_response(&config(None), &inertia_get()).is_none());
    }

    #[tokio::test]
    async fn an_absent_asset_version_reaches_the_client_as_null() {
        let response = Inertia {
            request: Arc::new(inertia_get()),
            config: config(None),
            nonce: None,
        }
        .render_advanced("users/index", Props::new())
        .await
        .expect("render succeeds");
        let page: serde_json::Value =
            serde_json::from_str(&body_of(response).await).expect("json page");
        assert_eq!(page["version"], serde_json::Value::Null);
        assert_eq!(page["component"], "users/index");
        assert_eq!(page["url"], "/users");
    }

    #[tokio::test]
    async fn an_inertia_visit_gets_the_page_object_as_json() {
        let response = render(inertia_get(), PageOptions::new()).await;
        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(response.headers()[Headers::INERTIA], "true");
        assert_eq!(response.headers()[CONTENT_TYPE], "application/json");
        let page: serde_json::Value =
            serde_json::from_str(&body_of(response).await).expect("json page");
        assert_eq!(page["version"], "v1");
        assert_eq!(page["props"]["errors"], serde_json::json!({}));
    }

    #[tokio::test]
    async fn a_first_visit_gets_html_carrying_the_page_object() {
        let response = render(request(Method::GET, &[]), PageOptions::new()).await;
        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(response.headers()[CONTENT_TYPE], "text/html; charset=utf-8");
        assert!(!response.headers().contains_key(Headers::INERTIA));
        let html = body_of(response).await;
        assert!(html.contains("data-page=\"app\""), "{html}");
        assert!(html.contains("users\\/index"), "{html}");
    }

    #[tokio::test]
    async fn a_page_can_render_with_an_error_status() {
        let response = render(
            inertia_get(),
            PageOptions::new().status(StatusCode::NOT_FOUND),
        )
        .await;
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
        assert_eq!(response.headers()[Headers::INERTIA], "true");
    }

    #[tokio::test]
    async fn an_error_status_survives_the_html_path_too() {
        let response = render(
            request(Method::GET, &[]),
            PageOptions::new().status(StatusCode::NOT_FOUND),
        )
        .await;
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
        assert_eq!(response.headers()[CONTENT_TYPE], "text/html; charset=utf-8");
    }

    #[test]
    fn an_empty_inertia_ok_redirects_back_to_the_referer() {
        // The handler returned nothing, which for a form submission means
        // "stay where you were". Without this the client would replace the
        // page with an empty one.
        let response = post_process(
            empty(StatusCode::OK),
            &request(
                Method::POST,
                &[("x-inertia", "true"), ("referer", "/dashboard")],
            ),
        );
        assert_eq!(response.status(), StatusCode::FOUND);
        assert_eq!(response.headers()[LOCATION], "/dashboard");
    }

    #[test]
    fn an_empty_inertia_ok_falls_back_to_the_request_url() {
        let response = post_process(empty(StatusCode::OK), &inertia_get());
        assert_eq!(response.status(), StatusCode::FOUND);
        assert_eq!(response.headers()[LOCATION], "/users");
    }

    #[test]
    fn a_response_with_a_body_is_left_where_it_is() {
        let response = post_process(Response::new(Body::from("{}")), &inertia_get());
        assert_eq!(response.status(), StatusCode::OK);
        assert!(!response.headers().contains_key(LOCATION));
    }

    #[test]
    fn an_empty_ok_outside_inertia_is_still_an_empty_ok() {
        let response = post_process(empty(StatusCode::OK), &request(Method::GET, &[]));
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[test]
    fn a_found_after_a_delete_becomes_a_see_other() {
        for method in [Method::PUT, Method::PATCH, Method::DELETE] {
            let response = post_process(
                redirect_to(StatusCode::FOUND, "/users"),
                &request(method.clone(), &[("x-inertia", "true")]),
            );
            assert_eq!(response.status(), StatusCode::SEE_OTHER, "{method}");
        }
    }

    #[test]
    fn a_temporary_redirect_keeps_the_method_it_asked_to_keep() {
        // 307 says "repeat the method" on purpose. Rewriting it to 303 would
        // be this adapter overruling the handler, and no official adapter
        // does that -- only the ambiguous 302 is pinned down.
        let response = post_process(
            redirect_to(StatusCode::TEMPORARY_REDIRECT, "/users"),
            &request(Method::DELETE, &[("x-inertia", "true")]),
        );
        assert_eq!(response.status(), StatusCode::TEMPORARY_REDIRECT);
    }

    #[test]
    fn a_redirect_to_a_fragment_becomes_a_client_side_redirect() {
        // A fetch follows the redirect and drops the fragment on the floor,
        // so the destination has to travel in a header the client reads.
        let response = post_process(
            redirect_to(StatusCode::FOUND, "/users#team"),
            &inertia_get(),
        );
        assert_eq!(response.status(), StatusCode::CONFLICT);
        assert_eq!(response.headers()[Headers::REDIRECT], "/users#team");
        assert!(
            !response.headers().contains_key(LOCATION),
            "leaving Location behind would have the client follow it twice"
        );
    }

    #[test]
    fn a_prefetch_is_not_navigated_on_its_behalf() {
        // The user has not visited anything yet. Turning a prefetch into a
        // 409 would move the page they are still looking at.
        let response = post_process(
            redirect_to(StatusCode::FOUND, "/users#team"),
            &request(
                Method::GET,
                &[("x-inertia", "true"), ("purpose", "prefetch")],
            ),
        );
        assert_eq!(response.status(), StatusCode::FOUND);
        assert_eq!(response.headers()[LOCATION], "/users#team");
    }

    #[test]
    fn every_response_advertises_that_it_varies_on_x_inertia() {
        // Without it a cache serves an HTML document to an Inertia visit, or
        // a JSON page object to a browser navigation.
        let response = post_process(Response::new(Body::from("hi")), &request(Method::GET, &[]));
        assert_eq!(response.headers()[Headers::VARY], "X-Inertia");
    }

    #[test]
    fn an_application_vary_is_kept_alongside_it() {
        let mut original = Response::new(Body::from("hi"));
        original
            .headers_mut()
            .insert(Headers::VARY, HeaderValue::from_static("Accept-Encoding"));
        let response = post_process(original, &inertia_get());
        assert_eq!(
            response.headers()[Headers::VARY],
            "Accept-Encoding, X-Inertia"
        );
    }

    #[test]
    fn a_referer_is_read_from_the_standard_header() {
        // Guards the header name itself: `REFERER` is the misspelling the
        // HTTP standard froze, and a typo here silently loses the fallback.
        let mut headers = HeaderMap::new();
        headers.insert(REFERER, HeaderValue::from_static("/back"));
        let parsed = InertiaRequest::parse(&headers, &Method::GET, &Uri::from_static("/users"));
        assert_eq!(parsed.referer(), Some("/back"));
    }
}