use axum::{
extract::{MatchedPath, Request, State},
http::HeaderValue,
middleware::Next,
response::Response,
};
use capy_core::ErrorKind;
use std::{
sync::Arc,
time::{Duration, Instant},
};
use tracing::Instrument;
pub(crate) const DEFAULT_FILTER: &str = "info,sqlx=warn,sea_orm=warn";
#[derive(Clone, Debug)]
pub struct RequestObservation {
pub request_id: String,
pub method: String,
pub route: String,
pub status: u16,
pub duration: Duration,
pub error_kind: Option<&'static str>,
}
pub trait RequestObserver: Send + Sync + 'static {
fn on_response(&self, observation: &RequestObservation);
}
impl<F: Fn(&RequestObservation) + Send + Sync + 'static> RequestObserver for F {
fn on_response(&self, observation: &RequestObservation) {
self(observation);
}
}
pub(crate) type Observer = Option<Arc<dyn RequestObserver>>;
pub(crate) async fn request(
State(observer): State<Observer>,
mut request: Request,
next: Next,
) -> Response {
let id = request
.headers()
.get("x-request-id")
.and_then(|value| value.to_str().ok())
.filter(|value| {
!value.is_empty()
&& value.len() <= 128
&& value
.bytes()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_' | b'.'))
})
.map(str::to_owned)
.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
let header = HeaderValue::from_str(&id).expect("validated ASCII request ID");
request.headers_mut().insert("x-request-id", header.clone());
let method = request.method().clone();
let route = request
.extensions()
.get::<MatchedPath>()
.map(|path| path.as_str())
.unwrap_or_else(|| request.uri().path())
.to_owned();
let observed_route = request
.extensions()
.get::<MatchedPath>()
.map(|path| path.as_str())
.unwrap_or("<unmatched>")
.to_owned();
let span = tracing::info_span!("http.request", request_id = %id, %method, %route);
async move {
let started = Instant::now();
let mut response = next.run(request).await;
response.headers_mut().insert("x-request-id", header);
let status = response.status().as_u16();
let latency_ms = started.elapsed().as_secs_f64() * 1000.0;
if let Some(observer) = observer {
observer.on_response(&RequestObservation {
request_id: id.clone(), method: method.to_string(), route: observed_route,
status, duration: started.elapsed(),
error_kind: response.extensions().get::<ErrorKind>().map(|kind| kind.0),
});
}
if response.status().is_server_error() {
let error_kind = response.extensions().get::<ErrorKind>().map_or("internal", |kind| kind.0);
tracing::error!(request_id = %id, %method, %route, status, latency_ms, error_kind, "request failed");
} else {
tracing::info!(request_id = %id, %method, %route, status, latency_ms, "request completed");
}
response
}.instrument(span).await
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{App, AppConfig, AppContext, AppError, Routes};
use capy_testing::TestApp;
use std::{
io::Write,
sync::{Arc, Mutex},
};
use tracing::instrument::WithSubscriber;
#[derive(Clone)]
struct Capture(Arc<Mutex<Vec<u8>>>);
impl Write for Capture {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[tokio::test]
async fn production_diagnostics_correlate_requests_without_secrets() {
let bytes = Arc::new(Mutex::new(Vec::new()));
let capture = Capture(bytes.clone());
let subscriber = tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::new(DEFAULT_FILTER))
.json()
.with_ansi(false)
.with_writer(move || capture.clone())
.finish();
async {
let mut config = AppConfig::default();
config.app.environment = "production".into();
config.database.url = "sqlite::memory:".into();
let context = AppContext {
db: capy_db::connect(&config.database).await.unwrap(),
config: Arc::new(config),
};
let app = TestApp::new(
App::new()
.routes(
Routes::new()
.get("/posts/{id}", crate::health)
.get("/failure", || async {
AppError::Database(sea_orm::DbErr::Custom(
"postgres://secret:password@host/private SQL SELECT".into(),
))
})
.get("/native", || async {
axum::http::StatusCode::INTERNAL_SERVER_ERROR
}),
)
.into_router(context),
);
let response = app
.get("/posts/123?token=secret-query")
.header(
"x-request-id".parse().unwrap(),
HeaderValue::from_static("request-123"),
)
.header(
"authorization".parse().unwrap(),
HeaderValue::from_static("Bearer secret-header"),
)
.send()
.await;
response.assert_ok();
assert_eq!(response.headers["x-request-id"], "request-123");
let failure = app.get("/failure").send().await;
failure.assert_json(serde_json::json!({"message": "Internal server error"}));
assert!(
uuid::Uuid::parse_str(failure.headers["x-request-id"].to_str().unwrap()).is_ok()
);
for id in ["", "bad id", "x\"y", &"a".repeat(129)] {
let response = app
.get("/native")
.header(
"x-request-id".parse().unwrap(),
HeaderValue::from_str(id).unwrap(),
)
.send()
.await;
assert!(
uuid::Uuid::parse_str(response.headers["x-request-id"].to_str().unwrap())
.is_ok()
);
}
app.get("/missing?token=secret-query")
.send()
.await
.assert_status(axum::http::StatusCode::NOT_FOUND);
}
.with_subscriber(subscriber)
.await;
let output = String::from_utf8(bytes.lock().unwrap().clone()).unwrap();
for secret in [
"password",
"secret",
"SQL SELECT",
"authorization",
"123?token",
] {
assert!(!output.contains(secret), "{output}");
}
let events: Vec<serde_json::Value> = output
.lines()
.map(|line| serde_json::from_str(line).unwrap())
.collect();
let requests: Vec<_> = events
.iter()
.filter(|event| event["fields"]["status"].is_number())
.collect();
assert_eq!(requests.len(), 7, "one completion per request: {output}");
let success = requests
.iter()
.find(|e| e["fields"]["status"] == 200)
.unwrap();
assert_eq!(success["level"], "INFO");
assert_eq!(success["fields"]["route"], "/posts/{id}");
assert_eq!(success["fields"]["request_id"], "request-123");
assert_eq!(success["span"]["request_id"], "request-123");
assert!(requests
.iter()
.any(|e| e["fields"]["route"] == "/missing" && e["fields"]["status"] == 404));
assert!(requests.iter().any(|e| e["level"] == "ERROR"
&& e["fields"]["error_kind"] == "database"
&& e["fields"]["status"] == 500));
for event in requests {
assert_eq!(event["fields"]["method"], "GET");
assert!(event["fields"]["latency_ms"].is_number());
assert!(event["fields"]["request_id"].is_string());
}
}
#[tokio::test]
async fn startup_errors_retain_native_causes_but_format_safely() {
use std::error::Error;
let settings = crate::DatabaseSettings {
url: "postgres://private-user:private-password@127.0.0.1:1/private-db".into(),
connect_timeout_seconds: 1,
..Default::default()
};
let error = capy_db::connect(&settings).await.unwrap_err();
assert!(error
.source()
.unwrap()
.downcast_ref::<sea_orm::DbErr>()
.is_some());
let display = format!("{error} {error:?}");
assert!(display.contains("Failed to connect to database"));
for secret in [
"private-user",
"private-password",
"private-db",
"postgres://",
] {
assert!(!display.contains(secret));
}
let error = AppError::DatabaseConnection(sea_orm::DbErr::Conn(
sea_orm::RuntimeErr::SqlxError(sea_orm::SqlxError::Io(std::io::Error::new(
std::io::ErrorKind::ConnectionRefused,
"private-password",
))),
));
assert!(error.to_string().contains("connection refused"));
assert!(!format!("{error:?}").contains("private-password"));
assert!(error.source().unwrap().source().is_some());
}
}