1use 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
39pub const IDEMPOTENCY_HEADER: &str = "idempotency-key";
41
42pub const MAX_KEY_LEN: usize = 255;
45
46#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct IdempotencyKey(String);
51
52impl IdempotencyKey {
53 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 #[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#[derive(Debug, Clone)]
89pub struct OptionalIdempotencyKey(pub Option<IdempotencyKey>);
90
91impl<S: Sync> FromRequestParts<S> for OptionalIdempotencyKey {
92 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#[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 hasher.update((part.len() as u64).to_be_bytes());
124 hasher.update(part.as_bytes());
125 }
126 hex(&hasher.finalize())
127}
128
129#[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#[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#[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
171pub(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 assert_eq!(base, scoped_key(&acme, "POST", "/v1/orders", &key));
214 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 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 assert_ne!(a, fingerprint("POST", "/v1/o", None, &json!({"a":1,"b":3})));
229 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}