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")
}
#[tokio::test]
async fn context_extraction_prefers_extensions_and_keeps_header_fallback_untrusted() {
use axum::{extract::FromRequestParts, http::Request};
let request = Request::builder()
.header(REQUEST_ID_HEADER_NAME, "req_header")
.header("x-forwarded-for", "198.51.100.10")
.body(())
.unwrap();
let (mut parts, _) = request.into_parts();
let fallback = RequestContext::from_parts(&mut parts);
assert_eq!(fallback.request_id().as_str(), "req_header");
assert_eq!(fallback.client_ip(), None);
let installed = RequestContext::new(RequestId::new("req_installed").unwrap(), None)
.with_client_ip("192.0.2.10");
parts.extensions.insert(installed);
assert_eq!(
RequestContext::from_parts(&mut parts).request_id().as_str(),
"req_installed"
);
let extracted = RequestContext::from_request_parts(&mut parts, &())
.await
.unwrap();
assert_eq!(extracted.request_id().as_str(), "req_installed");
assert_eq!(extracted.client_ip(), Some("192.0.2.10"));
parts.extensions.clear();
let fallback = RequestContext::from_request_parts(&mut parts, &())
.await
.unwrap();
assert_eq!(fallback.request_id().as_str(), "req_header");
assert_eq!(fallback.client_ip(), None);
}
#[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"));
}
#[tokio::test]
async fn fallback_context_is_shared_by_request_parts_and_rejections() {
use crate::http::CurrentPrincipal;
use axum::{extract::FromRequestParts, http::Request};
for header in [None, Some("invalid/id")] {
let mut request = Request::new(());
if let Some(header) = header {
request
.headers_mut()
.insert(REQUEST_ID_HEADER_NAME, header.parse().unwrap());
}
let (mut parts, _) = request.into_parts();
let request_id = RequestContext::from_parts(&mut parts).request_id().clone();
let context = RequestContext::from_request_parts(&mut parts, &())
.await
.unwrap();
let again = RequestContext::from_request_parts(&mut parts, &())
.await
.unwrap();
let rejection = CurrentPrincipal::from_request_parts(&mut parts, &())
.await
.unwrap_err();
assert_eq!(context.request_id(), &request_id);
assert_eq!(again.request_id(), &request_id);
assert_eq!(rejection.body().request_id(), Some(request_id.as_str()));
assert_eq!(
parts
.extensions
.get::<RequestContext>()
.unwrap()
.request_id(),
&request_id
);
}
let (mut parts, _) = Request::new(()).into_parts();
let first = RequestContext::from_request_parts(&mut parts, &())
.await
.unwrap();
let second = RequestContext::from_request_parts(&mut parts, &())
.await
.unwrap();
assert_eq!(first.request_id(), second.request_id());
}
#[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_str(),
Some("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
);
assert_eq!(context.trace_id(), Some("4bf92f3577b34da6a3ce929d0e0e4736"));
assert_eq!(context.span_id(), Some("00f067aa0ba902b7"));
assert_eq!(
context.traceparent_value().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 malformed_client_ip_quotes_fall_back_to_peer() {
for name in ["x-forwarded-for", "x-real-ip"] {
for value in [
r#""198.51.100.10"#,
r#"198.51.100.10""#,
r#"""198.51.100.10"""#,
] {
let mut headers = HeaderMap::new();
headers.insert(name, value.parse().unwrap());
let context = trusted_forwarded_context(&headers);
assert_eq!(context.client_ip(), Some("10.0.0.3"), "{name}: {value}");
assert_eq!(context.client_ip_source(), Some(ClientIpSource::Peer));
}
}
}
#[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 forwarded_quoted_values_preserve_separators_and_escaped_characters() {
for value in [
r#"for=198.51.100.10;ext="one,two;three", for=10.0.0.2"#,
r#"ext="note\";for=203.0.113.9,other";for=198.51.100.10"#,
r#"for="198.51.100.\10";proto=https"#,
] {
let mut headers = HeaderMap::new();
headers.insert("forwarded", value.parse().unwrap());
let context = trusted_forwarded_context(&headers);
assert_eq!(context.client_ip(), Some("198.51.100.10"), "{value}");
assert_eq!(context.client_ip_source(), Some(ClientIpSource::Forwarded));
}
}
#[test]
fn forwarded_malformed_quotes_fall_back_to_the_peer() {
for value in [
r#"for="198.51.100.10"#,
r#"for=198.51.100.10;ext="unterminated"#,
r#"for=198.51.100.10;ext="escaped-end\""#,
] {
let mut headers = HeaderMap::new();
headers.insert("forwarded", value.parse().unwrap());
headers.insert("x-real-ip", "203.0.113.9".parse().unwrap());
let context = trusted_forwarded_context(&headers);
assert_eq!(
context.client_ip_source(),
Some(ClientIpSource::Peer),
"{value}"
);
}
}
#[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_str(), 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_str(), 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);
}