footing 0.1.22

Feature-gated foundations for Rust backend services
Documentation
use axum::{http::StatusCode, response::IntoResponse};
use serde_json::json;

use super::{
    ApiProblem, ApiProblemStatusError, PROBLEM_JSON_MEDIA_TYPE, ProblemCode,
    ProblemIdentifierError, ProblemType,
};
use crate::http::{RequestContext, RequestId};
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")
}

#[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)
    ));
    assert!(matches!(
        ProblemCode::try_new("invalid query"),
        Err(ProblemIdentifierError::InvalidCharacters)
    ));
}

#[test]
fn validates_problem_type() {
    let problem_type = ProblemType::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!(
        ProblemType::try_new("bad type"),
        Err(ProblemIdentifierError::InvalidCharacters)
    ));
    assert!(matches!(
        ProblemType::try_new("bad type"),
        Err(ProblemIdentifierError::InvalidCharacters)
    ));
}

#[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: ProblemType =
        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::<ProblemType>(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);
    }

    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"),
        ("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_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(instance)
        .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"),
        Some("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01".to_owned()),
    )
    .with_client_ip("198.51.100.10")
    .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"),
        None,
    )
    .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::from_error(&descriptor, policy)
            .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::from_error(
        &private_client_error,
        ErrorBoundaryPolicy::trusted_internal(),
    );
    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"
    );
}

#[test]
fn response_uses_problem_json_content_type() {
    let response = ApiProblem::bad_request(code("invalid_query"), "invalid query").into_response();
    let content_type = response
        .headers()
        .get(axum::http::header::CONTENT_TYPE)
        .and_then(|value| value.to_str().ok());

    assert_eq!(content_type, Some(PROBLEM_JSON_MEDIA_TYPE));
}