Skip to main content

fusion_stack/
idempotency.rs

1//! Idempotency keys, as the PHP package's `Idempotency` middleware handles them: a POST, PATCH or
2//! DELETE with an `Idempotency-Key` runs once, and retries with the same key get the stored
3//! response with `Idempotent-Replayed: true`. A retry must be the same request (the same version,
4//! query and body), or it gets a 422 `idempotency_key_mismatch`. While the first request runs,
5//! retries get a 409 `idempotency_in_progress`.
6//!
7//! Keys are scoped to the API client. A request without one is a guest's, scoped to the address
8//! it came from, as guest rate limits are, so guests at one address share their keys. A user
9//! signed in through Laravel's own guards rather than as a client has no scope of their own, and
10//! the framework says only that someone is signed in, not who. Such a request runs without its
11//! key: it is neither replayed a response from a guest scope nor stored in one, so a retry runs
12//! again. This sees only a user signed in before the `FusionStack` middleware runs.
13
14use std::time::Duration;
15
16use base64::Engine;
17use base64::engine::general_purpose::STANDARD;
18use laravel::axum::body::{Body, to_bytes};
19use laravel::axum::http::{HeaderName, HeaderValue, StatusCode};
20use laravel::cache::Repository;
21use laravel::http::{Request, Response};
22use serde::{Deserialize, Serialize};
23use sha2::{Digest, Sha256};
24
25use crate::errors::{ApiError, ApiErrorCode};
26use crate::{Config, Context};
27
28/// The request header that carries the key.
29pub const HEADER: &str = "Idempotency-Key";
30
31/// The response header that marks a replay.
32pub const REPLAYED_HEADER: &str = "idempotent-replayed";
33
34/// Headers that belong to one delivery of the response, not to the response itself.
35const UNSTORED_HEADERS: [&str; 3] = ["date", "x-request-id", "set-cookie"];
36
37#[derive(Serialize, Deserialize)]
38struct Stored {
39    fingerprint: String,
40    status: u16,
41    headers: Vec<(String, String)>,
42    body: String,
43}
44
45fn sha256(parts: &[&str]) -> String {
46    Sha256::digest(parts.join("\n").as_bytes())
47        .iter()
48        .map(|byte| format!("{byte:02x}"))
49        .collect()
50}
51
52/// Runs `inner` once per idempotency key. Requests without a key, with another method, or with
53/// idempotency off go straight to `inner`.
54pub(crate) async fn guard<F, Fut>(
55    config: &Config,
56    version: &str,
57    mut request: Request,
58    inner: F,
59) -> Result<Response, Box<(ApiError, Request)>>
60where
61    F: FnOnce(Request) -> Fut,
62    Fut: Future<Output = Response>,
63{
64    let settings = &config.idempotency;
65    let method = request.method().as_str().to_owned();
66    let key = request.header(HEADER).map(str::to_owned);
67    let Some(key) = key.filter(|_| settings.enabled && settings.methods.contains(&method)) else {
68        return Ok(inner(request).await);
69    };
70
71    if key.is_empty() || key.len() > 255 {
72        return Err(Box::new((
73            ApiError::new(
74                ApiErrorCode::InvalidIdempotencyKey,
75                "Use a unique value of up to 255 characters, such as a UUID.",
76            )
77            .header_source(HEADER),
78            request,
79        )));
80    }
81
82    let client = request
83        .extension::<Context>()
84        .and_then(|context| context.client.as_ref());
85    // Someone is signed in, but not as a client: their response must not go in a guest scope,
86    // and there is nothing else to scope the key to. The request runs without its key.
87    if client.is_none() {
88        match request.authenticated().await {
89            Ok(false) => {}
90            Ok(true) => return Ok(inner(request).await),
91            Err(error) => return Ok(Response::new(error)),
92        }
93    }
94    let scope = client.map_or_else(
95        || format!("guest:{}", request.ip()),
96        |client| format!("client:{}", client.idempotency_scope),
97    );
98    let store = match store(settings.store.as_deref()) {
99        Ok(store) => store,
100        Err(error) => return Ok(Response::new(error)),
101    };
102    let path = request.path().trim_start_matches('/').to_owned();
103    let store_key = format!(
104        "fusion-stack:idempotency:{}",
105        sha256(&[&scope, &method, &path, &key])
106    );
107    // The body as the client sent it, as PHP's getContent() reads it.
108    if let Err(error) = request.load_input().await {
109        return Ok(Response::new(error));
110    }
111    let body = request
112        .content()
113        .map(|bytes| String::from_utf8_lossy(bytes).into_owned())
114        .unwrap_or_default();
115    let fingerprint = sha256(&[version, request.uri().query().unwrap_or_default(), &body]);
116
117    if let Ok(Some(stored)) = store.get::<Stored>(&store_key).await {
118        return replay(stored, &fingerprint, request);
119    }
120
121    let lock = store.lock(
122        &store_key.replacen("idempotency:", "idempotency-lock:", 1),
123        Duration::from_secs(settings.lock_seconds),
124    );
125    if !lock.acquire().await.unwrap_or(false) {
126        return Err(Box::new((
127            ApiError::new(
128                ApiErrorCode::IdempotencyInProgress,
129                "A request with this Idempotency-Key is still running. Retry when it has finished.",
130            )
131            .header_source(HEADER),
132            request,
133        )));
134    }
135
136    // The first request may have finished between the lookup and the lock.
137    if let Ok(Some(stored)) = store.get::<Stored>(&store_key).await {
138        let _ = lock.release().await;
139        return replay(stored, &fingerprint, request);
140    }
141
142    let response = inner(request).await;
143    let response = remember(&store, &store_key, fingerprint, settings.ttl, response).await;
144    let _ = lock.release().await;
145    Ok(response)
146}
147
148fn store(name: Option<&str>) -> laravel::Result<Repository> {
149    match name {
150        Some(name) => laravel::cache::store(name),
151        None => laravel::cache::manager().default_store(),
152    }
153}
154
155fn replay(
156    stored: Stored,
157    fingerprint: &str,
158    request: Request,
159) -> Result<Response, Box<(ApiError, Request)>> {
160    if stored.fingerprint != fingerprint {
161        return Err(Box::new((
162            ApiError::new(
163                ApiErrorCode::IdempotencyKeyMismatch,
164                "This Idempotency-Key was used for a different request. Use a new key for each new request.",
165            )
166            .header_source(HEADER),
167            request,
168        )));
169    }
170    let mut response = laravel::axum::http::Response::new(Body::from(
171        STANDARD.decode(stored.body).unwrap_or_default(),
172    ));
173    *response.status_mut() = StatusCode::from_u16(stored.status).unwrap_or(StatusCode::OK);
174    let headers = response.headers_mut();
175    for (name, value) in stored.headers {
176        if let (Ok(name), Ok(value)) = (HeaderName::try_from(name), HeaderValue::try_from(value)) {
177            headers.append(name, value);
178        }
179    }
180    headers.insert(
181        HeaderName::from_static(REPLAYED_HEADER),
182        HeaderValue::from_static("true"),
183    );
184    Ok(Response::from_http(response))
185}
186
187/// Stores 2xx and 4xx responses. A 5xx, a 429 or a 401 says nothing final about the request, so
188/// it is not stored and the client can retry it: a 401 is about the caller's credentials, and a
189/// stored one would be replayed to them after they signed in.
190async fn remember(
191    store: &Repository,
192    key: &str,
193    fingerprint: String,
194    ttl: u64,
195    response: Response,
196) -> Response {
197    let http = response.into_http();
198    let status = http.status().as_u16();
199    // PHP checks scopes before it looks at the key, so a scope error is not kept either.
200    let denied = laravel::context::get_hidden::<bool>(crate::auth::DENIED).unwrap_or(false);
201    let storable = !denied
202        && ((200..300).contains(&status)
203            || ((400..500).contains(&status) && status != 401 && status != 429));
204    if !storable {
205        return Response::from_http(http);
206    }
207    let (parts, body) = http.into_parts();
208    let bytes = to_bytes(body, usize::MAX).await.unwrap_or_default();
209    let stored = Stored {
210        fingerprint,
211        status,
212        headers: parts
213            .headers
214            .iter()
215            .filter(|(name, _)| !UNSTORED_HEADERS.contains(&name.as_str()))
216            .filter_map(|(name, value)| {
217                Some((name.as_str().to_owned(), value.to_str().ok()?.to_owned()))
218            })
219            .collect(),
220        body: STANDARD.encode(&bytes),
221    };
222    // A store that can't be written only loses the replay; the request itself succeeded.
223    let _ = store.put(key, &stored, Duration::from_secs(ttl)).await;
224    Response::from_http(laravel::axum::http::Response::from_parts(
225        parts,
226        Body::from(bytes),
227    ))
228}