Merge pull request #49 from ModernRelay/ragnorc/x-request-id

Add X-Request-Id middleware
This commit is contained in:
Ragnor Comerford 2026-04-26 12:33:33 +02:00 committed by GitHub
commit b352fca13c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 142 additions and 0 deletions

View file

@ -2,6 +2,7 @@ pub mod api;
pub mod auth;
pub mod config;
pub mod policy;
pub mod request_id;
use std::collections::{HashMap, HashSet};
use std::fs;
@ -460,6 +461,7 @@ pub fn build_app(state: AppState) -> Router {
.merge(protected)
.layer(DefaultBodyLimit::max(DEFAULT_REQUEST_BODY_LIMIT_BYTES))
.layer(TraceLayer::new_for_http())
.layer(middleware::from_fn(request_id::request_id_middleware))
.with_state(state)
}

View file

@ -0,0 +1,59 @@
//! `X-Request-Id` middleware.
//!
//! Mints a ULID per inbound request, or echoes a caller-supplied
//! `X-Request-Id` header if it's well-formed. Stores the value in request
//! extensions so handlers can include it in error bodies, log lines, or
//! audit records, and surfaces it on the response header so SDK clients
//! can correlate logs across the wire.
use axum::{
body::Body,
extract::Request,
http::{HeaderName, HeaderValue},
middleware::Next,
response::Response,
};
use ulid::Ulid;
pub const X_REQUEST_ID: HeaderName = HeaderName::from_static("x-request-id");
/// Wraps a request id pulled out of (or minted into) request extensions.
#[derive(Clone, Debug)]
pub struct RequestId(pub String);
impl RequestId {
pub fn as_str(&self) -> &str {
&self.0
}
}
/// Acceptable inbound `X-Request-Id` shape: 1..=128 ASCII printable chars.
/// Rejecting wider input keeps the value safe to log and emit verbatim.
fn is_valid_inbound(raw: &str) -> bool {
!raw.is_empty()
&& raw.len() <= 128
&& raw
.bytes()
.all(|b| b.is_ascii_graphic() || b == b' ' || b == b'-' || b == b'_')
}
pub async fn request_id_middleware(mut req: Request<Body>, next: Next) -> Response {
let inbound = req
.headers()
.get(&X_REQUEST_ID)
.and_then(|v| v.to_str().ok())
.filter(|raw| is_valid_inbound(raw));
let id = match inbound {
Some(raw) => raw.to_owned(),
None => Ulid::new().to_string(),
};
req.extensions_mut().insert(RequestId(id.clone()));
let mut response = next.run(req).await;
if let Ok(value) = HeaderValue::from_str(&id) {
response.headers_mut().insert(X_REQUEST_ID, value);
}
response
}