diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml new file mode 100644 index 000000000..1630c7ff0 --- /dev/null +++ b/.github/workflows/fuzz.yml @@ -0,0 +1,86 @@ +# Go fuzzing (FP-7): every Fuzz* target in the module, found by +# `go test -list` in nix/scripts/fuzz-all.bash, so a new fuzzer is covered +# without editing this file. +# +# fuzz-pr every PR to main, 10 s per target +# fuzz-nightly daily and on demand, 2 min per target +# +# This is not a nix check: a derivation is cached by its inputs, so a nightly +# `nix build` would not fuzz again, and crashers would stay in the sandbox. +# On failure the new testdata/fuzz/ files are uploaded; commit the crasher as +# a seed once the bug is fixed. +# +# Actions are pinned by commit SHA; the comment names the tag it was taken from. +name: fuzz + +on: + pull_request: + branches: [main] + schedule: + - cron: "0 15 * * *" + workflow_dispatch: + inputs: + fuzztime: + description: "Per-target budget (Go duration)" + default: "2m" + required: true + +permissions: + contents: read + +concurrency: + group: fuzz-${{ github.ref }}-${{ github.event_name }} + cancel-in-progress: true + +jobs: + fuzz-pr: + name: fuzz-pr + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + # About 50 targets at 10 s plus their instrumented builds. + timeout-minutes: 30 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: cachix/install-nix-action@13d8dd58da0234aa297dedd986986ccb8e7f3e24 # v31.11.1 + - name: fuzz-all + env: + FUZZTIME: 10s + FUZZ_LOG_DIR: ${{ runner.temp }}/fuzz-logs + run: nix develop -c fuzz-all + - name: upload crashers and logs + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: fuzz-pr-crashers + path: | + **/testdata/fuzz/** + ${{ runner.temp }}/fuzz-logs/ + if-no-files-found: ignore + + fuzz-nightly: + name: fuzz-nightly + if: github.event_name != 'pull_request' + runs-on: ubuntu-latest + # About 50 targets at 2 min each. + timeout-minutes: 180 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: cachix/install-nix-action@13d8dd58da0234aa297dedd986986ccb8e7f3e24 # v31.11.1 + - name: fuzz-all + env: + FUZZTIME: ${{ inputs.fuzztime || '2m' }} + FUZZ_LOG_DIR: ${{ runner.temp }}/fuzz-logs + run: nix develop -c fuzz-all + - name: upload crashers and logs + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: fuzz-nightly-crashers + path: | + **/testdata/fuzz/** + ${{ runner.temp }}/fuzz-logs/ + if-no-files-found: ignore diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ad7eee9f..f30014dee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ - **Strings from tenants and the network are cleaned.** Container names and images, a tenant's interface names, LLDP and NIC strings, the ASN feed's network owner, netns names and congestion names are cut to 256 bytes (16 for interface and congestion names) at a UTF-8 boundary. Invalid UTF-8 and control characters (C0, DEL, C1) become U+FFFD. Each is cleaned once, where it enters, not per row. - **Per-namespace caps.** `-maxDumpBytes` (default 256 MiB) and `-maxRecordsPerNetns` (default 262144) bound one namespace's dump per poll: packets past the byte cap are drained undecoded, and records past the record cap are dropped before decode. `-maxNetns` (default 4096) bounds the namespaces tracked. At the cap, tracked namespaces keep their slots, and new ones wait for a freed slot, first come, first served. Alert on `xtcp_netns_dropped_total`. Drops are counted in `xtcp_dump_dropped_total{reason}` and `xtcp_netns_dropped_total`, with one log line per truncated dump or short reconcile. `0` turns a cap off; the matching env vars are `MAX_DUMP_BYTES`, `MAX_RECORDS_PER_NETNS` and `MAX_NETNS`. The caps are startup-only: `ConfigService.Set` keeps the running values. No healthy host should reach the defaults; a host that does now loses that namespace's excess rows, where it used to collect them all ([polling and batching](docs/polling-and-batching.md#per-namespace-caps)). - **Socket-count gate, reconcile limits, per-owner quota.** Before each poll xtcp2 reads each namespace's sockstat (an fd opened in the namespace; `pread`, or io_uring batches with `-ioUring`) and, when the total is over `-maxRecordsPerPoll` (default 1,048,576), degrades only the namespaces over their fair share: first TIME_WAIT/SYN_RECV are not asked for, then one of K port shards is dumped per poll. `-maxNetnsPerOwner` (default 64) caps namespaces tracked per owner (the container runtime's cgroup), `-maxNetnsAddsPerReconcile` (256) the adds per reconcile, and `-reconcileTimeout` (1s) the namespace scan; a timed-out scan deletes nothing. New metrics `xtcp_poll_sockets`, `xtcp_poll_degraded_total{level}` and `xtcp_reconcile_incomplete_total{reason}`; `xtcp_netns_dropped_total` gains `reason`. `0` turns each off; all are startup-only. Each tracked namespace now holds four fds (was two: sockstat and `ip_local_port_range` are new), and xtcp2 warns at startup when `RLIMIT_NOFILE` can't cover them ([polling and batching](docs/polling-and-batching.md#socket-count-gate), [network namespaces](docs/network-namespaces.md#configuration)). The analysis behind an upstream all-namespace dump is in [docs/kernel](docs/kernel/inet-diag-all-netns.md). +- **Fuzzing in CI.** `fuzz-all` (dev shell) finds every Go fuzz target with `go test -list` and fuzzes each in turn: 10 s per target on each PR, 2 min nightly (`.github/workflows/fuzz.yml`), with crashers uploaded as an artifact. Two new fuzzers cover tenant-reachable paths: `FuzzDockerProjection` (a Docker inspect body to a container's name and image) and `FuzzRowFromProto` (an S3 envelope through Parquet and back). `FuzzClean` now also checks idempotence and the fast path. The first run found `/ip/vrf/show/NAME` returning 500 for a name that is no VRF; it is now a 404. Docker API response bodies are now capped per endpoint, and an oversized `/events` line no longer stalls container-metadata refresh. - **Vulnerability check.** `checks.govulncheck` runs govulncheck against a pinned snapshot of the Go vulnerability database, with no tags and with every flavor tag, and fails on a reachable finding not in its accepted list. One is accepted: GO-2026-6859 in `net/http`, fixed in go1.27.4, until the toolchain moves. `nix run .#govulncheck-fresh` checks against the live database and runs `go mod verify`; `nix build .#sbom-` writes a CycloneDX SBOM for any binary package. ## 0.2.1 (2026-11) diff --git a/docs/security-hardening/focused-implementation-plan.md b/docs/security-hardening/focused-implementation-plan.md index 5a70b349a..df253c475 100644 --- a/docs/security-hardening/focused-implementation-plan.md +++ b/docs/security-hardening/focused-implementation-plan.md @@ -221,7 +221,7 @@ Non-blocking shortfalls found while implementing F1; none blocks R1. | `BenchmarkS3Send` queue vs the old channel send | 52 ns vs 118 ns | faster ✓ | | `microvm-x86_64-lifecycle-s3parquet` Check 14c: Garage stopped for 160 s (4× wait scale), `-s3QueueDepth 2` | polls kept running (343), 22 envelopes dropped, RSS 50.8 → 55.8 MB, a new object after restart | pass ✓ | -**Status:** open as #308. +**Status:** merged (#308). **FP-6 follow-ups (in #308):** @@ -230,8 +230,8 @@ Non-blocking shortfalls found while implementing F1; none blocks R1. ### FP-7 — fuzzers (D4) -- [ ] `FuzzDockerProjection` (`pkg/dockermeta`), `FuzzStrPolicy`, `FuzzRowFromProto`; corpora seeded from F0.5. -- [ ] CI runs every fuzzer (existing netlink ones included) for a fixed time budget per PR and longer nightly. +- [x] `FuzzDockerProjection` (`pkg/dockermeta`), `FuzzStrPolicy`, `FuzzRowFromProto`; corpora seeded from F0.5. *Done as:* `FuzzDockerProjection` drives a raw inspect body through `json.Unmarshal` and the new pure `project` (split out of `(*Index).inspect`); a projected name and image are always valid UTF-8, ≤ 256 bytes and control-free. `FuzzRowFromProto` (`dest_s3parquet`) takes arbitrary envelope bytes through the worker's row path (unmarshal, `rowFromProto`, event date, Parquet write) and reads the object back: every decoded row must round-trip unchanged. `FuzzStrPolicy` is `FuzzClean`, which now also checks idempotence and the fast path. Each fuzzer shares a table with a unit test (`TestDockerProjectionJSON` 12 rows, `TestRowFromProtoRoundTrip` 12, `TestCleanProperties` 7, plus `TestProject` 9), so every seed has a description and an expected result. F0.5 isn't captured yet, so the seeds are the fixtures and the real netlink dump; the F0.5 rows are a TODO below. Pinned on the way: invalid UTF-8 in a proto3 string fails the unmarshal, so the worker drops the whole envelope (the sources clean strings first, so it can't come from them). +- [x] CI runs every fuzzer (existing netlink ones included) for a fixed time budget per PR and longer nightly. *Done as:* `nix/scripts/fuzz-all.bash` (`fuzz-all` in the dev shell) finds every target with `go test -list` under the flavor tags (50 today), fails below `FUZZ_MIN_TARGETS`, runs them all even after a failure, and lists the crasher files. `.github/workflows/fuzz.yml`: `fuzz-pr` at 10 s per target, `fuzz-nightly` daily at 2 min (and `workflow_dispatch`); crashers and logs uploaded on failure. Not a nix check: a cached derivation would never fuzz again. `-fuzzminimizetime` is 5 s: with Go's 60 s default, `FuzzRowFromProto` spent a 10 s budget minimizing (0 execs/s after the first 3 s). First full run (50 targets at 10 s, loaded host): 588 s, one crasher in the existing `FuzzIPHandler`: `/i/v/s/0` (vrf show for a name that is no VRF) returned 500; `goip.ErrVrfInvalid` now maps to 404, the input is committed as a seed and a `TestFuzzIPHandlerRows` row. ### Phase F2 TODOs @@ -248,6 +248,8 @@ Non-blocking shortfalls found while implementing F1; none blocks R1. | ~~`microvm-x86_64-socket-scale`~~ done as FP-5.7 | — | | Fix `RegisterIOWQMaxWorkers` signature in the giouring fork | giouring PR | | Upstream RFC for an all-namespace inet_diag dump, only after the VM numbers and a lore.kernel.org search | F2 follow-up | +| Add the scrubbed F0.5 Parquet rows as `FuzzRowFromProto` seeds once F0.5 is captured | FP-7 follow-up | +| ~~Cap `dockermeta.getJSON`'s body~~ done in #312: per-endpoint caps (`/version` 64 KiB, `/containers/json` 32 MiB, inspect 1 MiB; over the cap the container is skipped or the re-list fails), and `drainClose` now discards at most 64 KiB: an `/events` line over the scanner's 1 MiB used to block the refresh goroutine draining the endless stream | — | | Re-tune the three caps' defaults from the F0.6 baseline (≥ 10× p99) | F0.6 | | The F2 gate's 1 M-socket synthetic netns run | after FP-6 | diff --git a/internal/godevlink/imports_test.go b/internal/godevlink/imports_test.go index 5e82c9a84..dfec2e502 100644 --- a/internal/godevlink/imports_test.go +++ b/internal/godevlink/imports_test.go @@ -33,6 +33,8 @@ var godevlinkClosure = []string{ modulePath + "/cmd/godevlink", modulePath + "/internal/godevlink", modulePath + "/pkg/xtcpnl", modulePath + "/internal/jsonw", modulePath + "/pkg/cint", + // Reached through xtcpnl's congestion-name decoder; stdlib only. + modulePath + "/pkg/strpolicy", // Reached through xtcpnl's inet_diag decoders; see internal/gordma. modulePath + "/gen/go/xtcp_flat_record", } diff --git a/internal/goip/goiphttp/handler.go b/internal/goip/goiphttp/handler.go index 9cfa53199..114afaac9 100644 --- a/internal/goip/goiphttp/handler.go +++ b/internal/goip/goiphttp/handler.go @@ -382,8 +382,9 @@ var ( // statusOf maps a show failure to its status. ErrNoSuchDevice is tested // before ErrNotImplemented because netconf's missing device carries both. // A refused write verb or option is the caller's request, so a 400, as is a -// device name no kernel takes (ip's "not a valid ifname"); a read goip does -// not serve is a 501. +// device name no kernel takes (ip's "not a valid ifname"); a vrf show NAME +// that names no VRF (ip's "Invalid VRF") is a 404, like a missing device; a +// read goip does not serve is a 501. func statusOf(err error) int { switch { case errors.Is(err, errParam), errors.Is(err, goip.ErrWriteVerb), errors.Is(err, goip.ErrRefusedOption), @@ -391,7 +392,7 @@ func statusOf(err error) int { return http.StatusBadRequest case errors.Is(err, goip.ErrUnknownObject): return http.StatusNotFound - case errors.Is(err, goip.ErrNoSuchDevice), errors.Is(err, unix.ENODEV): + case errors.Is(err, goip.ErrNoSuchDevice), errors.Is(err, unix.ENODEV), errors.Is(err, goip.ErrVrfInvalid): return http.StatusNotFound case errors.Is(err, goip.ErrNotImplemented): return http.StatusNotImplemented diff --git a/internal/goip/goiphttp/handler_fuzz_test.go b/internal/goip/goiphttp/handler_fuzz_test.go index dbff2518e..d44aa87a1 100644 --- a/internal/goip/goiphttp/handler_fuzz_test.go +++ b/internal/goip/goiphttp/handler_fuzz_test.go @@ -416,6 +416,8 @@ func TestFuzzIPHandlerRows(t *testing.T) { method: "PROPFIND", path: "/i/a/s", expected: is(http.StatusMethodNotAllowed), noOpen: true}, {name: "method_lowercase", category: "corner", description: "methods are case-sensitive: get is not GET", method: "get", path: "/ip/link", expected: is(http.StatusMethodNotAllowed), noOpen: true}, + {name: "vrf_show_not_a_vrf", category: "negative", description: "/i/v/s/0: a name that is no VRF is ip's Invalid VRF, a 404 not a 500", + method: http.MethodGet, path: "/i/v/s/0", expected: is(http.StatusNotFound)}, {name: "write_verb", category: "negative", description: "/i/l/s is ip link set: a 400 before any open", method: http.MethodGet, path: "/i/l/s", expected: is(http.StatusBadRequest), noOpen: true}, } diff --git a/internal/goip/goiphttp/testdata/fuzz/FuzzIPHandler/952e2269ec72e59f b/internal/goip/goiphttp/testdata/fuzz/FuzzIPHandler/952e2269ec72e59f new file mode 100644 index 000000000..422293087 --- /dev/null +++ b/internal/goip/goiphttp/testdata/fuzz/FuzzIPHandler/952e2269ec72e59f @@ -0,0 +1,4 @@ +go test fuzz v1 +string("GET") +string("/i/v/s/0") +string("") diff --git a/internal/gotipc/imports_test.go b/internal/gotipc/imports_test.go index 71b4005a4..d91210ed3 100644 --- a/internal/gotipc/imports_test.go +++ b/internal/gotipc/imports_test.go @@ -33,6 +33,8 @@ var gotipcClosure = []string{ modulePath + "/cmd/gotipc", modulePath + "/internal/gotipc", modulePath + "/pkg/xtcpnl", modulePath + "/internal/jsonw", modulePath + "/pkg/cint", + // Reached through xtcpnl's congestion-name decoder; stdlib only. + modulePath + "/pkg/strpolicy", // Reached through xtcpnl's inet_diag decoders; see internal/gordma. modulePath + "/gen/go/xtcp_flat_record", } diff --git a/internal/govdpa/imports_test.go b/internal/govdpa/imports_test.go index fbff3b090..7448be09c 100644 --- a/internal/govdpa/imports_test.go +++ b/internal/govdpa/imports_test.go @@ -33,6 +33,8 @@ var govdpaClosure = []string{ modulePath + "/cmd/govdpa", modulePath + "/internal/govdpa", modulePath + "/pkg/xtcpnl", modulePath + "/internal/jsonw", modulePath + "/pkg/cint", + // Reached through xtcpnl's congestion-name decoder; stdlib only. + modulePath + "/pkg/strpolicy", // Reached through xtcpnl's inet_diag decoders; see internal/gordma. modulePath + "/gen/go/xtcp_flat_record", } diff --git a/nix/README.md b/nix/README.md index 64bd11629..6d0060f91 100644 --- a/nix/README.md +++ b/nix/README.md @@ -28,6 +28,7 @@ The flake currently exports `x86_64-linux` only. See - [Development and maintenance](#development-and-maintenance) - [Binaries, images, and artifacts](#binaries-images-and-artifacts) - [Unit, flavor, and quality checks](#unit-flavor-and-quality-checks) +- [Fuzzing](#fuzzing) - [Nix integration testing](#nix-integration-testing) - [Netlink and RDMA fixture collection](#netlink-and-rdma-fixture-collection) - [Link-monitor verification](#link-monitor-verification) @@ -220,6 +221,29 @@ Use the full path: `nix build path:.#checks.x86_64-linux.NAME -L`. | `test-ipmeta-bootstrap-artifact`, `test-oci-ipmeta-bootstrap-contents`, `test-ipmeta-bootstrap-snapshot`, `test-oci-ipmeta-bootstrap-snapshot-contents` | Fixture and real-snapshot bootstrap checks, also available as packages above | | `microvm-lifecycle-x86_64`, `vm-*`, `vm-all` | Actual guest checks described next; `vm-*` here refers to guest checks, not the host helpers above | +## Fuzzing + +`fuzz-all` (in the dev shell; source `nix/scripts/fuzz-all.bash`) finds every `Fuzz*` target with `go test -list` and fuzzes each in turn, so a new fuzzer needs no list entry. It runs every target even after a failure, then names the failures and the crasher files Go wrote under `/testdata/fuzz//`. + +```bash +nix develop -c fuzz-all # every target, 10 s each +FUZZ_FILTER=dockermeta FUZZTIME=5m nix develop -c fuzz-all # one package, longer +``` + +| Variable | Default | Meaning | +|---|---|---| +| `FUZZTIME` | `10s` | Budget per target | +| `FUZZ_PARALLEL` | `2` | Fuzz workers per target | +| `FUZZ_MINIMIZE` | `5s` | `-fuzzminimizetime`. Go's 60 s default spends a short budget minimizing new inputs on slow targets | +| `FUZZ_TAGS` | `dest_s3parquet enrich_asn enrich_locality` | Build tags, so tagged fuzzers such as `FuzzRowFromProto` are found | +| `FUZZ_FILTER` | none | Extended regex on `pkg:target` | +| `FUZZ_MIN_TARGETS` | `50` | Fail if discovery finds fewer, so a broken discovery can't pass | +| `FUZZ_LOG_DIR` | a temporary directory | One log per target | + +CI (`.github/workflows/fuzz.yml`) runs it on every PR to main at 10 s per target (`fuzz-pr`), and daily at 2 min per target (`fuzz-nightly`, also `workflow_dispatch` with a chosen budget). It is not a nix check, because a cached derivation would never fuzz again. A failed run uploads the crashers and logs as an artifact. Fix the bug, then commit the crasher file and add the input as a row of the fuzzer's table, which its unit test and seed corpus share. + +`test-linkmonitor-fuzz` still fuzzes its own 10 targets for 30 s each under `nix build`. + ## Nix integration testing ### Prerequisites and suite boundaries @@ -662,6 +686,7 @@ as many guests at once as `max-jobs` allows; add `-j1` for one at a time. | [../flake.nix](../flake.nix) | Inputs, supported system, public outputs, and overlay | | [default.nix](default.nix) | Export names, package/app/check wiring, `integration-all` membership | | [versions.nix](versions.nix), [packages.nix](packages.nix), [devshell.nix](devshell.nix) | Tool versions, developer tools, and shell helpers | +| [scripts/fuzz-all.bash](scripts/fuzz-all.bash) | `fuzz-all`: discover and fuzz every Go fuzz target (dev shell and CI) | | [binaries.nix](binaries.nix), [containers/default.nix](containers/default.nix) | Binary and OCI flavor generation | | [lib/goSource.nix](lib/goSource.nix), [lib/goModules.nix](lib/goModules.nix) | Source filtering and vendored dependency preparation | | [checks/default.nix](checks/default.nix) | Static audits, lint tiers, and host harness checks | diff --git a/nix/devshell.nix b/nix/devshell.nix index a1ee1b03a..e67f1eede 100644 --- a/nix/devshell.nix +++ b/nix/devshell.nix @@ -29,6 +29,18 @@ let # The five golangci-lint tiers, shared verbatim with nix/default.nix's # `packages` so the shell and the flake cannot drift. lintTiers = import ./lint-tiers.nix { inherit pkgs; }; + # Every Go fuzz target, found by `go test -list` (FP-7). The script stays a + # plain file so CI and contributors run the same thing; the shebang is + # dropped because writeShellApplication adds its own. + fuzzAll = pkgs.writeShellApplication { + name = "fuzz-all"; + runtimeInputs = [ + pkgs.coreutils + pkgs.findutils + pkgs.gawk + ]; + text = pkgs.lib.removePrefix "#!/usr/bin/env bash\n" (builtins.readFile ./scripts/fuzz-all.bash); + }; # Shell-entry banner. A writeShellApplication rather than a shellHook # function so its (admittedly trivial) bash is shellcheck'd like everything @@ -98,6 +110,11 @@ let flake.nix does not export `tests`, so that name has never resolved.) + Fuzzing: + fuzz-all Fuzz every Fuzz* target in turn + (FUZZTIME=10s per target; set + FUZZ_FILTER= to pick some) + Nix: nix flake check Tier 0+1 lint + all custom audits nixfmt --check **/*.nix Verify nix formatting @@ -115,6 +132,7 @@ pkgs.mkShell { ++ [ regenProtos xtcp2Help + fuzzAll ]; shellHook = '' diff --git a/nix/scripts/fuzz-all.bash b/nix/scripts/fuzz-all.bash new file mode 100755 index 000000000..d39759749 --- /dev/null +++ b/nix/scripts/fuzz-all.bash @@ -0,0 +1,98 @@ +#!/usr/bin/env bash +# fuzz-all: find every Go fuzz target in the module and fuzz each one in turn. +# +# Discovery uses `go test -list`, so a new Fuzz* function is picked up without +# editing a list. Every target runs even after one fails; the summary at the +# end names the failures and the crasher files Go wrote under +# /testdata/fuzz//. Commit a crasher (and add it as a table row) +# once the bug is fixed, so it stays a regression seed. +# +# Environment: +# FUZZTIME per-target budget (default 10s) +# FUZZ_PARALLEL fuzz workers per target (default 2) +# FUZZ_MINIMIZE -fuzzminimizetime (default 5s). Go minimizes each new +# interesting input for up to 60s by default, and those +# runs are not counted as execs: with a 10s budget and a +# slow target (FuzzRowFromProto writes Parquet) the whole +# budget went on minimizing. +# FUZZ_TAGS build tags (default: dest_s3parquet enrich_asn enrich_locality) +# FUZZ_FILTER extended regex on "pkg:target"; only matches run +# FUZZ_MIN_TARGETS fail if discovery finds fewer (default 50) +# FUZZ_LOG_DIR per-target logs (default: a new temporary directory) +# +# Run from the repository root: nix develop -c fuzz-all +set -euo pipefail + +fuzztime=${FUZZTIME:-10s} +parallel=${FUZZ_PARALLEL:-2} +minimize=${FUZZ_MINIMIZE:-5s} +tags=${FUZZ_TAGS-dest_s3parquet enrich_asn enrich_locality} +filter=${FUZZ_FILTER:-} +min_targets=${FUZZ_MIN_TARGETS:-50} +log_dir=${FUZZ_LOG_DIR:-$(mktemp -d -t fuzz-all.XXXXXX)} + +if [[ ! -f go.mod ]]; then + echo "fuzz-all: run from the repository root (no go.mod here)" >&2 + exit 2 +fi +mkdir -p "$log_dir" + +# `go test -list` prints a package's matching names, then its "ok " line. +list_out=$(go test -list '^Fuzz' -tags "$tags" ./...) +mapfile -t all_targets < <( + awk ' + /^Fuzz/ { names[++n] = $1; next } + /^ok[ \t]/ { for (i = 1; i <= n; i++) print $2 ":" names[i]; n = 0 } + ' <<<"$list_out" +) + +echo "fuzz-all: discovered ${#all_targets[@]} targets (tags: ${tags:-none})" +if ((${#all_targets[@]} < min_targets)); then + echo "fuzz-all: expected at least $min_targets targets; discovery is broken or targets were removed" >&2 + exit 1 +fi + +targets=() +for entry in "${all_targets[@]}"; do + if [[ -z $filter || $entry =~ $filter ]]; then + targets+=("$entry") + fi +done +if ((${#targets[@]} == 0)); then + echo "fuzz-all: 0 targets matched FUZZ_FILTER=$filter" >&2 + exit 1 +fi + +echo "fuzz-all: running ${#targets[@]} targets for $fuzztime each; logs in $log_dir" +failed=() +start=$SECONDS +start_epoch=$(date +%s) +for entry in "${targets[@]}"; do + pkg=${entry%%:*} + target=${entry#*:} + log="$log_dir/${pkg//\//_}.$target.log" + t0=$SECONDS + if go test "$pkg" -tags "$tags" -run '^$' -fuzz "^${target}\$" \ + -fuzztime="$fuzztime" -fuzzminimizetime="$minimize" \ + -parallel="$parallel" -timeout=30m >"$log" 2>&1; then + printf 'PASS %-70s %4ds\n' "$entry" $((SECONDS - t0)) + else + printf 'FAIL %-70s %4ds\n' "$entry" $((SECONDS - t0)) + tail -n 30 "$log" + failed+=("$entry") + fi +done + +echo "fuzz-all: ${#targets[@]} targets in $((SECONDS - start))s, ${#failed[@]} failed" +if ((${#failed[@]} > 0)); then + for entry in "${failed[@]}"; do + pkg=${entry%%:*} + target=${entry#*:} + echo " $entry" + dir=$(go list -tags "$tags" -f '{{.Dir}}' "$pkg")/testdata/fuzz/$target + if [[ -d $dir ]]; then + find "$dir" -type f -newermt "@$start_epoch" -printf ' crasher: %p\n' + fi + done + exit 1 +fi diff --git a/pkg/dockermeta/dockermeta.go b/pkg/dockermeta/dockermeta.go index c3c5209d1..6cdd7fb5a 100644 --- a/pkg/dockermeta/dockermeta.go +++ b/pkg/dockermeta/dockermeta.go @@ -20,8 +20,10 @@ package dockermeta import ( "bufio" + "bytes" "context" "encoding/json" + "errors" "fmt" "io" "log" @@ -52,6 +54,25 @@ const relistInterval = 30 * time.Second // back to a re-list) after it errors or closes. const eventsRetryDelay = time.Second +// Response body caps. The daemon is trusted, but container names, images and +// labels in its bodies are the tenant's choice, so each read is bounded. +const ( + // maxVersionBody caps GET /version, a few hundred bytes in practice. + maxVersionBody = 64 << 10 + // maxListBody caps GET /containers/json: one summary per running + // container, labels included (a few KB each), so it scales with the host. + maxListBody = 32 << 20 + // maxInspectBody caps GET /containers/{id}/json for one container. + maxInspectBody = 1 << 20 + // maxDrain caps how much of an unread body drainClose discards for + // connection reuse; past it the connection is closed instead. /events + // never ends, so an unbounded drain there would block forever. + maxDrain = 64 << 10 +) + +// errBodyTooLarge is a response body over its cap. +var errBodyTooLarge = errors.New("response body over its cap") + // Container is the resolved identity of a container that owns a netns. type Container struct { ID string @@ -158,7 +179,7 @@ type versionInfo struct { // "use unversioned paths") when /version can't be read. func negotiateVersion(ctx context.Context, client *http.Client, base string) (string, error) { var vi versionInfo - if err := getJSON(ctx, client, base+"/version", &vi); err != nil { + if err := getJSON(ctx, client, base+"/version", maxVersionBody, &vi); err != nil { return "", err } if vi.APIVersion == "" { @@ -246,7 +267,7 @@ type inspect struct { // the whole index. func (ix *Index) build(ctx context.Context) (map[uint64]Container, error) { var refs []containerRef - if err := getJSON(ctx, ix.client, ix.baseURL+"/containers/json", &refs); err != nil { + if err := getJSON(ctx, ix.client, ix.baseURL+"/containers/json", maxListBody, &refs); err != nil { return nil, fmt.Errorf("list containers: %w", err) } m := make(map[uint64]Container, len(refs)) @@ -266,13 +287,21 @@ func (ix *Index) build(ctx context.Context) (map[uint64]Container, error) { // (host network), or an unresolvable inode. func (ix *Index) inspect(ctx context.Context, id string) (Container, bool) { var in inspect - if err := getJSON(ctx, ix.client, ix.baseURL+"/containers/"+id+"/json", &in); err != nil { + if err := getJSON(ctx, ix.client, ix.baseURL+"/containers/"+id+"/json", maxInspectBody, &in); err != nil { return Container{}, false } + return project(in, ix.stat) +} + +// project turns a decoded inspect body into a Container. It is pure apart from +// stat, so FuzzDockerProjection can drive it with arbitrary JSON. It returns +// ok=false for a host-network container (empty SandboxKey) or an unresolvable +// inode. +func project(in inspect, stat statFn) (Container, bool) { if in.NetworkSettings.SandboxKey == "" { return Container{}, false // host-net container: nothing to key on } - ino, err := ix.stat(in.NetworkSettings.SandboxKey) + ino, err := stat(in.NetworkSettings.SandboxKey) if err != nil || ino == 0 { return Container{}, false } @@ -396,9 +425,10 @@ func (ix *Index) rebuild(ctx context.Context) { ix.snapshot.Store(&m) } -// getJSON does a GET and decodes the JSON body into v. A non-2xx status or a -// decode error is returned so callers can skip/fall back. -func getJSON(ctx context.Context, client *http.Client, url string, v any) error { +// getJSON does a GET and decodes the JSON body into v. A non-2xx status, a +// body over limit bytes (errBodyTooLarge) or a decode error is returned so +// callers can skip/fall back. +func getJSON(ctx context.Context, client *http.Client, url string, limit int64, v any) error { req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return err @@ -411,13 +441,21 @@ func getJSON(ctx context.Context, client *http.Client, url string, v any) error if resp.StatusCode < 200 || resp.StatusCode >= 300 { return fmt.Errorf("GET %s: status %d", url, resp.StatusCode) } - return json.NewDecoder(resp.Body).Decode(v) + body, err := io.ReadAll(io.LimitReader(resp.Body, limit+1)) + if err != nil { + return err + } + if int64(len(body)) > limit { + return fmt.Errorf("GET %s: %w (%d bytes)", url, errBodyTooLarge, limit) + } + return json.NewDecoder(bytes.NewReader(body)).Decode(v) } -// drainClose drains and closes a response body so the underlying connection can -// be reused, then closes it. +// drainClose discards up to maxDrain bytes of a response body so the +// connection can be reused, then closes it. A longer body (or the endless +// /events stream) is cut off by Close, which costs only the connection. func drainClose(rc io.ReadCloser) { - if _, err := io.Copy(io.Discard, rc); err != nil { + if _, err := io.CopyN(io.Discard, rc, maxDrain); err != nil && !errors.Is(err, io.EOF) { // A drain failure only forfeits connection reuse; Close still frees it. log.Printf("dockermeta: drain response body: %v", err) } diff --git a/pkg/dockermeta/dockermeta_fuzz_test.go b/pkg/dockermeta/dockermeta_fuzz_test.go new file mode 100644 index 000000000..e0e967192 --- /dev/null +++ b/pkg/dockermeta/dockermeta_fuzz_test.go @@ -0,0 +1,244 @@ +package dockermeta + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "unicode/utf8" + + "github.com/randomizedcoder/xtcp2/pkg/strpolicy" +) + +// errFuzzStat is what fuzzStat returns for a path containing "missing". +var errFuzzStat = errors.New("stat: no such file") + +// fuzzStat resolves any SandboxKey, so the fuzzer reaches the ok path without +// guessing a fixture path. A path containing "missing" fails and one +// containing "zero" resolves to inode 0, so both reject paths stay reachable. +func fuzzStat(path string) (uint64, error) { + switch { + case strings.Contains(path, "missing"): + return 0, errFuzzStat + case strings.Contains(path, "zero"): + return 0, nil + } + return 4026531000 + uint64(len(path)), nil +} + +// isControlRune mirrors strpolicy's rule: C0, DEL and C1. +func isControlRune(r rune) bool { + return r < 0x20 || (r >= 0x7f && r <= 0x9f) +} + +// checkProjected asserts the invariants every projected Container must hold, +// whatever the inspect body was. +func checkProjected(t *testing.T, in inspect, c Container) { + t.Helper() + for field, v := range map[string]string{"Name": c.Name, "Image": c.Image} { + if !utf8.ValidString(v) { + t.Fatalf("%s %q: invalid UTF-8", field, v) + } + if len(v) > strpolicy.MaxLen { + t.Fatalf("%s: %d bytes, over %d", field, len(v), strpolicy.MaxLen) + } + for _, r := range v { + if isControlRune(r) { + t.Fatalf("%s %q: control rune %U kept", field, v, r) + } + } + } + if c.NetnsInode == 0 { + t.Fatal("ok with NetnsInode 0") + } + if c.SandboxKey == "" { + t.Fatal("ok with an empty SandboxKey") + } + if strings.HasPrefix(c.Name, "/") && !strings.HasPrefix(in.Name, "//") { + t.Fatalf("Name %q kept a leading slash from %q", c.Name, in.Name) + } +} + +func TestProject(t *testing.T) { + const key = "/var/run/docker/netns/aaaahash" + mk := func(name, cfgImage, image, sandbox string) inspect { + var in inspect + in.ID = "id1" + in.Name = name + in.Image = image + in.Config.Image = cfgImage + in.NetworkSettings.SandboxKey = sandbox + return in + } + type want struct { + ok bool + name, image string + } + cases := []struct { + name string + cat string + description string + in inspect + stat statFn + expected want + }{ + {"basic", "P", "name /web, Config.Image nginx, SandboxKey set", + mk("/web", "nginx", "", key), fakeStat, want{true, "web", "nginx"}}, + {"image_fallback", "P", "Config.Image empty: the top-level Image is used", + mk("/web", "", "x", key), fakeStat, want{true, "web", "x"}}, + {"host_net", "N", "an empty SandboxKey is a host-network container", + mk("/web", "nginx", "", ""), fakeStat, want{}}, + {"stat_error", "N", "the SandboxKey does not resolve", + mk("/web", "nginx", "", "/var/run/docker/netns/gone"), fakeStat, want{}}, + {"inode_zero", "B", "the stat returns inode 0", + mk("/web", "nginx", "", "/zero"), fuzzStat, want{}}, + {"name_slash_only", "B", "Name / strips to empty", + mk("/", "nginx", "", key), fakeStat, want{true, "", "nginx"}}, + {"long_name", "N", "a 10 kB name is cut to strpolicy.MaxLen", + mk("/"+strings.Repeat("a", 10<<10), "nginx", "", key), fakeStat, + want{true, strings.Repeat("a", strpolicy.MaxLen), "nginx"}}, + {"hostile_name", "N", "ESC, U+0085 and an invalid byte each become U+FFFD", + mk("/a\x1b\u0085\xffb", "nginx", "", key), fakeStat, + want{true, "a���b", "nginx"}}, + {"double_slash", "C", "only the first leading slash is stripped", + mk("//x", "nginx", "", key), fakeStat, want{true, "/x", "nginx"}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + c, ok := project(tc.in, tc.stat) + got := want{ok, c.Name, c.Image} + if got != tc.expected { + t.Fatalf("%s: got %+v, expected %+v", tc.description, got, tc.expected) + } + if ok { + checkProjected(t, tc.in, c) + } + }) + } +} + +// projectionCase is one raw inspect body. The rows drive both +// TestDockerProjectionJSON (exact expectations) and FuzzDockerProjection +// (seeds). +type projectionCase struct { + name string + cat string + description string + body string + fixture string // testdata file; overrides body + expected projectionWant +} + +type projectionWant struct { + unmarshalErr bool + ok bool + name, image string + pid int +} + +func projectionCases() []projectionCase { + const key = `"NetworkSettings":{"SandboxKey":"/var/run/docker/netns/aaaahash"}` + return []projectionCase{ + {name: "fixture_aaaa", cat: "P", description: "testdata/inspect_aaaa.json", + fixture: "inspect_aaaa.json", expected: projectionWant{ok: true, name: "web", image: "nginx:1.27", pid: 1234}}, + {name: "fixture_bbbb", cat: "P", description: "testdata/inspect_bbbb.json (image from the top level)", + fixture: "inspect_bbbb.json", expected: projectionWant{ok: true, name: "db", image: "postgres:16", pid: 5678}}, + {name: "fixture_cccc_hostnet", cat: "N", description: "testdata/inspect_cccc.json has no SandboxKey", + fixture: "inspect_cccc.json", expected: projectionWant{}}, + {name: "empty_object", cat: "B", description: "{} has no SandboxKey", + body: `{}`, expected: projectionWant{}}, + {name: "json_null", cat: "B", description: "null decodes to the zero inspect", + body: `null`, expected: projectionWant{}}, + {name: "not_json", cat: "N", description: "a truncated object fails to unmarshal", + body: `{"Name":`, expected: projectionWant{unmarshalErr: true}}, + {name: "name_10k", cat: "N", description: "a 10 kB name is cut to strpolicy.MaxLen", + body: `{"Name":"/` + strings.Repeat("n", 10<<10) + `",` + key + `}`, + expected: projectionWant{ok: true, name: strings.Repeat("n", strpolicy.MaxLen)}}, + {name: "name_escapes", cat: "N", description: "escaped ESC and U+0085 in the name become U+FFFD", + body: `{"Name":"/a\u001b[2J\u0085",` + key + `}`, + expected: projectionWant{ok: true, name: "a�[2J�"}}, + {name: "name_invalid_utf8", cat: "N", description: "a raw 0xff byte in the JSON string becomes U+FFFD", + body: "{\"Name\":\"/a\xffb\"," + key + "}", + expected: projectionWant{ok: true, name: "a�b"}}, + {name: "image_both_empty", cat: "C", description: "Config.Image and Image both empty", + body: `{"Name":"/x","Config":{"Image":""},"Image":"",` + key + `}`, + expected: projectionWant{ok: true, name: "x"}}, + {name: "wrong_types", cat: "N", description: "a string Pid is an unmarshal error", + body: `{"State":{"Pid":"x"},` + key + `}`, + expected: projectionWant{unmarshalErr: true}}, + {name: "huge_pid", cat: "B", description: "Pid 2^31 is kept", + body: `{"Name":"/p","State":{"Pid":2147483648},` + key + `}`, + expected: projectionWant{ok: true, name: "p", pid: 2147483648}}, + } +} + +// input returns the row's raw body, reading the fixture when it names one. +func (tc projectionCase) input() ([]byte, error) { + if tc.fixture == "" { + return []byte(tc.body), nil + } + return os.ReadFile(filepath.Join("testdata", tc.fixture)) +} + +func TestDockerProjectionJSON(t *testing.T) { + cases := projectionCases() + for i := range cases { + tc := &cases[i] + t.Run(tc.name, func(t *testing.T) { + data, err := tc.input() + if err != nil { + t.Fatalf("%s: %v", tc.name, err) + } + var in inspect + if err := json.Unmarshal(data, &in); err != nil { + if !tc.expected.unmarshalErr { + t.Fatalf("%s: unmarshal: %v", tc.description, err) + } + return + } + if tc.expected.unmarshalErr { + t.Fatalf("%s: unmarshal succeeded, expected an error", tc.description) + } + c, ok := project(in, fakeStat) + got := projectionWant{ok: ok, name: c.Name, image: c.Image, pid: c.Pid} + if got != tc.expected { + t.Fatalf("%s: got %+v, expected %+v", tc.description, got, tc.expected) + } + if ok { + checkProjected(t, in, c) + } + }) + } +} + +// FuzzDockerProjection feeds arbitrary inspect bodies through json.Unmarshal +// and project. The Docker daemon is trusted, but the container name and image +// are the tenant's choice, so whatever they hold must come out as bounded, +// valid UTF-8 without control runes. +// +// go test -run '^$' -fuzz '^FuzzDockerProjection$' -fuzztime=30s ./pkg/dockermeta/ +func FuzzDockerProjection(f *testing.F) { + cases := projectionCases() + for i := range cases { + data, err := cases[i].input() + if err != nil { + f.Fatalf("%s: %v", cases[i].name, err) + } + f.Add(data) + } + f.Fuzz(func(t *testing.T, data []byte) { + var in inspect + if err := json.Unmarshal(data, &in); err != nil { + return + } + c, ok := project(in, fuzzStat) + if in.NetworkSettings.SandboxKey == "" && ok { + t.Fatal("ok for an empty SandboxKey") + } + if ok { + checkProjected(t, in, c) + } + }) +} diff --git a/pkg/dockermeta/dockermeta_limit_test.go b/pkg/dockermeta/dockermeta_limit_test.go new file mode 100644 index 000000000..5a18838b7 --- /dev/null +++ b/pkg/dockermeta/dockermeta_limit_test.go @@ -0,0 +1,219 @@ +package dockermeta + +import ( + "bufio" + "context" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +// versionJSON returns a /version body of exactly n bytes (n >= 17). +func versionJSON(n int) string { + const pre, suf = `{"ApiVersion":"`, `"}` + return pre + strings.Repeat("9", n-len(pre)-len(suf)) + suf +} + +func TestGetJSONLimit(t *testing.T) { + const limit = 64 + type outcome int + const ( + ok outcome = iota + tooLarge + decodeErr + statusErr + ) + cases := []struct { + name string + cat string + description string + status int + body string + expected outcome + }{ + {"under_cap", "P", "a 21-byte body decodes", + http.StatusOK, `{"ApiVersion":"1.44"}`, ok}, + {"at_cap", "B", "a body of exactly the cap decodes", + http.StatusOK, versionJSON(limit), ok}, + {"over_by_one", "B", "cap+1 bytes is refused before decoding", + http.StatusOK, versionJSON(limit + 1), tooLarge}, + {"huge", "N", "a 1 MiB body is refused, only cap+1 bytes read", + http.StatusOK, versionJSON(1 << 20), tooLarge}, + {"malformed_under_cap", "N", "truncated JSON under the cap is a decode error, not a size error", + http.StatusOK, `{"ApiVersion":`, decodeErr}, + {"empty_body", "C", "an empty 200 body is a decode error (EOF)", + http.StatusOK, "", decodeErr}, + {"error_status_huge", "C", "a 500 with a 1 MiB body is a status error; the body is not read", + http.StatusInternalServerError, versionJSON(1 << 20), statusErr}, + {"trailing_data", "C", "data after the first value is ignored, as json.Decoder did before the cap", + http.StatusOK, `{"ApiVersion":"1.44"} trailing`, ok}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(tc.status) + _, _ = io.WriteString(w, tc.body) + })) + defer srv.Close() + + var vi versionInfo + err := getJSON(context.Background(), srv.Client(), srv.URL+"/version", limit, &vi) + var got outcome + switch { + case err == nil: + got = ok + case errors.Is(err, errBodyTooLarge): + got = tooLarge + case strings.Contains(err.Error(), "status"): + got = statusErr + default: + got = decodeErr + } + if got != tc.expected { + t.Fatalf("%s: outcome %d (err %v), expected %d", tc.description, got, err, tc.expected) + } + if got == ok && vi.APIVersion == "" { + t.Fatalf("%s: decoded no ApiVersion", tc.description) + } + }) + } +} + +// inspectJSON is a usable inspect body for aaaa, padded with a label to at +// least size bytes. +func inspectJSON(size int) string { + const head = `{"Id":"aaaa","Name":"/web","Config":{"Image":"nginx","Labels":{"pad":"` + const tail = `"}},"State":{"Pid":1},"NetworkSettings":{"SandboxKey":"/var/run/docker/netns/aaaahash"}}` + return head + strings.Repeat("x", max(0, size-len(head)-len(tail))) + tail +} + +func TestInspectBodyCap(t *testing.T) { + cases := []struct { + name string + cat string + description string + size int + expected bool // aaaa indexed + }{ + {"small", "P", "an ordinary inspect body", 0, true}, + {"big_labels", "B", "900 KiB of labels, under the 1 MiB cap", 900 << 10, true}, + {"at_cap", "B", "exactly maxInspectBody bytes", maxInspectBody, true}, + {"over_cap", "N", "maxInspectBody+1 bytes: aaaa skipped, the rest indexed", maxInspectBody + 1, false}, + {"far_over_cap", "N", "8 MiB of labels: aaaa skipped", 8 << 20, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + fs, srv := newFixtureServer(t) + fs.mu.Lock() + fs.inspects["aaaa111111111111111111111111111111111111111111111111111111111111"] = inspectJSON(tc.size) + fs.mu.Unlock() + + ix, err := newIndexFromClient(context.Background(), srv.Client(), srv.URL, fakeStat) + if err != nil { + t.Fatalf("newIndexFromClient: %v", err) + } + defer ix.Close() + if _, got := ix.Lookup(4026531001); got != tc.expected { + t.Fatalf("%s: aaaa indexed %v, expected %v", tc.description, got, tc.expected) + } + if _, ok := ix.Lookup(4026531002); !ok { + t.Fatalf("%s: bbbb must stay indexed", tc.description) + } + }) + } +} + +// countingBody is a ReadCloser of n bytes (n < 0: endless) that records how +// much was read and whether it was closed; failAfter > 0 returns an error +// once that many bytes are read. +type countingBody struct { + n, read, failAfter int + closed bool +} + +var errBodyRead = errors.New("read: connection reset") + +func (b *countingBody) Read(p []byte) (int, error) { + if b.failAfter > 0 && b.read >= b.failAfter { + return 0, errBodyRead + } + if b.n >= 0 && b.read >= b.n { + return 0, io.EOF + } + k := len(p) + if b.n >= 0 { + k = min(k, b.n-b.read) + } + if b.failAfter > 0 { + k = min(k, b.failAfter-b.read) + } + b.read += k + return k, nil +} + +func (b *countingBody) Close() error { b.closed = true; return nil } + +func TestDrainCloseBounded(t *testing.T) { + cases := []struct { + name string + cat string + description string + body countingBody + expected int // bytes read + }{ + {"short", "P", "a short body is drained to EOF", countingBody{n: 100}, 100}, + {"empty", "B", "an empty body", countingBody{n: 0}, 0}, + {"at_drain_cap", "B", "exactly maxDrain bytes", countingBody{n: maxDrain}, maxDrain}, + {"over_drain_cap", "N", "maxDrain+1 bytes: the last byte is left to Close", countingBody{n: maxDrain + 1}, maxDrain}, + {"endless", "C", "an endless stream (/events) returns after maxDrain", countingBody{n: -1}, maxDrain}, + {"read_error", "N", "a read error stops the drain; the body is still closed", countingBody{n: -1, failAfter: 10}, 10}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + b := tc.body + drainClose(&b) + if b.read != tc.expected || !b.closed { + t.Fatalf("%s: read %d closed %v, expected read %d closed true", tc.description, b.read, b.closed, tc.expected) + } + }) + } +} + +// TestEventsOversizedLineReturns: an /events line over the scanner's 1 MiB +// buffer ends the stream with bufio.ErrTooLong, and streamEvents returns +// promptly so refresh can fall back to re-listing. With an unbounded drain it +// blocked on the endless stream until ctx ended. +func TestEventsOversizedLineReturns(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fl, _ := w.(http.Flusher) + if _, err := fmt.Fprintf(w, "{\"Type\":\"container\",\"pad\":\"%s\"}\n", strings.Repeat("x", 2<<20)); err != nil { + return + } + for r.Context().Err() == nil { + if _, err := io.WriteString(w, "{}\n"); err != nil { + return + } + if fl != nil { + fl.Flush() + } + } + })) + defer srv.Close() + + ix := &Index{client: srv.Client(), baseURL: srv.URL, stat: fakeStat} + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + start := time.Now() + err := ix.streamEvents(ctx) + if !errors.Is(err, bufio.ErrTooLong) { + t.Fatalf("streamEvents: %v, expected bufio.ErrTooLong", err) + } + if d := time.Since(start); d > 10*time.Second { + t.Fatalf("streamEvents took %v: the drain did not stop", d) + } +} diff --git a/pkg/strpolicy/strpolicy_test.go b/pkg/strpolicy/strpolicy_test.go index 20ee321e6..85a7cc15d 100644 --- a/pkg/strpolicy/strpolicy_test.go +++ b/pkg/strpolicy/strpolicy_test.go @@ -4,6 +4,7 @@ import ( "strings" "testing" "unicode/utf8" + "unsafe" ) func TestClean(t *testing.T) { @@ -70,9 +71,49 @@ func TestCleanNoAlloc(t *testing.T) { } } +// cleanPropertyCases drive both TestCleanProperties (exact expectations) +// and FuzzClean (seeds). +var cleanPropertyCases = []struct { + name string + cat string + description string + in string + max int + expected string + identity bool // the input string itself comes back (no copy) +}{ + {"ascii_identity", "P", "short printable ASCII takes the fast path", "web-1", MaxLen, "web-1", true}, + {"ascii_at_max", "B", "16 ASCII bytes at max 16", "eth0-tenant-abcd", MaxIfname, "eth0-tenant-abcd", true}, + {"ascii_over_max", "B", "17 ASCII bytes at max 16 are cut to 16", "eth0-tenant-abcde", MaxIfname, "eth0-tenant-abcd", false}, + {"replaced_then_clean", "N", "ESC becomes U+FFFD, which a second Clean keeps", "a\x1bb", MaxLen, "a\uFFFDb", false}, + {"truncate_rune_twice", "C", "a 3-byte rune straddling max is dropped, and stays dropped", "ab\u20ac", 4, "ab", false}, + {"negative_max", "C", "a negative max gives the empty string", "abc", -1, "", false}, + {"space_and_tilde", "B", "0x20 and 0x7e are the printable ASCII edges", " ~", MaxLen, " ~", true}, +} + +func TestCleanProperties(t *testing.T) { + for _, tc := range cleanPropertyCases { + t.Run(tc.name, func(t *testing.T) { + got := Clean(tc.in, tc.max) + if got != tc.expected { + t.Fatalf("%s: Clean(%q, %d) = %q, expected %q", tc.description, tc.in, tc.max, got, tc.expected) + } + if again := Clean(got, tc.max); again != got { + t.Fatalf("%s: not idempotent: %q then %q", tc.description, got, again) + } + if tc.identity && unsafe.StringData(got) != unsafe.StringData(tc.in) { + t.Fatalf("%s: expected the input string back, got a copy", tc.description) + } + }) + } +} + func FuzzClean(f *testing.F) { f.Add("web-1", 256) f.Add("a\xffb\x1b", 3) + for _, tc := range cleanPropertyCases { + f.Add(tc.in, tc.max) + } f.Fuzz(func(t *testing.T, s string, maxBytes int) { maxBytes %= 512 got := Clean(s, maxBytes) @@ -87,6 +128,12 @@ func FuzzClean(f *testing.F) { t.Fatalf("Clean(%q, %d) = %q: control rune %U kept", s, maxBytes, got, r) } } + if again := Clean(got, maxBytes); again != got { + t.Fatalf("Clean not idempotent for (%q, %d): %q then %q", s, maxBytes, got, again) + } + if maxBytes > 0 && len(s) <= maxBytes && printableASCII(s) && got != s { + t.Fatalf("Clean(%q, %d) = %q: printable ASCII within max must come back unchanged", s, maxBytes, got) + } }) } diff --git a/pkg/xtcp/destinations_s3parquet_fuzz_test.go b/pkg/xtcp/destinations_s3parquet_fuzz_test.go new file mode 100644 index 000000000..aabb0633d --- /dev/null +++ b/pkg/xtcp/destinations_s3parquet_fuzz_test.go @@ -0,0 +1,306 @@ +//go:build dest_s3parquet + +package xtcp + +import ( + "bytes" + "context" + "encoding/binary" + "errors" + "io" + "math" + "reflect" + "strings" + "testing" + + "github.com/parquet-go/parquet-go" + "google.golang.org/protobuf/encoding/protodelim" + "google.golang.org/protobuf/proto" + + "github.com/randomizedcoder/xtcp2/gen/go/xtcp_flat_record" +) + +// roundTripEnvelope runs one delimited envelope through the S3 worker's row +// path (processItem in destinations_s3parquet.go): unmarshal, rowFromProto, +// the event_date stamp, a Parquet write, and then reads the object back. An +// unmarshal error is returned (the worker drops such an envelope and counts +// it); a Parquet write or read failure fails the test, since every decoded +// row must be writable. +func roundTripEnvelope(tb testing.TB, data []byte) (written, read []ParquetRow, err error) { + tb.Helper() + var env xtcp_flat_record.Envelope + if err := protodelim.UnmarshalFrom(bytes.NewReader(data), &env); err != nil { + return nil, nil, err + } + written = make([]ParquetRow, 0, len(env.Row)) + for _, r := range env.Row { + row := rowFromProto(r) + row.EventDate = utcDateFromNs(r.TimestampNs) + written = append(written, row) + } + var buf bytes.Buffer + w := parquet.NewGenericWriter[ParquetRow](&buf) + if _, err := w.Write(written); err != nil { + tb.Fatalf("parquet write of %d rows: %v", len(written), err) + } + if err := w.Close(); err != nil { + tb.Fatalf("parquet close: %v", err) + } + rd := parquet.NewGenericReader[ParquetRow](bytes.NewReader(buf.Bytes())) + defer func() { + if err := rd.Close(); err != nil { + tb.Errorf("parquet reader close: %v", err) + } + }() + read = make([]ParquetRow, rd.NumRows()) + n, err := rd.Read(read) + if err != nil && !errors.Is(err, io.EOF) { + tb.Fatalf("parquet read: %v", err) + } + return written, read[:n], nil +} + +// checkRoundTrip asserts what must hold for any envelope that decodes: every +// row comes back, each column equal to what was written, and event_date is +// the UTC day of timestamp_ns. +func checkRoundTrip(tb testing.TB, written, read []ParquetRow) { + tb.Helper() + if len(read) != len(written) { + tb.Fatalf("read %d rows, wrote %d", len(read), len(written)) + } + for i := range written { + if !reflect.DeepEqual(normalizeRow(written[i]), normalizeRow(read[i])) { + tb.Fatalf("row %d changed in the round trip:\nwrote %+v\nread %+v", i, written[i], read[i]) + } + if want := utcDateFromNs(written[i].TimestampNs); read[i].EventDate != want { + tb.Fatalf("row %d: EventDate %q, expected %q", i, read[i].EventDate, want) + } + } +} + +// normalizeRow maps empty byte slices to nil: Parquet does not keep the +// difference between a nil and an empty BYTE_ARRAY, and neither do readers. +func normalizeRow(r ParquetRow) ParquetRow { + v := reflect.ValueOf(&r).Elem() + for i := 0; i < v.NumField(); i++ { + f := v.Field(i) + if f.Kind() == reflect.Slice && f.Len() == 0 && f.CanSet() { + f.Set(reflect.Zero(f.Type())) + } + } + return r +} + +// delimited marshals rows into one length-delimited envelope, the form the +// worker's queue carries. +func delimited(tb testing.TB, rows ...*xtcp_flat_record.XtcpFlatRecord) []byte { + tb.Helper() + var buf bytes.Buffer + if _, err := protodelim.MarshalTo(&buf, &xtcp_flat_record.Envelope{Row: rows}); err != nil { + tb.Fatalf("marshal envelope: %v", err) + } + return buf.Bytes() +} + +// sentinelRecord sets every string field to a distinct value and every +// numeric field to its ordinal, so a crossed or dropped column shows in the +// round trip. +func sentinelRecord(tb testing.TB) *xtcp_flat_record.XtcpFlatRecord { + tb.Helper() + rec := &xtcp_flat_record.XtcpFlatRecord{} + v := reflect.ValueOf(rec).Elem() + for i := 0; i < v.NumField(); i++ { + f := v.Field(i) + if !v.Type().Field(i).IsExported() { + continue + } + switch f.Kind() { + case reflect.String: + f.SetString("s" + v.Type().Field(i).Name) + case reflect.Int32, reflect.Int64: + f.SetInt(int64(i + 1)) + case reflect.Uint32, reflect.Uint64: + f.SetUint(uint64(i + 1)) + case reflect.Bool: + f.SetBool(true) + case reflect.Slice: + if f.Type().Elem().Kind() == reflect.Uint8 { + f.SetBytes([]byte{byte(i), 0xA5}) + } + default: + tb.Fatalf("field %s: kind %s has no sentinel; add one", v.Type().Field(i).Name, f.Kind()) + } + } + rec.TimestampNs = 1_700_000_000_000_000_000 + return rec +} + +// realDumpEnvelope decodes the captured netlink dump that FuzzDeserialize +// also seeds from, and returns its records as one delimited envelope. +func realDumpEnvelope(tb testing.TB) []byte { + tb.Helper() + x := newTestDeserializeXTCP(tb) + x.dest = newRecordingDest(x) + x.currentEnvelope = &xtcp_flat_record.Envelope{} + buf := loadRealMultipart(tb) + ns := "fuzz-ns" + if _, err := x.Deserialize(context.Background(), DeserializeArgs{ + ns: &ns, + NLPacket: &buf, + xtcpRecordPool: &x.xtcpRecordPool, + nlhPool: &x.nlhPool, + rtaPool: &x.rtaPool, + pC: x.pC, + pH: x.pH, + }); err != nil { + tb.Fatalf("deserialize the real dump: %v", err) + } + if len(x.currentEnvelope.Row) == 0 { + tb.Fatal("the real dump decoded to zero rows") + } + return delimited(tb, x.currentEnvelope.Row...) +} + +// invalidUTF8Envelope marshals a valid record, then overwrites its hostname +// bytes in place with 0xff, which proto3 string fields must reject. +func invalidUTF8Envelope(tb testing.TB) []byte { + tb.Helper() + b := delimited(tb, &xtcp_flat_record.XtcpFlatRecord{Hostname: "HOSTNAME", TimestampNs: 1}) + i := bytes.Index(b, []byte("HOSTNAME")) + if i < 0 { + tb.Fatal("hostname bytes not found in the envelope") + } + b[i], b[i+1] = 0xff, 0xfe + return b +} + +type rowRoundTripWant struct { + unmarshalErr bool + rows int + eventDates []string // checked when set +} + +// rowRoundTripCase is one envelope. The rows drive both +// TestRowFromProtoRoundTrip (exact expectations) and FuzzRowFromProto (seeds). +type rowRoundTripCase struct { + name string + cat string + description string + envelope func(tb testing.TB) []byte + expected rowRoundTripWant +} + +func rowRoundTripCases() []rowRoundTripCase { + const midnight = 1_700_006_400_000_000_000 // 2023-11-15T00:00:00Z + rec := func(host string, ts int64) *xtcp_flat_record.XtcpFlatRecord { + return &xtcp_flat_record.XtcpFlatRecord{Hostname: host, TimestampNs: ts} + } + return []rowRoundTripCase{ + {"empty_envelope", "B", "an envelope with zero rows", + func(tb testing.TB) []byte { return delimited(tb) }, + rowRoundTripWant{rows: 0}}, + {"sentinel_all_fields", "P", "every field carries a distinct sentinel; every column must come back equal", + func(tb testing.TB) []byte { return delimited(tb, sentinelRecord(tb)) }, + rowRoundTripWant{rows: 1, eventDates: []string{"2023-11-14"}}}, + {"three_rows", "P", "three rows with distinct hostnames keep their order", + func(tb testing.TB) []byte { + return delimited(tb, rec("a", 1), rec("b", 2), rec("c", 3)) + }, + rowRoundTripWant{rows: 3}}, + {"hostile_strings", "N", "ESC, U+FFFD, C1 and a 1 kB string in string fields round-trip byte for byte", + func(tb testing.TB) []byte { + r := rec("\x1b[2J\x1b]0;x\x07", midnight) + r.Netns = "�\u0085" + r.Label = strings.Repeat("L", 1024) + r.ContainerName = "web\x00null" + return delimited(tb, r) + }, + rowRoundTripWant{rows: 1, eventDates: []string{"2023-11-15"}}}, + {"invalid_utf8_rejected", "N", "invalid UTF-8 in a proto3 string fails the unmarshal, so the worker drops the envelope", + invalidUTF8Envelope, + rowRoundTripWant{unmarshalErr: true}}, + {"truncated_prefix", "N", "a varint length prefix cut short", + func(testing.TB) []byte { return []byte{0x80} }, + rowRoundTripWant{unmarshalErr: true}}, + {"length_over_body", "N", "the prefix says 1 MB but only 10 bytes follow", + func(testing.TB) []byte { + b := binary.AppendUvarint(nil, 1<<20) + return append(b, make([]byte, 10)...) + }, + rowRoundTripWant{unmarshalErr: true}}, + {"zero_timestamp", "B", "timestamp_ns 0 is the Unix epoch", + func(tb testing.TB) []byte { return delimited(tb, rec("z", 0)) }, + rowRoundTripWant{rows: 1, eventDates: []string{"1970-01-01"}}}, + {"max_timestamp", "B", "timestamp_ns MaxInt64 formats without a panic", + func(tb testing.TB) []byte { return delimited(tb, rec("m", math.MaxInt64)) }, + rowRoundTripWant{rows: 1, eventDates: []string{"2262-04-11"}}}, + {"negative_timestamp", "C", "a negative timestamp_ns is before the epoch", + func(tb testing.TB) []byte { return delimited(tb, rec("n", -1)) }, + rowRoundTripWant{rows: 1, eventDates: []string{"1969-12-31"}}}, + {"day_boundary", "C", "rows 1 ns either side of midnight UTC get different event dates", + func(tb testing.TB) []byte { + return delimited(tb, rec("a", midnight-1), rec("b", midnight)) + }, + rowRoundTripWant{rows: 2, eventDates: []string{"2023-11-14", "2023-11-15"}}}, + {"real_dump", "P", "records decoded from the captured netlink dump", + realDumpEnvelope, + rowRoundTripWant{rows: -1}}, // -1: as many as the dump holds + } +} + +func TestRowFromProtoRoundTrip(t *testing.T) { + for _, tc := range rowRoundTripCases() { + t.Run(tc.name, func(t *testing.T) { + data := tc.envelope(t) + written, read, err := roundTripEnvelope(t, data) + if (err != nil) != tc.expected.unmarshalErr { + t.Fatalf("%s: unmarshal err %v, expected error %v", tc.description, err, tc.expected.unmarshalErr) + } + if err != nil { + return + } + checkRoundTrip(t, written, read) + if tc.expected.rows >= 0 && len(read) != tc.expected.rows { + t.Fatalf("%s: %d rows, expected %d", tc.description, len(read), tc.expected.rows) + } + if tc.expected.rows < 0 && len(read) == 0 { + t.Fatalf("%s: no rows", tc.description) + } + for i, want := range tc.expected.eventDates { + if read[i].EventDate != want { + t.Fatalf("%s: row %d EventDate %q, expected %q", tc.description, i, read[i].EventDate, want) + } + } + if tc.name == "three_rows" { + for i, want := range []string{"a", "b", "c"} { + if read[i].Hostname != want { + t.Fatalf("%s: row %d Hostname %q, expected %q", tc.description, i, read[i].Hostname, want) + } + } + } + }) + } +} + +// FuzzRowFromProto feeds arbitrary bytes to the S3 worker's row path. Rows +// come from tenant-influenced records (container names, netns names, +// interface names), so any envelope that decodes must write to Parquet and +// read back unchanged. +// +// go test -tags dest_s3parquet -run '^$' -fuzz '^FuzzRowFromProto$' -fuzztime=30s ./pkg/xtcp/ +func FuzzRowFromProto(f *testing.F) { + for _, tc := range rowRoundTripCases() { + f.Add(tc.envelope(f)) + } + // A bare record, not delimited: the fuzzer can learn the framing from it. + if b, err := proto.Marshal(&xtcp_flat_record.Envelope{}); err == nil { + f.Add(b) + } + f.Fuzz(func(t *testing.T, data []byte) { + written, read, err := roundTripEnvelope(t, data) + if err != nil { + return + } + checkRoundTrip(t, written, read) + }) +}