Skip to main content

Crate http_extract

Crate http_extract 

Source
Expand description

Strict, trust-aware extraction of HTTP request metadata.

This crate operates primarily on http types and does not require a web framework, Tower, tracing, or OpenTelemetry. An opt-in axum feature adds only transport-peer extraction from Axum request extensions. Forwarding fields are never trusted implicitly.

The crate root exposes small synchronous extractors for coherent field responsibilities. Applications compose only the functions they need at their framework boundary; this crate does not impose a request-context aggregate or an asynchronous adapter. Cargo features gate field-specific APIs; disabling default features leaves the shared Header helpers and Error available, and enabling a feature exposes only its documented API and dependencies.

§http-extract

§Extract the signal. Keep trust explicit.

Strict, synchronous HTTP request metadata extraction for Rust, built on ordinary http types.

Crates.io Documentation Rust License

Guide · API reference · Features · Axum example

http-extract provides small, direct functions for reading request metadata. The default API is framework-independent; an optional axum feature reads an existing socket peer from ConnectInfo<SocketAddr>.

Its central rule is simple: transport facts and Header assertions are not the same thing. Values from Forwarded, X-Forwarded-*, and provider-specific client-IP fields remain raw and untrusted until the deployment establishes an explicit proxy trust boundary.

§Quick start

Default features enable all common extractor families:

[dependencies]
http-extract = "0.1"

Header functions contain the parsing logic. Matching Request functions are convenience wrappers over request.headers():

use http_extract::{HeaderName, Request, extract_single_header_text};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let name = HeaderName::from_static("x-example");
    let request = Request::builder()
        .uri("https://example.com/items")
        .header(name.clone(), "metadata")
        .body(())?;

    assert_eq!(
        extract_single_header_text(request.headers(), &name)?,
        Some("metadata")
    );

    Ok(())
}

Feature-specific Header and Request pairs follow the same direct shape. See the Features guide for the complete API families.

For a smaller dependency surface, disable defaults and select only what the application uses:

[dependencies]
http-extract = { version = "0.1", default-features = false, features = [
  "authority",
  "content-type",
] }

§Trust is part of the input

socket peer ──────────────────────── transport fact

Forwarded / X-Forwarded-* ───────── raw Header assertion
provider client-IP fields ───────── raw Header assertion
                                             │
                                             ▼
                              deployment-specific trust policy
SourceLibrary behaviorSecurity meaning
Socket peerRead from the request extension supplied by the server adapterConnection fact; identifies the immediate peer
ForwardedStrict RFC 7239 for= IP-chain parsingUntrusted until the proxy boundary is established
X-Forwarded-*Strict parsing of common de facto fieldsUntrusted Header assertion
Provider fieldsOne explicit extractor per supported fieldUntrusted vendor assertion

extract_client_ip checks Header sources in this order:

  1. RFC 7239 Forwarded;
  2. X-Forwarded-For;
  3. X-Real-IP;
  4. CF-Connecting-IP.

That order is a library convention, not an RFC-defined trust policy. If a first-present source has an invalid supported value, extraction fails instead of silently falling through. For Forwarded, parameters other than for are ignored after quote-aware element splitting; their names and values are not validated. extract_client_ip_with_headers accepts an explicit ordered source list.

extract_socket_ip never reads Headers. extract_proxy_client_ip uses the default Header order and falls back to the socket peer only when every supported Header is absent; it does not authenticate a proxy.

Read the client IP trust boundary before using a Header-derived address for authorization, rate limiting, or auditing.

§Features

Cargo featureWhat it adds
api-keyX-API-Key, then Api-Key extraction
authorityURI authority and strict Host extraction
authorizationRaw Authorization and Bearer/Basic scheme routing
client-ipSocket-peer helpers and default/custom Header selection
client-ip-headersCommon provider and proxy client-IP fields
content-typeStrict parsing into mime::Mime
forwardedRFC 7239 Forwarded for= IP chains
request-idX-Request-Id, then Request-Id fallback
x-forwardedX-Forwarded-For and X-Forwarded-Proto parsing
axumOptional ConnectInfo<SocketAddr> peer adapter

Default features include every row except axum. With no default features, the crate-wide Error and generic Header helpers remain available. The normal default dependency tree does not include Axum, Tower, Tokio, tracing, or OpenTelemetry.

See the complete Features guide for exact functions, return types, and feature relationships.

§Errors and sensitive values

Missing optional metadata returns Ok(None). Duplicate, non-text, and malformed fields return the crate-wide Error. Errors identify the field and category, never the raw value.

Authorization credentials and API keys are exposed only by their explicit extractors. Do not log those values, cookies, request bodies, complete query strings, or raw forwarding fields.

§Axum example

The runnable Axum example demonstrates peer extraction, request metadata, client-IP selection, generic error responses, and safe observable output:

cargo run --example axum-demo --features axum

Axum is an optional integration boundary, not part of the default library core.

§Compatibility and standards

  • Rust 1.96.0 or newer;
  • HTTP semantics from RFC 9110;
  • narrow Forwarded support from RFC 7239;
  • lightweight Bearer and Basic scheme routing informed by RFC 6750 and RFC 7617.

The crate extracts metadata; it is not a complete HTTP, proxy, or authentication implementation. X-Forwarded-* and provider-specific fields are de facto or vendor conventions, not IETF standards. See Standards and compatibility for the exact support boundary.

§License

Licensed under either of

at your option.

Structs§

HeaderMap
A specialized multimap for header names and values.
HeaderName
Represents an HTTP header field name
HeaderValue
Represents an HTTP header field value.
Request
Represents an HTTP request.

Enums§

ClientIpHeader
A supported client IP Header and its parsing rule.
Error
An error produced while extracting request metadata.

Constants§

API_KEY
The fallback Api-Key field name.
BASIC_SCHEME
The Basic scheme.
BEARER_SCHEME
The Bearer scheme.
CF_CONNECTING_IP
The CF-Connecting-IP field name.
CLIENT_IP_HEADERS
The effective header lookup order used by extract_client_ip.
CLOUDFRONT_VIEWER_ADDRESS
The CloudFront-Viewer-Address field name.
FLY_CLIENT_IP
The Fly-Client-IP field name.
FORWARDED
The standardized Forwarded field name from RFC 7239, Section 4.
REQUEST_ID
The fallback Request-Id field name.
SCHEME_SEPARATOR
The space character that separates the scheme from the credentials.
TRUE_CLIENT_IP
The True-Client-IP field name.
X_API_KEY
The preferred X-API-Key field name.
X_ENVOY_EXTERNAL_ADDRESS
The X-Envoy-External-Address field name.
X_FORWARDED_FOR
The de facto, non-IETF X-Forwarded-For field name.
X_FORWARDED_PROTO
The de facto, non-IETF X-Forwarded-Proto field name.
X_REAL_IP
The X-Real-IP field name.
X_REQUEST_ID
The preferred X-Request-Id field name.

Functions§

append_header_value
Append one already validated field value without replacing existing values.
extract_axum_socket_address
Extract the Axum transport peer stored in a request extension.
extract_axum_socket_ip
Extract the Axum socket peer IP stored in a request extension.
extract_client_ip
Extract a raw client IP assertion using the effective field order.
extract_client_ip_with_headers
Extract a raw client IP assertion using caller-defined fields and order.
extract_header_api_key
Extract an API key from request fields.
extract_header_authority
Extract a strict, singular, syntactically valid Host authority.
extract_header_authorization
Extract the singular Authorization field as text.
extract_header_basic_credentials
Extract raw Basic credentials from the Authorization field.
extract_header_bearer_token
Extract raw Bearer credentials from the Authorization field.
extract_header_cf_connecting_ip
Extract the raw, untrusted IP asserted by CF-Connecting-IP.
extract_header_cloudfront_viewer_address
Extract an untrusted client IP from AWS CloudFront’s CloudFront-Viewer-Address IP:port value.
extract_header_content_type
Extract and parse a singular Content-Type field as a media type.
extract_header_fly_client_ip
Extract the raw, untrusted IP asserted by Fly-Client-IP.
extract_header_forwarded_for
Extract RFC 7239 Forwarded for= values as an untrusted IP chain.
extract_header_request_id
Extract a request ID from request fields.
extract_header_true_client_ip
Extract an untrusted client IP asserted by True-Client-IP.
extract_header_x_envoy_external_address
Extract an untrusted client IP asserted by Envoy’s X-Envoy-External-Address.
extract_header_x_forwarded_for
Extract all X-Forwarded-For field lines as an untrusted asserted IP chain.
extract_header_x_forwarded_proto
Extract all X-Forwarded-Proto field lines as untrusted protocol tokens.
extract_header_x_real_ip
Extract the raw, untrusted IP asserted by X-Real-IP.
extract_proxy_client_ip
Extract a proxy-aware client IP, falling back to the socket peer.
extract_request_api_key
Extract an API key from a complete request.
extract_request_authority
Extract the authority from a complete request.
extract_request_authorization
Extract the raw Authorization field from a complete request.
extract_request_basic_credentials
Extract raw Basic credentials from a complete request.
extract_request_bearer_token
Extract raw Bearer credentials from a complete request.
extract_request_cf_connecting_ip
Extract CF-Connecting-IP from a complete request.
extract_request_cloudfront_viewer_address
Extract CloudFront-Viewer-Address from a complete request.
extract_request_content_type
Extract and parse Content-Type from a complete request.
extract_request_fly_client_ip
Extract Fly-Client-IP from a complete request.
extract_request_forwarded_for
Extract the untrusted Forwarded for= IP chain from a complete request.
extract_request_request_id
Extract a request ID from a complete request.
extract_request_socket_address
Extract a SocketAddr stored directly in a request extension.
extract_request_socket_ip
Extract the IP component of a SocketAddr request extension.
extract_request_true_client_ip
Extract True-Client-IP from a complete request.
extract_request_x_envoy_external_address
Extract X-Envoy-External-Address from a complete request.
extract_request_x_forwarded_for
Extract the untrusted X-Forwarded-For chain from a complete request.
extract_request_x_forwarded_proto
Extract untrusted X-Forwarded-Proto tokens from a complete request.
extract_request_x_real_ip
Extract X-Real-IP from a complete request.
extract_rightmost_forwarded
Extract the rightmost Forwarded for= IP address from a header.
extract_rightmost_x_forwarded_for
Extract the rightmost X-Forwarded-For IP address from a header.
extract_single_header_text
Extract a singular field as text without silently discarding invalid bytes.
extract_single_header_value
Extract a field value only when the field has at most one field line.
extract_socket_ip
Extract the request’s socket peer IP without inspecting HTTP fields.