wasi:http is the WASI 0.2 interface that a component uses to send HTTP requests and to answer them. Read this page in three cases: a component you run calls wasi:http/outgoing-handler to reach a server; a component exports wasi:http/incoming-handler and you want it to serve requests; or you need a wire protocol that the host does not include. The component only sees requests and responses. The host chooses the wire protocol (HTTP/1.1 or HTTP/2), does TLS, and decides which addresses the component may reach. For running components in general, read WASI 0.2 first. A WASI 0.3 handler (wasi:http/handler) is served the same way; see WASI 0.3.

The host side has these modules:

  • wasi_http: the wasi:http/types resources and the outgoing handler.
  • wasi_http_transport: the behaviour that a transport implements. A transport is the module that sends a request on the network.
  • wasi_http_h1 and wasi_http_h2: the two transports, for HTTP/1.1 and HTTP/2.
  • wasi_http_listener: a server that accepts real connections.

Let a component make requests

wasi:http is always in the import map that wasi_preview2:command/1 builds, so a component that imports it links with no options. The host refuses its requests until you pass a network grant that names what it may reach:

{ok, Bin} = file:read_file("client.component.wasm"),
Grant = #{connect => [{tcp, ~"127.0.0.1", 8080}], resolve => allow},
{ok, #{exit_code := Code, stdout := Out}} =
    wasi_preview2:run_command(Bin, <<>>, #{network => Grant}).

It is the same grant that wasi:sockets uses, described in WASI preview 1. Before each request, the host splits the authority (the host:port part of the URL) into a host and a port. Without a port, it uses 80 for http and 443 for https. Then it checks them against the connect rules:

  • An IP address is checked as it is.
  • A host name needs resolve => allow. The host resolves the name once and checks each address it gets. The request goes to the first address the rules allow. The name is still sent as the Host header and as the TLS server name.
  • If a name resolves to no address, the guest gets DNS-error. For any other refusal, the guest gets HTTP-request-denied.

As for sockets, grants name addresses, never host names. So grant the addresses that you expect your host names to resolve to, or grant http and decide by name in http_authorize, as the next section shows.

Grant HTTP by host name

resolve => allow in the network grant is what lets wasi:http reach a host by name, and it also lets the guest resolve any name it likes through wasi:sockets/ip-name-lookup, which a guest can use to send data out in its lookups. Grant http instead when the component should make HTTP requests and nothing else: it is a grant for wasi:http alone, and an http_authorize hook decides by name.

{ok, Bin} = file:read_file("client.component.wasm"),
Allowed = [~"api.example.com"],
Authorize = fun(#{address := Address}) ->
                    case Address of
                        {127, _, _, _} -> deny;
                        _ -> allow
                    end;
               (#{host := Host}) ->
                    case lists:member(Host, Allowed) of
                        true -> allow;
                        false -> deny
                    end
            end,
Opts = #{http => #{connect => [{tcp, ~"0.0.0.0/0", 443}]},
         http_authorize => Authorize},
{ok, #{exit_code := Code}} = wasi_preview2:run_command(Bin, <<>>, Opts).
  • http takes the connect rules of a network grant, and nothing else: #{connect => Rules}. Any other key raises {bad_net_grant, {http, Key}} when the imports are built.
  • Under http, the host resolves a host name a request names, once, and checks each address it gets against the rules, as above. No resolve flag is needed.
  • http gives the guest no wasi:sockets and no name lookup. Those come only with network, which keeps its meaning for wasi:sockets. When you give both, wasi:http uses http and wasi:sockets uses network.
  • http_authorize is called with #{scheme, host, port} before the name is resolved, so a name it refuses is never looked up. It is called again with address added, once an address has passed the rules, so you can refuse private, loopback or metadata addresses that a public name resolves to. scheme and host are binaries, port an integer and address an inet:ip_address(). An http_authorize that is not a fun of one argument raises {bad_http_authorize, Term} when the imports are built.
  • Only allow lets a request through. Any other answer, and a hook that raises, refuses it, and the guest gets HTTP-request-denied, as for a refused grant.
  • The hook works with network too.
  • At 0.2 the hook runs in the instance's process; at 0.3 a request is sent from a process of its own, and the hook runs there.
  • The host does not follow redirects. A 3xx response reaches the guest as it is, and a request the guest makes to the new location is checked like any other.

What the guest gets back

The host sends the request when the guest first reads the response future (a value that is ready later), after the guest has finished writing the body. Failures reach the guest as wasi:http error codes:

the host seesthe guest gets
no path, or an empty or malformed authorityHTTP-request-URI-invalid
a scheme other than http or httpsHTTP-protocol-error
the grant refuses the addressHTTP-request-denied
the connect times outconnection-timeout
any other connect failureconnection-refused
no response line within the first-byte timeoutconnection-read-timeout
the body pauses longer than the between-bytes timeout, or is not complete by the overall deadlineHTTP-response-timeout
the response body is larger than max_body_bytesHTTP-response-body-size
the server closes before the response is completeHTTP-response-incomplete

The overall deadline is 30 seconds, counted from the start of the request to the last byte of the response. You cannot change it. The guest can set connect-timeout, first-byte-timeout and between-bytes-timeout in its request-options; both transports apply all three, each within the overall deadline.

Every HTTP body the host holds is limited to 8 MiB: a response an outgoing request reads, and a body the guest writes, whether it declares a content-length or not. A write past the limit fails with HTTP-request-body-size. To change it, pass max_body_bytes to wasi_http:http/1, or http_max_body_bytes in the options of wasi_preview2:run_command/3 and run_serve/3.

The host enforces two limits on the request the guest builds. Headers larger than 64 KiB in total cause a trap, because the WIT type header-error has no case for this error. A body that declares a content-length and then writes more bytes than that fails with HTTP-request-body-size.

Make HTTPS requests

The guest sets the scheme to HTTPS, and the host does TLS. By default the host checks the server's certificate against the system CA store, with the host name from the authority. Pass http_tls to give your own ssl client options, for example to trust a private CA:

CaCerts = public_key:cacerts_get(),
#{network => Grant, http_tls => [{cacerts, CaCerts}]}.

wasi_http_h1 merges these options with its defaults, one key at a time. So the example still verifies the server, and replaces only the list of trusted CAs.

Against a test server with a self-signed certificate, this is what wasm_wasi2_https_SUITE passes:

wasi_preview2:run_command(Bin, <<>>,
                          #{network  => Grant,
                            http_tls => [{verify, verify_none}],
                            env      => [{~"HTTPS_SERVER", Addr}]}).

Without http_tls a self-signed server is refused.

Speak HTTP/2

Choose the transport with http_transport:

#{network => Grant, http_transport => wasi_http_h2}

Over https, wasi_http_h2 agrees on HTTP/2 with the server through ALPN. Over http, it uses unencrypted HTTP/2 (h2c). The guest cannot tell which transport answered.

If you build the import map yourself, wasi_http:http/1 takes the same three settings as grant, transport and tls:

Http = wasi_http:http(#{grant     => Grant,
                        transport => wasi_http_h2,
                        tls       => []}).

Serve one request

A reactor component (one that exports functions and stays ready, see the glossary) can export wasi:http/incoming-handler. Give it one request with wasi_preview2:run_serve/3, and you get back the response it set:

{ok, Bin} = file:read_file("hello.component.wasm"),
Request = #{method    => ~"GET",
            path      => ~"/",
            scheme    => ~"http",
            authority => ~"localhost",
            headers   => [],
            body      => <<>>},
{ok, Status, Headers, Body} = wasi_preview2:run_serve(Bin, Request, #{}).

Each call instantiates the component, calls its handle function, reads the response from the outparam (the response-outparam resource where the guest sets its answer), and destroys the instance. The third argument takes the options of wasi_preview2:command/1. Pass network so the reactor can send its own requests, and compile => true to build the core modules in the calling process instead of through the module cache. Execution limits (fuel, max_depth, max_memory_pages, max_heap_words, max_host_calls) and resource_limit apply to the guest, as they do for wasm:instantiate/3.

The other results:

resultmeans
{error, no_incoming_handler}no wasi:http/incoming-handler export
{error, no_response}handle returned without setting the outparam
{error, Code}the guest set an error code on the outparam

Run a live server

wasi_http_listener accepts connections and serves each request through wasi_preview3:run_serve/4, with its imports built once when it starts, so a listener takes a 0.2 incoming-handler or a 0.3 handler component:

{ok, L} = wasi_http_listener:start(#{component => Bin, port => 8080}),
Addr = wasi_http_listener:address(L),
ok = wasi_http_listener:stop(L).
optionmeaningdefault
componentthe reactor's bytes, or a component from wasm_component:prepare/1required
ipthe address to listen on; {0, 0, 0, 0} listens on every interface{127, 0, 0, 1}, this machine only
portthe port to listen on; 0 picks one0
transporth1, or h2 for cleartext HTTP/2h1
schemethe scheme the guest is told~"http"
serve_optsthe options passed to run_serve/3, execution limits included#{}
request_timeoutmilliseconds from a request's arrival to its answer, body and guest included60000
max_body_bytesthe largest request body8 MiB

Notes on how it behaves:

  • The listener creates a new instance for each request. So a slow guest, or a guest that traps, affects only its own request.
  • The listener prepares the component once, when it starts: it decodes, checks and parses it, so a request only builds its instance. To do the same in your own server, call wasm_component:prepare/1 and pass the result wherever you would pass the bytes.
  • The listener loads the component's core modules once, when it starts, and keeps them loaded until it stops. Each request's instance uses them, so requests do not count against max_module_loads_per_second. To do the same in your own server, call wasm_component:hold/1 from a process that lives as long as it does.
  • A trap, a link failure or an error result is answered with a 500 and the body wasi:http reactor error. The socket is not dropped.
  • The request body is read to its end, chunked or not, within request_timeout. A body that does not arrive in time is answered 408, and one larger than max_body_bytes is answered 413; the guest does not run for either.
  • A guest still running at request_timeout is stopped, and the request is answered 504.
  • A 0.2 response is sent once the guest has written all of it, and gets a content-length unless the guest set one.
  • A 0.3 response is sent as the guest writes it: the status and headers as soon as the handler returns them, then each piece of the body as the guest writes it, then the trailers. The listener holds one piece at a time, so http_max_body_bytes does not limit it, and a client that reads slowly makes the guest wait. Without a content-length from the guest, HTTP/1.1 sends the body chunked. A body that does not match the content-length the guest set, a guest that fails once the headers are out, and a response still unfinished at request_timeout all reset the stream (HTTP/2) or close the connection (HTTP/1.1), so the client does not take what it got for the whole response.
  • Over HTTP/1.1, trailers need a chunked body: a 0.3 response that set a content-length is sent without its trailers.
  • address/1 returns the address the listener listens on, 127.0.0.1:Port unless you passed ip.

Write a transport

A transport is a module implementing wasi_http_transport: one callback, request/2, which sends one request and waits for the response. This example logs each request and passes it to the HTTP/1.1 transport:

-module(my_http_transport).
-behaviour(wasi_http_transport).
-export([request/2]).

request(#{host := Host, port := Port, method := Method,
          path := Path} = Req, Timeout) ->
    logger:info("wasi:http ~s ~s:~p~s", [Method, Host, Port, Path]),
    wasi_http_h1:request(Req, Timeout).

The request map carries host, port, method, path, headers and body, plus scheme, tls, connect_timeout, first_byte_timeout and between_bytes_timeout (milliseconds, or undefined when the guest set none), and max_body_bytes. Timeout is the overall deadline: fix it when the request starts, and do not start it again with each message. wasi_http_transport:deadline/1 and within/2 do that for you. Return {ok, Status, Headers, Body} with binary header pairs, or {error, {ErrorCodeName, Payload}} naming a wasi:http error code, such as {error, {~"connection-refused", none}}. Then select it:

#{network => Grant, http_transport => my_http_transport}

wasm_wasi2_http_SUITE calls the request/2 of each transport directly, against an echo server. Test your transport the same way before a guest uses it.

Read this next

WASI 0.2 for the other interfaces and grants, or Security for what the sandbox does not cover.