use std::{convert::Infallible, fmt, net::IpAddr};
use axum::{
extract::FromRequestParts,
http::{HeaderMap, HeaderValue, request::Parts},
};
use serde::{Deserialize, Deserializer, Serialize};
use crate::{auth::Principal, http::trusted_proxy::ForwardedHeadersPolicy, net::ClientIp};
use super::{
forwarding::{ClientIpSource, client_ip_from_forwarded_headers},
identifiers::{REQUEST_ID_HEADER_NAME, RequestId, TRACEPARENT_HEADER_NAME, TraceParent},
};
pub const LOCALE_HEADER_NAME: &str = "x-locale";
pub const TIME_ZONE_HEADER_NAME: &str = "x-time-zone";
pub const UTC_OFFSET_HEADER_NAME: &str = "x-utc-offset";
pub const CLIENT_ID_HEADER_NAME: &str = "x-client-id";
pub const SESSION_ID_HEADER_NAME: &str = "x-session-id";
pub const MAX_REQUEST_CONTEXT_VALUE_LENGTH: usize = 256;
pub const MAX_USER_AGENT_LENGTH: usize = 512;
#[derive(Clone, Serialize)]
pub struct RequestContext {
request_id: RequestId,
traceparent: Option<TraceParent>,
client_ip: Option<ClientIp>,
client_ip_source: Option<ClientIpSource>,
locale: Option<String>,
time_zone: Option<String>,
utc_offset_minutes: Option<i16>,
user_agent: Option<String>,
client_id: Option<String>,
session_id: Option<String>,
principal: Option<Principal>,
}
impl fmt::Debug for RequestContext {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("RequestContext")
.field("request_id", &self.request_id)
.field("traceparent", &self.traceparent)
.field("client_ip", &self.client_ip.as_ref().map(|_| "[REDACTED]"))
.field("client_ip_source", &self.client_ip_source)
.field("locale", &self.locale.as_ref().map(|_| "[REDACTED]"))
.field("time_zone", &self.time_zone.as_ref().map(|_| "[REDACTED]"))
.field("utc_offset_minutes", &self.utc_offset_minutes)
.field(
"user_agent",
&self.user_agent.as_ref().map(|_| "[REDACTED]"),
)
.field("client_id", &self.client_id.as_ref().map(|_| "[REDACTED]"))
.field(
"session_id",
&self.session_id.as_ref().map(|_| "[REDACTED]"),
)
.field("principal", &self.principal)
.finish()
}
}
impl<'de> Deserialize<'de> for RequestContext {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
struct RequestContextWire {
request_id: RequestId,
#[serde(default)]
traceparent: Option<TraceParent>,
#[serde(default)]
client_ip: Option<ClientIp>,
#[serde(default)]
client_ip_source: Option<ClientIpSource>,
#[serde(default)]
locale: Option<String>,
#[serde(default)]
time_zone: Option<String>,
#[serde(default)]
utc_offset_minutes: Option<i16>,
#[serde(default)]
user_agent: Option<String>,
#[serde(default)]
client_id: Option<String>,
#[serde(default)]
session_id: Option<String>,
#[serde(default)]
principal: Option<Principal>,
}
let wire = RequestContextWire::deserialize(deserializer)?;
let mut context = Self {
request_id: wire.request_id,
traceparent: wire.traceparent,
client_ip: None,
client_ip_source: None,
locale: wire.locale.as_deref().and_then(normalize_locale),
time_zone: wire.time_zone.as_deref().and_then(normalize_time_zone),
utc_offset_minutes: wire
.utc_offset_minutes
.filter(|value| valid_utc_offset_minutes(*value)),
user_agent: wire.user_agent.as_deref().and_then(normalize_user_agent),
client_id: wire.client_id.as_deref().and_then(normalize_context_id),
session_id: wire.session_id.as_deref().and_then(normalize_context_id),
principal: wire.principal,
};
if let Some(client_ip) = wire.client_ip {
context.client_ip = Some(client_ip);
context.client_ip_source = wire.client_ip_source.or(Some(ClientIpSource::Explicit));
}
Ok(context)
}
}
impl RequestContext {
pub(crate) fn from_parts(parts: &mut Parts) -> &mut Self {
parts
.extensions
.get_or_insert_with(|| Self::from_headers(&parts.headers))
}
#[must_use]
pub fn new(request_id: RequestId, traceparent: Option<String>) -> Self {
let traceparent = traceparent.and_then(|value| TraceParent::new(value).ok());
Self {
request_id,
traceparent,
client_ip: None,
client_ip_source: None,
locale: None,
time_zone: None,
utc_offset_minutes: None,
user_agent: None,
client_id: None,
session_id: None,
principal: None,
}
}
#[must_use]
pub fn from_headers(headers: &HeaderMap) -> Self {
Self::from_headers_and_peer_ip(headers, None)
}
#[must_use]
pub fn from_headers_and_peer_ip(headers: &HeaderMap, peer_client_ip: Option<IpAddr>) -> Self {
Self::from_headers_with_peer_ip_and_forwarded_policy(
headers,
peer_client_ip,
&ForwardedHeadersPolicy::never(),
)
}
#[must_use]
pub fn from_headers_and_peer_ip_with_forwarded_policy(
headers: &HeaderMap,
peer_client_ip: Option<IpAddr>,
forwarded_headers: &ForwardedHeadersPolicy,
) -> Self {
Self::from_headers_with_peer_ip_and_forwarded_policy(
headers,
peer_client_ip,
forwarded_headers,
)
}
fn from_headers_with_peer_ip_and_forwarded_policy(
headers: &HeaderMap,
peer_client_ip: Option<IpAddr>,
forwarded_headers: &ForwardedHeadersPolicy,
) -> Self {
let request_id = headers
.get(REQUEST_ID_HEADER_NAME)
.and_then(|value| value.to_str().ok())
.and_then(RequestId::parse)
.unwrap_or_default();
let traceparent = headers
.get(TRACEPARENT_HEADER_NAME)
.and_then(|value| value.to_str().ok())
.and_then(TraceParent::parse);
let peer_client_ip = peer_client_ip
.map(|client_ip| (ClientIp::from_ip_addr(client_ip), ClientIpSource::Peer));
let client_ip = client_ip_from_forwarded_headers(
headers,
peer_client_ip
.as_ref()
.map(|(client_ip, _)| client_ip.as_ip_addr()),
forwarded_headers,
)
.or(peer_client_ip);
let (client_ip, client_ip_source) = match client_ip {
Some((client_ip, source)) => (Some(client_ip), Some(source)),
None => (None, None),
};
let locale = locale_from_headers(headers);
let time_zone = header_values(headers, TIME_ZONE_HEADER_NAME).find_map(normalize_time_zone);
let utc_offset_minutes =
header_values(headers, UTC_OFFSET_HEADER_NAME).find_map(parse_utc_offset_minutes);
let user_agent = header_values(headers, "user-agent").find_map(normalize_user_agent);
let client_id =
header_values(headers, CLIENT_ID_HEADER_NAME).find_map(normalize_context_id);
let session_id =
header_values(headers, SESSION_ID_HEADER_NAME).find_map(normalize_context_id);
Self {
request_id,
traceparent,
client_ip,
client_ip_source,
locale,
time_zone,
utc_offset_minutes,
user_agent,
client_id,
session_id,
principal: None,
}
}
#[must_use]
pub const fn request_id(&self) -> &RequestId {
&self.request_id
}
#[must_use]
pub fn traceparent_str(&self) -> Option<&str> {
self.traceparent.as_ref().map(TraceParent::as_str)
}
#[must_use]
pub fn traceparent_value(&self) -> Option<&TraceParent> {
self.traceparent.as_ref()
}
#[must_use]
pub fn trace_id(&self) -> Option<&str> {
self.traceparent.as_ref().map(TraceParent::trace_id)
}
#[must_use]
pub fn span_id(&self) -> Option<&str> {
self.traceparent.as_ref().map(TraceParent::span_id)
}
#[must_use]
pub fn client_ip(&self) -> Option<&str> {
self.client_ip.as_ref().map(ClientIp::as_str)
}
#[must_use]
pub fn client_ip_addr(&self) -> Option<IpAddr> {
self.client_ip.as_ref().map(ClientIp::as_ip_addr)
}
#[must_use]
pub const fn client_ip_source(&self) -> Option<ClientIpSource> {
self.client_ip_source
}
#[must_use]
pub fn locale(&self) -> Option<&str> {
self.locale.as_deref()
}
#[must_use]
pub fn time_zone(&self) -> Option<&str> {
self.time_zone.as_deref()
}
#[must_use]
pub const fn utc_offset_minutes(&self) -> Option<i16> {
self.utc_offset_minutes
}
#[must_use]
pub fn user_agent(&self) -> Option<&str> {
self.user_agent.as_deref()
}
#[must_use]
pub fn client_id(&self) -> Option<&str> {
self.client_id.as_deref()
}
#[must_use]
pub fn session_id(&self) -> Option<&str> {
self.session_id.as_deref()
}
#[must_use]
pub const fn principal(&self) -> Option<&Principal> {
self.principal.as_ref()
}
#[must_use]
pub fn with_principal(mut self, principal: Principal) -> Self {
self.principal = Some(principal);
self
}
#[must_use]
pub fn with_traceparent(mut self, traceparent: TraceParent) -> Self {
self.traceparent = Some(traceparent);
self
}
pub fn set_traceparent(&mut self, traceparent: TraceParent) {
self.traceparent = Some(traceparent);
}
#[must_use]
pub fn with_client_ip(mut self, client_ip: impl AsRef<str>) -> Self {
self.set_client_ip(client_ip);
self
}
#[must_use]
pub fn with_client_ip_addr(mut self, client_ip: IpAddr) -> Self {
self.set_client_ip_addr(client_ip);
self
}
pub fn set_client_ip(&mut self, client_ip: impl AsRef<str>) {
self.set_explicit_client_ip(ClientIp::new(client_ip).ok());
}
pub fn set_client_ip_addr(&mut self, client_ip: IpAddr) {
self.set_explicit_client_ip(Some(ClientIp::from_ip_addr(client_ip)));
}
fn set_explicit_client_ip(&mut self, client_ip: Option<ClientIp>) {
self.client_ip_source = client_ip.as_ref().map(|_| ClientIpSource::Explicit);
self.client_ip = client_ip;
}
#[must_use]
pub fn with_locale(mut self, locale: impl AsRef<str>) -> Self {
self.locale = normalize_locale(locale.as_ref());
self
}
pub fn set_locale(&mut self, locale: impl AsRef<str>) {
self.locale = normalize_locale(locale.as_ref());
}
#[must_use]
pub fn clear_locale(mut self) -> Self {
self.locale = None;
self
}
#[must_use]
pub fn with_time_zone(mut self, time_zone: impl AsRef<str>) -> Self {
self.time_zone = normalize_time_zone(time_zone.as_ref());
self
}
pub fn set_time_zone(&mut self, time_zone: impl AsRef<str>) {
self.time_zone = normalize_time_zone(time_zone.as_ref());
}
#[must_use]
pub fn clear_time_zone(mut self) -> Self {
self.time_zone = None;
self
}
#[must_use]
pub const fn with_utc_offset_minutes(mut self, utc_offset_minutes: i16) -> Self {
self.utc_offset_minutes = if valid_utc_offset_minutes(utc_offset_minutes) {
Some(utc_offset_minutes)
} else {
None
};
self
}
pub fn set_utc_offset_minutes(&mut self, utc_offset_minutes: i16) {
self.utc_offset_minutes = if valid_utc_offset_minutes(utc_offset_minutes) {
Some(utc_offset_minutes)
} else {
None
};
}
#[must_use]
pub const fn clear_utc_offset_minutes(mut self) -> Self {
self.utc_offset_minutes = None;
self
}
#[must_use]
pub fn with_user_agent(mut self, user_agent: impl AsRef<str>) -> Self {
self.user_agent = normalize_user_agent(user_agent.as_ref());
self
}
pub fn set_user_agent(&mut self, user_agent: impl AsRef<str>) {
self.user_agent = normalize_user_agent(user_agent.as_ref());
}
#[must_use]
pub fn clear_user_agent(mut self) -> Self {
self.user_agent = None;
self
}
#[must_use]
pub fn with_client_id(mut self, client_id: impl AsRef<str>) -> Self {
self.client_id = normalize_context_id(client_id.as_ref());
self
}
pub fn set_client_id(&mut self, client_id: impl AsRef<str>) {
self.client_id = normalize_context_id(client_id.as_ref());
}
#[must_use]
pub fn clear_client_id(mut self) -> Self {
self.client_id = None;
self
}
#[must_use]
pub fn with_session_id(mut self, session_id: impl AsRef<str>) -> Self {
self.session_id = normalize_context_id(session_id.as_ref());
self
}
pub fn set_session_id(&mut self, session_id: impl AsRef<str>) {
self.session_id = normalize_context_id(session_id.as_ref());
}
#[must_use]
pub fn clear_session_id(mut self) -> Self {
self.session_id = None;
self
}
#[must_use]
pub fn clear_client_ip(mut self) -> Self {
self.client_ip = None;
self.client_ip_source = None;
self
}
#[must_use]
pub fn clear_traceparent(mut self) -> Self {
self.traceparent = None;
self
}
pub fn set_principal(&mut self, principal: Principal) {
self.principal = Some(principal);
}
pub fn clear_principal(&mut self) {
self.principal = None;
}
pub fn write_response_headers(&self, headers: &mut HeaderMap) {
if let Ok(value) = HeaderValue::from_str(self.request_id().as_str()) {
headers.insert(REQUEST_ID_HEADER_NAME, value);
}
}
}
impl<S> FromRequestParts<S> for RequestContext
where
S: Send + Sync,
{
type Rejection = Infallible;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
Ok(Self::from_parts(parts).clone())
}
}
fn header_values<'a>(headers: &'a HeaderMap, name: &'static str) -> impl Iterator<Item = &'a str> {
headers
.get_all(name)
.iter()
.filter_map(|value| value.to_str().ok())
.map(str::trim)
.filter(|value| !value.is_empty())
}
fn locale_from_headers(headers: &HeaderMap) -> Option<String> {
header_values(headers, LOCALE_HEADER_NAME)
.find_map(normalize_locale)
.or_else(|| {
header_values(headers, "accept-language")
.flat_map(|value| value.split(','))
.find_map(|part| normalize_locale(part.split(';').next().unwrap_or(part)))
})
}
fn normalize_locale(value: &str) -> Option<String> {
normalize_context_token(value, MAX_REQUEST_CONTEXT_VALUE_LENGTH, |character| {
character.is_ascii_alphanumeric() || matches!(character, '-' | '_')
})
}
fn normalize_time_zone(value: &str) -> Option<String> {
normalize_context_token(value, MAX_REQUEST_CONTEXT_VALUE_LENGTH, |character| {
character.is_ascii_alphanumeric() || matches!(character, '/' | '_' | '-' | '+')
})
}
fn normalize_user_agent(value: &str) -> Option<String> {
normalize_context_token(value, MAX_USER_AGENT_LENGTH, |character| {
!character.is_control()
})
}
fn normalize_context_id(value: &str) -> Option<String> {
normalize_context_token(value, MAX_REQUEST_CONTEXT_VALUE_LENGTH, |character| {
character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.' | ':' | '@')
})
}
fn normalize_context_token(
value: &str,
max_bytes: usize,
valid_character: impl Fn(char) -> bool,
) -> Option<String> {
let value = value.trim();
if value.is_empty() || value.len() > max_bytes || !value.chars().all(valid_character) {
return None;
}
Some(value.to_owned())
}
fn parse_utc_offset_minutes(value: &str) -> Option<i16> {
let value = value.trim();
if value.is_empty() {
return None;
}
if let Ok(minutes) = value.parse::<i16>() {
return valid_utc_offset_minutes(minutes).then_some(minutes);
}
let sign = match value.as_bytes().first()? {
b'+' => 1,
b'-' => -1,
_ => return None,
};
let value = value.strip_prefix(['+', '-']).unwrap_or_default();
let (hours, minutes) = value.split_once(':')?;
let hours = hours.parse::<i16>().ok()?;
let minutes = minutes.parse::<i16>().ok()?;
if !(0..=23).contains(&hours) || !(0..=59).contains(&minutes) {
return None;
}
let total = sign * (hours * 60 + minutes);
valid_utc_offset_minutes(total).then_some(total)
}
const fn valid_utc_offset_minutes(value: i16) -> bool {
value >= -23 * 60 - 59 && value <= 23 * 60 + 59
}