footing 0.4.4

Feature-gated foundations for Rust backend services
Documentation
//! HTTP helpers for Axum services.
//!
//! This module contains reusable HTTP infrastructure: request context
//! propagation, RFC 9457 problem responses, validation extractors, pagination
//! extractors, CORS/security layers, route-aware runtime policy, and principal
//! extraction.
//!
//! ```rust
//! use axum::http::StatusCode;
//! use footing::http::{ApiProblem, ProblemCode};
//!
//! let problem = ApiProblem::bad_request(
//!     ProblemCode::try_new("invalid_query").unwrap(),
//!     "query is invalid",
//! );
//! assert_eq!(problem.status(), StatusCode::BAD_REQUEST);
//! ```
//!
/// Authentication hooks and principal extractors.
pub mod auth;
/// Endpoint contracts and route registration.
pub mod contract;
/// RFC 9457 problem responses and API error boundaries.
pub mod error;
/// Public health-response projection.
pub mod health;
pub mod idempotency;
pub mod layers;
/// Bounded-cardinality HTTP metrics middleware and responses.
pub mod metrics;
/// Request-context middleware entry points.
pub mod middleware;
#[cfg(feature = "openapi")]
#[cfg_attr(docsrs, doc(cfg(feature = "openapi")))]
pub mod openapi;
/// Offset pagination extractors.
pub mod pagination;
/// Query deserialization helpers.
pub mod query;
pub mod rate_limit;
pub mod request_context;
/// Forwarded-header trust policy.
pub mod trusted_proxy;
/// Validated JSON extraction and field violations.
pub mod validation;

pub use crate::net::{ClientIp, ClientIpError, MAX_CLIENT_IP_LENGTH};
pub use auth::{
    CurrentPrincipal, HttpAuthenticationHook, HttpAuthorizationHook, VerifiedAuthentication,
};
pub use contract::{
    EndpointAudit, EndpointAuth, EndpointContract, EndpointContractDocument,
    EndpointContractRegistry, EndpointContractSnapshot, EndpointContractSnapshotSummary,
    EndpointContractValidationError, EndpointMethod, EndpointMethodError, EndpointPagination,
    EndpointPathPattern, EndpointPermissions, EndpointPermissionsDocument, EndpointPolicy,
    EndpointRisk, EndpointRouter,
};
pub use error::{
    ApiProblem, ApiProblemStatusError, DEFAULT_PROBLEM_CODE, MAX_PROBLEM_CODE_LENGTH,
    MAX_PROBLEM_TYPE_LENGTH, ProblemCode, ProblemDetails, ProblemIdentifierError, ProblemType,
};
pub use health::HealthResponse;
pub use idempotency::{
    DEFAULT_IDEMPOTENCY_MAX_BODY_BYTES, DEFAULT_IDEMPOTENCY_PROCESSING_TTL,
    DEFAULT_IDEMPOTENCY_TTL, DEFAULT_MAX_IDEMPOTENCY_RECORDS,
    DEFAULT_MAX_IDEMPOTENCY_STORED_HEADER_BYTES, DEFAULT_MAX_IDEMPOTENCY_STORED_RESPONSE_BYTES,
    IDEMPOTENCY_KEY_HEADER_NAME, IDEMPOTENCY_REPLAYED_HEADER_NAME, IdempotencyConfig,
    IdempotencyConfigError, IdempotencyHeaderError, IdempotencyKey, IdempotencyKeyError,
    IdempotencyLayer, IdempotencyLease, IdempotencyRejection, IdempotencyRequestHash,
    IdempotencyRequestPolicy, IdempotencyReservation, IdempotencyRuntime, IdempotencyScope,
    IdempotencyService, IdempotencyStore, IdempotencyStoreError, MAX_IDEMPOTENCY_KEY_LENGTH,
    MemoryIdempotencyStore, RequiredIdempotencyKey, StoredIdempotencyResponse,
    idempotency_key_from_headers, is_valid_idempotency_key, parse_required_idempotency_key,
    run_idempotent_service,
};
pub use layers::{
    CorsConfig, CorsMode, CorsPolicy, CorsSettings, DEFAULT_HSTS_MAX_AGE,
    DEFAULT_HTTP_REQUEST_BODY_LIMIT, DEFAULT_HTTP_TIMEOUT, EffectiveHttpRequestPolicy,
    ForwardedHeadersMode, ForwardedHeadersSettings, HttpIdempotencySettings, HttpMiddlewareConfig,
    HttpMiddlewareError, HttpMiddlewareSettings, HttpMiddlewareStack, HttpMiddlewareStackBuilder,
    HttpRateLimitConfig, HttpRateLimitSettings, HttpRequestPolicy, HttpRequestPolicySettings,
    HttpRouteRule, HttpRouteRuleSettings, RateLimitKeySourceSettings, RequestBodyLimitPolicy,
    RequestBodyLimitSettings, RouteMatcher, RouteMatcherSettings, SecurityHeadersConfig,
    SecurityHeadersSettings, StrictTransportSecuritySettings,
};
pub use metrics::{
    HTTP_METRICS_UNMATCHED_ROUTE, HttpMetricsBody, HttpMetricsLayer, HttpMetricsService,
    MetricsResponse, OPENMETRICS_CONTENT_TYPE, PROMETHEUS_CONTENT_TYPE, record_http_metrics,
};
pub use middleware::{
    request_context_middleware, request_context_middleware_with_forwarded_policy,
};
pub use pagination::{
    CursorPagination, CursorPaginationQuery, OffsetPagination, OffsetPaginationQuery,
};
pub use query::{QueryParams, deserialize_bool_from_query, deserialize_optional_u32_from_query};
pub use rate_limit::{
    DEFAULT_MAX_RATE_LIMIT_BUCKETS, MAX_RATE_LIMIT_HEADER_VALUE_BYTES, RateLimitConfig,
    RateLimitDecision, RateLimitError, RateLimitKeySource, RateLimitLayer, RateLimitRejection,
    RateLimitRequestPolicy, RateLimitRuntime, RateLimitService, RateLimitStore,
    TokenBucketRateLimiter, enforce_rate_limit,
};
pub use request_context::{
    CLIENT_ID_HEADER_NAME, ClientIpSource, LOCALE_HEADER_NAME, MAX_REQUEST_CONTEXT_VALUE_LENGTH,
    MAX_REQUEST_ID_LENGTH, MAX_TRACEPARENT_LENGTH, MAX_USER_AGENT_LENGTH, REQUEST_ID_HEADER_NAME,
    RequestContext, RequestId, RequestIdError, SESSION_ID_HEADER_NAME, TIME_ZONE_HEADER_NAME,
    TRACEPARENT_HEADER_NAME, TRACEPARENT_LENGTH, TraceParent, TraceParentError,
    UTC_OFFSET_HEADER_NAME, is_valid_request_id, is_valid_traceparent,
};
pub use trusted_proxy::ForwardedHeadersPolicy;
pub use validation::{FieldViolation, Validate, ValidatedJson, ValidationError};

/// Lexical path validation shared by route policies and endpoint contracts.
fn is_valid_route_path(path: &str) -> bool {
    path.starts_with('/')
        && path.is_ascii()
        && !path.bytes().any(|byte| {
            byte.is_ascii_control()
                || byte.is_ascii_whitespace()
                || matches!(byte, b'?' | b'#' | b'\\')
        })
}

/// HTTP quality values are fixed-point thousandths, without floating-point rounding.
fn parse_quality(value: &str) -> Option<u16> {
    let (whole, fraction) = value.split_once('.').unwrap_or((value, ""));
    if !matches!(whole, "0" | "1")
        || fraction.len() > 3
        || !fraction.bytes().all(|b| b.is_ascii_digit())
    {
        return None;
    }
    let fractional = fraction
        .bytes()
        .fold(0u16, |n, b| n * 10 + u16::from(b - b'0'))
        * 10u16.pow(3 - fraction.len() as u32);
    match whole {
        "0" => Some(fractional),
        "1" if fractional == 0 => Some(1000),
        _ => None,
    }
}

fn to_lower_hex(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";

    let mut output = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        output.push(char::from(HEX[usize::from(byte >> 4)]));
        output.push(char::from(HEX[usize::from(byte & 0x0f)]));
    }
    output
}