Skip to main content

Crate servoh_axum

Crate servoh_axum 

Source
Expand description

§servoh-axum

servoh-axum serves ordinary Hyper HTTP/1 exchanges and RFC 6455 WebSocket Upgrades on authenticated iroh streams, then dispatches them to explicit Axum/Tower services. There is no private HTTP framing or loopback proxy.

§Minimal server

[dependencies]
axum = { version = "0.8", features = ["ws"] }
iroh = "1"
servoh-axum = "0.1"
use axum::{Router, routing::get};
use iroh::{Endpoint, endpoint::presets, protocol};
use servoh_axum::{AccessPolicy, Adapter, ServiceRegistry};

let endpoint = Endpoint::builder(presets::N0).bind().await?;
let app = Router::new().route("/", get(|| async { "hello over iroh" }));

let mut services = ServiceRegistry::new();
services.register_root(app, AccessPolicy::public())?;
let adapter = Adapter::new(&endpoint, services, AccessPolicy::public());
let router = adapter.register(protocol::Router::builder(endpoint))?.spawn();

router.endpoint().online().await;

Adapter::new borrows the endpoint that defines its canonical HTTP authority. Adapter::register checks that the protocol router owns that same endpoint and fails before serving if they differ. Adapter::ALPN (also re-exported as servoh_axum::HTTP_ALPN) is available for advanced manual router composition.

§Exposure and policy composition

AccessPolicy::public() is internet-facing exposure: every peer that can reach the endpoint and authenticate at the iroh transport can issue requests. An iroh EndpointId authenticates a transport peer, not an application user. AccessPolicy::allowlist restricts a boundary to exact endpoint identities.

Four checks compose independently:

BoundaryConfigurationMeaning
Connection/profileAdapter policyA peer may establish the shared HTTP ALPN connection. HTTP and attached WebSocket profile policies form a union here.
HTTP profileAdapter policyRechecked after an ordinary request is classified.
WebSocket profileWebSocketAdapter policyRechecked after an Upgrade candidate is classified.
Selected servicepolicy passed to register_root/addRechecked for the exact canonical authority.

An allowlisted service behind a public adapter is reachable only by its service allowlist. A public service behind an allowlisted adapter is reachable only by the adapter allowlist. When HTTP and WebSocket policies differ, either policy can admit the shared connection, but only the selected profile and service receive a request. Unknown and unauthorized services share a fail-closed 421 response.

Private peer admission is explicit:

let private = AccessPolicy::allowlist([trusted_peer]);

Applications remain responsible for user authentication, authorization, CORS, CSRF protection, Origin decisions, request semantics, and established WebSocket frame/message, ping/pong, idle, lifetime, and close policy. The adapter removes spoofable forwarding/client-identity headers and inserts the trusted ClientIdentity Axum extension for both ordinary HTTP handlers and WebSocket handshakes.

use axum::extract::Extension;
use servoh_axum::ClientIdentity;

async fn authenticated_peer(
    Extension(ClientIdentity(peer)): Extension<ClientIdentity>,
) -> String {
    peer.to_string()
}

Specifically, the adapter removes Forwarded, X-Forwarded-{For,Host,Proto}, X-Real-IP, X-Iroh-Client-Id, and X-Servoh-Client-Id. Ordinary HTTP also removes Connection, every field it nominates, Keep-Alive, Proxy-Connection, TE, Trailer, Transfer-Encoding, and Upgrade. WebSocket validation retains the required Connection/Upgrade handshake fields for Axum while removing other nominated and static hop-by-hop fields.

§Named services

Named services use lowercase DNS-style labels separated by dots. Each label is 1–63 ASCII characters, starts and ends with a letter or digit, may contain internal hyphens, and the complete service name is at most 253 bytes. Root and named services require explicit registration; an unknown name never falls back to the root.

let mut services = ServiceRegistry::new();
services.add("api-v1", app, AccessPolicy::public())?;

§Safe limits

Limit fields are private and every override is validated without panicking. Defaults are:

  • 64 established connections globally and 8 per authenticated peer;
  • 64 active HTTP exchanges globally and 8 per authenticated peer;
  • 128 MiB request and response bodies;
  • 5 minutes of established-connection idle time;
  • 30 seconds to read request headers and 5 minutes for a complete exchange;
  • 64 live WebSockets globally and 8 per peer, with a 30-second opening handshake.

Body limits apply after HTTP transfer decoding and before any content-coding decoding (this adapter does not decode content codings). The request limit also wraps WebSocket Upgrade candidates. Declared oversize is rejected before the application; unknown-length bodies fail at the boundary while being read.

let limits = AdapterLimits::default()
    .with_max_connections(128)?
    .with_max_connections_per_client(16)?
    .with_max_request_body_bytes(8 * 1024 * 1024)?
    .with_connection_idle_timeout(Duration::from_secs(120))?;

Established idle connections are closed and release their permits. Connections with active exchanges or upgraded WebSockets are not idle-expired; pooled clients can reuse them. Over-limit connections are closed immediately, and over-limit native streams are reset rather than queued.

§WebSocket registration

WebSockets share Adapter::ALPN and the pooled iroh connection, but require a separate registry and policy:

use axum::{
    Router,
    extract::{Extension, ws::WebSocketUpgrade},
    response::Response,
    routing::get,
};
use servoh_axum::{
    AccessPolicy, Adapter, ClientIdentity, ServiceRegistry, WebSocketAdapter,
};

async fn upgrade(
    ws: WebSocketUpgrade,
    Extension(ClientIdentity(peer)): Extension<ClientIdentity>,
) -> Response {
    ws.on_upgrade(move |_socket| async move {
        // The application owns frame/message limits, idle/lifetime policy,
        // authorization above `peer`, and graceful close behavior here.
        let _ = peer;
    })
}

let ws_app = Router::new().route("/socket", get(upgrade));
let mut websocket_services = ServiceRegistry::new();
websocket_services.add("chat", ws_app, AccessPolicy::public())?;
let websockets = WebSocketAdapter::new(websocket_services, AccessPolicy::public());
let adapter = adapter.with_websockets(websockets);

Malformed Upgrade-shaped requests cannot fall through to ordinary HTTP routes. A successful 101 transfers the native stream and WebSocket permits into Hyper’s upgraded I/O until teardown.

§Compatibility and security

The current ALPN servoh-http-spike/1 is an experimental, separately versioned wire-profile marker. A Rust API release number does not imply ALPN compatibility; a future incompatible wire profile will use a different ALPN and explicit migration guidance.

For 0.x, patch releases preserve documented APIs and wire behavior to the extent allowed by Cargo SemVer. Intentional breaking Rust API or behavior changes ship in the next minor release with migration notes. The project reviews public API diffs before release. iroh is pinned exactly in the workspace because its protocol APIs are tightly coupled; updating it requires protocol, interop, and security review.

Review this crate’s security notes, the project security model, HTTP profile, WebSocket profile, canonical authority, and public-service decision before exposure. The governing records are linked rather than copied into the crate archive.

Servoh requires Rust 1.91 or newer. Dual-licensed under MIT or Apache-2.0.

Structs§

AccessPolicy
Explicit authenticated-client access policy for connection or service admission.
Adapter
An iroh ALPN handler serving standard HTTP/1 to policy-controlled Axum services.
AdapterEndpointMismatch
Adapter and iroh protocol-router endpoint identities do not match.
AdapterLimits
Availability limits applied to every HTTP-over-iroh adapter.
ClientIdentity
Authenticated transport peer injected into HTTP and WebSocket handshakes.
LimitsError
Invalid adapter limit configuration.
ServiceRegistry
An explicit root and exact named services with authenticated-client policies.
WebSocketAdapter
Separately registered WebSocket services served by the shared HTTP adapter.
WebSocketAdapterLimits
Concurrency and setup limits for the WebSocket-over-iroh adapter.

Enums§

ServiceRegistryError
A configuration error that would make service dispatch ambiguous.

Constants§

HTTP_ALPN
Versioned ALPN for standard HTTP/1 bytes over one iroh stream per exchange.