Eio HTTP server over HTTP/1.1, HTTP/2 and HTTP/3
README.md

ocaml-respond #

An HTTP server for OCaml 5 and Eio, for APIs and static files.

A small Eio service usually wants a few JSON routes and a directory of static
files from its HTTP layer, and a parser strict enough that a malformed
request never reaches a handler. respond covers that. You give it a list of
routes, each mapping a path to a handler; the handler receives a typed
request record and returns a response. A GET request that matches no route
can fall through to a document root. Files there are served with MIME
detection, ETag and If-None-Match revalidation (304), byte ranges (206
and 416), directory indexes and precompressed copies, with
Cache-Control: public, max-age=3600 unless the server passes its own
~cache_control, such as no-cache for files rebuilt at fixed URLs.
Responses are compressed when the client accepts it. A route can also upgrade to a WebSocket (RFC
6455) or stream Server-Sent Events.

nox-http parses the request head. It refuses, with the matching 4xx or
5xx and before any handler runs, a request that carries both
Content-Length and Transfer-Encoding, lengths that disagree, or a bare CR
or LF. Handlers read the request headers through Http.Headers.t, a view
that copies nothing.

By default Respond_eio.run serves HTTP/1.1. Given a TLS configuration, it
serves HTTP/2 and HTTP/1.1 over TLS and picks between them with ALPN. It can
also serve HTTP/3 over QUIC on a separate UDP socket, which it advertises
with Alt-Svc, and it can spread connections over several domains. Three
more libraries ship in the package:

  • respond.problem is the RFC 9457 problem details document and its JSON
    codec, so that a client reading one links no server. respond serves a
    document with Response.problem, and every refusal it answers by itself
    (404, 405, 400, 429, 500 and the request-level 413, 431 and 505) is one,
    served as application/problem+json.
  • respond-eio.plain is a minimal HTTP/1.1 adapter, without static files,
    TLS, upgrades, HTTP/2 or HTTP/3.
  • respond-eio.proxy forwards HTTP/1.1 requests to an upstream service
    according to a typed policy. It streams bodies and tunnels CONNECT to
    that upstream; its forward mode tunnels each CONNECT to the host it
    names (Forward proxy).

Installation #

Install with opam:

$ opam install respond respond-eio

If opam cannot find the package, it may not yet be released in the public
opam-repository. Add the overlay repository, then install it:

$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam update
$ opam install respond respond-eio

Usage #

let run () =
  Eio_main.run @@ fun env ->
  let routes =
    let open Respond in
    [
      get "/api/health" (fun _req -> Response.json {|{"ok":true}|});
      post "/api/echo" (fun req -> Response.text req.body);
    ]
  in
  Respond_eio.run ~max_connections:1024 ~mono:(Eio.Stdenv.mono_clock env)
    ~net:(Eio.Stdenv.net env)
    ~addr:(`Tcp (Eio.Net.Ipaddr.V4.any, 8080))
    ~root:(Eio.Stdenv.cwd env) routes

Respond.get builds a route whose handler gets a get_request, and
Respond.post one whose handler gets a post_request. Both records carry
params and headers, and the POST one also has the body. The
constructors for responses live in Respond.Response: JSON, text and HTML
bodies, redirects, and errors, which are RFC 9457 problem details
(Response.error ~detail:"no such item" 404).

Compression #

A client that sends Accept-Encoding: gzip gets a compressible body (text,
JSON, XML, JavaScript, SVG and the like) of 1 KiB or more as gzip, with
Content-Encoding: gzip and Vary: Accept-Encoding, over HTTP/1.1, HTTP/2
and HTTP/3 alike. The negotiation follows RFC 9110 section 12.5.3, weights
included. A body that is compressed already, such as an image or an archive,
a smaller one, and a streamed one go as they are.

A static file can also be compressed ahead of time. A file.br, file.zst
or file.gz beside file, no older than it, is served to a client that
accepts that coding, in that order of preference, with the media type of
file. Without a fresh file.gz, a compressible file of at most 64 MiB is
compressed once and kept in a bounded cache. Each coded copy has an ETag of
its own, and a Range counts the bytes of the copy the request selects. A
file or a copy beside it is read as its body goes out, a slice at a time, so
serving a large file holds none of it whole.

The policy is an argument of every entry point:

let run_compressing_more () =
  Eio_main.run @@ fun env ->
  Respond_eio.run ~max_connections:1024 ~mono:(Eio.Stdenv.mono_clock env)
    ~net:(Eio.Stdenv.net env)
    ~addr:(`Tcp (Eio.Net.Ipaddr.V4.loopback, 8080))
    ~encoding:(Respond.Encoding.v ~min_size:256 ())
    ~root:(Eio.Stdenv.cwd env) []

Respond.Encoding.none turns compression off, precompressed files included.

Client certificates #

A TLS server can ask each client for a certificate, as mutual-TLS client
authentication and certificate-bound tokens (RFC 8705) need. The policy is
given with the server's certificates: `None (the default) asks for
none; `Request v asks for one and lets a client without one through;
`Require v fails the handshake of a client without one. The chain a
client sends is checked by `Authenticator a, such as a chain of trust
to the CAs that issue client certificates, or let through by `Any for
the handler to check itself, as a self-signed certificate registered with
the server is.

Every request carries the chain the client sent, leaf first, in its
peer_certificates field, over HTTP/1.1 and HTTP/2 alike, and [] when
the client sent none:

let thumbprint (req : Respond.get_request) =
  match req.peer_certificates with
  | [] -> Respond.Response.error 401
  | leaf :: _ ->
      Respond.Response.text (X509.Certificate.fingerprint `SHA256 leaf)

let run_requiring_client_certificates ~time ~own ~client_cas =
  Eio_main.run @@ fun env ->
  let authenticator = X509.Authenticator.chain_of_trust ~time client_cas in
  match
    Respond_eio.Certificates.v ~client:(`Require (`Authenticator authenticator))
      own
  with
  | Error (`Msg m) -> failwith m
  | Ok tls ->
      Respond_eio.run ~max_connections:1024 ~tls
        ~mono:(Eio.Stdenv.mono_clock env) ~net:(Eio.Stdenv.net env)
        ~addr:(`Tcp (Eio.Net.Ipaddr.V4.any, 8443))
        [ Respond.get "/whoami" thumbprint ]

A QUIC handshake asks for no client certificate, so while the certificates
an HTTP/3 listener holds ask for one, it answers each request 421 Misdirected Request and the client retries it over TLS on TCP.

Forward proxy #

Respond_proxy.Forward is a forward proxy for CONNECT, for clients whose
egress is confined to it. Each client address has an allowlist of its own,
whose host names are matched whole and without regard to case, so
github.com admits neither api.github.com nor evilgithub.com. A granted
CONNECT names port 443 (or a port of ~ports), its host is resolved once
through the network the proxy is given, and the tunnel connects to the first
address ~address admits: by default Forward.global, a globally routable
unicast address, so no client reaches loopback, a private range or the
cloud's link-local metadata address through it. Any other request is
refused with 405.

Every request leaves a record: a refusal and its reason, or the tunnel's open
(the address it reached) and its close (the bytes each way and its duration).
Forward.Record.append writes each as one JSON line, opening the file for
each record so that a reader can seal the file by renaming it.

let run_forward_proxy ~records =
  Eio_main.run @@ fun env ->
  Eio.Switch.run @@ fun sw ->
  let net = Eio.Stdenv.net env in
  let module Forward = Respond_proxy.Forward in
  let allowlist =
    Forward.Allowlist.v
      [ (Ipaddr.of_string_exn "10.77.0.3", [ "github.com"; "opam.ocaml.org" ]) ]
  in
  let proxy =
    Forward.v ~net ~clock:(Eio.Stdenv.clock env)
      ~mono:(Eio.Stdenv.mono_clock env)
      ~record:(Forward.Record.append records)
      allowlist
  in
  let socket =
    Eio.Net.listen ~sw ~backlog:128 net
      (`Tcp (Eio.Net.Ipaddr.V4.loopback, 8888))
  in
  Eio.Net.run_server socket ~on_error:raise (fun flow addr ->
      match Eio_addr.of_stream addr with
      | Some client -> Forward.serve_connection proxy ~client flow
      | None -> ())

Forward.set_allowlist replaces the allowlist for the next CONNECT, and a
tunnel already open stays open.

Licence #

ISC. See LICENSE.md.