Http Clients
In The “🗼 Services all the way down 🐢” chapter you can read and learn that a big pillar of Rama’s architecture is build on top of the Service concept. A Service takes a Request, and uses it to serve either a Response or Error. Such a Service can produce the response “directly” (also called ☘️ Leaf services) or instead pass the request to an inner Service which it wraps around (so called 🍔 Middlewares).
It’s a powerful concept, originally introduced to Rust by the Tower ecosystem and allows you build complex stacks specialised to your needs in a modular and easy manner. Even cooler is that this works for both clients and servers alike.
Rama provides an EasyHttpWebClient which sends your Http Request over the network and returns the Response if it receives and read one or an Error otherwise. Combined with the many Layers (middleware) that Rama provides and perhaps also some developed by you it is possible to create a powerful Http client suited to your needs.
As a 🍒 cherry on the cake you can import the HttpClientExt trait in your Rust module to be able to use your Http Client Service stack using a high level API to build and send requests with ease.
Note
The same client-side composition model is also used by Rama’s gRPC support. See the dedicated gRPC chapter for how a regular Rama HTTP client can act as the transport substrate for typed gRPC clients.
Http Client Example
See for a full and tested “high level” example of a http client at https://github.com/plabayo/rama/tree/main/examples/src/http_high_level_client.rs.
For opt-in resumed requests and gateway policy, see Early data and HTTP 425.
More client examples:
- /examples/src/http3_client_server.rs: an authenticated HTTP/3 client and server using common request, response and body types, with pooled requests, streaming uploads, trailers and graceful shutdown;
- /examples/src/http_datagram_echo.rs: HTTP Datagrams (RFC 9297) over HTTP/3 Extended CONNECT with a custom upgrade token, native QUIC datagrams when negotiated and DATAGRAM capsules otherwise;
- /examples/src/http_blocking_https_client.rs: a blocking HTTPS client that creates and owns its runtime thread;
- /examples/src/http_pooled_client.rs: an example demonstrating how to create a pooled HTTP client that can be used to make concurrent requests to the same host;
- /examples/src/http_proxy_db_exclude_broken.rs: a client that selects its proxy from an in-memory proxy database and stops selecting a proxy once a connection through it fails;
Alternative services and custom connectors
The easy client enables Alt-Svc discovery by default. With a QUIC TLS provider,
this can open UDP connections for HTTP/3. Use without_alt_svc() to disable
advertised-endpoint selection; explicit HTTP/3 requests remain supported.
Clear shared discovery with AltSvcCache::clear_all(), and report network changes
with network_changed(). Apply destination restrictions in your connector so
they cover origins, advertisements and DNS results alike.
Alternative services change where and how Rama connects, while preserving the request’s origin and certificate identity. The easy client selects a service before choosing a proxy route and consulting the connection pool.
HTTPS discovery is a reusable layer that supplies HttpServiceCandidates to
the existing selector. Each candidate can carry its own endpoint, ECH configuration
and address knowledge in optional extensions. Custom preknowledge producers use
the same contract; easy client is one consumer of these components.
Discovery runs before pool lookup because the selected service determines which
connection can be reused. A/AAAA resolution is lazy: unused candidates and pool
hits cause no address lookup. Each candidate retains its own address hints; DNS
caching and optional answer limits stay in the configured resolver. Address queries
start after service discovery; cached answers and hints can avoid that extra wait. With the
quic feature, the easy client’s default DNS path enables HTTPS discovery;
with_dns_resolver shares a custom resolver with discovery and transport, while
with_https_resolver configures discovery explicitly. Custom stacks compose
HttpsServiceLayer with the existing HttpServiceConnector; there is no separate
HTTPS connector with its own ALPN registry or retry loop. This layer does not
upgrade http:// requests to HTTPS.
Named-proxy routes disable local HTTPS discovery by default to preserve remote-DNS
privacy. Use with_proxy_discovery(true) only with an appropriate resolver, or
provide endpoint-bound preknowledge. Required ECH needs that configuration even
when the destination is reached through a proxy. Applications that require DNS
errors to be fatal can set with_fail_on_discovery_error(true) on the discovery
layer; the default permits optional fallback. This setting does not infer DNSSEC
validation and does not reject successful empty answers.
HTTPS records select transports: a TCP candidate preserves the client’s normal H2/H1 ALPN offer, including emulated profiles. Alt-Svc advertisements and explicit caller version requirements still constrain the exact HTTP protocol.
TLS enables opportunistic ECH by default when a capable backend has matching
endpoint configuration. Explicitly disabling ECH and emulated profile settings
override that default; an explicit caller setting takes precedence over a profile.
Real ECH needs configuration from HTTPS discovery, TargetEchConfigLayer, or custom
preknowledge. Without the quic feature, easy-client automatic discovery is absent;
TLS defaults alone do not perform DNS queries. Discovery facts remain separate from caller policy; final
TLS/profile settings determine ECH requirements for new handshakes. EchRequirement::Required
also restricts pooled reuse to authenticated connections that accepted real ECH.
Optional adds no caller requirement; DNS-derived rules still govern new handshakes.
An ECH-capable client discovering only ECH-bearing compatible services therefore
fails closed instead of falling back without ECH. Real ECH also disables QUIC
early data for that endpoint; endpoints without ECH configuration keep their
existing early-data policy.
See the custom resolver
and ECH preknowledge
examples for both integration paths.
ECH protects the inner ClientHello, not DNS queries or traffic patterns; resolver
privacy remains a separate choice. The current BoringSSL backend keeps real session
ticket identities out of the outer ClientHello but does not add a GREASE PSK there,
so observers can distinguish resumed ECH handshakes. Use ClientHandshake::Full
when that distinction is unacceptable.
HttpServiceConnector returns the underlying connection unchanged. Compose
AltSvcLayer::new(cache) separately with MapEstablishedConnection; the easy
client does this automatically. The layer resolves each request’s origin, learns response
headers and sets Alt-Used from the established endpoint. An optional H2 observer
feeds ALTSVC frames into the same cache. Advertisements are not automatically
forwarded. To send H2 advertisements, enable set_alt_svc(true) before the server
handshake and use AltSvcSender; ordinary connections allocate no sender queue.
Selection tries alternatives sequentially. Pure Alt-Svc attempts have a configurable
300 ms attempt_timeout including DNS and TLS; DNS-selected services use the
ordinary connection budget. Increase the Alt-Svc timeout for slower networks. There
is no overall deadline unless timeout is set. Failed alternatives back off;
selection can fall back to the origin with the same TLS policy. Explicit version
requirements remain binding. A completed response resets backoff; reconnecting
or re-advertising does not. Request-specific TLS trust cannot change shared discovery.
Custom connectors use these contracts:
| Type | Responsibility |
|---|---|
HttpServiceSelection | Request-local advertisement snapshot, index and lookup route plan; never store it on a pooled connection. |
EstablishedHttpService | Verified connection endpoint and logical origin; selection alone proves neither. |
TlsTunnel::from_extensions | Resolve routing-supplied tunnel settings before caller settings; preserve their distinct reuse scopes. |
TargetHttpVersion | Honor the requested version; report the established version. |
ConnectorTarget / ConnectorTargetStream | Dial the selected endpoint using matching DNS results, preserving the origin. |
TlsServerAuthentication / NegotiatedTlsParameters | Report verified origin identity and actual ALPN; missing proof prevents alternative use. |
ConnectionReuse | Publish endpoint reuse rules after connecting; pools check them against each request. |
AltSvcObserverExtension | Install before H2 handshake; authorize origins and process frames promptly. |
ConnectionAttempt / ConnectionPolicyScope | Check peer requirements and restrict request-specific DNS/TLS policy; preserve failure scope across timeouts and pool hits. |
TLS configuration stays in its connector. Built-in connectors publish reuse rules
automatically. Custom components publish owned TlsPoolComponent::Identity
values: equal identities permit reuse. with_shared_instance instead retains an
existing Arc and compares allocation identity without boxing a snapshot.
Policy changes need a new identity. Custom secure connectors without reuse rules
receive fresh connections. Apply request-policy
middleware outside the pool so lookup and establishment see the same input.
Unclassified policy failures never suppress shared alternatives.
Connectors report unsupported protocols or routes as local capability failures;
clients need no separate protocol-support list. These refusals preserve cache health.
The CLI enables command-local discovery by default; --http3 requires H3
directly. --no-alt-svc disables advertisement learning and use, independently
of HTTPS DNS discovery.
Disk persistence is not implemented.
Server certificate pinning
Rama clients can pin the server leaf through TlsServerCertPins, backend
agnostic for rustls and BoringSSL. The standard pin is the SHA-256 of the
leaf’s public key (TlsServerCertPin::SpkiSha256), exchanged in the usual
sha256/<base64> format and printed by rama probe tls. Parsing also accepts
a PEM certificate, deriving its key pin. It remains valid across
certificate renewal as long as the key pair is unchanged. Pin the exact
DER-encoded certificate (TlsServerCertPin::ExactDer) only when you control
the certificate file itself.
With the default ServerVerifyMode::Auto, both the pin and normal certificate
verification must succeed. ServerVerifyMode::Disable makes the applicable
pins the only certificate check.
Pins are grouped in sets: pins within a set and applicable sets are alternatives (e.g. the current and next key during rotation). A set without server names applies globally; otherwise only when the effective TLS server name matches — never inferred from certificate contents. If no set applies, pinning imposes no check and normal verification continues.
Build a TlsServerCertPins from one or more
TlsServerCertPinSet values (new, then
with_pin_set for each extra set). Each set is made with new or try_new from
TlsServerCertPin values, which parse from the
sha256/<base64> form, and is scoped to a host with with_server_name.
The default trust roots come from the native store, with Rama’s bundled Mozilla
(CCADB) roots as an empty-store fallback. Extend those roots with a private CA,
or select the bundled roots explicitly for OS-independent behavior. On
TlsClientConfig, try_with_extra_server_trust_anchors
adds private CA certificates to the roots, and with_webpki_roots selects the bundled roots.
Use try_with_server_trust_anchors instead for a custom-only store. These common
settings have the same semantics with rustls and BoringSSL. Normal chain,
validity, usage, and server-name checks remain enabled, and certificate pins can
be required in addition.
The native store is read once, as a snapshot. To let the operating system judge
each chain instead, including enterprise trust settings, its distrust decisions
and revocation, select its verifier. It is available on Apple platforms, Windows
and Android; elsewhere it verifies against the native roots. Additional anchors
are trusted next to what the operating system trusts. Select it with
TlsClientConfig::with_platform_verifier; it composes with
try_with_extra_server_trust_anchors.
Operators can adjust trust through the environment. SSL_CERT_FILE and
SSL_CERT_DIR replace the native roots, as OpenSSL and most TLS tools do; the
platform verifier ignores them. SSL_CERT_EXTRA_FILE and SSL_CERT_EXTRA_DIR
add roots instead, for both the native roots and the platform verifier.
A chain policy rejects certificate chains on top of any of these, and also when
verification is disabled. DistrustedServerKeys refuses every chain containing
one of the given public keys, at any position, so a distrusted CA is caught
under each of its certificates, cross-signed ones included. It parses from the
same sha256/<base64> pin format and is installed with
TlsClientConfig::with_server_cert_chain_policy.
Implement TlsServerCertChainPolicy for other rules. Rama’s verifiers hand it the
path they built, ending at the trust anchor; without verification, or with a
custom rustls verifier, it sees the chain as the server presented it. Without
verification a policy only judges what the server chose to present, so it
cannot stop an attacker who presents another chain.
- /examples/src/tls_rustls_cert_pinning.rs: HTTPS certificate pinning using rustls;
- /examples/src/tls_boring_cert_pinning.rs: HTTPS certificate pinning using BoringSSL.