SCUA 0.44.0 lets an http.serve handler read a large
upload as it arrives. The handler accepts the body with
http.body and reads it in pieces, so it can hash or store
each piece before the next one comes in, and the server never holds the
whole file. The release also adds secret values, which print as
<secret> and refuse to become text by accident, a
hash.hasher that hashes data in pieces, body limits an
operator can lower from the command line, and encryption and hashing
that use the processor's AES and SHA instructions on Linux and
Windows.
#http.serve can now stream large uploads
Set max_upload on http.serve, and a request
body larger than max_body and no larger than
max_upload reaches the handler before any of it has been
read. http.body(req, { max_bytes }) accepts it, with
max_bytes as this route's own limit, and
b.read(n) returns what has arrived, at most 64 KiB, until
empty bytes mark the end. This handler hashes each piece as it reads
it:
import http
import hash
import hex
import bytes
fn handle(req)
let b = http.body(req, { max_bytes = 2 * 1024 * 1024 * 1024 })?
let h = hash.hasher("sha256")?
let total = 0
while true do
let piece = b.read(65536)?
if len(piece) == 0 then break end -- empty bytes: the body has ended
h.update(piece)
total = total + len(piece)
end
let digest = hex.encode(h.digest())
return { status = 200, body = bytes.from_string(`{total} bytes, sha256 {digest}\n`) }
end
http.serve(handle, { bind = "127.0.0.1:8080", max_upload = 2 * 1024 * 1024 * 1024 })?
Start it with
scua --allow-serve=127.0.0.1:8080 upload.scua and send it a
1 GiB file:
$ curl -s -T photos.tar http://127.0.0.1:8080/photos
1073741824 bytes, sha256 8f62a46046e4f3627a0f87367b8deb3c022e6766f9c136b0945aaf6b7fe22d31
$ shasum -a 256 photos.tar
8f62a46046e4f3627a0f87367b8deb3c022e6766f9c136b0945aaf6b7fe22d31 photos.tar
On a Mac, the whole server peaked at about 11 MB of memory while it
took that upload. A read that waits for the client holds only its own
request, so the server goes on answering everything else. A body that
declares more than max_bytes is refused before any of it is
read, and a client that asked for 100 Continue is only told
to go ahead once http.body accepts. A body sent chunked,
such as a browser's streamed fetch or
curl -T -, works the same way, and max_bytes
is checked chunk by chunk as it arrives. http.body also
works on a small body the server read whole, and on a request record
built by hand in a test, so one route serves every size.
hash.hasher takes "sha1",
"sha256", "sha384" or "sha512",
and { key = k } makes it an HMAC. However the data is
split, the digest is the one hash.sha256 (or
hash.hmac) gives for all of it at once.
examples/serve_upload.scua is a whole upload service. It
checks the caller before it accepts the body, keeps a per-user quota in
a partition so parallel uploads share it, writes and syncs the file
before renaming it into place, and sweeps away unfinished files.
examples/sealing/ holds a tested module that encrypts an
upload chunk by chunk as it is written. Receive a large
upload covers the clocks and what each failure answers, and Behind a proxy
or load balancer has nginx settings for each way of running upload
routes behind it.
#SCUA now has secret values
A secret holds a password, key or token and refuses to
become text by accident. print, logs, fault messages,
Error values, scua test and the debugger show
it as <secret>, and building a string from it stops
with a message that says what to write instead:
import env
import secrets
let token = env.get("API_TOKEN", { as_secret = true })
if token == nil then error("API_TOKEN is not set") end
print(token, len(token))
print({ service = "photos", token = token })
print(secrets.equal(token, "tok-3f9a1c"))
print(pcall(fn() return "Bearer " .. token end))
let header = secrets.format("Bearer {}", token) -- a new secret, ready for http.request
print(header)
$ API_TOKEN=tok-3f9a1c scua --allow-env=API_TOKEN token.scua
<secret> 10
{service = photos, token = <secret>}
true
Error(can't build a string from a secret. To put it in a header, URL or body, build a secret: secrets.format("Bearer {}", s). http.request, exec.run, fs.write, crypto and http.serve responses take a secret as it is. (s.reveal() makes a plain copy and gives up the protection.))
<secret>
{ as_secret = true } on env.get,
fs.read, crypto.random_bytes,
sys.readpassword, exec.run and the decrypts
reads the bytes straight into a secret, so they never exist as a string.
json.decode makes secrets of the fields a record types
secret. On a server,
secret_headers = ["authorization", "cookie"] delivers those
request headers as secrets, and secrets.strip_prefix and
secrets.cookie take a bearer token or a session cookie out
of them. The calls that need the bytes take a secret as it is: every
crypto key and password, hash and
hmac, http.request, http.serve
responses, exec arguments, and fs and
net writes. secrets.format,
secrets.encode, secrets.concat and
secrets.json build a header or a JSON body that is itself a
secret. == on a secret faults, and
secrets.equal compares in constant time.
s.reveal() gives a plain copy on purpose, and
scua check --secrets lists every reveal and every write out
of the process, in the program and in its packages, without running
anything:
$ scua check --secrets app.scua
the program:
app.scua:6: http.request writes out of the process, and may carry a secret
app.scua:9: token.reveal() reveals a secret: from here it is a plain copy
1 reveal, 1 write out of the process, in 1 module. Not seen: code loaded at run time.
A hibernated partition's snapshot never holds a secret's bytes. After a revive the secret is wiped, and the program reads it again. A secret guards against accidents, such as a log line that shows it. Its bytes still live in ordinary memory, where they can reach swap or a crash dump, and any code you hand one to can reveal it. Handle secrets covers each case, and What a secret does not protect says exactly where the protection stops.
#Operators can now lower a server's body limits
The program sets its limits on http.serve:
max_body, the largest body handed to a handler whole (8 MiB
by default), and max_upload, the largest it streams. The
operator's flags, --serve-max-body and
--serve-max-upload, are ceilings. They lower what the
program asked for and never stop it starting, so an operator can lower a
limit across a fleet during an incident. Here the program asks for 16
MiB and is run with --serve-max-body=4M:
import http
import bytes
fn handle(req)
return { status = 200, body = bytes.from_string(`got {len(req.body)} bytes\n`) }
end
http.serve(handle, { bind = "127.0.0.1:8080", max_body = 16 * 1024 * 1024 })?
$ curl -s --data-binary @small.jpg http://127.0.0.1:8080/photos
got 3000000 bytes
$ curl -s --data-binary @photo.jpg http://127.0.0.1:8080/photos
request body of 6,000,000 bytes is over this server's limit of 4,194,304 bytes
The startup line says
request bodies up to 4 MiB each (max_body 16 MiB lowered to 4 MiB by --serve-max-body),
and the first 413 writes a line on stderr naming the
setting to change. --serve-check prints every limit and
budget the server would run with, each with where it came from, without
opening the port, and http.stats().limits gives a program
the same. See How big a body,
and who decides.
Bodies of 64 KiB or more also have memory of their own,
--serve-body-budget (128 MiB, or an eighth of a container's
memory limit). A body takes its room when its headers arrive, before any
of it is read, so a body that is admitted always has room to finish. One
that does not fit waits unread, with none of its clocks running, and
requests with no body or a small one never wait behind it. See Room for request
bodies.
Encryption and hashing now use the processor's AES and SHA instructions
On Linux and Windows, AES in every mode
(crypto.aes_gcm_encrypt and aes_gcm_decrypt,
aes_ctr, aes_cbc_hmac_encrypt and
aes_cbc_hmac_decrypt, aes_key_wrap and
aes_key_unwrap), and SHA-256 with
hash.hmac("sha256", …), hash.hasher("sha256")
and crypto.pbkdf2("sha256", …), use the processor's own
instructions for them when it has them. On an Intel Core i7-10700, one
core encrypts with crypto.aes_gcm_encrypt at about 880 MB/s
in 64 KiB pieces. That is faster than a gigabit link delivers, so the
sealing module above can encrypt an upload as it arrives. Your code does
not change, and the bytes are the same either way, so data sealed or
signed on one machine opens and checks on any other.
On x86-64, AES needs AES-NI with AVX, which Intel and AMD processors
have had since 2011, and SHA-256 needs the SHA extensions, which AMD has
had since Zen and Intel since Ice Lake. On 64-bit ARM it is the ARMv8
Cryptography Extension, and macOS on Apple silicon already used them.
With the instructions, AES also takes the same time whatever the key and
data. SCUA_CRYPTO=soft turns them off for testing. See Speed,
and the processor's AES and SHA instructions.
#Smaller additions
- In an
http.servehandler, a message handler, or code under--io=async,fs.write_chunk,fs.syncandfs.renamewith{ sync = true }now wait on the I/O pool's threads, asfs.readandfs.writealready did. A handler saving an upload to a slow disk holds only its own request. See Writing an upload to a file. --serve-max-uploads=Ncaps the bodies streaming at once, andhttp.stats().streams.bodiescounts uploads open, started, finished, unread and cut short by cause.http.stats().bytes_ingives the body bytes received.- Every
--serve-logline carriescontent_length,bytes_in,recv_msandadmit_wait_ms, and every answer the server gives on its own, such as a413or a408, writes a line. A413's line names the limit, its value and where it came from. --serve-body-min-rateand--serve-body-rate-graceset the slowest a body may arrive (1 KiB a second, after 10 seconds of waiting).--serve-max-idlecaps the idle time a response stream or a streamed body may ask for, and--serve-pool-budgetsets the request partitions' memory budget.- From the start of a stop,
http.bodyreturnsstopping, and an upload still arriving at the end of the grace is answered503withRetry-After, so its client reads an answer. The stop's last line counts uploads refused and abandoned. - Uploads stream under
scua debugand the editor's debugger too, each request in the session's frame. - A package's capability list names less for serving.
http.start,http.write,http.finish,http.bodyand reading a body need no grant, so a router package lists nothing for them, andhttp.statsneeds the newserve_stats, which--allow-serveincludes. bytes.wipe(b)zeroes abytesvalue or a{ u8 }buffer in place, andhash.equaltakes secrets.- A host that embeds SCUA can hand a script a secret with
scua_secret_new, andscua_arg_secretlends a host function a working copy, zeroed when it returns.
#Upgrading
secretsis now a built-in module, and a built-in module always wins over a file of the same name. A program with its ownsecrets.scuamust rename it and change itsimportto match.http.servetakes request bodies up to 8 MiB by default, where the limit was 1 MiB. A program that relied on the old limit to turn larger uploads away should setmax_body = 1024 * 1024, or run with--serve-max-body=1M. In a container with a small memory limit the default is lowered so four bodies fit the body budget, to about 2 MiB in a 64 MiB container, and the startup line says so.- A program that sets
max_bodyormax_uploadis refused by an older SCUA, so roll such a program back with the runtime. The same goes for a package budget narrowed toserve_stats. --serve-body-timeoutis now the longest a body may go with no byte arriving, where it was the time for the whole body, and--serve-timeoutcounts from the end of a request's body.- A server's stop budget, on the startup line and in
stop_budget_ms, is now the drain delay plus the grace plus 2 seconds. A deploy check that compares it with an orchestrator's termination grace sees the number move. http.starttakes only the request the handler was given. A record copied from its fields is refused withError({ kind = "state" }), so a framework that rebuilds the request keepsreqbeside its own record.- In
http.stats().causes, the stats line and the access log, a413is counted astoo_largeand a411aslength_required, where both werebad_request. - An
httpcall that finds the connection closed before any of the response arrived returns the new error kindconnection_closed, where it wasclient. Code that matcheskind == "client"for these must match"connection_closed". http.serveanswers417 Expectation Failedto anExpectheader other than100-continueon HTTP/1.1, and400to a header holding a stray carriage return, line feed or NUL. A request body the program cannot hold under--max-memis a503withRetry-After: 1, where it was a500.- On Linux, SCUA reads a container's memory limit, CPU limit and
listen backlog limit. In a container,
http.servesizes its budgets from the memory limit, and--workers=autocounts the CPUs the container is given. - A script whose file is called
checknow runs asscua ./check, sincescua checkis the command.
#What's next
SCUA is in private evaluation with a small group of testers, and what they hit steers the work. The next step on the roadmap is the public package registry: a static index served from a CDN, with a signed transparency log from the first public publish. For the agent runtime, snapshot, fork and replay of agent sessions are designed and queued.
The changelog lists everything else in 0.44.0.