diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..7bcac39 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,103 @@ +name: ci + +on: + push: + branches: [main] + pull_request: + branches: [main] + +permissions: + contents: read + +# CI pins the Go release below (Renovate moves it). 1.27.3 fails govulncheck (GO-2026-6859, net/http). The go.mod floor is 1.27.1. +jobs: + gofmt: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@v7 + with: + go-version: '1.27.4' + - name: gofmt + run: | + unformatted=$(gofmt -l .) + if [ -n "$unformatted" ]; then + echo "::error::these files are not gofmt-clean:"; echo "$unformatted" + exit 1 + fi + + # The bomb tests run under a memory limit: a worker that builds what a hostile + # file claims is killed by it instead of passing. + test: + name: test (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + defaults: + run: + shell: bash + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + env: + GOMEMLIMIT: 1GiB + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@v7 + with: + go-version: '1.27.4' + - run: go version + - run: go vet ./... + - run: go build ./... + - run: go test -race ./... + + # The worker module itself: GOOS=js GOARCH=wasm, with its size reported. + wasm: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@v7 + with: + go-version: '1.27.4' + - run: GOOS=js GOARCH=wasm go vet ./cmd/avkit-worker + - run: GOOS=js GOARCH=wasm go build -trimpath -ldflags="-s -w" -o avkit-worker.wasm ./cmd/avkit-worker + - name: size + run: | + gzip -9 -c avkit-worker.wasm > avkit-worker.wasm.gz + ls -l avkit-worker.wasm avkit-worker.wasm.gz + + # A header and a file are untrusted. The corpus in testdata/fuzz runs as + # ordinary tests above; this job also mutates it for a while. + fuzz: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@v7 + with: + go-version: '1.27.4' + - run: go test -fuzz FuzzDecodeRequest -fuzztime 30s ./proto + - run: go test -fuzz FuzzClampOnlyLowers -fuzztime 20s ./proto + - run: go test -fuzz FuzzHandle -fuzztime 60s ./serve + + vuln: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@v7 + with: + go-version: '1.27.4' + - run: go install golang.org/x/vuln/cmd/govulncheck@latest + - run: govulncheck ./... + - run: GOOS=js GOARCH=wasm govulncheck ./cmd/avkit-worker + + # The one 32-bit target, where int is 32 bits wide: a length converted to int + # before it is compared wraps only here. + arch-386: + name: arch 386 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@v7 + with: + go-version: '1.27.4' + - run: GOARCH=386 go vet ./... + - run: GOARCH=386 go test ./... diff --git a/README.md b/README.md index 1f17bb5..89f7fba 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,139 @@ # worker -Video worker for go-avkit: request/response protocol, server (poster, probe) and a js/wasm Web Worker + +[![ci](https://github.com/go-avkit/worker/actions/workflows/ci.yml/badge.svg)](https://github.com/go-avkit/worker/actions/workflows/ci.yml) +[![Go Reference](https://pkg.go.dev/badge/github.com/go-avkit/worker.svg)](https://pkg.go.dev/github.com/go-avkit/worker) +[![License: BSD-3-Clause](https://img.shields.io/badge/license-BSD--3--Clause-blue.svg)](LICENSE) + +A video worker for [avkit](https://github.com/go-avkit/avkit): a program that +reads video files for a page that must not link a container reader or a +decoder. It answers two requests, **poster** (a JPEG of the frame at time *t*) +and **probe** (container, codec, size, duration), with go-avkit's container +reader (MP4, WebM / Matroska) and [H.264 decoder](https://github.com/go-avkit/decode). +Part of [go-avkit/avkit#89](https://github.com/go-avkit/avkit/issues/89). + +| Package | What it is | +|---|---| +| `proto` | The request/response protocol. Standard library only: no `syscall/js`, no decoder. A client and a server both import it. | +| `serve` | `Server.Handle(req, payload)`: the server. Links go-avkit/decode and go-avkit/container. Pure Go, tested natively. | +| `cmd/avkit-worker` | The `js/wasm` Web Worker main (about 80 lines): a MessagePort in front of `serve`. | + +## Using it from a host + +Build the worker once, serve the `.wasm` next to Go's `wasm_exec.js`: + +```sh +GOOS=js GOARCH=wasm go build -trimpath -ldflags="-s -w" -o avkit-worker.wasm ./cmd/avkit-worker +``` + +A host loads it in a Web Worker (`importScripts("wasm_exec.js")`, then +`WebAssembly.instantiateStreaming` and `go.run`), waits for `{"ready":true}`, +and gives it one end of a `MessageChannel`: + +```js +const ch = new MessageChannel(); +worker.postMessage({ videoPort: ch.port2 }, [ch.port2]); +ch.port1.postMessage({ json: JSON.stringify(req), data: fileArrayBuffer }); +ch.port1.onmessage = (e) => { const res = JSON.parse(e.data.json); /* e.data.data: the JPEG */ }; +``` + +Each message is `{json, data}`: the JSON header, and beside it the binary payload +(the file in a request, the poster's JPEG in a response). The transport is the +host's: another host can call `serve.Server.Handle` directly. + +## The protocol + +A **request** header (`proto.Request`): + +| Field | Meaning | +|---|---| +| `id` | pairs the answer with the request | +| `op` | `"poster"` or `"probe"` | +| `key` | the file's version: `proto.Fingerprint`, its length and CRC-64/ECMA (at most 128 bytes) | +| `hasData` | the payload is the file; otherwise the worker's copy named by `key` is read | +| `format` | `"mp4"` or `"webm"`, informative (the worker sniffs again) | +| `t` | the poster's time, in seconds | +| `limits` | the bounds asked for (see below) | + +A **response** header (`proto.Response`): `id`; on a refusal `code` and `error`; +otherwise `format`, `mime`, `codec`, `width`, `height`, `duration`, `decodable`, +and for a poster `image` (`"image/jpeg"`, the payload; its size is `width` x `height`). + +The worker keeps the last 2 files it was sent, by `key`. A request for a file +it does not hold is answered `video.notheld` (never shown to a user); the client +sends it again with `hasData`. + +| Code | Meaning | +|---|---| +| `video.limit` | the file, its boxes or elements, its frame, or the work of a poster is over a bound | +| `video.syntax` | not an MP4 or WebM, a container that cannot be read, no video track, a bad time, a bad request | +| `video.codec` | the poster cannot be decoded: a codec other than H.264 (the file still probes), or an H.264 tool that is not decoded | +| `video.unavailable` | the client could not reach a worker; a `Server` never answers it | +| `video.notheld` | the key names no held file: send it again with the data | + +The wire format is that of go-slides' `video` client: the limits' field names are +those of its `video.Limits`. + +## Limits: a request can only lower them + +The worker's own bounds are `proto.DefaultLimits`: 64 MiB file, 262144 boxes, +nesting depth 16, 4096 x 4096 frame, 600 samples per poster, 262144 samples per +track, 8 MiB per sample, 1280 pixels of poster width. `proto.Clamp` is the limits +applied for a request, field by field: + +- a value from 1 to the default is a lowering and is kept; +- a value above the default (`MaxInt`, 2^40), `0` and a negative mean **use the + default**: never a refusal, never the value asked. + +So for every request, every effective bound is in 1..default. This is a test +(`TestClampOnlyLowers`, `TestClampReviewerTable`), a fuzz property over all nine +fields (`FuzzClampOnlyLowers`, and `FuzzDecodeRequest` for any header), and the +bomb tests of `serve`. A held file is checked again against the limits of each +request that reads it. + +## Security + +A header and a file are untrusted. The header is bounded (64 KiB), and a +payload is bounded before it is copied (the worker refuses a file over 64 MiB on +its length alone). Before the container reader builds anything, a pre-scan counts +the boxes (MP4) or elements (Matroska), measures their nesting, and, for +Matroska, counts the **frames** the blocks hold: it reads each SimpleBlock and +Block's lacing header, because the reader unlaces every block up front and a +7-byte laced block stands for 256 frames +([go-avkit/avkit#120](https://github.com/go-avkit/avkit/issues/120)). More than +`MaxTrackSamples` frames in a track, or twice that in the file, is `video.limit` +(a 70 KB file of 10,000 laced blocks is refused with under 3 KB allocated). The +MP4 sample tables are not pre-scanned: the reader's own bounds apply there. + +A panic in the reader or the decoder is answered as a `video.syntax` refusal, in +`Server.Handle` and again at the worker boundary, and the worker keeps serving. +The message types the page sends are checked: a payload that is not an +ArrayBuffer is refused, and a message that is not an object, or a `videoPort` +that is not a port, is ignored, not a crash. + +**A file just under the cap costs memory.** The reader builds its tables up +front: the reviewer measured a 7 KB file of valid structure at 96 MiB allocated, +35 MiB retained per held file, so about 160 MiB with the 2 files held. That cost +is bounded by the frame and sample limits above, not by the file's size. + +**Decode time is not bounded by a clock.** A poster is bounded by samples +(`MaxSamples`, 600), not by time: a 4096 x 4096, 600-frame, single-GOP H.264 file +took 12.4 s for one poster natively (indicative, machine at load 12). The decoder +has no deadline hook; a page should treat a poster request as slow and keep its +own timeout. Lower `MaxSamples`, `MaxWidth` and `MaxHeight` in the request to +shorten the worst case. + +Fuzz targets: `FuzzDecodeRequest`, `FuzzClampOnlyLowers`, `FuzzHandle` (all nine +limits, hostile payloads; corpus in `testdata/fuzz`); the bomb tests +(`TestBombsAreRefusedWithinMemory`, `TestLacedBlockBombsAreRefused`) assert a +refusal and a small allocation, and CI runs the suite under `GOMEMLIMIT`. +The test videos in `serve/testdata` are the small files of go-slides' video tests. + +## Size + +`cmd/avkit-worker` built with Go 1.27.4 (`-trimpath -ldflags="-s -w"`, js/wasm): +12,881,038 bytes raw, 3,297,044 bytes gzip -9 (12.3 MiB, 3.1 MiB). Serve it +compressed. + +## Licence + +BSD-3-Clause, see [LICENSE](LICENSE). diff --git a/cmd/avkit-worker/main.go b/cmd/avkit-worker/main.go new file mode 100644 index 0000000..aabe899 --- /dev/null +++ b/cmd/avkit-worker/main.go @@ -0,0 +1,115 @@ +// Copyright (c) 2026, go-avkit +// SPDX-License-Identifier: BSD-3-Clause + +//go:build js && wasm + +// Command avkit-worker is a video worker for the browser: go-avkit's container +// reader and H.264 decoder in a WebAssembly module of its own, run in a Web +// Worker the first time a page needs a poster or a probe. The page's own module +// links none of it. +// +// A host posts {videoPort: port} to the worker; the requests (package proto) +// arrive on that port as {json, data}: the request's JSON header and, in data, +// the file (an ArrayBuffer). The answer goes back the same way: {json, data}, +// with the poster's JPEG in data. Nothing is fetched here. The worker posts +// {"ready":true} once it listens. +package main + +import ( + "encoding/json" + "fmt" + "math" + "syscall/js" + + "github.com/go-avkit/worker/proto" + "github.com/go-avkit/worker/serve" +) + +func main() { + srv := &serve.Server{} + js.Global().Set("onmessage", js.FuncOf(func(_ js.Value, args []js.Value) any { + // a message of the wrong shape, or a port that is not one, is ignored + defer func() { _ = recover() }() + if len(args) == 0 || args[0].Type() != js.TypeObject { + return nil + } + data := args[0].Get("data") + if data.Type() != js.TypeObject { + return nil + } + port := data.Get("videoPort") + if port.Type() != js.TypeObject || port.Get("addEventListener").Type() != js.TypeFunction || + port.Get("postMessage").Type() != js.TypeFunction || port.Get("start").Type() != js.TypeFunction { + return nil + } + port.Call("addEventListener", "message", js.FuncOf(func(_ js.Value, a []js.Value) any { + if len(a) > 0 { + answer(srv, port, a[0].Get("data")) + } + return nil + })) + port.Call("start") + return nil + })) + js.Global().Call("postMessage", `{"ready":true}`) + select {} +} + +// answer reads one request off a port and posts its answer. +// A message of the wrong shape, or a panic, is answered with a refusal and the +// worker keeps serving. +func answer(srv *serve.Server, port, msg js.Value) { + id := 0 + defer func() { + if p := recover(); p != nil { + post(port, proto.Response{ID: id, Code: proto.CodeSyntax, Error: fmt.Sprint("the request could not be served: ", p)}, nil) + } + }() + if msg.Type() != js.TypeObject || msg.Get("json").Type() != js.TypeString { + return + } + req, err := proto.DecodeRequest([]byte(msg.Get("json").String())) + id = req.ID + if err != nil { + code, text := codeOf(err) + post(port, proto.Response{ID: req.ID, Code: code, Error: text}, nil) + return + } + var payload []byte + if d := msg.Get("data"); !d.IsUndefined() && !d.IsNull() { + // the file is bounded before it is copied into this module's memory + if d.Type() != js.TypeObject || d.Get("byteLength").Type() != js.TypeNumber { + post(port, proto.Response{ID: req.ID, Code: proto.CodeSyntax, Error: "the payload is not an ArrayBuffer"}, nil) + return + } + n := d.Get("byteLength").Float() + if n < 0 || n != math.Floor(n) || n > float64(proto.DefaultLimits.MaxBytes) { + post(port, proto.Response{ID: req.ID, Code: proto.CodeLimit, Error: "the file is larger than the 64 MiB read"}, nil) + return + } + payload = make([]byte, int(n)) + js.CopyBytesToGo(payload, js.Global().Get("Uint8Array").New(d)) + } + res, img := srv.Handle(req, payload) + post(port, res, img) +} + +func codeOf(err error) (string, string) { + if e, ok := err.(*proto.Error); ok { + return e.Code, e.Msg + } + return proto.CodeSyntax, err.Error() +} + +func post(port js.Value, res proto.Response, img []byte) { + b, _ := json.Marshal(res) + m := map[string]any{"json": string(b)} + if len(img) > 0 { + buf := js.Global().Get("Uint8Array").New(len(img)) + js.CopyBytesToJS(buf, img) + m["data"] = buf.Get("buffer") + port.Call("postMessage", m, []any{buf.Get("buffer")}) + return + } + port.Call("postMessage", m) +} diff --git a/cmd/avkit-worker/main_other.go b/cmd/avkit-worker/main_other.go new file mode 100644 index 0000000..507dd40 --- /dev/null +++ b/cmd/avkit-worker/main_other.go @@ -0,0 +1,21 @@ +// Copyright (c) 2026, go-avkit +// SPDX-License-Identifier: BSD-3-Clause + +//go:build !(js && wasm) + +// Command avkit-worker is a video worker for the browser and only builds for +// GOOS=js GOARCH=wasm; this file stands in on every other platform so that +// `go build ./...` and `go vet ./...` see a package. +package main + +import ( + "fmt" + "os" +) + +var osExit = os.Exit + +func main() { + fmt.Fprintln(os.Stderr, "avkit-worker runs in a browser: build it with GOOS=js GOARCH=wasm") + osExit(2) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..50db6b0 --- /dev/null +++ b/go.mod @@ -0,0 +1,26 @@ +module github.com/go-avkit/worker + +go 1.27.1 + +require ( + github.com/go-avkit/avkit v0.16.0 + github.com/go-avkit/decode v0.5.4 +) + +require ( + github.com/Eyevinn/mp4ff v0.62.1 // indirect + github.com/asticode/go-astikit v0.30.0 // indirect + github.com/asticode/go-astits v1.17.0 // indirect + github.com/at-wat/ebml-go v0.19.4 // indirect + github.com/gen2brain/h265 v0.2.4 // indirect + github.com/go-avkit/bitstream v0.3.1 // indirect + github.com/go-avkit/h264 v0.9.0 // indirect + github.com/icza/bitio v1.1.0 // indirect + github.com/mewkiz/flac v1.0.14 // indirect + github.com/mewkiz/pkg v0.0.0-20250417130911-3f050ff8c56d // indirect + github.com/mewpkg/term v0.0.0-20241026122259-37a80af23985 // indirect + github.com/pion/opus v0.1.0 // indirect + github.com/tphakala/go-mp3 v0.3.0 // indirect + github.com/tphakala/simd v1.16.0 // indirect + golang.org/x/sys v0.49.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..a5f0504 --- /dev/null +++ b/go.sum @@ -0,0 +1,42 @@ +github.com/Eyevinn/mp4ff v0.62.1 h1:EMuNIrmTCm5acOCVENca5Fzk+Mdek/l4bQZdk2EfReo= +github.com/Eyevinn/mp4ff v0.62.1/go.mod h1:97zsDIJUiDTYqKpqq/b1K9foamxXmvsgE4GdPrPK3ks= +github.com/asticode/go-astikit v0.30.0 h1:DkBkRQRIxYcknlaU7W7ksNfn4gMFsB0tqMJflxkRsZA= +github.com/asticode/go-astikit v0.30.0/go.mod h1:h4ly7idim1tNhaVkdVBeXQZEE3L0xblP7fCWbgwipF0= +github.com/asticode/go-astits v1.17.0 h1:KrDxalNhZ/GJkbgVweD5xxCA9XoaW7tHuFiJB/sAZxs= +github.com/asticode/go-astits v1.17.0/go.mod h1:psImoC1BhcAWIsyM/RnbO1OgUW+XSf8fZpFvF5McDyo= +github.com/at-wat/ebml-go v0.19.4 h1:6F767ThzH/JqNUsF79PwRFP0pwUF5ALXWJ6pXuiolI8= +github.com/at-wat/ebml-go v0.19.4/go.mod h1:wu3fQj+DWo6SOOl9c4yDi+gFs9Oa96Z2B5qxo1OxFYY= +github.com/gen2brain/h265 v0.2.4 h1:JUSbGkRAYZpd7ucCL192yx4ViEo75ZO6OEdm1TQt9qM= +github.com/gen2brain/h265 v0.2.4/go.mod h1:kefpLxLhGpNCUG/q/aabJcD6GqB9Nhet3fNi9xX9Wzw= +github.com/go-avkit/avkit v0.16.0 h1:QoFoIgAHy8xv+kdnROQ8P3GSqveV5/BJtxPa0i+ZM64= +github.com/go-avkit/avkit v0.16.0/go.mod h1:itL/gmFP0/hIVAQgxn0JTTvlGgY9vi5uL8XI2sOQl/c= +github.com/go-avkit/bitstream v0.3.1 h1:hZL/9IyRQaXmDd8iEm8ZKT79Tec4pS+HZ+wnQiLaQSc= +github.com/go-avkit/bitstream v0.3.1/go.mod h1:aA50I8nXKyJu6ElfTHM957BRrx5JjgSYUxs++n5VM8o= +github.com/go-avkit/decode v0.5.4 h1:j4jJYR5MHdLzljxAz/nlOScBtLE31OSkzf4jh3G2hXU= +github.com/go-avkit/decode v0.5.4/go.mod h1:bL60pm/MHwx+3e+7klXgNR1o+UkbWfxOHCMtDzGH6bg= +github.com/go-avkit/h264 v0.9.0 h1:yrXbVFZCfZhG9okTJqITHdldVciXMw0ioPaH/NorWsQ= +github.com/go-avkit/h264 v0.9.0/go.mod h1:LcFlgGaV0CHWk4oEpO3GWv+93vylXsuJeepcDW9Md3I= +github.com/go-test/deep v1.1.0 h1:WOcxcdHcvdgThNXjw0t76K42FXTU7HpNQWHpA2HHNlg= +github.com/go-test/deep v1.1.0/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE= +github.com/icza/bitio v1.1.0 h1:ysX4vtldjdi3Ygai5m1cWy4oLkhWTAi+SyO6HC8L9T0= +github.com/icza/bitio v1.1.0/go.mod h1:0jGnlLAx8MKMr9VGnn/4YrvZiprkvBelsVIbA9Jjr9A= +github.com/icza/mighty v0.0.0-20180919140131-cfd07d671de6 h1:8UsGZ2rr2ksmEru6lToqnXgA8Mz1DP11X4zSJ159C3k= +github.com/icza/mighty v0.0.0-20180919140131-cfd07d671de6/go.mod h1:xQig96I1VNBDIWGCdTt54nHt6EeI639SmHycLYL7FkA= +github.com/mewkiz/flac v1.0.14 h1:hyRGAM8NCKznoPmIi9zz2jyO+nfmxY2ErqBnHZ+gxh4= +github.com/mewkiz/flac v1.0.14/go.mod h1:HfPYDA+oxjyuqMu2V+cyKcxF51KM6incpw5eZXmfA6k= +github.com/mewkiz/pkg v0.0.0-20250417130911-3f050ff8c56d h1:IL2tii4jXLdhCeQN69HNzYYW1kl0meSG0wt5+sLwszU= +github.com/mewkiz/pkg v0.0.0-20250417130911-3f050ff8c56d/go.mod h1:SIpumAnUWSy0q9RzKD3pyH3g1t5vdawUAPcW5tQrUtI= +github.com/mewpkg/term v0.0.0-20241026122259-37a80af23985 h1:h8O1byDZ1uk6RUXMhj1QJU3VXFKXHDZxr4TXRPGeBa8= +github.com/mewpkg/term v0.0.0-20241026122259-37a80af23985/go.mod h1:uiPmbdUbdt1NkGApKl7htQjZ8S7XaGUAVulJUJ9v6q4= +github.com/pion/opus v0.1.0 h1:GgK/a3DNDrffKjUFsK39rZKqfv7bQ2S2eqRKt0BnqAE= +github.com/pion/opus v0.1.0/go.mod h1:t5Xog2n682JnawoykACE6nKVmupFvmJvkpM7x6bTv6g= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/tphakala/go-mp3 v0.3.0 h1:qPW9PN4KLP+aIeDtcwAbCy+nGDeUJGxodFJediCjpdo= +github.com/tphakala/go-mp3 v0.3.0/go.mod h1:gxl4OIovd0Ojr0De5uocbszCVmf3PBRs/wgrpn6sSgw= +github.com/tphakala/simd v1.16.0 h1:dHw1NIuN56pjKsbi3uYdXQMYaGgT7brYXkdn3tsWDKQ= +github.com/tphakala/simd v1.16.0/go.mod h1:eO53GkWg40mRbr2tzs0Xb1IMZQ5U8cMR+Aa1RlXUinE= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= diff --git a/proto/fuzz_test.go b/proto/fuzz_test.go new file mode 100644 index 0000000..e3d34b9 --- /dev/null +++ b/proto/fuzz_test.go @@ -0,0 +1,48 @@ +// Copyright (c) 2026, go-avkit +// SPDX-License-Identifier: BSD-3-Clause + +package proto + +import ( + "math" + "testing" +) + +// FuzzDecodeRequest: no header, however hostile, panics the decoder; a header +// that decodes holds a bounded key; and the limits the worker would apply for +// it are, field by field, in 1..DefaultLimits. The corpus in testdata/fuzz runs +// as ordinary tests. +func FuzzDecodeRequest(f *testing.F) { + for _, s := range []string{ + `{"id":1,"op":"poster","key":"9-ab","hasData":true,"format":"mp4","t":1.5,"limits":{"MaxBytes":67108864,"MaxBoxes":262144,"MaxDepth":16,"MaxWidth":4096,"MaxHeight":4096,"MaxSamples":600,"MaxTrackSamples":262144,"MaxSampleBytes":8388608,"PosterWidth":1280}}`, + `{"id":2,"op":"probe","key":"0-0","limits":{"MaxBytes":9223372036854775807,"MaxBoxes":-1,"MaxDepth":0,"MaxWidth":99999999,"PosterWidth":-9223372036854775808}}`, + `{"id":3,"limits":{"MaxBytes":1e30}}`, `{"id":4} {"id":5}`, `[]`, `null`, `{"limits":null}`, `{"t":1e999}`, ``, + } { + f.Add([]byte(s)) + } + f.Fuzz(func(t *testing.T, b []byte) { + req, err := DecodeRequest(b) + if err != nil { + if _, ok := err.(*Error); !ok { + t.Fatalf("an error with no code: %v", err) + } + return + } + if len(req.Key) > MaxKeyBytes { + t.Fatalf("a key of %d bytes", len(req.Key)) + } + within(t, req.Limits, Clamp(req.Limits)) + }) +} + +// FuzzClampOnlyLowers: for every ask, every effective bound is at most the +// worker's default and positive, and a lowering is kept exactly. +func FuzzClampOnlyLowers(f *testing.F) { + f.Add(0, 0, 0, 0, 0, 0, 0, 0, 0) + f.Add(math.MaxInt, math.MaxInt, math.MaxInt, math.MaxInt, math.MaxInt, math.MaxInt, math.MaxInt, math.MaxInt, math.MaxInt) + f.Add(-1, math.MinInt, 5, 1, 4097, 4096, 600, 601, 1280) + f.Fuzz(func(t *testing.T, a, b, c, d, e, g, h, i, j int) { + ask := Limits{MaxBytes: a, MaxBoxes: b, MaxDepth: c, MaxWidth: d, MaxHeight: e, MaxSamples: g, MaxTrackSamples: h, MaxSampleBytes: i, PosterWidth: j} + within(t, ask, Clamp(ask)) + }) +} diff --git a/proto/proto.go b/proto/proto.go new file mode 100644 index 0000000..982e1be --- /dev/null +++ b/proto/proto.go @@ -0,0 +1,199 @@ +// Copyright (c) 2026, go-avkit +// SPDX-License-Identifier: BSD-3-Clause + +// Package proto is the message protocol of a video worker: a program that +// reads video files for a page that must not link a container reader or a +// decoder (a WebAssembly module of its own, run in a Web Worker). It is two +// typed requests, +// +// poster(file, t) -> a JPEG, its width and height +// probe(file) -> container, codec, size, duration +// +// answered with coded refusals (video.limit, video.syntax, video.codec, +// video.unavailable). The messages are plain data: the transport is the host's +// (a MessagePort between two Web Workers in a browser; a function call in the +// tests). This package imports nothing but the standard library: no syscall/js, +// no decoder, so a client and a server can both use it. +// +// A message is a JSON header and, beside it, a binary payload: the file in a +// request, the picture in a response. The payload is never inside the JSON (a +// file is up to 64 MiB). A worker keeps the last files it was sent, by Key, so +// that the next requests for the same file (a poster at another time) do not +// carry it again; a request for a file it does not hold is answered CodeNotHeld, +// and the client sends it again with the file. +// +// The limits are the worker's: a request may LOWER any bound, never raise one +// (Clamp). +package proto + +import ( + "bytes" + "encoding/json" + "errors" + "hash/crc64" + "io" + "strconv" +) + +// The operations. +const ( + OpPoster = "poster" + OpProbe = "probe" +) + +// The codes of a refusal. +const ( + CodeLimit = "video.limit" + CodeSyntax = "video.syntax" + CodeCodec = "video.codec" + CodeUnavailable = "video.unavailable" +) + +// CodeNotHeld is the code of an answer that is not a refusal of the file: the +// worker does not hold the file the request names. It is never shown. +const CodeNotHeld = "video.notheld" + +// Error is a refusal with the code that names it. +type Error struct { + Code string + Msg string +} + +func (e *Error) Error() string { return e.Msg } + +// MaxHeaderBytes is the largest JSON header DecodeRequest reads. A request +// header is a few hundred bytes; the file is the payload, not the header. +const MaxHeaderBytes = 64 << 10 + +// MaxKeyBytes is the longest Key accepted (a length, a dash and 16 hex digits +// is under 32 bytes). +const MaxKeyBytes = 128 + +// Limits bound what a file may cost. The field names are the wire names: they +// are those of go-slides' video.Limits, which the clients encode as they are. +type Limits struct { + // MaxBytes is the largest file read. + MaxBytes int + // MaxBoxes is the most boxes (MP4) or elements (EBML) a file may hold, and + // MaxDepth how deeply they may nest. + MaxBoxes, MaxDepth int + // MaxWidth and MaxHeight bound the frame, in pixels. + MaxWidth, MaxHeight int + // MaxSamples is the most samples decoded for one poster (a keyframe far + // from the time asked for is refused); MaxTrackSamples the most a track may + // list; MaxSampleBytes the largest sample. + MaxSamples, MaxTrackSamples, MaxSampleBytes int + // PosterWidth is the width the poster is scaled down to (never up). + PosterWidth int +} + +// DefaultLimits are the worker's own bounds, which no request raises. +var DefaultLimits = Limits{ + MaxBytes: 64 << 20, MaxBoxes: 1 << 18, MaxDepth: 16, + MaxWidth: 4096, MaxHeight: 4096, + MaxSamples: 600, MaxTrackSamples: 1 << 18, MaxSampleBytes: 8 << 20, + PosterWidth: 1280, +} + +// Request asks a worker to read a file. +type Request struct { + // ID pairs the answer with the request. + ID int `json:"id"` + // Op is OpPoster or OpProbe. + Op string `json:"op"` + // Key names the version of the file (Fingerprint). + Key string `json:"key"` + // HasData says the payload is the file; otherwise the worker's copy of the + // file named by Key is read. + HasData bool `json:"hasData,omitempty"` + // Format is "mp4" or "webm", as the client sniffed it (informative: the + // worker sniffs again). + Format string `json:"format,omitempty"` + // T is the poster's time, in seconds. + T float64 `json:"t,omitempty"` + // Limits are the bounds the host asks for; the worker never exceeds + // DefaultLimits (Clamp). + Limits Limits `json:"limits"` +} + +// Response answers a Request. The poster's picture is the payload. +type Response struct { + ID int `json:"id"` + // Code and Error are a refusal: a video.* code and its message. + Code string `json:"code,omitempty"` + Error string `json:"error,omitempty"` + // Probe's answer: the container ("mp4", "webm"), the video track, and + // whether a poster can be decoded for it. + Format string `json:"format,omitempty"` + MIME string `json:"mime,omitempty"` + Codec string `json:"codec,omitempty"` + Width int `json:"width,omitempty"` + Height int `json:"height,omitempty"` + Duration float64 `json:"duration,omitempty"` + Decodable bool `json:"decodable,omitempty"` + // Image is the type of the payload of a poster's answer ("image/jpeg"); its + // size is Width x Height for a poster. + Image string `json:"image,omitempty"` +} + +// OK reports whether the answer is a refusal's or not. +func (r Response) OK() bool { return r.Code == "" } + +// DecodeRequest reads a request header. The header is bounded +// (MaxHeaderBytes), must be exactly one JSON object, and its Key is bounded +// (MaxKeyBytes). On an error the Request still carries the ID when one could +// be read, so that the worker can answer the refusal to the right request. +func DecodeRequest(b []byte) (Request, error) { + var req Request + if len(b) > MaxHeaderBytes { + return req, &Error{CodeLimit, "the request header is larger than " + strconv.Itoa(MaxHeaderBytes) + " bytes"} + } + dec := json.NewDecoder(bytes.NewReader(b)) + if err := dec.Decode(&req); err != nil { + var id struct { + ID int `json:"id"` + } + if json.Unmarshal(b, &id) == nil { + req = Request{ID: id.ID} + } else { + req = Request{} + } + return req, &Error{CodeSyntax, "the request header is not a request: " + err.Error()} + } + if _, err := dec.Token(); !errors.Is(err, io.EOF) { + return Request{ID: req.ID}, &Error{CodeSyntax, "the request header holds more than one value"} + } + if len(req.Key) > MaxKeyBytes { + return Request{ID: req.ID}, &Error{CodeSyntax, "the key is longer than " + strconv.Itoa(MaxKeyBytes) + " bytes"} + } + return req, nil +} + +// Fingerprint names a version of a file: its length and a 64-bit checksum of +// every byte (CRC-64/ECMA), which costs a few milliseconds per 10 MiB and which +// a trimmed or re-encoded file does not keep. +func Fingerprint(data []byte) string { + return strconv.Itoa(len(data)) + "-" + strconv.FormatUint(crc64.Checksum(data, crcTable), 16) +} + +var crcTable = crc64.MakeTable(crc64.ECMA) + +// Clamp is the limits a worker applies for a request's: each bound of ask is +// kept when it is positive and not above the worker's own (DefaultLimits), and +// replaced by it otherwise. A host can lower the bounds, never raise them: +// for every ask, every field of the result is in 1..DefaultLimits. +func Clamp(ask Limits) Limits { + d := DefaultLimits + c := func(a, max int) int { + if a <= 0 || a > max { + return max + } + return a + } + return Limits{ + MaxBytes: c(ask.MaxBytes, d.MaxBytes), MaxBoxes: c(ask.MaxBoxes, d.MaxBoxes), MaxDepth: c(ask.MaxDepth, d.MaxDepth), + MaxWidth: c(ask.MaxWidth, d.MaxWidth), MaxHeight: c(ask.MaxHeight, d.MaxHeight), + MaxSamples: c(ask.MaxSamples, d.MaxSamples), MaxTrackSamples: c(ask.MaxTrackSamples, d.MaxTrackSamples), + MaxSampleBytes: c(ask.MaxSampleBytes, d.MaxSampleBytes), PosterWidth: c(ask.PosterWidth, d.PosterWidth), + } +} diff --git a/proto/proto_test.go b/proto/proto_test.go new file mode 100644 index 0000000..d0a1699 --- /dev/null +++ b/proto/proto_test.go @@ -0,0 +1,166 @@ +// Copyright (c) 2026, go-avkit +// SPDX-License-Identifier: BSD-3-Clause + +package proto + +import ( + "encoding/json" + "errors" + "math" + "reflect" + "strings" + "testing" +) + +// fields lists a Limits' bounds by name, so that a check cannot forget one +// when a field is added: the count is asserted against the struct. +func fields(t testing.TB, l Limits) map[string]int { + t.Helper() + v, out := reflect.ValueOf(l), map[string]int{} + for i := range v.NumField() { + out[v.Type().Field(i).Name] = int(v.Field(i).Int()) + } + if len(out) != 9 { + t.Fatalf("Limits has %d fields; this test knows 9: extend Clamp and the tests", len(out)) + } + return out +} + +// within says every field of got is in 1..default, naming the first that is not. +func within(t testing.TB, ask, got Limits) { + t.Helper() + d, g, a := fields(t, DefaultLimits), fields(t, got), fields(t, ask) + for name, max := range d { + if g[name] < 1 || g[name] > max { + t.Fatalf("ask %s=%d gave %d; want 1..%d", name, a[name], g[name], max) + } + if a[name] > 0 && a[name] <= max && g[name] != a[name] { + t.Fatalf("ask %s=%d (a lowering) gave %d", name, a[name], g[name]) + } + } +} + +// A request can only LOWER limits: each field, one at a time, at the values +// that matter (zero, negative, just below, equal, just above, the integer's +// extremes), and all at once. +func TestClampOnlyLowers(t *testing.T) { + d := fields(t, DefaultLimits) + for name, max := range d { + for _, ask := range []int{math.MinInt, -1, 0, 1, max - 1, max, max + 1, 2 * max, math.MaxInt32, math.MaxInt} { + var l Limits + reflect.ValueOf(&l).Elem().FieldByName(name).SetInt(int64(ask)) + got := Clamp(l) + within(t, l, got) + switch want := ask; { + case ask <= 0 || ask > max: + if g := fields(t, got)[name]; g != max { + t.Errorf("%s=%d: %d, want the default %d", name, ask, g, max) + } + default: + if g := fields(t, got)[name]; g != want { + t.Errorf("%s=%d: %d, want it kept", name, ask, g) + } + } + } + } + var huge Limits + v := reflect.ValueOf(&huge).Elem() + for i := range v.NumField() { + v.Field(i).SetInt(math.MaxInt) + } + if got := Clamp(huge); got != DefaultLimits { + t.Errorf("a request of the maximum asks %+v, got %+v", huge, got) + } + if got := Clamp(Limits{}); got != DefaultLimits { + t.Errorf("no request: %+v", got) + } +} + +// The independent reviewer's probe: for each of the 9 fields, a request of +// MaxInt, 2^40, 0 and -1. The meaning is written down here and in Clamp: a +// value above the default (MaxInt, 2^40), zero and a negative are all "use the +// default" (never a refusal and never the value asked); only a value in +// 1..default is a lowering and is kept. The effective value never exceeds the +// default. +func TestClampReviewerTable(t *testing.T) { + for name, max := range fields(t, DefaultLimits) { + for label, ask := range map[string]int64{"MaxInt": math.MaxInt, "2^40": 1 << 40, "0": 0, "-1": -1} { + if int64(int(ask)) != ask { + continue // 2^40 does not exist as an int on a 32-bit target + } + var l Limits + reflect.ValueOf(&l).Elem().FieldByName(name).SetInt(ask) + got := fields(t, Clamp(l)) + if got[name] > max || got[name] != max { + t.Errorf("%s=%s: effective %d, want the default %d (use the default)", name, label, got[name], max) + } + for other, v := range got { + if other != name && v != fields(t, DefaultLimits)[other] { + t.Errorf("%s=%s moved %s to %d", name, label, other, v) + } + } + } + } +} + +// The wire names are those of go-slides' video.Limits (Go field names), so +// that its client works unchanged. +func TestWireCompatibility(t *testing.T) { + b, err := json.Marshal(Request{ID: 7, Op: OpPoster, Key: "9-ab", HasData: true, Format: "mp4", T: 1.5, Limits: DefaultLimits}) + if err != nil { + t.Fatal(err) + } + const want = `{"id":7,"op":"poster","key":"9-ab","hasData":true,"format":"mp4","t":1.5,"limits":{"MaxBytes":67108864,"MaxBoxes":262144,"MaxDepth":16,"MaxWidth":4096,"MaxHeight":4096,"MaxSamples":600,"MaxTrackSamples":262144,"MaxSampleBytes":8388608,"PosterWidth":1280}}` + if string(b) != want { + t.Errorf("request wire form\n got %s\nwant %s", b, want) + } + b, _ = json.Marshal(Response{ID: 7, Format: "mp4", MIME: "video/mp4", Codec: "avc1", Width: 2, Height: 3, Duration: 1.5, Decodable: true, Image: "image/jpeg"}) + const wantRes = `{"id":7,"format":"mp4","mime":"video/mp4","codec":"avc1","width":2,"height":3,"duration":1.5,"decodable":true,"image":"image/jpeg"}` + if string(b) != wantRes { + t.Errorf("response wire form\n got %s\nwant %s", b, wantRes) + } + b, _ = json.Marshal(Response{ID: 1, Code: CodeNotHeld, Error: "x"}) + if string(b) != `{"id":1,"code":"video.notheld","error":"x"}` || (Response{ID: 1, Code: CodeLimit}).OK() || !(Response{}).OK() { + t.Errorf("refusal wire form %s", b) + } +} + +func TestDecodeRequest(t *testing.T) { + req, err := DecodeRequest([]byte(` {"id":3,"op":"probe","key":"5-1f","future":true} `)) + if err != nil || req.ID != 3 || req.Op != OpProbe || req.Key != "5-1f" { + t.Fatalf("a request with an unknown field: %+v, %v", req, err) + } + for name, tc := range map[string]struct { + in string + code string + id int + }{ + "not json": {"hello", CodeSyntax, 0}, + "empty": {"", CodeSyntax, 0}, + "wrong type": {`{"id":9,"op":5}`, CodeSyntax, 9}, + "two values": {`{"id":4} {"id":5}`, CodeSyntax, 4}, + "trailing junk": {`{"id":4}x`, CodeSyntax, 4}, + "long key": {`{"id":6,"key":"` + strings.Repeat("k", MaxKeyBytes+1) + `"}`, CodeSyntax, 6}, + "huge header": {`{"id":8,"op":"` + strings.Repeat("o", MaxHeaderBytes) + `"}`, CodeLimit, 0}, + "id out of range": {`{"id":1e999}`, CodeSyntax, 0}, + } { + req, err := DecodeRequest([]byte(tc.in)) + var e *Error + if !errors.As(err, &e) || e.Code != tc.code || req.ID != tc.id { + t.Errorf("%s: id %d, %v; want %s, id %d", name, req.ID, err, tc.code, tc.id) + } + } +} + +func TestFingerprint(t *testing.T) { + a, b := Fingerprint([]byte("abc")), Fingerprint([]byte("abd")) + if a == b || !strings.HasPrefix(a, "3-") || Fingerprint(nil) != "0-0" { + t.Errorf("fingerprints %q %q %q", a, b, Fingerprint(nil)) + } +} + +func TestErrorMessage(t *testing.T) { + if (&Error{CodeLimit, "m"}).Error() != "m" { + t.Error("Error() is the message") + } +} diff --git a/proto/testdata/fuzz/FuzzClampOnlyLowers/boundaries b/proto/testdata/fuzz/FuzzClampOnlyLowers/boundaries new file mode 100644 index 0000000..f3977e8 --- /dev/null +++ b/proto/testdata/fuzz/FuzzClampOnlyLowers/boundaries @@ -0,0 +1,10 @@ +go test fuzz v1 +int(0) +int(-1) +int(1) +int(4097) +int(4096) +int(600) +int(601) +int(8388609) +int(1281) diff --git a/proto/testdata/fuzz/FuzzDecodeRequest/float-limit b/proto/testdata/fuzz/FuzzDecodeRequest/float-limit new file mode 100644 index 0000000..be19d84 --- /dev/null +++ b/proto/testdata/fuzz/FuzzDecodeRequest/float-limit @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("{\"id\":3,\"limits\":{\"MaxBytes\":1e30}}") diff --git a/proto/testdata/fuzz/FuzzDecodeRequest/huge-limits b/proto/testdata/fuzz/FuzzDecodeRequest/huge-limits new file mode 100644 index 0000000..2c704ce --- /dev/null +++ b/proto/testdata/fuzz/FuzzDecodeRequest/huge-limits @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("{\"id\":2,\"op\":\"probe\",\"key\":\"0-0\",\"limits\":{\"MaxBytes\":9223372036854775807,\"MaxBoxes\":-1,\"MaxDepth\":0,\"MaxWidth\":1099511627776,\"PosterWidth\":-9223372036854775808}}") diff --git a/proto/testdata/fuzz/FuzzDecodeRequest/two-values b/proto/testdata/fuzz/FuzzDecodeRequest/two-values new file mode 100644 index 0000000..576301f --- /dev/null +++ b/proto/testdata/fuzz/FuzzDecodeRequest/two-values @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("{\"id\":4} {\"id\":5}") diff --git a/renovate.json b/renovate.json new file mode 100644 index 0000000..87842c8 --- /dev/null +++ b/renovate.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "extends": ["github>go-avkit/.github"] +} diff --git a/serve/fuzz_test.go b/serve/fuzz_test.go new file mode 100644 index 0000000..78fbd8e --- /dev/null +++ b/serve/fuzz_test.go @@ -0,0 +1,75 @@ +// Copyright (c) 2026, go-avkit +// SPDX-License-Identifier: BSD-3-Clause + +package serve + +import ( + "bytes" + "image/jpeg" + "math" + "testing" + + "github.com/go-avkit/worker/proto" +) + +// FuzzHandle feeds Handle hostile requests (any operation, key, time and ALL +// NINE limits) with hostile payloads (seeded from real files and from the +// laced-block bomb). Whatever comes in: no panic, an answer that carries the +// request's ID, a refusal that has a known code and a message, a successful +// poster that is a JPEG of the size it says, and sizes within the worker's own +// bounds, which no request raises. The corpus in testdata/fuzz runs as ordinary +// tests. +func FuzzHandle(f *testing.F) { + for _, n := range []string{"bframes.mp4", "bframes.mkv", "hvc1.mp4"} { + d := read(f, n) + f.Add(d, "poster", 0.5, true, 0, 0, 0, 0, 0, 0, 0, 0, 0) + f.Add(d, "probe", 0.0, true, 1, 3, 1, 8, 8, 1, 1, 1, 1) + } + f.Add([]byte(nil), "poster", -1.0, false, 0, 0, 0, 0, 0, 0, 0, 0, 0) + m := math.MaxInt + f.Add(ftyp, "poster", 1e300, true, m, m, m, m, m, m, m, m, m) + f.Add([]byte("hello"), "\xff\x00", 0.0, true, -5, -5, -5, -5, -5, -5, -5, -5, -5) + f.Add(laced(2000, 256, 1, false), "probe", 0.0, true, m, m, m, m, m, m, m, m, m) + f.Add(laced(300, 256, 2, true), "poster", 0.0, true, 0, 0, 0, 0, 0, 0, 5000, 0, 0) + known := map[string]bool{proto.CodeLimit: true, proto.CodeSyntax: true, proto.CodeCodec: true, proto.CodeNotHeld: true} + s := &Server{} + f.Fuzz(func(t *testing.T, data []byte, op string, tm float64, hasData bool, + maxBytes, maxBoxes, maxDepth, maxWidth, maxHeight, maxSamples, maxTrackSamples, maxSampleBytes, posterW int) { + if len(data) > 1<<20 { + return + } + ask := proto.Limits{ + MaxBytes: maxBytes, MaxBoxes: maxBoxes, MaxDepth: maxDepth, MaxWidth: maxWidth, MaxHeight: maxHeight, + MaxSamples: maxSamples, MaxTrackSamples: maxTrackSamples, MaxSampleBytes: maxSampleBytes, PosterWidth: posterW, + } + req := proto.Request{ID: 7, Op: op, Key: proto.Fingerprint(data), HasData: hasData, T: tm, Limits: ask} + res, img := s.Handle(req, data) + if res.ID != 7 { + t.Fatalf("answer to id %d", res.ID) + } + if !res.OK() { + if !known[res.Code] || res.Error == "" || img != nil { + t.Fatalf("refusal %+v with %d image bytes", res, len(img)) + } + return + } + eff := proto.Clamp(ask) + if op == proto.OpPoster { + pic, err := jpeg.Decode(bytes.NewReader(img)) + if err != nil || pic.Bounds().Dx() != res.Width || pic.Bounds().Dy() != res.Height { + t.Fatalf("the poster is not the JPEG it says: %v", err) + } + if res.Width > eff.PosterWidth { + t.Fatalf("a poster %d wide, over the clamped width %d", res.Width, eff.PosterWidth) + } + } + // a frame is within the limits of THIS request, and so within the worker's + if res.Width > eff.MaxWidth && op == proto.OpProbe || res.Height > eff.MaxHeight && op == proto.OpProbe || + res.Width > proto.DefaultLimits.MaxWidth || res.Height > proto.DefaultLimits.MaxHeight { + t.Fatalf("a frame %dx%d over the bounds %dx%d", res.Width, res.Height, eff.MaxWidth, eff.MaxHeight) + } + if len(data) > eff.MaxBytes && hasData { + t.Fatalf("a file of %d bytes accepted, over MaxBytes %d", len(data), eff.MaxBytes) + } + }) +} diff --git a/serve/lace_test.go b/serve/lace_test.go new file mode 100644 index 0000000..c077168 --- /dev/null +++ b/serve/lace_test.go @@ -0,0 +1,117 @@ +// Copyright (c) 2026, go-avkit +// SPDX-License-Identifier: BSD-3-Clause + +package serve + +import ( + "math" + "testing" + + "github.com/go-avkit/worker/proto" +) + +var ( + ebmlHead = []byte{0x1A, 0x45, 0xDF, 0xA3, 0x80} + unknown = []byte{0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF} +) + +// block is a SimpleBlock of `lacing` (0x02 Xiph, 0x04 fixed, 0x06 EBML) whose +// count byte says n frames; the 7 bytes of the element stand for n frames to a +// reader that unlaces up front (go-avkit/avkit#120). The frame bytes are not +// there: the header is what the pre-scan reads. +func block(id byte, track byte, lacing byte, n int) []byte { + body := []byte{0x80 | track, 0, 0, lacing} + if lacing != 0 { + body = append(body, byte(n-1)) + } + return append([]byte{id, 0x80 | byte(len(body))}, body...) +} + +// laced is a Matroska file of blocks laced n frames each, cycling over tracks. +func laced(blocks, n, tracks int, group bool) []byte { + d := append(append([]byte{}, ebmlHead...), 0x18, 0x53, 0x80, 0x67) + d = append(append(d, unknown...), 0x1F, 0x43, 0xB6, 0x75) + d = append(d, unknown...) + for i := range blocks { + b := block(idSimpleBlock, byte(1+i%tracks), 0x04, n) + if group { // a BlockGroup (0xA0) around a Block (0xA1) + in := block(idBlock, byte(1+i%tracks), 0x04, n) + b = append([]byte{0xA0, 0x80 | byte(len(in))}, in...) + } + d = append(d, b...) + } + return d +} + +func TestBlockFrames(t *testing.T) { + for name, tc := range map[string]struct { + body []byte + track uint64 + frames int + ok bool + }{ + "unlaced": {[]byte{0x81, 0, 0, 0x80, 'x'}, 1, 1, true}, + "fixed 256": {[]byte{0x81, 0, 0, 0x04, 0xFF}, 1, 256, true}, + "xiph 3": {[]byte{0x82, 0, 0, 0x02, 2}, 2, 3, true}, + "ebml 2": {[]byte{0x83, 0, 0, 0x06, 1}, 3, 2, true}, + "track on 2 byte": {[]byte{0x40, 0x05, 0, 0, 0x04, 7}, 5, 8, true}, + "short": {[]byte{0x81, 0, 0}, 0, 0, false}, + "laced no count": {[]byte{0x81, 0, 0, 0x04}, 0, 0, false}, + "empty": {nil, 0, 0, false}, + "bad track": {[]byte{0x00, 0, 0, 0}, 0, 0, false}, + } { + track, frames, ok := blockFrames(tc.body) + if ok != tc.ok || frames != tc.frames || (ok && track != tc.track) { + t.Errorf("%s: track %d, %d frames, %v", name, track, frames, ok) + } + } +} + +// The pre-scan bounds the frames, laced ones included: a track may list +// MaxTrackSamples (262144) and the file twice that. 1023 blocks of 256 frames +// are 261,888; 1025 are 262,400. +func TestLacedFramesAreCountedAtTheBound(t *testing.T) { + lim := proto.DefaultLimits + if _, _, err := sniff(laced(1023, 256, 1, false), lim); err != nil { + t.Errorf("under the bound: %v", err) + } + for _, group := range []bool{false, true} { + if _, _, err := sniff(laced(1025, 256, 1, group), lim); err == nil || err.(*proto.Error).Code != proto.CodeLimit { + t.Errorf("over the bound (group %v): %v", group, err) + } + } + // a request lowers the bound: 1000 blocks are 256,000 frames + low := lim + low.MaxTrackSamples = 100000 + if _, _, err := sniff(laced(1000, 256, 1, false), low); err == nil { + t.Error("a lowered MaxTrackSamples is not applied to laced frames") + } + // three tracks each under the bound, together over twice it + if _, _, err := sniff(laced(3000, 256, 3, false), lim); err == nil { + t.Error("the total over twice the track bound is accepted") + } +} + +// The bomb of go-avkit/avkit#120: a file of a few KB of laced blocks, which a +// reader that unlaces up front would turn into hundreds of MiB. It is refused +// as video.limit before the reader runs, and the refusal allocates next to +// nothing, under a memory limit. +func TestLacedBlockBombsAreRefused(t *testing.T) { + huge := proto.Limits{MaxBytes: math.MaxInt, MaxTrackSamples: math.MaxInt} + for _, tc := range []struct { + name string + blocks, tracks int + group bool + }{ + {"10000 laced blocks", 10000, 1, false}, + {"10000 laced block groups", 10000, 1, true}, + {"10000 laced blocks, 3 tracks", 10000, 3, false}, + {"1000 laced blocks, lowered", 1000, 1, false}, + } { + lim := huge + if tc.name == "1000 laced blocks, lowered" { + lim = proto.Limits{MaxTrackSamples: 100000} + } + bomb(t, tc.name, laced(tc.blocks, 256, tc.tracks, tc.group), lim, proto.CodeLimit, 1<<20) + } +} diff --git a/serve/poster.go b/serve/poster.go new file mode 100644 index 0000000..b752b18 --- /dev/null +++ b/serve/poster.go @@ -0,0 +1,154 @@ +// Copyright (c) 2026, go-avkit +// SPDX-License-Identifier: BSD-3-Clause + +package serve + +import ( + "bytes" + "errors" + "image" + "image/color" + "image/jpeg" + "math" + + "github.com/go-avkit/avkit/container" + "github.com/go-avkit/decode" + "github.com/go-avkit/worker/proto" +) + +// file is a video file that passed the limits, and what the container says of +// it: the reader is built once and serves the posters asked later. +type file struct { + data []byte + format, mime, codec string + width, height int + duration float64 + decodable bool + reader *container.Reader + track uint32 +} + +// open reads the description of data, which sniff has accepted. +func open(data []byte, format, mime string, lim proto.Limits) (*file, error) { + r, err := container.NewReader(data) + if err != nil { + return nil, refuse(proto.CodeSyntax, "the %s container cannot be read: %v", format, err) + } + f := &file{data: data, format: format, mime: mime, reader: r} + cf := r.File() + for _, t := range cf.Tracks { + if t.Kind == container.Video { + f.codec, f.width, f.height, f.track = t.Codec, t.Width, t.Height, t.ID + break + } + } + if f.track == 0 { + return nil, refuse(proto.CodeSyntax, "the file has no video track") + } + if cf.Timescale > 0 { + f.duration = float64(cf.Duration) / float64(cf.Timescale) + } + f.decodable = f.codec == "avc1" || f.codec == "avc3" + return f, f.frameWithin(lim) +} + +// frameWithin refuses a frame outside the limits. +func (f *file) frameWithin(lim proto.Limits) error { + if f.width <= 0 || f.height <= 0 || f.width > lim.MaxWidth || f.height > lim.MaxHeight { + return refuse(proto.CodeLimit, "the frame is %dx%d; at most %dx%d are read", f.width, f.height, lim.MaxWidth, lim.MaxHeight) + } + return nil +} + +// poster decodes the picture shown at t seconds (the one before it, if none is +// exactly at t; the last one when t is past the end), scaled down to +// lim.PosterWidth, as a JPEG. +func (f *file) poster(t float64, lim proto.Limits) ([]byte, int, int, error) { + if !f.decodable { + return nil, 0, 0, refuse(proto.CodeCodec, "the poster of a %s video cannot be decoded (H.264 only)", f.codec) + } + if math.IsNaN(t) || math.IsInf(t, 0) { + return nil, 0, 0, refuse(proto.CodeSyntax, "#t=%g is not a time in the video", t) + } + cfg := decode.PosterConfig{ + Config: decode.Config{MaxFrameMBs: (lim.MaxWidth/16 + 1) * (lim.MaxHeight/16 + 1), MaxSampleBytes: lim.MaxSampleBytes}, + MaxSamples: lim.MaxSamples, + MaxTrackSamples: lim.MaxTrackSamples, + } + fr, err := decode.PosterFrame(f.reader, f.track, t, cfg) + if err != nil { + switch { + case errors.Is(err, decode.ErrPosterLimit), errors.Is(err, decode.ErrOverLimit): + return nil, 0, 0, refuse(proto.CodeLimit, "the poster at %gs is over a limit of this worker: %v", t, err) + case errors.Is(err, decode.ErrUnsupported): + return nil, 0, 0, refuse(proto.CodeCodec, "the H.264 stream uses a tool that is not decoded: %v", err) + case errors.Is(err, decode.ErrTime): + return nil, 0, 0, refuse(proto.CodeSyntax, "#t=%g is not a time in the video", t) + } + return nil, 0, 0, refuse(proto.CodeSyntax, "the poster cannot be decoded: %v", err) + } + img := toRGBA(fr, lim.PosterWidth) + var buf bytes.Buffer + if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 85}); err != nil { + return nil, 0, 0, refuse(proto.CodeSyntax, "the poster cannot be encoded: %v", err) + } + return buf.Bytes(), img.Bounds().Dx(), img.Bounds().Dy(), nil +} + +// toRGBA converts a 4:2:0 or 4:0:0 8-bit picture (BT.601 below 720 lines, +// BT.709 above; limited range) and scales it down by averaging boxes to at +// most width pixels across. +func toRGBA(f decode.Frame, width int) *image.RGBA { + w, h := f.Width, f.Height + step := 1 + if width > 0 && w > width { + step = (w + width - 1) / width + } + ow, oh := max(w/step, 1), max(h/step, 1) + out := image.NewRGBA(image.Rect(0, 0, ow, oh)) + kr, kb := 0.299, 0.114 + if h >= 720 { + kr, kb = 0.2126, 0.0722 + } + kg := 1 - kr - kb + cl := func(v float64) uint8 { + if v < 0 { + return 0 + } + if v > 255 { + return 255 + } + return uint8(v + 0.5) + } + for y := 0; y < oh; y++ { + for x := 0; x < ow; x++ { + var sr, sg, sb, n float64 + for dy := 0; dy < step; dy++ { + for dx := 0; dx < step; dx++ { + px, py := x*step+dx, y*step+dy + if px >= w || py >= h { + continue + } + Y := (float64(f.Y[py*f.YStride+px]) - 16) * 255 / 219 + cb, cr := 0.0, 0.0 + if f.Chroma != decode.Chroma400 && len(f.Cb) > 0 { + ci := (py/2)*f.CStride + px/2 + if ci < len(f.Cb) && ci < len(f.Cr) { + cb = (float64(f.Cb[ci]) - 128) * 255 / 224 + cr = (float64(f.Cr[ci]) - 128) * 255 / 224 + } + } + r := Y + 2*(1-kr)*cr + b := Y + 2*(1-kb)*cb + g := (Y - kr*r - kb*b) / kg + sr, sg, sb, n = sr+r, sg+g, sb+b, n+1 + } + } + if n == 0 { + continue + } + out.SetRGBA(x, y, color.RGBA{cl(sr / n), cl(sg / n), cl(sb / n), 255}) + } + } + return out +} diff --git a/serve/scan.go b/serve/scan.go new file mode 100644 index 0000000..d4d5e32 --- /dev/null +++ b/serve/scan.go @@ -0,0 +1,199 @@ +// Copyright (c) 2026, go-avkit +// SPDX-License-Identifier: BSD-3-Clause + +package serve + +import ( + "bytes" + "encoding/binary" + "fmt" + + "github.com/go-avkit/worker/proto" +) + +func refuse(code, format string, a ...any) error { + return &proto.Error{Code: code, Msg: fmt.Sprintf(format, a...)} +} + +// sniff checks a file against the limits that need no container reader (its +// size, the number and nesting of its boxes or elements) and says what it is +// by its first bytes. These run before the container reader is asked anything, +// whatever the client said of the file. +func sniff(data []byte, lim proto.Limits) (format, mime string, err error) { + if len(data) > lim.MaxBytes { + return "", "", refuse(proto.CodeLimit, "the file is %d bytes; at most %d are read", len(data), lim.MaxBytes) + } + switch { + case len(data) >= 12 && string(data[4:8]) == "ftyp": + return "mp4", "video/mp4", scanBoxes(data, lim) + case len(data) >= 4 && bytes.Equal(data[:4], []byte{0x1A, 0x45, 0xDF, 0xA3}): + return "webm", "video/webm", scanEBML(data, lim) + } + return "", "", refuse(proto.CodeSyntax, "not an MP4 or WebM file") +} + +// mp4Containers are the boxes whose children are boxes (ISO/IEC 14496-12: +// moov, trak, mdia, minf, stbl, dinf, edts, udta, mvex, moof, traf, mfra, sinf, +// schi). meta, a full box, holds boxes after four bytes. +var mp4Containers = map[string]bool{ + "moov": true, "trak": true, "mdia": true, "minf": true, "stbl": true, "dinf": true, "edts": true, + "udta": true, "mvex": true, "moof": true, "traf": true, "mfra": true, "sinf": true, "schi": true, "meta": true, +} + +// scanBoxes walks the boxes without decoding any: it counts them and measures +// their nesting, so that a file made of millions of empty boxes is refused +// before the container reader builds a tree of them. +func scanBoxes(data []byte, lim proto.Limits) error { + count := 0 + var walk func(b []byte, depth int) error + walk = func(b []byte, depth int) error { + if depth > lim.MaxDepth { + return refuse(proto.CodeLimit, "boxes nest deeper than %d", lim.MaxDepth) + } + for len(b) >= 8 { + if count++; count > lim.MaxBoxes { + return refuse(proto.CodeLimit, "the file holds more than %d boxes", lim.MaxBoxes) + } + size, hdr := uint64(binary.BigEndian.Uint32(b)), 8 + typ := string(b[4:8]) + if size == 1 { + if len(b) < 16 { + return nil + } + size, hdr = binary.BigEndian.Uint64(b[8:]), 16 + } else if size == 0 { + size = uint64(len(b)) + } + if size < uint64(hdr) || size > uint64(len(b)) { + return nil // truncated or malformed: the container reader judges + } + if mp4Containers[typ] { + body := b[hdr:size] + if typ == "meta" { + if len(body) < 4 { + body = nil + } else { + body = body[4:] + } + } + if err := walk(body, depth+1); err != nil { + return err + } + } + b = b[size:] + } + return nil + } + return walk(data, 1) +} + +// ebmlMasters are the Matroska elements whose children are elements: Segment, +// SeekHead, Info, Tracks, TrackEntry, Video, Cluster, BlockGroup, Cues, +// CuePoint, CueTrackPositions, Tags, Tag, Chapters, EditionEntry, ChapterAtom, +// BlockAdditions, Attachments. +var ebmlMasters = map[uint32]bool{ + 0x18538067: true, 0x114D9B74: true, 0x1549A966: true, 0x1654AE6B: true, 0xAE: true, 0xE0: true, + 0x1F43B675: true, 0xA0: true, 0x1C53BB6B: true, 0xBB: true, 0xB7: true, 0x1254C367: true, 0x7373: true, + 0x1043A770: true, 0x45B9: true, 0xB6: true, 0x75A1: true, 0x1941A469: true, 0x61A7: true, 0x4DBB: true, +} + +func ebmlVint(b []byte, keepMarker bool) (v uint64, n int) { + if len(b) == 0 || b[0] == 0 { + return 0, 0 + } + n = 1 + for m := byte(0x80); b[0]&m == 0; m >>= 1 { + n++ + } + if n > len(b) || n > 8 { + return 0, 0 + } + v = uint64(b[0]) + if !keepMarker { + v &= 0xFF >> uint(n) + } + for _, c := range b[1:n] { + v = v<<8 | uint64(c) + } + return v, n +} + +// The Matroska block elements: a SimpleBlock, and the Block of a BlockGroup. +const ( + idSimpleBlock = 0xA3 + idBlock = 0xA1 +) + +// blockFrames is the number of frames a block carries, from its header alone +// (Matroska, "Block Lacing"): the track number (a vint), a 16-bit timecode, a +// flags byte whose bits 0x06 name the lacing (none, Xiph, fixed-size, EBML), and +// for a laced block a byte holding the number of frames less one. A reader +// unlaces every block up front, so a 7-byte block can stand for 256 frames +// (go-avkit/avkit#120). ok is false for a block too short to say; the container +// reader judges it. +func blockFrames(body []byte) (track uint64, frames int, ok bool) { + track, n := ebmlVint(body, false) + if n == 0 || len(body) < n+3 { + return 0, 0, false + } + if body[n+2]&0x06 == 0 { + return track, 1, true + } + if len(body) < n+4 { + return 0, 0, false + } + return track, int(body[n+3]) + 1, true +} + +// scanEBML counts and nests the elements as scanBoxes does the boxes, and +// counts the frames the blocks hold, laced ones included: at most +// lim.MaxTrackSamples for one track and twice that for the file, since the +// container reader builds a record for every frame before the first poster is +// asked for. +func scanEBML(data []byte, lim proto.Limits) error { + count, total := 0, 0 + perTrack := map[uint64]int{} + var walk func(b []byte, depth int) error + walk = func(b []byte, depth int) error { + if depth > lim.MaxDepth { + return refuse(proto.CodeLimit, "elements nest deeper than %d", lim.MaxDepth) + } + for len(b) > 0 { + if count++; count > lim.MaxBoxes { + return refuse(proto.CodeLimit, "the file holds more than %d elements", lim.MaxBoxes) + } + id, n := ebmlVint(b, true) + if n == 0 { + return nil + } + size, m := ebmlVint(b[n:], false) + if m == 0 { + return nil + } + body := b[n+m:] + unknown := size == (uint64(1)<<(7*uint(m)))-1 + if unknown || size > uint64(len(body)) { + size = uint64(len(body)) // unknown or cut short: to the end + } + if ebmlMasters[uint32(id)] { + if err := walk(body[:size], depth+1); err != nil { + return err + } + } else if id == idSimpleBlock || id == idBlock { + if track, frames, ok := blockFrames(body[:size]); ok { + perTrack[track] += frames + total += frames + if perTrack[track] > lim.MaxTrackSamples { + return refuse(proto.CodeLimit, "track %d holds more than %d frames (laced blocks counted)", track, lim.MaxTrackSamples) + } + if total > 2*lim.MaxTrackSamples { + return refuse(proto.CodeLimit, "the file holds more than %d frames (laced blocks counted)", 2*lim.MaxTrackSamples) + } + } + } + b = body[size:] + } + return nil + } + return walk(data, 1) +} diff --git a/serve/serve.go b/serve/serve.go new file mode 100644 index 0000000..bbc6985 --- /dev/null +++ b/serve/serve.go @@ -0,0 +1,149 @@ +// Copyright (c) 2026, go-avkit +// SPDX-License-Identifier: BSD-3-Clause + +// Package serve answers proto requests with go-avkit: the worker's side of the +// protocol. It links go-avkit's container reader (MP4, WebM / Matroska) and +// go-avkit/decode's H.264 decoder, and nothing of a host: no syscall/js, so it +// is tested natively and run in a Web Worker by cmd/avkit-worker. +// +// A file is untrusted. Whatever the client said of it (its key, its size, its +// limits), it is checked against the clamped limits (proto.Clamp) before the +// container reader is asked anything, and again, against the limits of the +// request at hand, each time a held file is read. +package serve + +import ( + "errors" + "fmt" + "sync" + + "github.com/go-avkit/worker/proto" +) + +// Keep is how many files a Server holds: the project's videos that the +// renders of a page ask about, the most recent ones. Two 64 MiB files at most. +const Keep = 2 + +// Server holds the files it was sent and answers requests about them. Its +// methods are safe for concurrent use; they run one at a time. +type Server struct { + mu sync.Mutex + files []held // most recent last +} + +type held struct { + key string + file *file +} + +// Handle answers one request. payload is the file when req.HasData, and the +// picture of a poster's answer is the second result. The limits are +// proto.Clamp(req.Limits): a request lowers them, never raises them. +// +// A panic in the container reader or the decoder, on a file nobody foresaw, is +// answered as a video.syntax refusal and the worker keeps serving. +func (s *Server) Handle(req proto.Request, payload []byte) (res proto.Response, img []byte) { + s.mu.Lock() + defer s.mu.Unlock() + defer func() { + if p := recover(); p != nil { + res = proto.Response{ID: req.ID, Code: proto.CodeSyntax, Error: fmt.Sprintf("the file could not be read (internal error: %v)", p)} + img = nil + } + }() + beforeHandle() + return s.handle(req, payload) +} + +// beforeHandle is a seam for the test of the recover: nothing else sets it. +var beforeHandle = func() {} + +func (s *Server) handle(req proto.Request, payload []byte) (proto.Response, []byte) { + res := proto.Response{ID: req.ID} + lim := proto.Clamp(req.Limits) + if req.Op != proto.OpPoster && req.Op != proto.OpProbe { + res.Code, res.Error = proto.CodeSyntax, "unknown operation "+quote(req.Op) + return res, nil + } + f, err := s.file(req, payload, lim) + if err != nil { + if errors.Is(err, errNotHeld) { + res.Code, res.Error = proto.CodeNotHeld, "the worker does not hold this file" + return res, nil + } + res.Code, res.Error = codeOf(err) + return res, nil + } + res.Format, res.MIME, res.Codec = f.format, f.mime, f.codec + res.Width, res.Height, res.Duration, res.Decodable = f.width, f.height, f.duration, f.decodable + if req.Op == proto.OpProbe { + return res, nil + } + jpg, w, h, err := f.poster(req.T, lim) + if err != nil { + res.Code, res.Error = codeOf(err) + return res, nil + } + res.Width, res.Height, res.Image = w, h, "image/jpeg" + return res, jpg +} + +var errNotHeld = errors.New("not held") + +// file is the checked file a request names: the payload, opened and kept, or +// the copy held under the key, checked again against this request's limits. +func (s *Server) file(req proto.Request, payload []byte, lim proto.Limits) (*file, error) { + if !req.HasData { + for _, h := range s.files { + if h.key == req.Key { + if _, _, err := sniff(h.file.data, lim); err != nil { + return nil, err + } + return h.file, h.file.frameWithin(lim) + } + } + return nil, errNotHeld + } + format, mime, err := sniff(payload, lim) + if err != nil { + return nil, err + } + f, err := open(payload, format, mime, lim) + if err != nil { + return nil, err + } + // a file is held under the key the client gave it: the worker does not + // trust it to be the file's checksum, only to name what to look up + s.files = append(without(s.files, req.Key), held{req.Key, f}) + if len(s.files) > Keep { + s.files = s.files[len(s.files)-Keep:] + } + return f, nil +} + +func without(h []held, key string) []held { + out := make([]held, 0, len(h)+1) + for _, x := range h { + if x.key != key { + out = append(out, x) + } + } + return out +} + +// codeOf is a refusal's code and message; an error with no code is +// video.syntax. +func codeOf(err error) (code, msg string) { + var e *proto.Error + if errors.As(err, &e) { + return e.Code, e.Msg + } + return proto.CodeSyntax, err.Error() +} + +func quote(s string) string { + if len(s) > 32 { + s = s[:32] + "..." + } + return `"` + s + `"` +} diff --git a/serve/serve_test.go b/serve/serve_test.go new file mode 100644 index 0000000..67f5167 --- /dev/null +++ b/serve/serve_test.go @@ -0,0 +1,300 @@ +// Copyright (c) 2026, go-avkit +// SPDX-License-Identifier: BSD-3-Clause + +package serve + +import ( + "bytes" + "encoding/binary" + "image/jpeg" + "math" + "os" + "path/filepath" + "runtime" + "runtime/debug" + "strings" + "testing" + + "github.com/go-avkit/worker/proto" +) + +func read(t testing.TB, name string) []byte { + t.Helper() + b, err := os.ReadFile(filepath.Join("testdata", name)) + if err != nil { + t.Fatal(err) + } + return b +} + +func send(s *Server, op string, data []byte, tm float64, lim proto.Limits) (proto.Response, []byte) { + return s.Handle(proto.Request{ID: 1, Op: op, Key: proto.Fingerprint(data), HasData: true, T: tm, Limits: lim}, data) +} + +func TestProbeAndPoster(t *testing.T) { + for _, name := range []string{"bframes.mp4", "bframes.mkv"} { + data := read(t, name) + s := &Server{} + res, img := send(s, proto.OpProbe, data, 0, proto.Limits{}) + if !res.OK() || img != nil || !res.Decodable || res.Codec != "avc1" || res.Width <= 0 || res.Duration <= 0 || res.ID != 1 { + t.Fatalf("%s probe: %+v", name, res) + } + for _, at := range []float64{0, 0.3, 1000} { // 1000: past the end, the last picture + res, img := send(s, proto.OpPoster, data, at, proto.Limits{}) + if !res.OK() || res.Image != "image/jpeg" { + t.Fatalf("%s poster at %g: %+v", name, at, res) + } + pic, err := jpeg.Decode(bytes.NewReader(img)) + if err != nil || pic.Bounds().Dx() != res.Width || pic.Bounds().Dy() != res.Height { + t.Fatalf("%s at %g: not the JPEG it says (%v)", name, at, err) + } + } + } +} + +func TestPosterWidthIsLoweredNotRaised(t *testing.T) { + data := read(t, "bframes.mp4") + res, _ := send(&Server{}, proto.OpPoster, data, 0, proto.Limits{}) + if res.Width > proto.DefaultLimits.PosterWidth { + t.Fatalf("default poster is %d wide", res.Width) + } + low, _ := send(&Server{}, proto.OpPoster, data, 0, proto.Limits{PosterWidth: res.Width / 2}) + if !low.OK() || low.Width > res.Width/2 { + t.Errorf("a lowered PosterWidth: %+v from %+v", low, res) + } + up, _ := send(&Server{}, proto.OpPoster, data, 0, proto.Limits{PosterWidth: 1 << 30}) + if up.Width != res.Width { + t.Errorf("a raised PosterWidth changed the answer: %d, want %d", up.Width, res.Width) + } +} + +func TestOtherCodecsHaveNoPoster(t *testing.T) { + s := &Server{} + data := read(t, "hvc1.mp4") + if res, _ := send(s, proto.OpProbe, data, 0, proto.Limits{}); !res.OK() || res.Decodable { + t.Fatalf("probe: %+v", res) + } + if res, img := send(s, proto.OpPoster, data, 0, proto.Limits{}); res.Code != proto.CodeCodec || img != nil { + t.Errorf("poster: %+v", res) + } +} + +func TestNotHeldThenResent(t *testing.T) { + s := &Server{} + data := read(t, "bframes.mp4") + key := proto.Fingerprint(data) + ask := proto.Request{ID: 9, Op: proto.OpPoster, Key: key} + if res, _ := s.Handle(ask, nil); res.Code != proto.CodeNotHeld || res.ID != 9 { + t.Fatalf("before: %+v", res) + } + if res, _ := s.Handle(proto.Request{ID: 10, Op: proto.OpProbe, Key: key, HasData: true}, data); !res.OK() { + t.Fatalf("send: %+v", res) + } + if res, img := s.Handle(ask, nil); !res.OK() || len(img) == 0 { + t.Fatalf("held: %+v", res) + } +} + +// The worker keeps the last Keep files; the oldest is let go, a resent file is +// moved to the front, not held twice. +func TestKeepsTheLastTwo(t *testing.T) { + s := &Server{} + a, b, c := read(t, "bframes.mp4"), read(t, "bframes.mkv"), read(t, "hvc1.mp4") + for _, d := range [][]byte{a, b, a, c} { // a is refreshed, so b is the oldest when c comes + if res, _ := send(s, proto.OpProbe, d, 0, proto.Limits{}); !res.OK() { + t.Fatal(res) + } + } + held := func(d []byte) bool { + res, _ := s.Handle(proto.Request{Op: proto.OpProbe, Key: proto.Fingerprint(d)}, nil) + return res.OK() + } + if !held(a) || held(b) || !held(c) || len(s.files) != Keep { + t.Errorf("a %v b %v c %v, %d files", held(a), held(b), held(c), len(s.files)) + } +} + +func TestHeldFileIsCheckedAgainstTheLimitsOfEachRequest(t *testing.T) { + s := &Server{} + data := read(t, "bframes.mp4") + send(s, proto.OpProbe, data, 0, proto.Limits{}) + key := proto.Fingerprint(data) + for name, lim := range map[string]proto.Limits{ + "bytes": {MaxBytes: 100}, "boxes": {MaxBoxes: 3}, "width": {MaxWidth: 8}, "height": {MaxHeight: 8}, + } { + if res, _ := s.Handle(proto.Request{Op: proto.OpProbe, Key: key, Limits: lim}, nil); res.Code != proto.CodeLimit { + t.Errorf("%s: %+v", name, res) + } + } +} + +func TestRefusals(t *testing.T) { + mp4 := read(t, "bframes.mp4") + for name, tc := range map[string]struct { + data []byte + lim proto.Limits + want string + }{ + "not a video": {[]byte("hello, this is text"), proto.Limits{}, proto.CodeSyntax}, + "empty": {nil, proto.Limits{}, proto.CodeSyntax}, + "too big": {mp4, proto.Limits{MaxBytes: 100}, proto.CodeLimit}, + "too many": {mp4, proto.Limits{MaxBoxes: 3}, proto.CodeLimit}, + "too deep": {mp4, proto.Limits{MaxDepth: 1}, proto.CodeLimit}, + "too wide": {mp4, proto.Limits{MaxWidth: 8}, proto.CodeLimit}, + "too high": {mp4, proto.Limits{MaxHeight: 8}, proto.CodeLimit}, + "truncated mp4": {mp4[:40], proto.Limits{}, proto.CodeSyntax}, + "no video": {box("ftyp", []byte("isom\x00\x00\x02\x00isom")), proto.Limits{}, proto.CodeSyntax}, + } { + if res, _ := send(&Server{}, proto.OpProbe, tc.data, 0, tc.lim); res.Code != tc.want || res.Error == "" { + t.Errorf("%s: %+v, want %s", name, res, tc.want) + } + } + if res, _ := (&Server{}).Handle(proto.Request{ID: 4, Op: "format", Key: "x"}, nil); res.Code != proto.CodeSyntax || res.ID != 4 { + t.Errorf("unknown operation: %+v", res) + } + long := strings.Repeat("x", 100) + if res, _ := (&Server{}).Handle(proto.Request{Op: long}, nil); !strings.Contains(res.Error, "...") { + t.Errorf("a long operation is quoted whole: %q", res.Error) + } + if c, m := codeOf(os.ErrNotExist); c != proto.CodeSyntax || m == "" { + t.Errorf("an error with no code: %q %q", c, m) + } +} + +// Each code a worker answers is produced by a minimal input. video.unavailable +// is the one a Server never produces: it always has its reader and decoder, so +// the code is the client's, for a worker it could not reach; a test asserts +// that no input here yields it. +func TestEveryCodeHasAMinimalInput(t *testing.T) { + s := &Server{} + mp4, hvc := read(t, "bframes.mp4"), read(t, "hvc1.mp4") + got := map[string]proto.Response{} + got[proto.CodeLimit], _ = send(s, proto.OpProbe, mp4, 0, proto.Limits{MaxBytes: 1}) + got[proto.CodeSyntax], _ = send(s, proto.OpProbe, []byte("x"), 0, proto.Limits{}) + got[proto.CodeCodec], _ = send(s, proto.OpPoster, hvc, 0, proto.Limits{}) + got[proto.CodeNotHeld], _ = s.Handle(proto.Request{Op: proto.OpProbe, Key: "nothing"}, nil) + for code, res := range got { + if res.Code != code || res.Error == "" { + t.Errorf("%s: %+v", code, res) + } + } + if res, _ := send(s, proto.OpProbe, mp4, 0, proto.Limits{}); !res.OK() { + t.Errorf("control: %+v", res) + } + for _, res := range got { + if res.Code == proto.CodeUnavailable { + t.Errorf("a Server answered %s", res.Code) + } + } +} + +func TestPosterTimes(t *testing.T) { + data := read(t, "bframes.mp4") + s := &Server{} + for _, at := range []float64{-1, math.NaN(), math.Inf(1), math.Inf(-1)} { + if res, _ := send(s, proto.OpPoster, data, at, proto.Limits{}); res.Code != proto.CodeSyntax { + t.Errorf("t=%g: %+v", at, res) + } + } +} + +func TestPosterWorkIsBounded(t *testing.T) { + data := read(t, "bframes.mp4") + var refused bool + for _, at := range []float64{0.4, 0.8, 1.2, 2} { + if res, _ := send(&Server{}, proto.OpPoster, data, at, proto.Limits{MaxSamples: 1}); res.Code == proto.CodeLimit { + refused = true + } + } + if !refused { + t.Error("a poster far from its keyframe is not refused at MaxSamples=1") + } +} + +func box(typ string, body []byte) []byte { + b := make([]byte, 8, 8+len(body)) + binary.BigEndian.PutUint32(b, uint32(8+len(body))) + copy(b[4:], typ) + return append(b, body...) +} + +var ftyp = box("ftyp", []byte("isom\x00\x00\x02\x00isom")) + +// bomb runs one hostile request under a memory limit and asserts that it is +// REFUSED with a code, and that the worker did not build anything near the +// size of what the file claimed: the allocations of the call, beyond the +// payload that was handed in, stay under budget. +func bomb(t *testing.T, name string, data []byte, lim proto.Limits, want string, budget uint64) { + t.Helper() + old := debug.SetMemoryLimit(512 << 20) + defer debug.SetMemoryLimit(old) + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + res, img := send(&Server{}, proto.OpPoster, data, 0, lim) + runtime.ReadMemStats(&after) + if res.Code != want || img != nil { + t.Fatalf("%s: %+v, want a %s refusal", name, res, want) + } + got := after.TotalAlloc - before.TotalAlloc + t.Logf("%s: %d bytes in, refused %s, %d bytes allocated", name, len(data), res.Code, got) + if got > budget { + t.Errorf("%s: refusing cost %d bytes of allocation (budget %d)", name, got, budget) + } +} + +func TestBombsAreRefusedWithinMemory(t *testing.T) { + many := append([]byte{}, ftyp...) + for range 300000 { + many = append(many, box("free", nil)...) + } + deep := box("free", nil) + for range 40 { + deep = box("trak", box("moov", deep)) + } + deep = append(append([]byte{}, ftyp...), deep...) + ebml := []byte{0x1A, 0x45, 0xDF, 0xA3, 0x80, 0x18, 0x53, 0x80, 0x67, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF} + for range 300000 { + ebml = append(ebml, 0xEC, 0x80) + } + ebmlDeep := []byte{0x1A, 0x45, 0xDF, 0xA3, 0x80} + for range 40 { + ebmlDeep = append(ebmlDeep, 0x1F, 0x43, 0xB6, 0x75, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF) + } + // a file one byte over the largest the worker reads: refused on its length + // alone, whatever the request asked for + over := make([]byte, proto.DefaultLimits.MaxBytes+1) + copy(over, ftyp) + huge := proto.Limits{MaxBytes: math.MaxInt, MaxBoxes: math.MaxInt, MaxDepth: math.MaxInt} + + bomb(t, "300000 boxes", many, proto.Limits{}, proto.CodeLimit, 1<<20) + bomb(t, "boxes, a request asking for more", many, huge, proto.CodeLimit, 1<<20) + bomb(t, "deep boxes", deep, huge, proto.CodeLimit, 1<<20) + bomb(t, "300000 elements", ebml, huge, proto.CodeLimit, 1<<20) + bomb(t, "deep elements", ebmlDeep, huge, proto.CodeLimit, 1<<20) + bomb(t, "over the file size", over, huge, proto.CodeLimit, 1<<20) +} + +// A panic in a reader is a refusal, the lock is released and the worker serves +// the next request. +func TestAPanicIsARefusal(t *testing.T) { + s := &Server{} + beforeHandle = func() { panic("boom") } + res, img := s.Handle(proto.Request{ID: 5, Op: proto.OpProbe}, nil) + beforeHandle = func() {} + if res.Code != proto.CodeSyntax || res.ID != 5 || img != nil || !strings.Contains(res.Error, "boom") { + t.Errorf("%+v", res) + } + if res, _ := send(s, proto.OpProbe, read(t, "bframes.mp4"), 0, proto.Limits{}); !res.OK() { + t.Errorf("after the panic: %+v", res) + } +} + +// A held file is not a way round the bounds: nothing is held for a refused file. +func TestRefusedFileIsNotHeld(t *testing.T) { + s := &Server{} + send(s, proto.OpProbe, []byte("not a video"), 0, proto.Limits{}) + if len(s.files) != 0 { + t.Errorf("%d files held", len(s.files)) + } +} diff --git a/serve/testdata/bframes.mkv b/serve/testdata/bframes.mkv new file mode 100644 index 0000000..fe92db0 Binary files /dev/null and b/serve/testdata/bframes.mkv differ diff --git a/serve/testdata/bframes.mp4 b/serve/testdata/bframes.mp4 new file mode 100644 index 0000000..ccac39c Binary files /dev/null and b/serve/testdata/bframes.mp4 differ diff --git a/serve/testdata/fuzz/FuzzHandle/ebml-few-boxes b/serve/testdata/fuzz/FuzzHandle/ebml-few-boxes new file mode 100644 index 0000000..635976a --- /dev/null +++ b/serve/testdata/fuzz/FuzzHandle/ebml-few-boxes @@ -0,0 +1,14 @@ +go test fuzz v1 +[]byte("\x1a\x45\xdf\xa3\x80\x18\x53\x80\x67\x01\xff\xff\xff\xff\xff\xff\xff\xec\x80") +string("probe") +float64(0) +bool(true) +int(0) +int(2) +int(1) +int(0) +int(0) +int(0) +int(0) +int(0) +int(0) diff --git a/serve/testdata/fuzz/FuzzHandle/ftyp-huge-limits b/serve/testdata/fuzz/FuzzHandle/ftyp-huge-limits new file mode 100644 index 0000000..fbb1d5f --- /dev/null +++ b/serve/testdata/fuzz/FuzzHandle/ftyp-huge-limits @@ -0,0 +1,14 @@ +go test fuzz v1 +[]byte("\x00\x00\x00\x18ftypisom\x00\x00\x02\x00isom\x00\x00\x00\x08free") +string("poster") +float64(1e+300) +bool(true) +int(2147483647) +int(2147483647) +int(2147483647) +int(2147483647) +int(2147483647) +int(2147483647) +int(2147483647) +int(2147483647) +int(-1) diff --git a/serve/testdata/fuzz/FuzzHandle/laced-low-track-samples b/serve/testdata/fuzz/FuzzHandle/laced-low-track-samples new file mode 100644 index 0000000..3a22ae6 --- /dev/null +++ b/serve/testdata/fuzz/FuzzHandle/laced-low-track-samples @@ -0,0 +1,14 @@ +go test fuzz v1 +[]byte("\x1a\x45\xdf\xa3\x80\x18\x53\x80\x67\x01\xff\xff\xff\xff\xff\xff\xff\x1f\x43\xb6\x75\x01\xff\xff\xff\xff\xff\xff\xff\xa3\x85\x81\x00\x00\x04\xff\xa3\x85\x81\x00\x00\x04\xff\xa3\x85\x81\x00\x00\x04\xff") +string("probe") +float64(0) +bool(true) +int(0) +int(0) +int(0) +int(0) +int(0) +int(0) +int(500) +int(0) +int(0) diff --git a/serve/testdata/hvc1.mp4 b/serve/testdata/hvc1.mp4 new file mode 100644 index 0000000..e8c6f25 Binary files /dev/null and b/serve/testdata/hvc1.mp4 differ