footing 0.6.2

Feature-gated foundations for Rust backend services
Documentation
//! HTTP helpers for Axum services.
//!
//! This module contains reusable HTTP infrastructure: request context
//! propagation with trusted-proxy diagnostics, RFC 9457 problem responses, safe
//! JSON/path/query extractors, validation, browser request-origin checks, security
//! headers, route contracts, and principal extraction. `http-metrics` provides
//! independent HTTP metrics middleware and export responses. `http-stack`
//! includes `http-metrics`, CORS, timeouts, concurrency limits, rate limiting,
//! idempotency, health responses, and stack assembly. Pagination extractors
//! require `pagination`.
//! `http-locale` adds explicit language negotiation and localized response headers.
//!
//! ```rust
//! use axum::http::StatusCode;
//! use footing::http::{ApiProblem, ProblemCode};
//!
//! let problem = ApiProblem::bad_request(
//!     ProblemCode::from_static("invalid_query"),
//!     "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;
#[cfg(feature = "http-cookie")]
#[cfg_attr(docsrs, doc(cfg(feature = "http-cookie")))]
pub mod cookie;
/// RFC 9457 problem responses and API error boundaries.
pub mod error;
/// Public health-response projection.
#[cfg(feature = "http-stack")]
#[cfg_attr(docsrs, doc(cfg(feature = "http-stack")))]
pub mod health;
#[cfg(feature = "http-stack")]
#[cfg_attr(docsrs, doc(cfg(feature = "http-stack")))]
pub mod idempotency;
pub mod json;
#[cfg(feature = "http-stack")]
#[cfg_attr(docsrs, doc(cfg(feature = "http-stack")))]
pub mod layers;
#[cfg(feature = "http-locale")]
#[cfg_attr(docsrs, doc(cfg(feature = "http-locale")))]
pub mod locale;
/// Bounded-cardinality HTTP metrics middleware and responses.
#[cfg(feature = "http-metrics")]
#[cfg_attr(docsrs, doc(cfg(feature = "http-metrics")))]
pub mod metrics;
/// Request-context middleware entry points.
pub mod middleware;
#[cfg(feature = "openapi")]
#[cfg_attr(docsrs, doc(cfg(feature = "openapi")))]
pub mod openapi;
pub mod origin;
/// Offset pagination extractors.
#[cfg(feature = "pagination")]
#[cfg_attr(docsrs, doc(cfg(feature = "pagination")))]
pub mod pagination;
pub mod path;
/// Query deserialization helpers.
pub mod query;
#[cfg(feature = "http-stack")]
#[cfg_attr(docsrs, doc(cfg(feature = "http-stack")))]
pub mod rate_limit;
pub mod request_context;
/// Explicit Problem Details handlers for unmatched routes and methods.
pub mod routing;
/// Validated response security-header policies.
pub mod security;
#[cfg(feature = "http-static")]
#[cfg_attr(docsrs, doc(cfg(feature = "http-static")))]
pub mod static_site;
/// 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::{AuthenticationChallenge, CurrentPrincipal, InvalidAuthenticationChallenge};
#[cfg(feature = "http-stack")]
pub use auth::{HttpAuthenticationHook, HttpAuthorizationHook, VerifiedAuthentication};
pub use contract::EndpointRouter;
pub use contract::{
    EndpointAudit, EndpointAuth, EndpointContract, EndpointContractDocument,
    EndpointContractRegistry, EndpointContractSnapshot, EndpointContractSnapshotSummary,
    EndpointContractValidationError, EndpointMethod, EndpointMethodError, EndpointPagination,
    EndpointPathPattern, EndpointPermissions, EndpointPermissionsDocument, EndpointPolicy,
    EndpointRisk, IdempotencyRequestPolicy, RateLimitRequestPolicy,
};
pub use error::{
    ApiProblem, ApiProblemStatusError, DEFAULT_PROBLEM_CODE, MAX_PROBLEM_CODE_LENGTH,
    MAX_PROBLEM_URI_LENGTH, ProblemCode, ProblemDetails, ProblemIdentifierError, ProblemUri,
};
#[cfg(feature = "http-stack")]
pub use health::HealthResponse;
#[cfg(feature = "http-stack")]
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,
    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 json::JsonBody;
#[cfg(feature = "http-stack")]
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, ResponseTimeout, RouteMatcher, RouteMatcherSettings,
    SecurityHeadersSettings, StrictTransportSecuritySettings,
};
#[cfg(feature = "http-locale")]
pub use locale::{
    LocaleConfigError, LocaleNegotiationError, LocalePolicy, LocaleSource,
    MAX_ACCEPT_LANGUAGE_BYTES, MAX_LANGUAGE_RANGES, MAX_LOCALE_LENGTH, ResolvedLocale,
};
#[cfg(feature = "http-metrics")]
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 origin::{OriginPolicyError, OriginRejection, RequestOriginPolicy};
#[cfg(feature = "pagination")]
pub use pagination::{
    CursorPagination, CursorPaginationQuery, OffsetPagination, OffsetPaginationQuery,
};
pub use path::PathParams;
pub use query::{QueryParams, deserialize_bool_from_query, deserialize_optional_u32_from_query};
#[cfg(feature = "http-stack")]
pub use rate_limit::{
    DEFAULT_MAX_RATE_LIMIT_BUCKETS, MAX_RATE_LIMIT_HEADER_VALUE_BYTES, RateLimitConfig,
    RateLimitDecision, RateLimitError, RateLimitKeySource, RateLimitLayer, RateLimitRejection,
    RateLimitRuntime, RateLimitService, RateLimitStore, TokenBucketRateLimiter, enforce_rate_limit,
};
pub use request_context::{
    CLIENT_ID_HEADER_NAME, ClientIpSource, ForwardedHeadersStatus, 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 routing::{method_not_allowed, route_not_found};
pub use security::SecurityHeadersConfig;
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,
    }
}

/// Splits an HTTP list without splitting commas inside quoted strings.
#[cfg(any(feature = "http-metrics", feature = "http-static"))]
fn header_list_items(value: &[u8]) -> impl Iterator<Item = &[u8]> {
    let mut quoted = false;
    let mut escaped = false;
    value.split(move |&byte| {
        if escaped {
            escaped = false;
        } else if quoted && byte == b'\\' {
            escaped = true;
        } else if byte == b'"' {
            quoted = !quoted;
        } else if byte == b',' && !quoted {
            return true;
        }
        false
    })
}

#[cfg(any(feature = "http-stack", feature = "openapi"))]
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
}