use std::net::IpAddr;
use axum::http::{HeaderMap, HeaderValue};
use serde_json::json;
use crate::result::{ClassifyError, ErrorKind};
use crate::{
auth::Principal,
http::ForwardedHeadersPolicy,
net::{ClientIp, IpNetworkSet},
};
use super::{
ClientIpSource, ForwardedHeadersStatus, 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(
IpNetworkSet::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()).with_client_ip(peer_ip());
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"));
}
#[test]
fn validated_request_ids_always_replace_response_correlation_headers() {
for value in [
"req_018f.test:edge-1".to_owned(),
"r".repeat(super::MAX_REQUEST_ID_LENGTH),
RequestId::generate().to_string(),
] {
let request_id = RequestId::new(value.clone()).unwrap();
assert_eq!(HeaderValue::from(&request_id).as_bytes(), value.as_bytes());
let context = RequestContext::new(request_id);
let mut headers = HeaderMap::new();
headers.append(
REQUEST_ID_HEADER_NAME,
HeaderValue::from_static("previous-1"),
);
headers.append(
REQUEST_ID_HEADER_NAME,
HeaderValue::from_static("previous-2"),
);
headers.insert("cache-control", HeaderValue::from_static("no-store"));
context.write_response_headers(&mut headers);
assert_eq!(headers.get_all(REQUEST_ID_HEADER_NAME).iter().count(), 1);
assert_eq!(headers[REQUEST_ID_HEADER_NAME].as_bytes(), value.as_bytes());
assert_eq!(headers["cache-control"], "no-store");
}
}
#[tokio::test]
async fn fallback_context_is_shared_by_request_parts_and_rejections() {
use crate::http::{AuthenticationChallenge, 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,
&AuthenticationChallenge::try_new("Bearer").unwrap(),
)
.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!(HeaderValue::from(&traceparent), traceparent.as_str());
assert_eq!(
traceparent.to_string(),
"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
);
}
#[test]
fn future_traceparent_preserves_opaque_fields_and_request_context() {
let core = "4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-03";
for suffix in ["", "-", "-opaque=vendor-data-more", "-opaque\tvendor data"] {
let value = format!("01-{core}{suffix}");
let parent = TraceParent::new(&value).unwrap();
assert_eq!(parent.as_str(), value);
assert_eq!(parent.version(), "01");
assert_eq!(parent.trace_id(), "4bf92f3577b34da6a3ce929d0e0e4736");
assert!(parent.sampled());
assert_eq!(
serde_json::from_value::<TraceParent>(json!(value)).unwrap(),
parent
);
let headers = HeaderMap::from_iter([(
axum::http::HeaderName::from_static(TRACEPARENT_HEADER_NAME),
HeaderValue::from(&parent),
)]);
assert_eq!(
RequestContext::from_headers(&headers).traceparent_str(),
Some(value.as_str())
);
}
for value in [
format!("00-{core}-extension"),
format!("01-{core}extension"),
format!("ff-{core}-extension"),
] {
assert!(TraceParent::new(value).is_err());
}
let prefix = format!("fe-{core}-");
let value = format!(
"{prefix}{}",
"x".repeat(super::MAX_TRACEPARENT_LENGTH - prefix.len())
);
assert!(TraceParent::new(&value).is_ok());
assert!(TraceParent::new(format!("{value}x")).is_err());
}
#[test]
fn future_traceparent_rejects_controls_forbidden_in_http_headers() {
for control in (0u8..=31).chain([127]).filter(|byte| *byte != b'\t') {
let value = format!(
"01-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01-vendor{}data",
char::from(control),
);
assert!(axum::http::HeaderValue::from_str(&value).is_err());
assert!(
matches!(
TraceParent::new(&value),
Err(TraceParentError::InvalidFormat)
),
"accepted HTTP-invalid control {control} in a future-version suffix",
);
assert!(!is_valid_traceparent(&value));
assert!(TraceParent::try_from(value.as_str()).is_err());
assert!(serde_json::from_value::<TraceParent>(json!(value)).is_err());
}
}
#[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 repeated_request_id_headers_generate_a_new_identifier() {
for request_ids in [
["req_first", "req_first"],
["req_first", "req_second"],
["invalid id", "req_second"],
["req_first", "invalid id"],
] {
let mut headers = HeaderMap::new();
for value in request_ids {
headers.append(REQUEST_ID_HEADER_NAME, value.parse().unwrap());
}
let context = RequestContext::from_headers(&headers);
assert!(is_valid_request_id(context.request_id().as_str()));
assert!(!request_ids.contains(&context.request_id().as_str()));
}
}
#[test]
fn repeated_traceparent_headers_are_ignored() {
let traceparent = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";
let other_traceparent = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-00";
for traceparents in [
[traceparent, traceparent],
[traceparent, other_traceparent],
["invalid", traceparent],
[traceparent, "invalid"],
] {
let mut headers = HeaderMap::new();
for value in traceparents {
headers.append(TRACEPARENT_HEADER_NAME, value.parse().unwrap());
}
let context = RequestContext::from_headers(&headers);
assert_eq!(context.traceparent_value(), None);
}
}
#[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"))
.with_client_ip(ClientIp::new("198.51.100.10").unwrap())
.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"))
.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"))
.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]
#[cfg(feature = "http-locale")]
fn resolved_locale_is_independent_of_client_preference_and_survives_cloning() {
use crate::http::locale::LocalePolicy;
let policy = LocalePolicy::new(["en", "zh-CN"], "en").unwrap();
let mut headers = HeaderMap::new();
headers.insert("accept-language", "fr, zh-CN;q=0.8".parse().unwrap());
let mut context = RequestContext::from_headers(&headers);
assert_eq!(context.locale(), Some("fr"));
assert!(context.resolved_locale().is_none());
let resolved = policy.negotiate(&headers).unwrap();
let source = resolved.source();
context.set_resolved_locale(resolved);
let cloned = context.clone();
assert_eq!(cloned.locale(), Some("fr"));
assert_eq!(cloned.resolved_locale().unwrap().as_str(), "zh-CN");
assert_eq!(cloned.resolved_locale().unwrap().source(), source);
let debug = format!("{cloned:?}");
assert!(debug.contains("resolved_locale"));
assert!(debug.contains("zh-CN"));
context.clear_resolved_locale();
assert!(context.resolved_locale().is_none());
assert_eq!(context.locale(), Some("fr"));
assert_eq!(cloned.resolved_locale().unwrap().as_str(), "zh-CN");
}
#[test]
#[cfg(feature = "http-locale")]
fn resolved_locale_is_never_restored_from_serialized_context() {
use crate::http::locale::LocalePolicy;
let policy = LocalePolicy::new(["en", "zh-CN"], "en").unwrap();
let mut context =
RequestContext::new(RequestId::new("request-locale").unwrap()).with_locale("fr");
assert!(context.resolved_locale().is_none());
context.set_resolved_locale(policy.select("zh-CN").unwrap());
let mut serialized = serde_json::to_value(&context).unwrap();
assert!(serialized.get("resolved_locale").is_none());
let restored: RequestContext = serde_json::from_value(serialized.clone()).unwrap();
assert_eq!(restored.locale(), Some("fr"));
assert!(restored.resolved_locale().is_none());
serialized["resolved_locale"] = json!({ "locale": "zh-CN", "source": "explicit" });
let mut injected: RequestContext = serde_json::from_value(serialized).unwrap();
assert!(injected.resolved_locale().is_none());
injected.set_resolved_locale(policy.default_locale());
assert_eq!(injected.resolved_locale().unwrap().as_str(), "en");
assert_eq!(injected.locale(), Some("fr"));
}
#[test]
fn accept_language_respects_quality_and_excludes_invalid_preferences() {
for (header, expected) in [
("en;q=0, zh-CN;q=1", Some("zh-CN")),
("en;q=0.1, fr;q=0.900, zh-CN;q=0.8", Some("fr")),
("fr;q=0.8, en;q=0.8", Some("fr")),
("en;q=0.9, zh-CN", Some("zh-CN")),
("*;q=1, en;q=0.5", Some("en")),
(
"en;q=NaN, fr;q=1.1, de;q=0.1234, zh-CN;q=0.5",
Some("zh-CN"),
),
(
"en;q=0.5;q=1, fr;invalid=1, 12-GB, en_US, zh-CN",
Some("zh-CN"),
),
("en;q=0, *;q=1", None),
] {
let mut headers = HeaderMap::new();
headers.insert("accept-language", header.parse().unwrap());
assert_eq!(
RequestContext::from_headers(&headers).locale(),
expected,
"{header}"
);
}
}
#[test]
fn accept_language_considers_all_header_lines_and_retains_tie_order() {
let mut headers = HeaderMap::new();
headers.append("accept-language", "en;q=0.5".parse().unwrap());
headers.append("accept-language", "fr;q=0.9".parse().unwrap());
headers.append("accept-language", "zh-CN;q=0.9".parse().unwrap());
assert_eq!(RequestContext::from_headers(&headers).locale(), Some("fr"));
}
#[test]
fn mapped_ipv4_peers_preserve_trusted_proxy_forwarding() {
let mut headers = HeaderMap::new();
headers.insert("x-forwarded-for", "198.51.100.10".parse().unwrap());
for (peer, policy) in [
(
"::ffff:127.0.0.1",
ForwardedHeadersPolicy::local_development(),
),
(
"::ffff:10.1.2.3",
ForwardedHeadersPolicy::trusted_proxies(
IpNetworkSet::from_cidrs(["10.0.0.0/8"]).unwrap(),
),
),
] {
let context = RequestContext::from_headers_and_peer_ip_with_forwarded_policy(
&headers,
Some(peer.parse().unwrap()),
&policy,
);
assert_eq!(context.client_ip(), Some("198.51.100.10"), "{peer}");
assert_eq!(
context.client_ip_source(),
Some(ClientIpSource::XForwardedFor)
);
}
}
#[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() {
for (name, value) in [
("x-forwarded-for", "unknown, _hidden"),
("x-forwarded-for", ""),
("x-forwarded-for", "198.51.100.10,"),
("forwarded", ""),
("forwarded", "for=unknown"),
("forwarded", "for=198.51.100.10,"),
] {
let mut headers = HeaderMap::new();
headers.insert(name, value.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"), "{name}: {value}");
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 direct_context_preserves_validated_traceparent_including_future_fields() {
let context = RequestContext::new(RequestId::new("req_test").unwrap());
assert_eq!(context.traceparent_str(), None);
assert_eq!(context.trace_id(), None);
for value in [
"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
"01-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01-opaque-future-fields",
] {
let traceparent = TraceParent::new(value).unwrap();
let configured = context.clone().with_traceparent(traceparent.clone());
assert_eq!(configured.traceparent_value(), Some(&traceparent));
assert_eq!(configured.traceparent_str(), Some(value));
assert_eq!(
configured.trace_id(),
Some("4bf92f3577b34da6a3ce929d0e0e4736")
);
let restored: RequestContext =
serde_json::from_value(serde_json::to_value(&configured).unwrap()).unwrap();
assert_eq!(restored.traceparent_value(), Some(&traceparent));
}
}
#[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"))
.with_traceparent(traceparent)
.clear_traceparent();
assert_eq!(context.traceparent_str(), None);
}
#[test]
fn can_set_and_clear_client_ip() {
let mut context =
RequestContext::new(RequestId::new("req_test").expect("request id should be valid"))
.with_client_ip(
"::ffff:198.51.100.40"
.parse::<IpAddr>()
.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"))
);
context.set_client_ip(ClientIp::new("[2001:db8::1]:443").unwrap());
assert_eq!(context.client_ip(), Some("2001:db8::1"));
assert_eq!(context.client_ip_source(), Some(ClientIpSource::Explicit));
let context = context.clear_client_ip();
assert_eq!(context.client_ip(), None);
assert_eq!(context.client_ip_source(), None);
}
#[test]
fn forwarding_diagnostics_distinguish_peer_fallback_reasons() {
use ForwardedHeadersStatus::{Absent, Conflicting, Malformed, NoUntrustedHop};
let cases: &[(&[(&str, &str)], ForwardedHeadersStatus)] = &[
(&[], Absent),
(&[("x-forwarded-for", "invalid")], Malformed),
(&[("forwarded", "for=unknown")], Malformed),
(
&[("forwarded", "for=198.51.100.10;for=203.0.113.20")],
Malformed,
),
(
&[
("x-real-ip", "198.51.100.10"),
("x-real-ip", "198.51.100.10"),
],
Malformed,
),
(
&[
("x-forwarded-for", "198.51.100.10"),
("forwarded", "for=203.0.113.20"),
],
Conflicting,
),
(
&[
("x-forwarded-for", "192.0.2.1, 198.51.100.10"),
("forwarded", "for=192.0.2.2, for=198.51.100.10"),
],
Conflicting,
),
(&[("x-forwarded-for", "10.0.0.1, 10.0.0.2")], NoUntrustedHop),
];
for (pairs, expected) in cases {
let mut headers = HeaderMap::new();
for (name, value) in *pairs {
headers.append(
axum::http::HeaderName::from_bytes(name.as_bytes()).unwrap(),
value.parse().unwrap(),
);
}
let context = trusted_forwarded_context(&headers);
assert_eq!(context.client_ip(), Some("10.0.0.3"), "{pairs:?}");
assert_eq!(context.client_ip_source(), Some(ClientIpSource::Peer));
assert_eq!(
context.forwarded_headers_status(),
Some(*expected),
"{pairs:?}"
);
let restored: RequestContext =
serde_json::from_value(serde_json::to_value(&context).unwrap()).unwrap();
assert_eq!(restored.client_ip(), context.client_ip());
assert_eq!(restored.client_ip_source(), context.client_ip_source());
assert_eq!(restored.forwarded_headers_status(), Some(*expected));
}
}
#[test]
fn forwarding_diagnostics_report_success_without_changing_source_precedence() {
for (name, value, source) in [
(
"x-forwarded-for",
"198.51.100.10",
ClientIpSource::XForwardedFor,
),
("forwarded", "for=198.51.100.10", ClientIpSource::Forwarded),
("x-real-ip", "198.51.100.10", ClientIpSource::XRealIp),
] {
let mut headers = HeaderMap::new();
headers.insert(name, value.parse().unwrap());
let context = trusted_forwarded_context(&headers);
assert_eq!(context.client_ip(), Some("198.51.100.10"));
assert_eq!(context.client_ip_source(), Some(source));
assert_eq!(
context.forwarded_headers_status(),
Some(ForwardedHeadersStatus::Resolved)
);
let restored: RequestContext =
serde_json::from_value(serde_json::to_value(&context).unwrap()).unwrap();
assert_eq!(restored.client_ip_source(), Some(source));
assert_eq!(
restored.forwarded_headers_status(),
Some(ForwardedHeadersStatus::Resolved)
);
}
let mut headers = HeaderMap::new();
headers.insert(
"x-forwarded-for",
"198.51.100.10, 10.0.0.2".parse().unwrap(),
);
headers.insert(
"forwarded",
"for=198.51.100.10, for=10.0.0.2".parse().unwrap(),
);
headers.insert("x-real-ip", "invalid".parse().unwrap());
let context = trusted_forwarded_context(&headers);
assert_eq!(context.client_ip(), Some("198.51.100.10"));
assert_eq!(context.client_ip_source(), Some(ClientIpSource::Forwarded));
assert_eq!(
context.forwarded_headers_status(),
Some(ForwardedHeadersStatus::Resolved)
);
headers.insert("forwarded", "for=invalid".parse().unwrap());
headers.insert("x-real-ip", "203.0.113.20".parse().unwrap());
let context = trusted_forwarded_context(&headers);
assert_eq!(context.client_ip_source(), Some(ClientIpSource::Peer));
assert_eq!(
context.forwarded_headers_status(),
Some(ForwardedHeadersStatus::Malformed)
);
}
#[test]
fn forwarding_diagnostics_do_not_parse_untrusted_input_or_infer_missing_peers() {
let trusted = ForwardedHeadersPolicy::local_development();
for (policy, peer, expected) in [
(
ForwardedHeadersPolicy::never(),
None,
ForwardedHeadersStatus::Disabled,
),
(trusted.clone(), None, ForwardedHeadersStatus::MissingPeer),
(
trusted.clone(),
Some(peer_ip()),
ForwardedHeadersStatus::UntrustedPeer,
),
(
ForwardedHeadersPolicy::always(),
None,
ForwardedHeadersStatus::Malformed,
),
] {
let mut headers = HeaderMap::new();
let absent =
RequestContext::from_headers_and_peer_ip_with_forwarded_policy(&headers, peer, &policy);
assert_eq!(
absent.forwarded_headers_status(),
Some(ForwardedHeadersStatus::Absent)
);
headers.insert("x-forwarded-for", "private-invalid-input".parse().unwrap());
let context =
RequestContext::from_headers_and_peer_ip_with_forwarded_policy(&headers, peer, &policy);
assert_eq!(context.client_ip_addr(), peer);
assert_eq!(context.forwarded_headers_status(), Some(expected));
assert!(!format!("{context:?}").contains("private-invalid-input"));
let restored: RequestContext =
serde_json::from_value(serde_json::to_value(&context).unwrap()).unwrap();
assert_eq!(restored.forwarded_headers_status(), Some(expected));
}
let mut headers = HeaderMap::new();
headers.insert("x-forwarded-for", "198.51.100.10".parse().unwrap());
let context = RequestContext::from_headers_and_peer_ip_with_forwarded_policy(
&headers,
None,
&ForwardedHeadersPolicy::always(),
);
assert_eq!(context.client_ip(), Some("198.51.100.10"));
assert_eq!(
context.forwarded_headers_status(),
Some(ForwardedHeadersStatus::Resolved)
);
}
#[test]
fn explicit_client_ip_changes_clear_diagnostics_and_policy_refresh_updates_them() {
let mut headers = HeaderMap::new();
headers.insert("x-forwarded-for", "198.51.100.10".parse().unwrap());
let context = trusted_forwarded_context(&headers);
let mut explicit = context
.clone()
.with_client_ip(ClientIp::new("203.0.113.20").unwrap());
assert_eq!(explicit.forwarded_headers_status(), None);
explicit.refresh_client_ip(
&headers,
Some(trusted_proxy_ip()),
&ForwardedHeadersPolicy::never(),
);
assert_eq!(explicit.client_ip_source(), Some(ClientIpSource::Explicit));
assert_eq!(explicit.forwarded_headers_status(), None);
assert_eq!(
context
.clone()
.with_client_ip(peer_ip())
.forwarded_headers_status(),
None
);
assert_eq!(
context.clone().clear_client_ip().forwarded_headers_status(),
None
);
assert_eq!(
RequestContext::new(RequestId::default()).forwarded_headers_status(),
None
);
let mut refreshed = context;
refreshed.refresh_client_ip(
&headers,
Some(trusted_proxy_ip()),
&ForwardedHeadersPolicy::never(),
);
assert_eq!(refreshed.client_ip_source(), Some(ClientIpSource::Peer));
assert_eq!(
refreshed.forwarded_headers_status(),
Some(ForwardedHeadersStatus::Disabled)
);
refreshed.refresh_client_ip(&HeaderMap::new(), None, &ForwardedHeadersPolicy::never());
assert_eq!(refreshed.client_ip(), None);
assert_eq!(
refreshed.forwarded_headers_status(),
Some(ForwardedHeadersStatus::Absent)
);
}
#[test]
fn deserialized_forwarding_diagnostics_must_match_the_resolved_ip_source() {
for (status, source, client_ip) in [
("resolved", "peer", Some("192.0.2.10")),
("resolved", "x_forwarded_for", None),
("malformed", "forwarded", Some("192.0.2.10")),
("absent", "explicit", Some("192.0.2.10")),
("missing_peer", "peer", Some("192.0.2.10")),
("untrusted_peer", "peer", None),
("no_untrusted_hop", "peer", None),
] {
let value = json!({
"request_id": "req_test", "client_ip": client_ip,
"client_ip_source": source, "forwarded_headers_status": status,
});
let error = serde_json::from_value::<RequestContext>(value).unwrap_err();
assert!(!error.to_string().contains("192.0.2.10"));
}
let context: RequestContext = serde_json::from_value(json!({
"request_id": "req_test", "client_ip": "192.0.2.10", "client_ip_source": "forwarded",
}))
.unwrap();
assert_eq!(context.forwarded_headers_status(), None);
}