Skip to main content

seiva_http/
idempotency.rs

1//! HTTP-facing building blocks for durable idempotency (ADR 0011).
2//!
3//! The durable guarantee itself lives in the **application layer**, inside the
4//! `UnitOfWork` transaction, so the reservation commits atomically with the
5//! domain mutation and the outbox write (`seiva_ports::IdempotencyStore`, proven
6//! against a real database by `seiva_data_dorm::DormIdempotencyStore`). A generic
7//! outer middleware could not keep that atomicity — it runs above any
8//! transaction — so this module gives the transport only its half:
9//!
10//! 1. [`IdempotencyKey`] — validate the `Idempotency-Key` header (bounded length,
11//!    visible-ASCII only), via the [`OptionalIdempotencyKey`] extractor.
12//! 2. [`scoped_key`] — fold the caller's tenant + subject + the operation
13//!    (method + path, which carries the API version segment) into the key the
14//!    store sees, so two tenants (or two identities) can never collide or replay
15//!    one another's result.
16//! 3. [`fingerprint`] — a canonical SHA-256 of the request's semantically
17//!    relevant arguments (method, path, query, and the body as canonical JSON —
18//!    `serde_json`'s default sorts object keys). The store answers
19//!    [`Mismatch`](seiva_ports::IdempotencyOutcome::Mismatch) when the same key
20//!    arrives with a different fingerprint.
21//! 4. [`mismatch_problem`] / [`in_progress_problem`] — map the non-`Fresh`
22//!    outcomes to RFC 9457 responses.
23//!
24//! The application threads the key + fingerprint into `IdempotencyStore::begin`
25//! inside its transaction; on `Fresh` it performs the effect and `finish`es, on
26//! `Replay` it returns the stored result, on `Mismatch`/`InProgress` it returns
27//! the problem below. Re-authorization holds because the scoped key is bound to
28//! the caller's identity: a different caller gets a different key and never reads
29//! a prior caller's response.
30
31use axum::extract::FromRequestParts;
32use axum::http::request::Parts;
33use axum::http::StatusCode;
34use seiva_identity::Principal;
35use sha2::{Digest, Sha256};
36
37use crate::problem::{Problem, ProblemResponse};
38
39/// The header carrying the client's idempotency key.
40pub const IDEMPOTENCY_HEADER: &str = "idempotency-key";
41
42/// The maximum accepted key length (bytes). Longer keys are rejected `400`, so a
43/// client cannot store unbounded data under a key.
44pub const MAX_KEY_LEN: usize = 255;
45
46/// A validated `Idempotency-Key`: non-empty, at most [`MAX_KEY_LEN`] bytes, and
47/// visible ASCII only (`0x21..=0x7E`) so it cannot smuggle control characters or
48/// whitespace into a header or a storage key.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct IdempotencyKey(String);
51
52impl IdempotencyKey {
53    /// Validates `raw` into a key, or a `400` [`Problem`] explaining why not.
54    ///
55    /// # Errors
56    ///
57    /// Returns a `400` problem when the key is empty, too long, or contains a
58    /// byte outside visible ASCII.
59    pub fn parse(raw: &str) -> Result<Self, Problem> {
60        if raw.is_empty() {
61            return Err(bad_key("the Idempotency-Key must not be empty"));
62        }
63        if raw.len() > MAX_KEY_LEN {
64            return Err(bad_key("the Idempotency-Key is too long (max 255 bytes)"));
65        }
66        if !raw.bytes().all(|b| (0x21..=0x7e).contains(&b)) {
67            return Err(bad_key(
68                "the Idempotency-Key must be visible ASCII with no spaces or control characters",
69            ));
70        }
71        Ok(Self(raw.to_owned()))
72    }
73
74    /// The validated key as a string slice.
75    #[must_use]
76    pub fn as_str(&self) -> &str {
77        &self.0
78    }
79}
80
81fn bad_key(detail: &str) -> Problem {
82    Problem::new(StatusCode::BAD_REQUEST, "Bad Idempotency-Key").with_detail(detail)
83}
84
85/// Extractor for an **optional** idempotency key: `Ok(None)` when the header is
86/// absent (idempotency is opt-in per request, never forced on every `POST`),
87/// `Err(400)` when it is present but malformed.
88#[derive(Debug, Clone)]
89pub struct OptionalIdempotencyKey(pub Option<IdempotencyKey>);
90
91impl<S: Sync> FromRequestParts<S> for OptionalIdempotencyKey {
92    // The `?` operator converts a `Problem` into the HTTP edge wrapper.
93    type Rejection = ProblemResponse;
94
95    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
96        match parts.headers.get(IDEMPOTENCY_HEADER) {
97            None => Ok(Self(None)),
98            Some(value) => {
99                let raw = value
100                    .to_str()
101                    .map_err(|_| bad_key("the Idempotency-Key must be valid ASCII"))?;
102                Ok(Self(Some(IdempotencyKey::parse(raw)?)))
103            }
104        }
105    }
106}
107
108/// Folds the caller's identity and the operation into the key the store sees, so
109/// keys are isolated per tenant and per subject (and per method+path, which
110/// carries the API version). Returns a fixed-length hex digest: bounded, and
111/// free of any delimiter a component could spoof.
112#[must_use]
113pub fn scoped_key(principal: &Principal, method: &str, path: &str, key: &IdempotencyKey) -> String {
114    let mut hasher = Sha256::new();
115    for part in [
116        principal.tenant.as_deref().unwrap_or(""),
117        principal.subject.as_str(),
118        method,
119        path,
120        key.as_str(),
121    ] {
122        // Length-prefix each field so distinct tuples cannot alias.
123        hasher.update((part.len() as u64).to_be_bytes());
124        hasher.update(part.as_bytes());
125    }
126    hex(&hasher.finalize())
127}
128
129/// A canonical SHA-256 fingerprint of the request's semantically relevant
130/// arguments. `body` is serialised with `serde_json` (whose default `Map` is a
131/// `BTreeMap`, so object keys are sorted) — the same body reorders to the same
132/// bytes, so a retry with logically-equal content matches.
133#[must_use]
134pub fn fingerprint(
135    method: &str,
136    path: &str,
137    query: Option<&str>,
138    body: &serde_json::Value,
139) -> String {
140    let mut hasher = Sha256::new();
141    for part in [
142        method.as_bytes(),
143        path.as_bytes(),
144        query.unwrap_or("").as_bytes(),
145    ] {
146        hasher.update((part.len() as u64).to_be_bytes());
147        hasher.update(part);
148    }
149    let body_bytes = serde_json::to_vec(body).unwrap_or_default();
150    hasher.update((body_bytes.len() as u64).to_be_bytes());
151    hasher.update(&body_bytes);
152    hex(&hasher.finalize())
153}
154
155/// The `409` problem for a key reused with a **different** request fingerprint:
156/// the same key must mean the same operation, so the server does not execute.
157#[must_use]
158pub fn mismatch_problem() -> Problem {
159    Problem::new(StatusCode::CONFLICT, "Idempotency-Key reused")
160        .with_detail("this Idempotency-Key was already used for a request with different content")
161}
162
163/// The `409` problem for a key whose first request is still in flight: the caller
164/// retries after a short delay (it adds its own `Retry-After` if it wishes).
165#[must_use]
166pub fn in_progress_problem() -> Problem {
167    Problem::new(StatusCode::CONFLICT, "Idempotent request in progress")
168        .with_detail("a request with this Idempotency-Key is still being processed; retry shortly")
169}
170
171/// Lowercase hex of a byte slice.
172pub(crate) fn hex(bytes: &[u8]) -> String {
173    let mut s = String::with_capacity(bytes.len() * 2);
174    for b in bytes {
175        s.push(char::from_digit((b >> 4) as u32, 16).unwrap());
176        s.push(char::from_digit((b & 0x0f) as u32, 16).unwrap());
177    }
178    s
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184    use serde_json::json;
185
186    #[test]
187    fn key_validation_bounds_and_charset() {
188        assert!(IdempotencyKey::parse("abc-123_XYZ").is_ok());
189        assert!(IdempotencyKey::parse("").is_err(), "empty rejected");
190        assert!(
191            IdempotencyKey::parse(&"x".repeat(MAX_KEY_LEN + 1)).is_err(),
192            "over-long rejected"
193        );
194        assert!(
195            IdempotencyKey::parse("has space").is_err(),
196            "space rejected"
197        );
198        assert!(
199            IdempotencyKey::parse("ctl\u{7}").is_err(),
200            "control rejected"
201        );
202    }
203
204    #[test]
205    fn scoped_key_isolates_tenant_subject_and_operation() {
206        let key = IdempotencyKey::parse("k1").unwrap();
207        let acme = Principal::in_tenant("alice", "acme", ["x"]);
208        let globex = Principal::in_tenant("alice", "globex", ["x"]);
209        let bob = Principal::in_tenant("bob", "acme", ["x"]);
210
211        let base = scoped_key(&acme, "POST", "/v1/orders", &key);
212        // Same inputs → same key.
213        assert_eq!(base, scoped_key(&acme, "POST", "/v1/orders", &key));
214        // Different tenant, subject, method or path → different key.
215        assert_ne!(base, scoped_key(&globex, "POST", "/v1/orders", &key));
216        assert_ne!(base, scoped_key(&bob, "POST", "/v1/orders", &key));
217        assert_ne!(base, scoped_key(&acme, "PUT", "/v1/orders", &key));
218        assert_ne!(base, scoped_key(&acme, "POST", "/v1/invoices", &key));
219    }
220
221    #[test]
222    fn fingerprint_is_canonical_and_content_sensitive() {
223        // Object key order does not matter (canonical JSON).
224        let a = fingerprint("POST", "/v1/o", None, &json!({"a":1,"b":2}));
225        let b = fingerprint("POST", "/v1/o", None, &json!({"b":2,"a":1}));
226        assert_eq!(a, b, "logically-equal bodies fingerprint the same");
227        // Different content → different fingerprint.
228        assert_ne!(a, fingerprint("POST", "/v1/o", None, &json!({"a":1,"b":3})));
229        // Query participates.
230        assert_ne!(
231            a,
232            fingerprint("POST", "/v1/o", Some("x=1"), &json!({"a":1,"b":2}))
233        );
234    }
235
236    #[test]
237    fn non_fresh_outcomes_map_to_409() {
238        assert_eq!(mismatch_problem().status, StatusCode::CONFLICT);
239        assert_eq!(in_progress_problem().status, StatusCode::CONFLICT);
240    }
241}