use std::{borrow::Cow, convert::Infallible, fmt, net::IpAddr};
use axum::{
extract::FromRequestParts,
http::{HeaderMap, HeaderValue, request::Parts},
};
use serde::{Deserialize, Deserializer, Serialize};
use thiserror::Error;
use uuid::Uuid;
use crate::auth::Principal;
use crate::http::trusted_proxy::ForwardedHeadersPolicy;
use crate::net::ClientIp;
use crate::result::{ClassifyError, ErrorKind};
pub const REQUEST_ID_HEADER_NAME: &str = "x-request-id";
pub const TRACEPARENT_HEADER_NAME: &str = "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_ID_LENGTH: usize = 128;
pub const TRACEPARENT_LENGTH: usize = 55;
pub const MAX_REQUEST_CONTEXT_VALUE_LENGTH: usize = 256;
pub const MAX_USER_AGENT_LENGTH: usize = 512;
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
pub struct RequestId(String);
impl RequestId {
pub fn new(value: impl Into<String>) -> Result<Self, RequestIdError> {
let value = value.into();
validate_request_id(&value)?;
Ok(Self(value))
}
pub fn try_new(value: impl Into<String>) -> Result<Self, RequestIdError> {
Self::new(value)
}
#[must_use]
pub fn generate() -> Self {
Self(format!("req_{}", Uuid::now_v7().simple()))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn parse(value: &str) -> Option<Self> {
Self::new(value).ok()
}
}
impl TryFrom<&str> for RequestId {
type Error = RequestIdError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl TryFrom<String> for RequestId {
type Error = RequestIdError;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl Default for RequestId {
fn default() -> Self {
Self::generate()
}
}
impl fmt::Display for RequestId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for RequestId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
Self::new(value).map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum RequestIdError {
#[error("request id must not be empty")]
Empty,
#[error("request id must be less than or equal to {max} bytes")]
TooLong {
#[doc = "The configured upper bound."]
max: usize,
},
#[error("request id contains unsupported characters")]
InvalidCharacters,
}
impl ClassifyError for RequestIdError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> Cow<'static, str> {
Cow::Borrowed(match self {
Self::Empty => "request_id_empty",
Self::TooLong { .. } => "request_id_too_long",
Self::InvalidCharacters => "request_id_invalid_characters",
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
pub struct TraceParent(String);
impl TraceParent {
pub fn new(value: impl Into<String>) -> Result<Self, TraceParentError> {
let value = value.into().trim().to_owned();
validate_traceparent(&value)?;
Ok(Self(value))
}
pub fn try_new(value: impl Into<String>) -> Result<Self, TraceParentError> {
Self::new(value)
}
#[must_use]
pub fn parse(value: &str) -> Option<Self> {
Self::new(value).ok()
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_string(self) -> String {
self.0
}
#[must_use]
pub fn version(&self) -> &str {
self.0.get(0..2).unwrap_or("")
}
#[must_use]
pub fn trace_id(&self) -> &str {
self.0.get(3..35).unwrap_or("")
}
#[must_use]
pub fn span_id(&self) -> &str {
self.0.get(36..52).unwrap_or("")
}
#[must_use]
pub fn trace_flags(&self) -> &str {
self.0.get(53..55).unwrap_or("")
}
#[must_use]
pub fn sampled(&self) -> bool {
parse_hex_byte(self.trace_flags().as_bytes()).is_some_and(|flags| flags & 1 == 1)
}
}
impl TryFrom<&str> for TraceParent {
type Error = TraceParentError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl TryFrom<String> for TraceParent {
type Error = TraceParentError;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl fmt::Display for TraceParent {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for TraceParent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
Self::new(value).map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum TraceParentError {
#[error("traceparent header shape is invalid")]
InvalidFormat,
#[error("traceparent version is invalid")]
InvalidVersion,
#[error("traceparent trace id is invalid")]
InvalidTraceId,
#[error("traceparent span id is invalid")]
InvalidSpanId,
#[error("traceparent flags are invalid")]
InvalidFlags,
}
impl ClassifyError for TraceParentError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> Cow<'static, str> {
Cow::Borrowed(match self {
Self::InvalidFormat => "traceparent_invalid_format",
Self::InvalidVersion => "traceparent_invalid_version",
Self::InvalidTraceId => "traceparent_invalid_trace_id",
Self::InvalidSpanId => "traceparent_invalid_span_id",
Self::InvalidFlags => "traceparent_invalid_flags",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ClientIpSource {
Peer,
XForwardedFor,
XRealIp,
Forwarded,
Explicit,
}
impl ClientIpSource {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Peer => "peer",
Self::XForwardedFor => "x_forwarded_for",
Self::XRealIp => "x_real_ip",
Self::Forwarded => "forwarded",
Self::Explicit => "explicit",
}
}
}
impl fmt::Display for ClientIpSource {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[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 {
#[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(&self) -> Option<&str> {
self.traceparent.as_ref().map(TraceParent::as_str)
}
#[must_use]
pub fn trace_parent(&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 {
match ClientIp::new(client_ip) {
Ok(client_ip) => {
self.client_ip = Some(client_ip);
self.client_ip_source = Some(ClientIpSource::Explicit);
}
Err(_) => {
self.client_ip = None;
self.client_ip_source = None;
}
}
self
}
#[must_use]
pub fn with_client_ip_addr(mut self, client_ip: IpAddr) -> Self {
self.client_ip = Some(ClientIp::from_ip_addr(client_ip));
self.client_ip_source = Some(ClientIpSource::Explicit);
self
}
pub fn set_client_ip(&mut self, client_ip: impl AsRef<str>) {
match ClientIp::new(client_ip) {
Ok(client_ip) => {
self.client_ip = Some(client_ip);
self.client_ip_source = Some(ClientIpSource::Explicit);
}
Err(_) => {
self.client_ip = None;
self.client_ip_source = None;
}
}
}
pub fn set_client_ip_addr(&mut self, client_ip: IpAddr) {
self.client_ip = Some(ClientIp::from_ip_addr(client_ip));
self.client_ip_source = Some(ClientIpSource::Explicit);
}
#[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);
}
#[must_use]
pub fn clear_principal(mut self) -> Self {
self.principal = None;
self
}
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(parts
.extensions
.get::<Self>()
.cloned()
.unwrap_or_else(|| Self::from_headers(&parts.headers)))
}
}
#[must_use]
pub fn is_valid_request_id(value: &str) -> bool {
validate_request_id(value).is_ok()
}
fn validate_request_id(value: &str) -> Result<(), RequestIdError> {
if value.is_empty() {
return Err(RequestIdError::Empty);
}
if value.len() > MAX_REQUEST_ID_LENGTH {
return Err(RequestIdError::TooLong {
max: MAX_REQUEST_ID_LENGTH,
});
}
if !value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
{
return Err(RequestIdError::InvalidCharacters);
}
Ok(())
}
fn client_ip_from_forwarded_headers(
headers: &HeaderMap,
peer_client_ip: Option<IpAddr>,
policy: &ForwardedHeadersPolicy,
) -> Option<(ClientIp, ClientIpSource)> {
if !policy.should_trust(peer_client_ip) {
return None;
}
match forwarding_chain(headers) {
Ok(Some((chain, source))) => {
forwarded_chain_client_ip(&chain, policy).map(|client_ip| (client_ip, source))
}
Ok(None) => single_proxy_real_ip(headers)
.ok()
.flatten()
.map(|client_ip| (client_ip, ClientIpSource::XRealIp)),
Err(()) => None,
}
}
fn forwarding_chain(headers: &HeaderMap) -> Result<Option<(Vec<ClientIp>, ClientIpSource)>, ()> {
let forwarded_for = parse_x_forwarded_for(headers)?;
let forwarded = parse_forwarded(headers)?;
match (forwarded_for, forwarded) {
(None, None) => Ok(None),
(Some(chain), None) => Ok(Some((chain, ClientIpSource::XForwardedFor))),
(None, Some(chain)) => Ok(Some((chain, ClientIpSource::Forwarded))),
(Some(forwarded_for), Some(forwarded)) if forwarded_for == forwarded => {
Ok(Some((forwarded, ClientIpSource::Forwarded)))
}
(Some(_), Some(_)) => Err(()),
}
}
fn parse_x_forwarded_for(headers: &HeaderMap) -> Result<Option<Vec<ClientIp>>, ()> {
let values = headers.get_all("x-forwarded-for");
let mut present = false;
let mut chain = Vec::new();
for value in &values {
present = true;
let value = value.to_str().map_err(|_| ())?;
for hop in value.split(',') {
chain.push(ClientIp::parse(hop.trim()).ok_or(())?);
}
}
if !present {
return Ok(None);
}
(!chain.is_empty()).then_some(chain).ok_or(()).map(Some)
}
fn parse_forwarded(headers: &HeaderMap) -> Result<Option<Vec<ClientIp>>, ()> {
let values = headers.get_all("forwarded");
let mut present = false;
let mut chain = Vec::new();
for value in &values {
present = true;
let value = value.to_str().map_err(|_| ())?;
for element in value.split(',') {
let mut forwarded_for = None;
for parameter in element.split(';') {
let (name, value) = parameter.split_once('=').ok_or(())?;
if !name.trim().eq_ignore_ascii_case("for") {
continue;
}
if forwarded_for.is_some() {
return Err(());
}
forwarded_for = Some(ClientIp::parse(value.trim()).ok_or(())?);
}
chain.push(forwarded_for.ok_or(())?);
}
}
if !present {
return Ok(None);
}
(!chain.is_empty()).then_some(chain).ok_or(()).map(Some)
}
fn forwarded_chain_client_ip(
chain: &[ClientIp],
policy: &ForwardedHeadersPolicy,
) -> Option<ClientIp> {
match policy {
ForwardedHeadersPolicy::Never => None,
ForwardedHeadersPolicy::Always => chain.last().cloned(),
ForwardedHeadersPolicy::TrustedProxies(config) => chain
.iter()
.rev()
.find(|hop| !config.is_trusted(hop.as_ip_addr()))
.cloned(),
}
}
fn single_proxy_real_ip(headers: &HeaderMap) -> Result<Option<ClientIp>, ()> {
let mut values = headers.get_all("x-real-ip").iter();
let Some(value) = values.next() else {
return Ok(None);
};
if values.next().is_some() {
return Err(());
}
let value = value.to_str().map_err(|_| ())?;
if value.contains(',') {
return Err(());
}
ClientIp::parse(value.trim()).ok_or(()).map(Some)
}
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
}
#[must_use]
pub fn is_valid_traceparent(value: &str) -> bool {
validate_traceparent(value).is_ok()
}
fn validate_traceparent(value: &str) -> Result<(), TraceParentError> {
let bytes = value.as_bytes();
if bytes.len() != TRACEPARENT_LENGTH
|| bytes.get(2) != Some(&b'-')
|| bytes.get(35) != Some(&b'-')
|| bytes.get(52) != Some(&b'-')
{
return Err(TraceParentError::InvalidFormat);
}
let version = bytes.get(0..2).ok_or(TraceParentError::InvalidFormat)?;
let trace_id = bytes.get(3..35).ok_or(TraceParentError::InvalidFormat)?;
let span_id = bytes.get(36..52).ok_or(TraceParentError::InvalidFormat)?;
let flags = bytes.get(53..55).ok_or(TraceParentError::InvalidFormat)?;
if !is_lower_hex(version) || version == b"ff" {
return Err(TraceParentError::InvalidVersion);
}
if !is_lower_hex(trace_id) || trace_id.iter().all(|byte| *byte == b'0') {
return Err(TraceParentError::InvalidTraceId);
}
if !is_lower_hex(span_id) || span_id.iter().all(|byte| *byte == b'0') {
return Err(TraceParentError::InvalidSpanId);
}
if !is_lower_hex(flags) {
return Err(TraceParentError::InvalidFlags);
}
Ok(())
}
fn is_lower_hex(bytes: &[u8]) -> bool {
bytes
.iter()
.all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
}
fn parse_hex_byte(bytes: &[u8]) -> Option<u8> {
if bytes.len() != 2 || !is_lower_hex(bytes) {
return None;
}
let high = *bytes.first()?;
let low = *bytes.get(1)?;
Some(hex_value(high)? << 4 | hex_value(low)?)
}
fn hex_value(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
_ => None,
}
}
#[cfg(test)]
mod tests {
use std::net::IpAddr;
use axum::http::HeaderMap;
use serde_json::json;
use crate::result::{ClassifyError, ErrorKind};
use crate::{
auth::Principal,
http::{ForwardedHeadersPolicy, TrustedProxyConfig},
};
use super::{
ClientIpSource, REQUEST_ID_HEADER_NAME, RequestContext, RequestId, RequestIdError,
TRACEPARENT_HEADER_NAME, TraceParent, TraceParentError, is_valid_request_id,
is_valid_traceparent,
};
fn trusted_forwarded_context(headers: &HeaderMap) -> RequestContext {
trusted_forwarded_context_from_peer(headers, trusted_proxy_ip())
}
fn trusted_forwarded_context_from_peer(
headers: &HeaderMap,
peer_client_ip: IpAddr,
) -> RequestContext {
let policy = ForwardedHeadersPolicy::trusted_proxies(
TrustedProxyConfig::from_cidrs(["10.0.0.0/8"])
.expect("trusted proxy CIDR should be valid"),
);
RequestContext::from_headers_and_peer_ip_with_forwarded_policy(
headers,
Some(peer_client_ip),
&policy,
)
}
fn peer_ip() -> IpAddr {
"192.0.2.10".parse().expect("peer IP should parse")
}
fn trusted_proxy_ip() -> IpAddr {
"10.0.0.3".parse().expect("trusted proxy IP should parse")
}
#[test]
fn accepts_bounded_request_id_charset() {
assert!(is_valid_request_id("req_018f.test:edge-1"));
assert!(!is_valid_request_id(""));
assert!(!is_valid_request_id("bad/request"));
}
#[test]
fn request_id_constructor_rejects_invalid_values() {
assert!(matches!(RequestId::new(""), Err(RequestIdError::Empty)));
assert!(matches!(
RequestId::new("bad/request"),
Err(RequestIdError::InvalidCharacters)
));
}
#[test]
fn request_id_errors_are_classified() {
let error = RequestId::new("bad/request").unwrap_err();
assert_eq!(error.error_kind(), ErrorKind::Validation);
assert_eq!(error.error_code(), "request_id_invalid_characters");
}
#[test]
fn validates_traceparent_shape() {
assert!(is_valid_traceparent(
"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
));
assert!(!is_valid_traceparent(
"00-00000000000000000000000000000000-00f067aa0ba902b7-01"
));
assert!(!is_valid_traceparent(
"ff-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
));
assert!(!is_valid_traceparent("not-a-traceparent"));
}
#[test]
fn traceparent_constructor_exposes_parts() {
let traceparent =
TraceParent::new("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
.expect("traceparent should be valid");
assert_eq!(traceparent.version(), "00");
assert_eq!(traceparent.trace_id(), "4bf92f3577b34da6a3ce929d0e0e4736");
assert_eq!(traceparent.span_id(), "00f067aa0ba902b7");
assert_eq!(traceparent.trace_flags(), "01");
assert!(traceparent.sampled());
assert_eq!(
traceparent.to_string(),
"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
);
}
#[test]
fn traceparent_constructor_rejects_specific_invalid_parts() {
assert!(matches!(
TraceParent::new("not-a-traceparent"),
Err(TraceParentError::InvalidFormat)
));
assert!(matches!(
TraceParent::new("ff-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"),
Err(TraceParentError::InvalidVersion)
));
assert!(matches!(
TraceParent::new("00-00000000000000000000000000000000-00f067aa0ba902b7-01"),
Err(TraceParentError::InvalidTraceId)
));
assert!(matches!(
TraceParent::new("00-4bf92f3577b34da6a3ce929d0e0e4736-0000000000000000-01"),
Err(TraceParentError::InvalidSpanId)
));
assert!(matches!(
TraceParent::new("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-0g"),
Err(TraceParentError::InvalidFlags)
));
}
#[test]
fn traceparent_errors_are_classified() {
let error = TraceParent::new("not-a-traceparent").unwrap_err();
assert_eq!(error.error_kind(), ErrorKind::Validation);
assert_eq!(error.error_code(), "traceparent_invalid_format");
}
#[test]
fn builds_context_from_valid_headers() {
let mut headers = HeaderMap::new();
headers.insert(
REQUEST_ID_HEADER_NAME,
"req_test".parse().expect("valid header"),
);
headers.insert(
TRACEPARENT_HEADER_NAME,
"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
.parse()
.expect("valid header"),
);
let context = RequestContext::from_headers(&headers);
assert_eq!(context.request_id().as_str(), "req_test");
assert_eq!(
context.traceparent(),
Some("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
);
assert_eq!(context.trace_id(), Some("4bf92f3577b34da6a3ce929d0e0e4736"));
assert_eq!(context.span_id(), Some("00f067aa0ba902b7"));
assert_eq!(context.trace_parent().map(TraceParent::sampled), Some(true));
}
#[test]
fn extracts_user_facing_context_from_headers() {
let mut headers = HeaderMap::new();
headers.insert(
"accept-language",
"zh-CN, en;q=0.8".parse().expect("valid header"),
);
headers.insert(
"x-time-zone",
"Asia/Shanghai".parse().expect("valid header"),
);
headers.insert("x-utc-offset", "+08:00".parse().expect("valid header"));
headers.insert(
"user-agent",
"Desktop Chrome".parse().expect("valid header"),
);
headers.insert("x-client-id", "opsline".parse().expect("valid header"));
headers.insert("x-session-id", "sess_123".parse().expect("valid header"));
let context = RequestContext::from_headers(&headers);
assert_eq!(context.locale(), Some("zh-CN"));
assert_eq!(context.time_zone(), Some("Asia/Shanghai"));
assert_eq!(context.utc_offset_minutes(), Some(480));
assert_eq!(context.user_agent(), Some("Desktop Chrome"));
assert_eq!(context.client_id(), Some("opsline"));
assert_eq!(context.session_id(), Some("sess_123"));
}
#[test]
fn request_context_debug_redacts_client_and_identity_values() {
let principal_id = "private-principal-id";
let context = RequestContext::new(
RequestId::new("req_test").expect("request id should be valid"),
None,
)
.with_client_ip("198.51.100.10")
.with_locale("en-US")
.with_time_zone("Asia/Shanghai")
.with_user_agent("private-user-agent")
.with_client_id("private-client-id")
.with_session_id("private-session-id")
.with_principal(Principal::user(principal_id).expect("principal should be valid"));
let debug = format!("{context:?}");
assert!(debug.contains("req_test"));
assert!(debug.contains("[REDACTED]"));
for sensitive in [
"198.51.100.10",
"en-US",
"Asia/Shanghai",
"private-user-agent",
"private-client-id",
"private-session-id",
principal_id,
] {
assert!(!debug.contains(sensitive));
}
}
#[test]
fn drops_invalid_user_facing_context_instead_of_rewriting_values() {
let mut headers = HeaderMap::new();
headers.insert("x-locale", "en US".parse().expect("valid header"));
headers.insert(
"x-time-zone",
"Asia/Shanghai<script>".parse().expect("valid header"),
);
headers.insert("x-client-id", "ops/line".parse().expect("valid header"));
headers.insert("x-session-id", "sess 123".parse().expect("valid header"));
let context = RequestContext::from_headers(&headers);
assert_eq!(context.locale(), None);
assert_eq!(context.time_zone(), None);
assert_eq!(context.client_id(), None);
assert_eq!(context.session_id(), None);
}
#[test]
fn drops_invalid_direct_context_values_instead_of_rewriting_values() {
let context = RequestContext::new(
RequestId::new("req_test").expect("request id should be valid"),
None,
)
.with_user_agent("bad\nagent")
.with_locale("en US")
.with_client_id("ops/line");
assert_eq!(context.user_agent(), None);
assert_eq!(context.locale(), None);
assert_eq!(context.client_id(), None);
}
#[test]
fn direct_utc_offset_setters_apply_bounds() {
let mut context = RequestContext::new(
RequestId::new("req_test").expect("request id should be valid"),
None,
)
.with_utc_offset_minutes(1_440);
assert_eq!(context.utc_offset_minutes(), None);
context.set_utc_offset_minutes(480);
assert_eq!(context.utc_offset_minutes(), Some(480));
context.set_utc_offset_minutes(-1_440);
assert_eq!(context.utc_offset_minutes(), None);
}
#[test]
fn request_identifiers_deserialize_with_constructor_validation() {
assert!(serde_json::from_value::<RequestId>(json!("bad/request")).is_err());
assert!(serde_json::from_value::<TraceParent>(json!("not-a-traceparent")).is_err());
let traceparent: TraceParent = serde_json::from_value(json!(
"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
))
.expect("traceparent should deserialize");
assert_eq!(traceparent.trace_id(), "4bf92f3577b34da6a3ce929d0e0e4736");
}
#[test]
fn request_context_deserialization_reuses_normalizers() {
let context: RequestContext = serde_json::from_value(json!({
"request_id": "req_test",
"traceparent": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
"client_ip": "198.51.100.10:443",
"client_ip_source": "x_forwarded_for",
"locale": "en US",
"time_zone": "Asia/Shanghai<script>",
"utc_offset_minutes": 1_440,
"user_agent": "Desktop Chrome",
"client_id": "ops/line",
"session_id": "sess_123"
}))
.expect("context should deserialize");
assert_eq!(context.request_id().as_str(), "req_test");
assert_eq!(context.trace_id(), Some("4bf92f3577b34da6a3ce929d0e0e4736"));
assert_eq!(context.client_ip(), Some("198.51.100.10"));
assert_eq!(
context.client_ip_source(),
Some(ClientIpSource::XForwardedFor)
);
assert_eq!(context.locale(), None);
assert_eq!(context.time_zone(), None);
assert_eq!(context.utc_offset_minutes(), None);
assert_eq!(context.user_agent(), Some("Desktop Chrome"));
assert_eq!(context.client_id(), None);
assert_eq!(context.session_id(), Some("sess_123"));
}
#[test]
fn request_context_deserialization_drops_orphaned_client_ip_source() {
let context: RequestContext = serde_json::from_value(json!({
"request_id": "req_test",
"client_ip_source": "x_forwarded_for"
}))
.expect("context should deserialize");
assert_eq!(context.client_ip(), None);
assert_eq!(context.client_ip_source(), None);
}
#[test]
fn explicit_locale_header_takes_precedence() {
let mut headers = HeaderMap::new();
headers.insert("x-locale", "en-US".parse().expect("valid header"));
headers.insert("accept-language", "zh-CN".parse().expect("valid header"));
let context = RequestContext::from_headers(&headers);
assert_eq!(context.locale(), Some("en-US"));
}
#[test]
fn trusted_proxy_ignores_attacker_prepended_forwarded_for_value() {
let mut headers = HeaderMap::new();
headers.insert(
"x-forwarded-for",
"203.0.113.66, 198.51.100.10:443"
.parse()
.expect("valid header"),
);
let context = trusted_forwarded_context(&headers);
assert_eq!(context.client_ip(), Some("198.51.100.10"));
assert_eq!(
context.client_ip_source(),
Some(ClientIpSource::XForwardedFor)
);
assert_eq!(
context.client_ip_addr(),
Some("198.51.100.10".parse::<IpAddr>().expect("IP should parse"))
);
}
#[test]
fn trusted_proxy_peels_multiple_trusted_hops_from_the_right() {
let mut headers = HeaderMap::new();
headers.append(
"x-forwarded-for",
"198.51.100.10, 10.0.0.1".parse().expect("valid header"),
);
headers.append("x-forwarded-for", "10.0.0.2".parse().expect("valid header"));
let context = trusted_forwarded_context(&headers);
assert_eq!(context.client_ip(), Some("198.51.100.10"));
assert_eq!(
context.client_ip_source(),
Some(ClientIpSource::XForwardedFor)
);
}
#[test]
fn invalid_forwarding_chain_falls_back_to_peer() {
let mut headers = HeaderMap::new();
headers.insert(
"x-forwarded-for",
"198.51.100.10, unknown".parse().expect("valid header"),
);
let context = trusted_forwarded_context(&headers);
assert_eq!(context.client_ip(), Some("10.0.0.3"));
assert_eq!(context.client_ip_source(), Some(ClientIpSource::Peer));
}
#[test]
fn invalid_chain_never_falls_through_to_real_ip() {
let mut headers = HeaderMap::new();
headers.insert(
"x-forwarded-for",
"unknown, _hidden".parse().expect("valid header"),
);
headers.insert("x-real-ip", "198.51.100.20".parse().expect("valid header"));
let context = trusted_forwarded_context(&headers);
assert_eq!(context.client_ip(), Some("10.0.0.3"));
assert_eq!(context.client_ip_source(), Some(ClientIpSource::Peer));
}
#[test]
fn unique_real_ip_is_supported_only_without_chain_headers() {
let mut headers = HeaderMap::new();
headers.insert("x-real-ip", "198.51.100.20".parse().expect("valid header"));
let context = trusted_forwarded_context(&headers);
assert_eq!(context.client_ip(), Some("198.51.100.20"));
assert_eq!(context.client_ip_source(), Some(ClientIpSource::XRealIp));
}
#[test]
fn normalizes_bracketed_forwarded_ipv6_values() {
let mut headers = HeaderMap::new();
headers.insert(
"forwarded",
r#"for="[2001:db8::1]:443""#.parse().expect("valid header"),
);
let context = trusted_forwarded_context(&headers);
assert_eq!(context.client_ip(), Some("2001:db8::1"));
assert_eq!(context.client_ip_source(), Some(ClientIpSource::Forwarded));
}
#[test]
fn parses_forwarded_header_lists_and_repeated_values() {
let mut headers = HeaderMap::new();
headers.append(
"forwarded",
r#"for="[2001:db8::2]:443";proto=https"#
.parse()
.expect("valid header"),
);
headers.append(
"forwarded",
"for=10.0.0.2;proto=https".parse().expect("valid header"),
);
let context = trusted_forwarded_context(&headers);
assert_eq!(context.client_ip(), Some("2001:db8::2"));
assert_eq!(context.client_ip_source(), Some(ClientIpSource::Forwarded));
}
#[test]
fn trusted_proxy_policy_ignores_headers_from_an_untrusted_peer() {
let mut headers = HeaderMap::new();
headers.insert(
"x-forwarded-for",
"198.51.100.10, 203.0.113.10".parse().expect("valid header"),
);
let context = trusted_forwarded_context_from_peer(&headers, peer_ip());
assert_eq!(context.client_ip(), Some("192.0.2.10"));
assert_eq!(context.client_ip_source(), Some(ClientIpSource::Peer));
}
#[test]
fn conflicting_forwarded_header_families_fall_back_to_peer() {
let mut headers = HeaderMap::new();
headers.insert(
"x-forwarded-for",
"198.51.100.10, 10.0.0.2".parse().expect("valid header"),
);
headers.insert(
"forwarded",
"for=203.0.113.10, for=10.0.0.2"
.parse()
.expect("valid header"),
);
let context = trusted_forwarded_context(&headers);
assert_eq!(context.client_ip(), Some("10.0.0.3"));
assert_eq!(context.client_ip_source(), Some(ClientIpSource::Peer));
}
#[test]
fn header_only_context_does_not_trust_forwarded_client_ip() {
let mut headers = HeaderMap::new();
headers.insert(
"x-forwarded-for",
"198.51.100.10".parse().expect("valid header"),
);
let context = RequestContext::from_headers(&headers);
assert_eq!(context.client_ip(), None);
assert_eq!(context.client_ip_source(), None);
}
#[test]
fn falls_back_to_peer_client_ip() {
let headers = HeaderMap::new();
let context = RequestContext::from_headers_and_peer_ip_with_forwarded_policy(
&headers,
Some(peer_ip()),
&ForwardedHeadersPolicy::always(),
);
assert_eq!(context.client_ip(), Some("192.0.2.10"));
assert_eq!(context.client_ip_source(), Some(ClientIpSource::Peer));
}
#[test]
fn drops_invalid_traceparent_when_constructed_directly() {
let context = RequestContext::new(
RequestId::new("req_test").expect("request id should be valid"),
Some("invalid-traceparent".to_owned()),
);
assert_eq!(context.traceparent(), None);
assert_eq!(context.trace_id(), None);
}
#[test]
fn can_set_and_clear_traceparent() {
let traceparent =
TraceParent::new("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00")
.expect("traceparent should be valid");
let context = RequestContext::new(
RequestId::new("req_test").expect("request id should be valid"),
None,
)
.with_traceparent(traceparent)
.clear_traceparent();
assert_eq!(context.traceparent(), None);
}
#[test]
fn can_set_and_clear_client_ip() {
let context = RequestContext::new(
RequestId::new("req_test").expect("request id should be valid"),
None,
)
.with_client_ip_addr("198.51.100.40".parse().expect("IP should parse"));
assert_eq!(context.client_ip(), Some("198.51.100.40"));
assert_eq!(context.client_ip_source(), Some(ClientIpSource::Explicit));
assert_eq!(
context.client_ip_addr(),
Some("198.51.100.40".parse::<IpAddr>().expect("IP should parse"))
);
let context = context.clear_client_ip();
assert_eq!(context.client_ip(), None);
assert_eq!(context.client_ip_source(), None);
}
}