use axum::{
http::{StatusCode, header},
response::IntoResponse,
};
use serde_json::json;
use super::{
ApiProblem, ApiProblemStatusError, PROBLEM_JSON_MEDIA_TYPE, ProblemCode,
ProblemIdentifierError, ProblemUri,
};
use crate::http::{AuthenticationChallenge, RequestContext, RequestId, TraceParent};
use crate::result::{ClassifyError, ErrorBoundaryPolicy, ErrorCode, ErrorDescriptor, ErrorKind};
fn code(value: &'static str) -> ProblemCode {
ProblemCode::try_new(value).expect("test problem code should be valid")
}
#[tokio::test]
async fn problem_headers_preserve_repeated_fields_and_keep_payload_separate() {
use axum::{body::to_bytes, http::HeaderValue};
let mut problem = ApiProblem::unauthorized(
code("unauthenticated"),
"authentication required",
&AuthenticationChallenge::try_new("Bearer realm=\"api\"").unwrap(),
);
problem.headers_mut().append(
header::WWW_AUTHENTICATE,
AuthenticationChallenge::try_new("Basic realm=\"legacy\"")
.unwrap()
.as_header_value()
.clone(),
);
for cookie in [
"first=private-cookie-one; HttpOnly",
"second=private-cookie-two; HttpOnly",
] {
problem
.headers_mut()
.append(header::SET_COOKIE, HeaderValue::from_static(cookie));
}
problem
.headers_mut()
.insert(header::RETRY_AFTER, HeaderValue::from_static("30"));
let payload = serde_json::to_value(problem.clone().into_body()).unwrap();
assert_eq!(payload["status"], 401);
assert_eq!(payload["code"], "unauthenticated");
assert!(payload.get("headers").is_none());
assert!(!payload.to_string().contains("private-cookie"));
let response = problem.into_response();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
let headers = response.headers();
assert_eq!(
headers
.get_all(header::WWW_AUTHENTICATE)
.iter()
.collect::<Vec<_>>(),
["Bearer realm=\"api\"", "Basic realm=\"legacy\""]
);
assert_eq!(
headers
.get_all(header::SET_COOKIE)
.iter()
.collect::<Vec<_>>(),
[
"first=private-cookie-one; HttpOnly",
"second=private-cookie-two; HttpOnly"
]
);
assert_eq!(headers[header::RETRY_AFTER], "30");
assert_eq!(headers[header::CACHE_CONTROL], "no-store");
assert_eq!(headers[header::CONTENT_TYPE], PROBLEM_JSON_MEDIA_TYPE);
let body = to_bytes(response.into_body(), 4096).await.unwrap();
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&body).unwrap(),
payload
);
}
#[test]
fn problem_headers_allow_explicit_cache_policy_and_preserve_problem_media_type() {
use axum::http::HeaderValue;
let mut problem = ApiProblem::not_found(code("not_found"), "not found");
problem.headers_mut().insert(
header::CACHE_CONTROL,
HeaderValue::from_static("private, max-age=60"),
);
for content_type in ["text/html", "text/plain"] {
problem
.headers_mut()
.append(header::CONTENT_TYPE, HeaderValue::from_static(content_type));
}
let response = problem.into_response();
assert_eq!(
response.headers()[header::CACHE_CONTROL],
"private, max-age=60"
);
assert_eq!(
response.headers()[header::CONTENT_TYPE],
PROBLEM_JSON_MEDIA_TYPE
);
assert_eq!(
response
.headers()
.get_all(header::CONTENT_TYPE)
.iter()
.count(),
1
);
}
#[test]
fn problem_headers_debug_redacts_values_without_sensitive_markers() {
use axum::http::HeaderValue;
let mut problem = ApiProblem::unauthorized(
code("unauthenticated"),
"authentication required",
&AuthenticationChallenge::try_new("Bearer realm=\"private-realm\"").unwrap(),
);
for (name, value) in [
(header::SET_COOKIE, "session=private-credential; HttpOnly"),
(
header::HeaderName::from_static("x-private"),
"private-header",
),
] {
problem
.headers_mut()
.append(name, HeaderValue::from_static(value));
}
let output = format!("{problem:?} {problem}");
assert!(output.contains("header_count: 3"));
assert!(!output.contains("private-"));
}
#[test]
fn validates_problem_code() {
let code = ProblemCode::try_new(" invalid_query ").expect("problem code should be valid");
assert_eq!(code.as_str(), "invalid_query");
assert!(matches!(
ProblemCode::try_new("invalid query"),
Err(ProblemIdentifierError::InvalidCharacters)
));
}
#[test]
fn validates_problem_uri() {
let problem_type = ProblemUri::try_new("https://example.com/problems/invalid-query")
.expect("problem type should be valid");
assert_eq!(
problem_type.as_str(),
"https://example.com/problems/invalid-query"
);
assert!(matches!(
ProblemUri::try_new("bad type"),
Err(ProblemIdentifierError::InvalidCharacters)
));
}
#[test]
fn problem_types_reject_invalid_uri_characters_and_percent_encoding() {
for value in [
" https://example.com/problem",
"https://example.com/problem ",
"\t/problem",
"/problem\n",
" \t\n ",
"https://example.com/problems/%",
"https://example.com/problems/%2",
"https://example.com/problems/%zz",
"https://example.com/problems/\\invalid",
"https://example.com/problems/\"invalid\"",
"https://example.com/problems/{invalid}",
"https://example.com/problems/失敗",
"https://example.com/problems/a\u{0085}b",
] {
assert!(
matches!(
ProblemUri::try_new(value),
Err(ProblemIdentifierError::InvalidCharacters)
),
"invalid URI reference {value:?} should be rejected"
);
assert!(
serde_json::from_value::<ProblemUri>(json!(value)).is_err(),
"invalid URI reference {value:?} should not deserialize"
);
}
}
#[test]
fn problem_types_reject_invalid_uri_structure() {
for value in [
"1bad:problem",
"https://[broken",
"https://example.com/#first#second",
"https://user@@example.com/problem",
"https://example.com:port/problem",
] {
assert!(
matches!(
ProblemUri::try_new(value),
Err(ProblemIdentifierError::InvalidCharacters)
),
"invalid URI reference {value:?} should be rejected"
);
assert!(
serde_json::from_value::<ProblemUri>(json!(value)).is_err(),
"invalid URI reference {value:?} should not deserialize"
);
}
}
#[test]
fn problem_uris_enforce_length_limits() {
let max = super::MAX_PROBLEM_URI_LENGTH;
let value = format!("/{}", "a".repeat(max - 1));
let problem_type = ProblemUri::try_new(value.clone())
.expect("URI reference at the length limit should be valid");
assert_eq!(problem_type.as_str(), value);
let oversized = format!("{value}a");
assert_eq!(
ProblemUri::try_new(&oversized),
Err(ProblemIdentifierError::TooLong { max })
);
assert!(serde_json::from_value::<ProblemUri>(json!(oversized)).is_err());
}
#[test]
fn problem_types_preserve_valid_uri_references() {
for value in [
"",
"about:blank",
"urn:example:problem:invalid-input",
"tag:example@example.org,2021-09-17:OutOfLuck",
"/problems/invalid-input",
"../problems/invalid-input?field=name#details",
"#invalid-input",
"?problem=invalid-input",
"//example.com/problems/invalid-input",
"https://[2001:db8::1]/problems/%E5%A4%B1%E6%95%97",
"custom://[v1.a:b]/problems/invalid-input",
"https://example.com/problems/a%2fb!$&'()*+,;=:@_~-.",
] {
let problem_type = ProblemUri::try_new(value).expect("URI reference should be valid");
assert_eq!(problem_type.as_str(), value);
let deserialized: ProblemUri =
serde_json::from_value(json!(value)).expect("URI reference should deserialize");
assert_eq!(deserialized, problem_type);
}
}
#[test]
fn problem_identifiers_deserialize_with_constructor_validation() {
let code: ProblemCode =
serde_json::from_value(json!(" invalid_query ")).expect("code should deserialize");
assert_eq!(code.as_str(), "invalid_query");
assert!(serde_json::from_value::<ProblemCode>(json!("invalid query")).is_err());
let problem_type: ProblemUri =
serde_json::from_value(json!("https://example.com/problems/invalid-query"))
.expect("type should deserialize");
assert_eq!(
problem_type.as_str(),
"https://example.com/problems/invalid-query"
);
assert!(serde_json::from_value::<ProblemUri>(json!("bad type")).is_err());
}
#[test]
fn problem_identifier_errors_are_classified_as_validation_failures() {
let error = ProblemCode::try_new("bad code").expect_err("problem code should be invalid");
let descriptor = error.error_descriptor();
assert_eq!(descriptor.kind(), ErrorKind::Validation);
assert_eq!(
descriptor.code().as_str(),
"problem_identifier_invalid_characters"
);
}
#[test]
fn problem_body_carries_status_and_request_id() {
let problem = ApiProblem::bad_request(code("invalid_query"), "invalid query")
.with_request_id(&RequestId::new("req_test").expect("request id should be valid"));
assert_eq!(problem.status(), StatusCode::BAD_REQUEST);
assert_eq!(problem.body().status(), 400);
assert_eq!(problem.body().title(), "Bad Request");
assert_eq!(problem.body().detail(), "invalid query");
assert_eq!(problem.body().request_id(), Some("req_test"));
}
#[test]
fn problem_details_deserialization_preserves_private_invariants() {
let valid = serde_json::json!({
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"code": "invalid_query",
"detail": "invalid query"
});
for status in [400, 599] {
let mut value = valid.clone();
value["status"] = json!(status);
let problem = serde_json::from_value::<super::ProblemDetails>(value)
.expect("error status should deserialize");
assert_eq!(problem.status(), status);
assert_eq!(problem.instance(), None);
assert_eq!(problem.request_id(), None);
assert_eq!(problem.trace_id(), None);
assert_eq!(problem.details(), None);
assert_eq!(serde_json::to_value(&problem).unwrap()["status"], status);
}
for status in [0, 200, 399, 600, 1000] {
let mut value = valid.clone();
value["status"] = json!(status);
assert!(
serde_json::from_value::<super::ProblemDetails>(value).is_err(),
"status {status} should be rejected"
);
}
for (field, value) in [
("type", "bad type"),
("instance", "/occurrences/bad instance"),
("instance", "/occurrences/%zz"),
("instance", " /occurrences/123"),
("instance", "https://[broken"),
("code", "invalid code"),
("request_id", "bad request id"),
] {
let mut problem = valid.clone();
problem[field] = json!(value);
assert!(
serde_json::from_value::<super::ProblemDetails>(problem).is_err(),
"invalid {field} should be rejected"
);
}
}
#[test]
fn problem_uri_fields_round_trip_without_normalization() {
for value in [
"",
"/occurrences/123",
"urn:example:problem:123",
"#occurrence-123",
"https://example.com/problems/%2f?q=123#detail",
] {
let uri = ProblemUri::try_new(value).unwrap();
let problem = ApiProblem::bad_request(code("invalid_input"), "Invalid input")
.with_type(uri.clone())
.with_instance(uri);
let wire = serde_json::to_value(problem.body()).unwrap();
assert_eq!(wire["type"], value);
assert_eq!(wire["instance"], value);
let decoded: super::ProblemDetails = serde_json::from_value(wire).unwrap();
assert_eq!(decoded.type_uri(), value);
assert_eq!(decoded.instance(), Some(value));
}
let mut wire = serde_json::to_value(
ApiProblem::bad_request(code("invalid_input"), "Invalid input").body(),
)
.unwrap();
wire["instance"] = json!(format!("/{}", "x".repeat(super::MAX_PROBLEM_URI_LENGTH)));
assert!(serde_json::from_value::<super::ProblemDetails>(wire).is_err());
}
#[test]
fn generic_problem_constructors_require_explicit_authentication_challenges() {
let descriptor = ErrorDescriptor::new(
ErrorKind::Authentication,
ErrorCode::internal("unauthenticated"),
"authentication is required",
);
for result in [
ApiProblem::try_new(
StatusCode::UNAUTHORIZED,
code("unauthenticated"),
"authentication is required",
),
ApiProblem::try_from_descriptor(descriptor.clone()),
ApiProblem::try_from_error(&descriptor, ErrorBoundaryPolicy::new()),
] {
assert_eq!(
result.unwrap_err(),
ApiProblemStatusError::AuthenticationChallengeRequired
);
}
let problem = ApiProblem::unauthorized(
code("unauthenticated"),
"authentication is required",
&AuthenticationChallenge::try_new("Bearer").unwrap(),
);
assert_eq!(problem.status(), StatusCode::UNAUTHORIZED);
assert_eq!(problem.headers()[header::WWW_AUTHENTICATE], "Bearer");
}
#[test]
fn problem_debug_redacts_arbitrary_payloads_without_changing_wire_data() {
let detail = "private-public-detail";
let instance = "https://example.com/problem?token=private-instance";
let details = "private-details";
let problem = ApiProblem::bad_request(code("invalid_query"), detail)
.with_instance(ProblemUri::try_new(instance).unwrap())
.with_details(json!({ "credential": details }));
let debug = format!("{problem:?}");
let display = problem.to_string();
assert!(debug.contains("invalid_query"));
assert!(debug.contains("[REDACTED]"));
for sensitive in [detail, instance, details] {
assert!(!debug.contains(sensitive));
assert!(!display.contains(sensitive));
}
assert_eq!(display, "HTTP problem invalid_query (400)");
let wire = serde_json::to_value(problem.body()).expect("problem should serialize");
assert_eq!(wire["detail"], detail);
assert_eq!(wire["instance"], instance);
assert_eq!(wire["details"]["credential"], details);
assert!(wire.get("context").is_none());
}
#[test]
fn request_context_exposes_only_safe_correlation_identifiers() {
let context =
RequestContext::new(RequestId::new("req_test").expect("request id should be valid"))
.with_traceparent(
TraceParent::new("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
.unwrap(),
)
.with_client_ip(crate::net::ClientIp::new("198.51.100.10").unwrap())
.with_locale("en-US")
.with_time_zone("UTC")
.with_utc_offset_minutes(0)
.with_client_id("opsline")
.with_session_id("sess_private");
let problem = ApiProblem::bad_request(code("invalid_query"), "invalid query")
.with_request_context(&context)
.into_body();
assert_eq!(problem.request_id(), Some("req_test"));
assert_eq!(problem.trace_id(), Some("4bf92f3577b34da6a3ce929d0e0e4736"));
let serialized = serde_json::to_value(problem).expect("problem should serialize");
assert!(serialized.get("context").is_none());
assert!(!serialized.to_string().contains("sess_private"));
}
#[test]
fn classified_errors_apply_disclosure_policy_before_http_conversion() {
let descriptor = ErrorDescriptor::new(
ErrorKind::Dependency,
ErrorCode::try_new("database_unavailable").expect("error code should be valid"),
"database connection failed",
);
let context =
RequestContext::new(RequestId::new("req_test").expect("request id should be valid"))
.with_client_id("private-client")
.with_session_id("private-session");
for (policy, detail) in [
(ErrorBoundaryPolicy::new(), "service is unavailable"),
(
ErrorBoundaryPolicy::trusted_internal(),
"database connection failed",
),
] {
let problem = ApiProblem::try_from_error(&descriptor, policy)
.unwrap()
.with_request_context(&context)
.into_body();
assert_eq!(problem.status(), 503);
assert_eq!(problem.code(), "database_unavailable");
assert_eq!(problem.detail(), detail);
assert_eq!(problem.request_id(), Some("req_test"));
assert!(
!serde_json::to_string(&problem)
.unwrap()
.contains("private-")
);
}
let private_client_error = ErrorDescriptor::new(
ErrorKind::Validation,
ErrorCode::internal("invalid_input"),
"private input detail",
)
.with_private_message();
let problem = ApiProblem::try_from_error(
&private_client_error,
ErrorBoundaryPolicy::trusted_internal(),
)
.unwrap();
assert_eq!(problem.status(), StatusCode::BAD_REQUEST);
assert_eq!(problem.body().detail(), "request validation failed");
}
#[test]
fn problem_status_must_be_error_status() {
let error =
ApiProblem::try_new(StatusCode::OK, code("ok"), "ok").expect_err("status is not an error");
assert!(matches!(
error,
ApiProblemStatusError::InvalidStatus { status: 200 }
));
assert_eq!(
error.error_descriptor().code().as_str(),
"api_problem_invalid_status"
);
}
#[tokio::test]
async fn response_uses_problem_json_with_matching_status_and_no_store() {
for status in [400, 404, 405, 422, 500, 599] {
let status = StatusCode::from_u16(status).unwrap();
let response = ApiProblem::try_new(status, code("test_problem"), "test problem")
.unwrap()
.into_response();
assert_eq!(response.status(), status);
assert_eq!(
response.headers()[header::CONTENT_TYPE],
PROBLEM_JSON_MEDIA_TYPE
);
assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store");
let body = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(body["status"], status.as_u16());
}
}
#[test]
fn application_can_explicitly_override_problem_cache_control() {
let response = (
[(header::CACHE_CONTROL, "private, max-age=60")],
ApiProblem::not_found(code("resource_not_found"), "Resource not found"),
)
.into_response();
assert_eq!(response.status(), StatusCode::NOT_FOUND);
assert_eq!(
response.headers()[header::CACHE_CONTROL],
"private, max-age=60"
);
assert_eq!(
response
.headers()
.get_all(header::CACHE_CONTROL)
.iter()
.count(),
1
);
assert_eq!(
response.headers()[header::CONTENT_TYPE],
PROBLEM_JSON_MEDIA_TYPE
);
}