dox_http_native 3.2.8
dox_http_native: ^3.2.8 copied to clipboard
Fast native HTTP/1.1 server for Dart and the Dox framework. Rust parses HTTP, your handlers stay in Dart. Implements the dart:io HttpServer API.
dox_http_native #
Native HTTP server for Dart. It speaks HTTP/1.1 and HTTP/2. It is the default HTTP server of Dox.
Part of Dox, a web backend framework for Dart. Source code: github.com/dartondox/dox-http-native.
Install #
Most apps do not add this package. dox_core depends on it and uses it by default.
Add it only to use the server without Dox:
dart pub add dox_http_native
To see what is ready and what can change, read Status and roadmap.
How it works #
- Rust owns the sockets and parses HTTP/1.1 with httparse. HTTP/2 has its own parser in this package.
- The socket work runs on the thread of your isolate. There is no extra network thread that gives requests to Dart.
- Your handlers stay in Dart.
- The server implements the
HttpServer,HttpRequestandHttpResponseAPI ofdart:io. Code fordart:ioworks with no change.
The native library #
A build hook (hook/build.dart) gets the Rust library. It tries these sources in this order:
- A path that you set in the
pubspec.yamlof your app:hooks: user_defines: dox_http_native: lib_path: .... - A local build in
native/target/release, for the same OS and CPU. - A ready-built library from the GitHub release. The hook checks its sha256. There are builds for macOS (arm64, x64), Linux (x64, arm64) and Windows (x64).
- A build from source with
cargo, when Rust is installed.
Outside the pub cache, step 4 runs before step 3. This applies to this repo, a path dependency and a git dependency. The source there can be newer than the release.
Thus Rust is not necessary on the systems of step 3.
Use dart run, dart test or dart build cli. dart compile exe does not run build hooks.
Use it #
import 'dart:io';
import 'package:dox_http_native/dox_http_native.dart';
void main() async {
NativeHttpServer server = await NativeHttpServer.bind(3000);
server.listen((HttpRequest req) {
req.response.write('Hello World');
req.response.close();
});
}
Dox always runs on this server. If the native library does not load, Dox stops at start. Then Dox prints the cause (for example an ABI mismatch) and the correction.
HTTP/2 #
HTTP/2 lets one connection carry many requests at the same time. gRPC needs it. It is off by default. When it is off, nothing changes.
NativeHttpServer server = await NativeHttpServer.bind(3000, http2: true);
How it works:
- The same port speaks HTTP/1.1 and HTTP/2 over plain TCP. This is h2c with prior knowledge.
curl --http2-prior-knowledgeis an example of a client. - A connection that starts with the HTTP/2 preface is HTTP/2. All other connections are HTTP/1.1.
- Browsers use HTTP/2 only with TLS. Turn on HTTPS, or put a proxy in front, for example Caddy or Envoy. The proxy ends TLS and speaks h2c to the server.
- Your handlers stay the same.
request.protocolVersionis2.0. Answers go out in any order.
Requests and answers:
- One connection has a maximum of
maxConcurrentStreamsopen requests. The default is 250. More requests getREFUSED_STREAM. - The server reads a request body fully before the handler gets it, as on HTTP/1.1. The limits are the same:
maxBodySize,maxMultipartSizeandbodyTimeout. - A body over the limit gets
413, and a slow body gets408. Only that stream stops. The other streams and the connection continue. - A request header block over 16 KiB gets
431on its stream. A block over 64 KiB closes the connection. - Streamed answers (
addStream,flush) go out as DATA frames. The windows of the client give the same backpressure as on HTTP/1.1. NativeResponse.hasRoomis true when a streamed answer started and Rust has room for more. Thenflush()completes immediately.- A graceful
close()sends GOAWAY, and the open streams get their answers. - A connection with no open stream for
idleTimeoutgets GOAWAY, then it closes. A PING does not keep it open.
Trailers are headers that go out after the body, for example grpc-status. They go out on HTTP/2 only. On HTTP/1.1 the server drops them.
NativeResponse res = req.response as NativeResponse;
res.trailers.set('grpc-status', '0');
gRPC:
- A request with
content-type: application/grpcreaches the handler when its headers come.request.isStreamedis true. This also applies to types such asapplication/grpc+proto. - The body of such a request comes in parts while the handler runs. It has no size limit and no body timeout.
- The client can send more only after the handler took the parts. A handler that does not read holds the client at the 1 MiB stream window.
- The unread body bytes of one connection have a limit of 16 MiB. Over the limit, the server resets the stream with the most unread bytes.
Flood limits:
- Stream resets have a rate limit (Rapid Reset, CVE-2023-44487). The limit is
http2ResetRateresets a second (default 100), after a burst ofhttp2ResetBurst. - The default of
http2ResetBurstis 2 xmaxConcurrentStreams, with a minimum of 1000. - Over the limit, the connection drains: it sends GOAWAY
NO_ERROR, and the open requests get their answers. If the resets continue, the connection closes with GOAWAYENHANCE_YOUR_CALM. - Too many SETTINGS frames, PING frames or frames with no work also close the connection.
- The answer bytes that wait for a client that does not read have a limit of 32 MiB for each connection. Over the limit, new streams get
REFUSED_STREAM.
The h2spec conformance suite runs in CI in strict mode, on a plain port and on a TLS port.
HTTPS #
The server can speak HTTPS without a proxy. Rust does the TLS work with rustls and its ring crypto provider. There is no OpenSSL. TLS is off by default. When it is off, nothing changes.
NativeHttpServer server = await NativeHttpServer.bind(
443,
http2: true,
tls: TlsOptions(certificatePath: 'fullchain.pem', keyPath: 'privkey.pem'),
);
Options of TlsOptions:
certificatePath: a PEM file. The certificate is first, then the intermediate certificates. An example isfullchain.pemof certbot.keyPath: a PEM file with the private key of the certificate (PKCS #8, PKCS #1 or SEC1). An example isprivkey.pemof certbot.
How it works:
- Rust reads the two files at
bind. A bad file, or a key of a different certificate, throws aTlsExceptionatbind. - A TLS port speaks only TLS. A plain HTTP client gets no answer, and the connection closes.
- The server uses TLS 1.2 and TLS 1.3, the rustls defaults. There are no cipher options.
- With
http2: true, the client selects HTTP/2 or HTTP/1.1 in the handshake (ALPNh2orhttp/1.1). Withhttp2: false, the server offers onlyhttp/1.1. - The handshake must end in
idleTimeout. There is no other TLS limit. - HTTP/1.1, HTTP/2, WebSocket (
wss://), gRPC and streamed answers work on the TLS port. Your handlers stay the same. request.requestedUrihas thehttpsscheme.- At a clean close, the server sends the TLS
close_notifyalert. When the server cuts a connection (for example after an error), it does not sendclose_notify. Thus the client can see that the data is not complete.
Check the files before the start #
Use check() to find a bad file before your app starts its isolates. Then the app fails one time, with one clear error.
TlsOptions tls = TlsOptions(certificatePath: 'cert.pem', keyPath: 'key.pem');
tls.check();
- The method reads the two files as
bindreads them. - If a file is bad, or the key is of a different certificate, the method throws a
TlsException. - The method opens no port and changes no server.
Reload the certificate #
Use reloadCertificate() to get a new certificate without a restart. An example is after certbot renews the certificate.
await server.reloadCertificate();
- The method reads the same two files again.
- New connections get the new certificate. Open connections keep the old certificate until they close.
- If a file is bad, the method throws a
TlsException. The server keeps the old certificate. - All servers in the process that use the same two files get the new certificate. This includes the servers of other isolates and the servers with a different
http2value. A relative path and an absolute path to the same file are the same file. Thus one call is sufficient. - The server does not watch the files and does not catch signals. Your app decides when to call the method, for example on
SIGHUPor from a scheduled task.
Not included #
- ACME: the server does not get or renew a certificate (for example from Let's Encrypt). Use certbot or a similar tool, then call
reloadCertificate(). - Redirect from port 80: the server does not send
http://visitors tohttps://. Bind a second plain server for this. - mTLS: the server does not ask the client for a certificate.
- SNI: one port has one certificate. The server does not select a certificate for each domain.
WebSocket #
server.listen((HttpRequest req) async {
if (!NativeWebSocket.isUpgradeRequest(req)) return; // a normal request
WebSocket ws = await NativeWebSocket.upgrade(
req,
protocol: 'chat', // optional subprotocol
maxMessageSize: 1024 * 1024,
);
ws.listen((dynamic message) => ws.add('echo: $message'));
});
How it works:
- Rust marks a request that can upgrade. Your Dart code runs first, as for all requests: the router, the middleware and the
Origincheck. - To refuse the upgrade, send a normal response, for example
403. NativeWebSocket.upgradeaccepts the request. Rust sends the101and speaks the WebSocket protocol with tungstenite.- Rust does the ping and the pong, the close handshake and the UTF-8 check of text.
- A message or a frame over
maxMessageSizebytes closes the socket with1009. Dart does not get it. - The server does not agree on compression (permessage-deflate).
- Dart gets full messages: a
Stringfor text, aUint8Listfor binary. They come in the same batches as requests. NativeWebSocketimplements theWebSocketAPI ofdart:io.detachSocketis not supported.- On a graceful
close(), each open WebSocket gets the close code1001(going away).
Features #
Isolates and threads:
- Each isolate can bind the same port. Linux uses
SO_REUSEPORT. macOS uses one shared socket. - There is one thread for each isolate. The socket work (accept, read, parse, write) runs on the thread of the isolate.
- A small helper thread only monitors the sockets while the isolate is idle. It tells the isolate when a request comes.
- If the isolate stops without
close()(for example on an uncaught error), the server closes in approximately 100 ms. New clients get "connection refused".
Connections:
- Keep-alive and pipelined requests are supported.
- A maximum of 64 requests of one connection wait for an answer. A maximum of 1 MB of answers waits for the write. At these limits, the server stops the read of that connection until answers go out.
- A request head must arrive in
idleTimeout(default 30 seconds). A connection with no request foridleTimeoutafter its last answer closes. - Behind a load balancer, set
idleTimeoutlonger than the idle timeout of the balancer. For AWS ALB, an example isbind(port, idleTimeout: Duration(seconds: 65)). - A client that closed its send side (a half-close) waits a maximum of
idleTimeoutfor its answer. With no write in that time, the connection closes, because most such clients are gone. - Set a longer
idleTimeoutwhen such clients call slow handlers. - A client that reads nothing of its answer for 30 seconds is closed.
bind(port, maxConnections: 1000)holds a maximum of 1000 connections open. At the limit, new clients wait in the listen queue of the OS. The default is no limit.bind(port, address: '127.0.0.1')listens on one host. With no address, the server listens on all interfaces.close()is graceful: the server accepts no new connections, open requests get their answers, thenclose()completes.close(force: true)closes all connections immediately.
Requests:
- Chunked request bodies and
Expect: 100-continueare supported. - A bad request gets
400. Headers over 16 KB get431. - A body over
maxBodySizegets413. For a multipart form, the limit ismaxMultipartSize. - If the
Content-Lengthis too large and the request hasExpect: 100-continue, the client gets413before it sends the body. - All other bodies that are too large are read and dropped first. Thus the client sees the
413. - The client gets
408when it sends no body bytes forbodyTimeout. This is idle time, and the default is 120 seconds. A slow upload that does not stop is permitted.
Answers:
autoCompress: Rust gzips the body on a helper thread, not on the isolate. It uses libdeflate.compressLevelsets the level, from 1 (fast, the default) to 12 (small).- A small body goes out in one piece on
close. - When
addStreampasses 64 KB, the answer starts, and the remaining body goes out in parts. A large file does not stay in memory. flush()also starts the answer: the head and the bytes so far go out. Later writes go out immediately, for example server-sent events from a timer.- After the head is out, the server ignores a header change or a status change. It logs a warning one time.
response.donecompletes with no error when the client is gone. This also applies when the handler does not close the response.- A handler that writes from its own timer can stop the timer there:
response.done.then((_) => timer.cancel()). The server drops writes after that.
Differences from dart:io #
The server implements the dart:io API. These parts are different on purpose. The tests in test/dart_io/ come from the Dart SDK. Each skipped test there names one of these differences.
bindSecureandlistenOndo not exist. For TLS, givetlstobind(see HTTPS), or use a proxy that ends TLS. There is noSecurityContext, andrequest.certificateis alwaysnull.- There is no
detachSocketand noHttpSession.connectionsInfo()andsessionTimeoutdo nothing.idleTimeoutis an argument ofbind. - Rust reads the whole request body before your handler runs. A request that the client cuts short never reaches the handler. The connection closes at once.
- A custom
reasonPhraseis not sent. The answer has the standard phrase of the status code. - A text body is always UTF-8, also when the content type is missing or has no charset.
HttpResponse.deadlinehas no effect.bufferOutputhas no effect. A buffered body goes out onclose. Useflush()to start the answer at once.addStreamstarts the answer after 64 KB or onflush().- The server sets
Content-Lengthand the framing from the real body. AcontentLengththat is too small for a buffered body does not throw. The answer has the real length.Transfer-Encodingthat your handler sets is ignored. - The server sends its own
Dateheader. ADateheader that your handler sets is ignored. - A
HEADanswer with no body keeps thecontentLengththat your handler set. - An HTTP/1.0 request with
Connection: keep-alivecan stay open, when the answer has a length. request.contentLengthis the length of the body. It is0, not-1, when there is noContent-Lengthheader.- A request header value is not split on commas. You get one list entry for each header line.
response.persistentConnectionistrueuntil you set it. The server still closes the connection after a request withConnection: close.requestedUridoes not usex-forwarded-protoorx-forwarded-host. A client can send them.- A header name is always lower case.
preserveHeaderCaseandnoFoldinghave no effect. - A folded request header (obs-fold) gets
400. flush()andaddStream()complete withnull, not with the response.- A failed
addStreambefore the head goes out gives a500with no body. dart:io cuts the connection. After the head, both cut the connection. response.addandwebSocket.addthrow anArgumentErrorfor a value that is not a byte.dart:iofailsdone.NativeWebSocket.upgradetakes aprotocol, not aprotocolSelector. As in dart:io, aprotocolthat the client did not offer gives a500and aWebSocketException. When the client offers no protocol, the answer has no protocol.
AES-GCM #
AesGcm is AES-256-GCM in Rust. It uses the AES instructions and the carry-less multiply instructions of the CPU. dox_core uses it for encrypted cookies. It works without a server.
Uint8List sealed = AesGcm.seal(key, plain, aad); // nonce + ciphertext + tag
Uint8List? plain = AesGcm.open(key, sealed, aad); // null when changed
keyis 32 bytes.aadbinds the value to a context, for example a cookie name.- Each
sealmakes a new random nonce of 12 bytes. - One cookie of 200 bytes takes 1 µs to 2 µs. The same work in pure Dart took approximately 100 µs.
Security notes #
- On the open internet, run the server behind a reverse proxy, for example nginx or a load balancer. The proxy must limit the request rate and drop slow clients. The proxy can also end TLS, or the server can do it (see HTTPS).
- Set limits that are correct for your app:
maxBodySize,maxMultipartSize,bodyTimeout,maxConnectionsandidleTimeout. - A different process can bind the same port and take some of the connections. On Linux, that is a process of the same OS user (
SO_REUSEPORT). On macOS, it is a process that binds a more specific address. - An example on macOS is
127.0.0.1while the server listens on all interfaces. Run the server as its own user, on a host that you control. req.uriis the target that the client sent. The server does not remove..and%2e%2e. Do a check of each path before you use it for files.- The server accepts a request head with bare LF line ends (no CR), as most servers do. A proxy in front must normalize it.
Content-Lengthmust be ASCII digits. A request with two different lengths gets400. A request withContent-LengthandTransfer-Encoding: chunkedalso gets400.Transfer-Encodingmust be exactlychunked, in one header. A different coding gets501. Two headers, orTransfer-Encodingin an HTTP/1.0 request, get400.- A WebSocket upgrade needs one
Sec-WebSocket-Keythat is base64 of 16 bytes (24 characters, RFC 6455). With a different key, or with two keys, there is no upgrade. The request goes to the app as a normal request. - Only
multipart/form-datagets the multipart body limit. All other content types get the normal body limit. - A streamed answer must have exactly the bytes of its
contentLength. More bytes throw, and fewer bytes makeclose()fail. In the two cases, the server cuts the connection. Thus the client can not read the remaining bytes as the next answer. - For the HTTP/2 flood limits, see HTTP/2.
Tests #
The CI and Fuzz badges at the top show the last result on main. CI runs the tests below on each push and on each pull request. The fuzz tests run only when native/ changes.
| Test set | Count (2026-11-25) | What it checks |
|---|---|---|
Dart tests of the dart:io server, from the Dart SDK |
48 files, 755 tests pass, 66 skipped | The server gives the same results as the dart:io server. |
| Request parser inputs from the Dart SDK (part of the 755 tests) | 519 tests | Bad, split and too large requests. Each request goes in as 1 piece, in 10-byte pieces and in 1-byte pieces. |
| Other Dart tests of this package | 136 tests | The server, the headers, HTTP/2, WebSocket, HTTPS and AES-GCM. |
| Rust unit tests | 199 tests | The parser, the body reader, the limits, the HTTP/2 frames and TLS. |
| h2spec (strict mode) | all specs but 1 on a plain port, all specs on a TLS port | The HTTP/2 conformance suite. |
| Fuzz tests | 7 targets | Random input on the parsers, on a full connection and on the TLS handshake. Refer to Fuzz tests. |
The SDK tests are in test/dart_io/. Each file has the same name as its source file in tests/standalone/io of the Dart SDK.
- The tests use the
dart:ioclient on the server of this package. - A skipped test has a reason that starts with
dox_http_native:. Most reasons are an API that this server does not have, for exampledetachSocket. - Refer to Differences from dart:io for the full list.
To run the Dart tests:
cd native
cargo build --release
cd ..
dart test -j 4
Fuzz tests #
The fuzz targets are in native/fuzz/. CI runs each target for 60 seconds when native/ changes.
parse_head: random bytes as one request. It compares the record for Dart with the data thathttparsereads from the same bytes: method, target, header names, header values, lengths and flags. It also compares the body framing (no body, a length, chunked, or a refusal) with a small reference of RFC 9112 section 6. The reference is written apart from the server. This target finds request smuggling bugs.chunked_body: a chunked body, in one piece and in random pieces. The two must give the same result.conn: many requests on one connection (pipelined, bodies, keep-alive, close, upgrade). The input goes in as one piece and in random pieces, with a large Dart buffer and a small Dart buffer. Dart must get the same records each time. The server must parse nothing after a close or a bad request.aead_open: the cookie decryption on random data. It must not panic. A sealed value must open again. One changed byte must make the open fail.hpack: random HTTP/2 header blocks (HPACK) on one decoder. It must not panic. The decoded list must stay below the size limit, and the table size must stay correct. Each decoded block is encoded again and must decode to the same fields.h2_conn: random bytes after the HTTP/2 preface, on one connection, with cuts as inconn. When Dart does not answer, one piece and random pieces must give the same records and the same bytes back. With answers (full or streamed), each frame that the server writes must be complete and valid. Nothing can come after a GOAWAY with an error. No stream can end two times.STREAM_SENTmust not count more bytes than the answers have.tls_handshake: random bytes as the client side of a TLS connection, through the same read and write code as a real connection. It must not panic or stop. One piece and random pieces must give the same result.
To run one target on your computer:
rustup toolchain install nightly
cargo install cargo-fuzz --locked
cd native
cp Cargo.lock fuzz/Cargo.lock
mkdir -p /tmp/corpus/conn fuzz/corpus/conn
cargo +nightly fuzz run conn /tmp/corpus/conn fuzz/corpus/conn -- -max_total_time=300 -max_len=32768
mkdiralso makes the seed folder, for a target that has no seeds.aead_openis such a target: all random bytes are a good input.- The first folder gets the new inputs that the fuzzer finds. Use a temporary folder, so
fuzz/corpus/keeps only the small seed files. Commit a new seed there only when it is useful. -max_len=32768lets inputs go above the head limit of 16 KB.- A crash stops the run. The input that caused it is in
fuzz/artifacts/<target>/. To run it again, usecargo +nightly fuzz run <target> fuzz/artifacts/<target>/<file>. - The fuzz crate builds the same source as
native/. Keep the dependencies innative/fuzz/Cargo.tomlthe same as innative/Cargo.toml. CI does a check of this.
Documentation #
License #
MIT. See LICENSE.