Skip to main content

ash_jsonapi/
layer.rs

1//! The middleware every generated handler needs.
2//!
3//! [`api!`](crate::api!)'s handlers take the request's [`Context`] as an axum
4//! extension. Something has to put it there, and that is [`layer`]: it reads
5//! the client's request id, generates one when there is none, and attaches
6//! the context.
7//!
8//! ```ignore
9//! let app = routes()
10//!     .layer(ash_jsonapi::layer())
11//!     .with_state(state);
12//! ```
13//!
14//! Without it, every request fails with axum's "Missing request extension"
15//! `500` — the handlers cannot build a context themselves, because what goes
16//! into one (the principal, the tenant) is decided by middleware that runs
17//! before them.
18//!
19//! # Adding your own
20//!
21//! Authentication runs after this and adds to what it built:
22//!
23//! ```ignore
24//! async fn authenticate(mut req: Request, next: Next) -> Response {
25//!     let ctx = req
26//!         .extensions()
27//!         .get::<Context>()
28//!         .expect("ash_jsonapi::layer() runs first")
29//!         .clone()
30//!         .with_principal("alice@example.com");
31//!
32//!     req.extensions_mut().insert(ctx);
33//!     next.run(req).await
34//! }
35//! ```
36
37use std::sync::atomic::{AtomicU64, Ordering};
38use std::time::{SystemTime, UNIX_EPOCH};
39
40use axum::extract::Request;
41use axum::middleware::{Next, from_fn};
42use axum::response::Response;
43
44use crate::context::Context;
45
46/// The header a correlation id is read from and echoed back on.
47pub const REQUEST_ID: &str = "x-request-id";
48
49/// The header the response locale is negotiated from.
50pub const ACCEPT_LANGUAGE: &str = "accept-language";
51
52/// Attach a [`Context`] to every request.
53///
54/// The one piece of wiring [`api!`](crate::api!) requires:
55///
56/// ```ignore
57/// let app = routes()
58///     .layer(ash_jsonapi::layer())
59///     .with_state(state);
60/// ```
61///
62/// The correlation id is the client's `X-Request-Id` where it sent one, and
63/// a generated id otherwise. Either way it is echoed back on the response, so
64/// a client can quote it, and it is the `id` on every error object this crate
65/// returns — the thread tying a failed response to the log line explaining
66/// it.
67///
68/// Add authentication *after* this layer and extend the context it built,
69/// rather than replacing it — see the [module docs](self).
70pub fn layer()
71-> axum::middleware::FromFnLayer<impl FnMut(Request, Next) -> WithContext + Clone, (), (Request,)> {
72    // The last type parameter is axum's argument list *before* `Next`, so a
73    // middleware taking the whole request is the 1-tuple `(Request,)`.
74    from_fn(|request: Request, next: Next| with_context(request, next))
75}
76
77/// The future [`layer`]'s middleware returns.
78pub type WithContext = std::pin::Pin<Box<dyn Future<Output = Response> + Send>>;
79
80/// Read or generate the correlation id, attach the context, echo the id back.
81fn with_context(request: Request, next: Next) -> WithContext {
82    Box::pin(run(request, next))
83}
84
85async fn run(mut request: Request, next: Next) -> Response {
86    let id = request
87        .headers()
88        .get(REQUEST_ID)
89        .and_then(|value| value.to_str().ok())
90        // A client-supplied id reaches the logs, so it is bounded and
91        // filtered: an unbounded or newline-bearing header would let a
92        // caller forge log entries.
93        .filter(|id| !id.is_empty() && id.len() <= 128 && id.chars().all(is_safe))
94        .map(ToString::to_string)
95        .unwrap_or_else(request_id);
96
97    // The locale the client asked for, recorded on the context so a handler
98    // can consult it and the response can say what it negotiated. An absent
99    // or unparsable header simply leaves it unset.
100    let locale = request
101        .headers()
102        .get(ACCEPT_LANGUAGE)
103        .and_then(|value| value.to_str().ok())
104        .and_then(crate::i18n::Locale::negotiate);
105
106    let ctx = match locale {
107        Some(locale) => Context::new(&id).with_locale(locale),
108        None => Context::new(&id),
109    };
110
111    request.extensions_mut().insert(ctx);
112
113    let mut response = next.run(request).await;
114
115    // Echoed back so a client can quote the id when reporting a failure.
116    if let Ok(value) = id.parse() {
117        response.headers_mut().insert(REQUEST_ID, value);
118    }
119
120    response
121}
122
123/// Whether a character may appear in a client-supplied correlation id.
124///
125/// Conservative on purpose: this string is written to logs.
126fn is_safe(c: char) -> bool {
127    c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | ':')
128}
129
130/// A correlation id for a request that arrived without one.
131///
132/// Enough to correlate one request's log lines within a deployment: the
133/// process start time, and a counter. Not a UUID and not unguessable — if you
134/// need either, set `X-Request-Id` at your proxy, which is where a
135/// distributed trace id comes from anyway.
136fn request_id() -> String {
137    static COUNTER: AtomicU64 = AtomicU64::new(0);
138
139    // Read once per process: two processes starting in the same microsecond
140    // is the collision this does not defend against.
141    static START: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
142    let start = *START.get_or_init(|| {
143        SystemTime::now()
144            .duration_since(UNIX_EPOCH)
145            .map(|since| since.as_micros() as u64)
146            .unwrap_or(0)
147    });
148
149    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
150    format!("{start:x}-{n:x}")
151}