use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use axum::http::StatusCode;
use seiva_identity::Principal;
use sha2::{Digest, Sha256};
use crate::problem::{Problem, ProblemResponse};
pub const IDEMPOTENCY_HEADER: &str = "idempotency-key";
pub const MAX_KEY_LEN: usize = 255;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IdempotencyKey(String);
impl IdempotencyKey {
pub fn parse(raw: &str) -> Result<Self, Problem> {
if raw.is_empty() {
return Err(bad_key("the Idempotency-Key must not be empty"));
}
if raw.len() > MAX_KEY_LEN {
return Err(bad_key("the Idempotency-Key is too long (max 255 bytes)"));
}
if !raw.bytes().all(|b| (0x21..=0x7e).contains(&b)) {
return Err(bad_key(
"the Idempotency-Key must be visible ASCII with no spaces or control characters",
));
}
Ok(Self(raw.to_owned()))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
fn bad_key(detail: &str) -> Problem {
Problem::new(StatusCode::BAD_REQUEST, "Bad Idempotency-Key").with_detail(detail)
}
#[derive(Debug, Clone)]
pub struct OptionalIdempotencyKey(pub Option<IdempotencyKey>);
impl<S: Sync> FromRequestParts<S> for OptionalIdempotencyKey {
type Rejection = ProblemResponse;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
match parts.headers.get(IDEMPOTENCY_HEADER) {
None => Ok(Self(None)),
Some(value) => {
let raw = value
.to_str()
.map_err(|_| bad_key("the Idempotency-Key must be valid ASCII"))?;
Ok(Self(Some(IdempotencyKey::parse(raw)?)))
}
}
}
}
#[must_use]
pub fn scoped_key(principal: &Principal, method: &str, path: &str, key: &IdempotencyKey) -> String {
let mut hasher = Sha256::new();
for part in [
principal.tenant.as_deref().unwrap_or(""),
principal.subject.as_str(),
method,
path,
key.as_str(),
] {
hasher.update((part.len() as u64).to_be_bytes());
hasher.update(part.as_bytes());
}
hex(&hasher.finalize())
}
#[must_use]
pub fn fingerprint(
method: &str,
path: &str,
query: Option<&str>,
body: &serde_json::Value,
) -> String {
let mut hasher = Sha256::new();
for part in [
method.as_bytes(),
path.as_bytes(),
query.unwrap_or("").as_bytes(),
] {
hasher.update((part.len() as u64).to_be_bytes());
hasher.update(part);
}
let body_bytes = serde_json::to_vec(body).unwrap_or_default();
hasher.update((body_bytes.len() as u64).to_be_bytes());
hasher.update(&body_bytes);
hex(&hasher.finalize())
}
#[must_use]
pub fn mismatch_problem() -> Problem {
Problem::new(StatusCode::CONFLICT, "Idempotency-Key reused")
.with_detail("this Idempotency-Key was already used for a request with different content")
}
#[must_use]
pub fn in_progress_problem() -> Problem {
Problem::new(StatusCode::CONFLICT, "Idempotent request in progress")
.with_detail("a request with this Idempotency-Key is still being processed; retry shortly")
}
pub(crate) fn hex(bytes: &[u8]) -> String {
let mut s = String::with_capacity(bytes.len() * 2);
for b in bytes {
s.push(char::from_digit((b >> 4) as u32, 16).unwrap());
s.push(char::from_digit((b & 0x0f) as u32, 16).unwrap());
}
s
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn key_validation_bounds_and_charset() {
assert!(IdempotencyKey::parse("abc-123_XYZ").is_ok());
assert!(IdempotencyKey::parse("").is_err(), "empty rejected");
assert!(
IdempotencyKey::parse(&"x".repeat(MAX_KEY_LEN + 1)).is_err(),
"over-long rejected"
);
assert!(
IdempotencyKey::parse("has space").is_err(),
"space rejected"
);
assert!(
IdempotencyKey::parse("ctl\u{7}").is_err(),
"control rejected"
);
}
#[test]
fn scoped_key_isolates_tenant_subject_and_operation() {
let key = IdempotencyKey::parse("k1").unwrap();
let acme = Principal::in_tenant("alice", "acme", ["x"]);
let globex = Principal::in_tenant("alice", "globex", ["x"]);
let bob = Principal::in_tenant("bob", "acme", ["x"]);
let base = scoped_key(&acme, "POST", "/v1/orders", &key);
assert_eq!(base, scoped_key(&acme, "POST", "/v1/orders", &key));
assert_ne!(base, scoped_key(&globex, "POST", "/v1/orders", &key));
assert_ne!(base, scoped_key(&bob, "POST", "/v1/orders", &key));
assert_ne!(base, scoped_key(&acme, "PUT", "/v1/orders", &key));
assert_ne!(base, scoped_key(&acme, "POST", "/v1/invoices", &key));
}
#[test]
fn fingerprint_is_canonical_and_content_sensitive() {
let a = fingerprint("POST", "/v1/o", None, &json!({"a":1,"b":2}));
let b = fingerprint("POST", "/v1/o", None, &json!({"b":2,"a":1}));
assert_eq!(a, b, "logically-equal bodies fingerprint the same");
assert_ne!(a, fingerprint("POST", "/v1/o", None, &json!({"a":1,"b":3})));
assert_ne!(
a,
fingerprint("POST", "/v1/o", Some("x=1"), &json!({"a":1,"b":2}))
);
}
#[test]
fn non_fresh_outcomes_map_to_409() {
assert_eq!(mismatch_problem().status, StatusCode::CONFLICT);
assert_eq!(in_progress_problem().status, StatusCode::CONFLICT);
}
}