From cdfb2452489aaf034e9caf3927740603a4adf91b Mon Sep 17 00:00:00 2001 From: "randomizedcoder dave.seddon.ca@gmail.com" Date: Mon, 23 Nov 2026 08:35:42 -0800 Subject: [PATCH] fix(dockermeta): stream Docker list/inspect bodies; 4 MiB per-container limits Replace the whole-body caps with a streaming JSON walker that keeps only the projected fields and skips the rest without buffering. An oversized container is skipped alone instead of failing the whole re-list. - maxInspectBody / maxListEntry = 4 MiB per container; no list total - maxIDRaw / maxTextRaw = 4 KiB for kept strings - requestTimeout = 10 s per Docker API request - walker matches encoding/json accept/reject (differential tests + fuzz) - limits documented in design-metadata-enrichment.md and hardening C5 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- docs/design-metadata-enrichment.md | 27 + .../focused-container-hardening.md | 1 + .../focused-implementation-plan.md | 2 +- pkg/dockermeta/dockermeta.go | 76 ++- pkg/dockermeta/dockermeta_fuzz_test.go | 18 +- pkg/dockermeta/dockermeta_limit_test.go | 100 ++- pkg/dockermeta/jsonwalk.go | 624 ++++++++++++++++++ pkg/dockermeta/jsonwalk_test.go | 222 +++++++ 9 files changed, 1025 insertions(+), 47 deletions(-) create mode 100644 pkg/dockermeta/jsonwalk.go create mode 100644 pkg/dockermeta/jsonwalk_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index f30014dee..e6fa043fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,7 +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. +- **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 container list and inspect bodies are now streamed, keeping only the fields used: memory stays bounded however large a container's labels are, a container whose entry passes 4 MiB is skipped and logged (never the whole list), each request has a 10 s timeout, and an oversized `/events` line no longer stalls container-metadata refresh. Limits: [Docker API limits](docs/design-metadata-enrichment.md#docker-api-limits). - **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/design-metadata-enrichment.md b/docs/design-metadata-enrichment.md index a1514a8da..414173234 100644 --- a/docs/design-metadata-enrichment.md +++ b/docs/design-metadata-enrichment.md @@ -83,6 +83,33 @@ usable routes count (up, not reject, not on `lo`: every host has the kernel's bridge) is replaced by the physical NICs under its `lower_*` sysfs links, since those carry the NIC attributes and the LLDP neighbours. +### Docker API limits + +Docker's list and inspect bodies carry tenant-chosen data (image labels, the +container name), so `pkg/dockermeta` streams them (`jsonwalk.go`): it keeps only +Id, Name, Image, `State.Pid` and `NetworkSettings.SandboxKey`, and validates and +discards everything else, labels included, without buffering it. Memory is about +37 KiB per body whatever its size. The limits bound CPU and are constants: + +| Constant | Value | Applies to | Over the limit | +|---|---|---|---| +| `maxInspectBody` | 4 MiB | one `GET /containers/{id}/json` | that container is skipped (logged) | +| `maxListEntry` | 4 MiB | one container's entry in `GET /containers/json` | that entry is dropped (logged); the list still builds | +| `maxIDRaw` | 4 KiB | `Id`, `SandboxKey` (set by the daemon) | that container is skipped (logged) | +| `maxTextRaw` | 4 KiB | `Name`, `Image` | cut; `strpolicy.Clean` then cuts to 256 bytes | +| `maxVersionBody` | 64 KiB | `GET /version` | version negotiation falls back to unversioned paths | +| `requestTimeout` | 10 s | every list, inspect and version request | the request fails: a skipped container, or a failed re-list that keeps the previous index | +| `maxDrain` | 64 KiB | the unread rest of any body | the connection is closed instead of reused | + +Measured on a host with 31 containers: inspect bodies are 6.8–13.7 KB (labels at +most 638 B) and the list is about 2.5 KB per container, so 4 MiB is about 300× +the largest. The list has no total limit on purpose: a total would let a few +padded containers fail every re-list for the whole host. A tenant can make +its own container unattributed by padding its image labels past 4 MiB, and +nothing more; each walk costs about 27 ms at that size. `/events` is a stream +and has no timeout; a line over 1 MiB ends it and the index falls back to +re-listing. + ## 3. Config: flags / env / config protobuf Precedence: **defaults < flags < env < `XTCP_CONFIG_JSON`** (`cmd/xtcp2/xtcp2.go`). diff --git a/docs/security-hardening/focused-container-hardening.md b/docs/security-hardening/focused-container-hardening.md index 77d63f97f..02fdd948d 100644 --- a/docs/security-hardening/focused-container-hardening.md +++ b/docs/security-hardening/focused-container-hardening.md @@ -177,6 +177,7 @@ Author and publish this as the reference `docker-compose`/OCI config (none exist | C2 | **(code)** Cap the number of tracked namespaces (`-maxNetns`), oldest-idle eviction, counter. | Bounded goroutines, sockets and memory. | | C3 | **(code)** Explicit, metered S3 queue depth and total buffered bytes; when full, drop oldest with a counter rather than grow. | Memory bound under S3 outage. | | C4 | **(code)** String policy in `rowFromProto` and the JSON/line marshallers for every tenant- or host-influenced string column (`container_name`, `container_image`, `label`, `*_lldp_chassis_name`, congestion-control name): max length (e.g. 256), valid UTF-8, control characters replaced. Same policy in log lines. | Keeps Parquet objects and logs predictable; stops log injection. | +| C5 | **(code)** Docker API bodies streamed, not buffered: list and inspect keep only the projected fields and skip the rest (labels) unbuffered; per-container limits (`maxInspectBody`, `maxListEntry`, 4 MiB), a 10 s `requestTimeout`, a bounded drain. Values and rationale: [Docker API limits](../design-metadata-enrichment.md#docker-api-limits). | A tenant's image labels can cost at most its own container's attribution, never another's, and never collector memory. | ### D. Build and supply chain diff --git a/docs/security-hardening/focused-implementation-plan.md b/docs/security-hardening/focused-implementation-plan.md index df253c475..332909b82 100644 --- a/docs/security-hardening/focused-implementation-plan.md +++ b/docs/security-hardening/focused-implementation-plan.md @@ -249,7 +249,7 @@ Non-blocking shortfalls found while implementing F1; none blocks R1. | 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 | — | +| ~~Cap `dockermeta.getJSON`'s body~~ done in #312 as focused design C5, a walk rather than a cap: a whole-body cap let a tenant image pad its labels to hide its container (inspect) or freeze the host's index (list). `jsonwalk.go` keeps only the projected fields and skips the rest unbuffered, with encoding/json's accept/reject (`FuzzDockerProjection`, `FuzzDecodeIDs` are differential). Limits: 4 MiB per inspect and per list entry, no list total, 10 s per request, 64 KiB drain ([Docker API limits](../design-metadata-enrichment.md#docker-api-limits)). The drain fix: an `/events` line over 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/pkg/dockermeta/dockermeta.go b/pkg/dockermeta/dockermeta.go index 6cdd7fb5a..fd6f14725 100644 --- a/pkg/dockermeta/dockermeta.go +++ b/pkg/dockermeta/dockermeta.go @@ -54,16 +54,16 @@ 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. +// Response body bounds. The list and inspect bodies carry tenant-chosen +// labels, so they are walked, not capped (see jsonwalk.go). const ( - // maxVersionBody caps GET /version, a few hundred bytes in practice. + // maxVersionBody caps GET /version, a few hundred bytes and no tenant + // data, so a plain cap is safe. 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 + // requestTimeout bounds one list, inspect or version request, so a body + // that trickles in cannot stall the refresh goroutine. Not /events, + // which is a stream by design. + requestTimeout = 10 * time.Second // 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. @@ -240,11 +240,6 @@ func splitVersion(s string) []int { return out } -// containerRef is one entry of GET /containers/json. -type containerRef struct { - ID string `json:"Id"` -} - // inspect is the subset of GET /containers/{id}/json we decode. type inspect struct { ID string `json:"Id"` @@ -266,16 +261,25 @@ type inspect struct { // per-container inspect failures are skipped so one bad container can't sink // 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", maxListBody, &refs); err != nil { + var ids []string + dropped := 0 + err := walkJSON(ctx, ix.client, ix.baseURL+"/containers/json", func(r io.Reader) error { + var err error + ids, dropped, err = decodeIDs(r, noLimit, maxListEntry) + return err + }) + if err != nil { return nil, fmt.Errorf("list containers: %w", err) } - m := make(map[uint64]Container, len(refs)) - for _, ref := range refs { - if ref.ID == "" { + if dropped > 0 { + log.Printf("dockermeta: list: %d container(s) skipped: entry over %d bytes or Id over %d", dropped, maxListEntry, maxIDRaw) + } + m := make(map[uint64]Container, len(ids)) + for _, id := range ids { + if id == "" { continue } - if c, ok := ix.inspect(ctx, ref.ID); ok { + if c, ok := ix.inspect(ctx, id); ok { m[c.NetnsInode] = c } } @@ -287,7 +291,17 @@ 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", maxInspectBody, &in); err != nil { + err := walkJSON(ctx, ix.client, ix.baseURL+"/containers/"+id+"/json", func(r io.Reader) error { + var err error + in, err = decodeInspect(r, maxInspectBody) + return err + }) + if err != nil { + // A size refusal is worth seeing: it is the one skip a body's + // content can force. Other errors (gone, malformed) stay quiet. + if errors.Is(err, errBodyTooLarge) || errors.Is(err, errFieldTooLong) { + log.Printf("dockermeta: inspect %.12s skipped: %v", id, err) + } return Container{}, false } return project(in, ix.stat) @@ -425,10 +439,32 @@ func (ix *Index) rebuild(ctx context.Context) { ix.snapshot.Store(&m) } +// walkJSON does a GET and hands a 2xx body to decode. A non-2xx status is an +// error without reading the body. +func walkJSON(ctx context.Context, client *http.Client, url string, decode func(io.Reader) error) error { + ctx, cancel := context.WithTimeout(ctx, requestTimeout) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return err + } + resp, err := client.Do(req) + if err != nil { + return err + } + defer drainClose(resp.Body) + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return fmt.Errorf("GET %s: status %d", url, resp.StatusCode) + } + return decode(resp.Body) +} + // 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 { + ctx, cancel := context.WithTimeout(ctx, requestTimeout) + defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return err diff --git a/pkg/dockermeta/dockermeta_fuzz_test.go b/pkg/dockermeta/dockermeta_fuzz_test.go index e0e967192..db969ee41 100644 --- a/pkg/dockermeta/dockermeta_fuzz_test.go +++ b/pkg/dockermeta/dockermeta_fuzz_test.go @@ -1,7 +1,6 @@ package dockermeta import ( - "encoding/json" "errors" "os" "path/filepath" @@ -191,15 +190,15 @@ func TestDockerProjectionJSON(t *testing.T) { if err != nil { t.Fatalf("%s: %v", tc.name, err) } - var in inspect - if err := json.Unmarshal(data, &in); err != nil { + in, err := checkInspectParity(t, data) + if err != nil { if !tc.expected.unmarshalErr { - t.Fatalf("%s: unmarshal: %v", tc.description, err) + t.Fatalf("%s: decode: %v", tc.description, err) } return } if tc.expected.unmarshalErr { - t.Fatalf("%s: unmarshal succeeded, expected an error", tc.description) + t.Fatalf("%s: decode succeeded, expected an error", tc.description) } c, ok := project(in, fakeStat) got := projectionWant{ok: ok, name: c.Name, image: c.Image, pid: c.Pid} @@ -213,10 +212,11 @@ func TestDockerProjectionJSON(t *testing.T) { } } -// FuzzDockerProjection feeds arbitrary inspect bodies through json.Unmarshal +// FuzzDockerProjection feeds arbitrary inspect bodies through decodeInspect // 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. +// valid UTF-8 without control runes. decodeInspect must also accept and +// project exactly what encoding/json would (checkInspectParity). // // go test -run '^$' -fuzz '^FuzzDockerProjection$' -fuzztime=30s ./pkg/dockermeta/ func FuzzDockerProjection(f *testing.F) { @@ -229,8 +229,8 @@ func FuzzDockerProjection(f *testing.F) { f.Add(data) } f.Fuzz(func(t *testing.T, data []byte) { - var in inspect - if err := json.Unmarshal(data, &in); err != nil { + in, err := checkInspectParity(t, data) + if err != nil { return } c, ok := project(in, fuzzStat) diff --git a/pkg/dockermeta/dockermeta_limit_test.go b/pkg/dockermeta/dockermeta_limit_test.go index 5a18838b7..9914ef525 100644 --- a/pkg/dockermeta/dockermeta_limit_test.go +++ b/pkg/dockermeta/dockermeta_limit_test.go @@ -84,38 +84,78 @@ func TestGetJSONLimit(t *testing.T) { } } -// 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 +// inspectJSON is a usable inspect body for aaaa with label bytes of padding +// and the given Id and SandboxKey. +func inspectJSON(labels int, id, sandbox string) string { + return `{"Id":"` + id + `","Name":"/web","Config":{"Image":"nginx","Labels":{"pad":"` + + strings.Repeat("x", labels) + `"}},"State":{"Pid":1},"NetworkSettings":{"SandboxKey":"` + sandbox + `"}}` } -func TestInspectBodyCap(t *testing.T) { +// listJSON is a /containers/json body for aaaa and bbbb, aaaa's entry padded +// with label bytes and carrying the given Id. +func listJSON(labels int, aaaaID string) string { + return `[{"Id":"` + aaaaID + `","Labels":{"pad":"` + strings.Repeat("x", labels) + `"}},` + + `{"Id":"bbbb222222222222222222222222222222222222222222222222222222222222"}]` +} + +// TestTenantBodySize: label padding, the part of a body a tenant image +// controls, drops at most its own container, never another's, and never +// fails the list. +func TestTenantBodySize(t *testing.T) { + const aaaaID = "aaaa111111111111111111111111111111111111111111111111111111111111" + const key = "/var/run/docker/netns/aaaahash" + long := strings.Repeat("a", maxIDRaw+1) + // Label padding that makes the inspect body, or aaaa's list entry, exactly + // its limit. + inspectPad := maxInspectBody - len(inspectJSON(0, aaaaID, key)) + entryPad := maxListEntry - (len(listJSON(0, aaaaID)) - len(listJSON(0, "")) + len(`{"Id":"","Labels":{"pad":""}}`)) + // Seventeen padded entries: past the 64 MiB a list total would have had. + many := "[" + strings.Repeat(`{"Id":"p","Labels":{"pad":"`+strings.Repeat("x", 4<<20-64)+`"}},`, 17) + listJSON(0, aaaaID)[1:] cases := []struct { name string cat string description string - size int - expected bool // aaaa indexed + list string + inspect string + expected bool // aaaa indexed; bbbb must be indexed in every row }{ - {"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}, + {"small", "P", "an ordinary list and inspect", + listJSON(0, aaaaID), inspectJSON(0, aaaaID, key), true}, + {"inspect_labels_3MiB", "P", "3 MiB of labels in inspect, under maxInspectBody", + listJSON(0, aaaaID), inspectJSON(3<<20, aaaaID, key), true}, + {"inspect_at_limit", "B", "an inspect body of exactly maxInspectBody", + listJSON(0, aaaaID), inspectJSON(inspectPad, aaaaID, key), true}, + {"inspect_over_limit", "B", "maxInspectBody+1: aaaa skipped (and logged)", + listJSON(0, aaaaID), inspectJSON(inspectPad+1, aaaaID, key), false}, + {"entry_at_limit", "B", "aaaa's list entry of exactly maxListEntry", + listJSON(entryPad, aaaaID), inspectJSON(0, aaaaID, key), true}, + {"entry_over_limit", "B", "maxListEntry+1: aaaa's entry dropped, the list still builds", + listJSON(entryPad+1, aaaaID), inspectJSON(0, aaaaID, key), false}, + {"many_padded_entries", "C", "17 entries of ~4 MiB (68 MiB) do not fail the list", + many, inspectJSON(0, aaaaID, key), true}, + {"inspect_id_at_cap", "B", "an inspect Id of exactly maxIDRaw bytes is kept", + listJSON(0, aaaaID), inspectJSON(0, strings.Repeat("a", maxIDRaw), key), true}, + {"inspect_id_over_cap", "N", "a daemon-set Id over maxIDRaw: aaaa skipped", + listJSON(0, aaaaID), inspectJSON(0, long, key), false}, + {"sandbox_over_cap", "N", "a SandboxKey over maxIDRaw: aaaa skipped", + listJSON(0, aaaaID), inspectJSON(0, aaaaID, "/"+long), false}, + {"list_id_over_cap", "C", "an over-long Id in one list entry drops that entry only", + listJSON(0, long), inspectJSON(0, aaaaID, key), false}, + {"malformed_label", "N", "a raw control byte in a skipped label is still a syntax error: aaaa skipped", + listJSON(0, aaaaID), strings.Replace(inspectJSON(4, aaaaID, key), "xxxx", "x\x01x", 1), 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.containers = tc.list + fs.inspects[aaaaID] = tc.inspect + fs.inspects[long] = tc.inspect fs.mu.Unlock() ix, err := newIndexFromClient(context.Background(), srv.Client(), srv.URL, fakeStat) if err != nil { - t.Fatalf("newIndexFromClient: %v", err) + t.Fatalf("%s: newIndexFromClient: %v", tc.description, err) } defer ix.Close() if _, got := ix.Lookup(4026531001); got != tc.expected { @@ -217,3 +257,31 @@ func TestEventsOversizedLineReturns(t *testing.T) { t.Fatalf("streamEvents took %v: the drain did not stop", d) } } + +// TestRequestTimeout: a list body that stalls after its first byte fails the +// request at requestTimeout instead of holding the refresh goroutine. +func TestRequestTimeout(t *testing.T) { + t.Parallel() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/version" { + _, _ = io.WriteString(w, `{"ApiVersion":"1.44","MinAPIVersion":"1.24"}`) + return + } + _, _ = io.WriteString(w, "[") + if fl, ok := w.(http.Flusher); ok { + fl.Flush() + } + <-r.Context().Done() + })) + defer srv.Close() + + start := time.Now() + _, err := newIndexFromClient(context.Background(), srv.Client(), srv.URL, fakeStat) + d := time.Since(start) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("newIndexFromClient: %v, expected a deadline error", err) + } + if d < requestTimeout || d > requestTimeout+5*time.Second { + t.Fatalf("took %v, expected about requestTimeout (%v)", d, requestTimeout) + } +} diff --git a/pkg/dockermeta/jsonwalk.go b/pkg/dockermeta/jsonwalk.go new file mode 100644 index 000000000..bb8df838e --- /dev/null +++ b/pkg/dockermeta/jsonwalk.go @@ -0,0 +1,624 @@ +package dockermeta + +import ( + "bufio" + "encoding/json" + "errors" + "fmt" + "io" + "strings" +) + +// The Docker bodies carry tenant-chosen data (image labels, names) that we +// never use. A cap on the whole body would let a tenant hide its container +// (or, through /containers/json, freeze the host's index) by padding its +// labels, so instead the walker below keeps only the projected fields and +// skips everything else without buffering it, so memory is bounded by the +// kept fields (about 37 KiB per walk) whatever the body's size. The byte +// limits below bound CPU (the walk reads ~130-200 MB/s) and are set far above +// real bodies; a body over one drops that one container, and is logged. +// +// Accept/reject matches json.NewDecoder(r).Decode into the same structs: +// syntax is validated everywhere (skipped values included), keys match +// case-insensitively and the last duplicate wins, null leaves a field +// unchanged, a wrong type is an error, nesting is limited to 10000 and +// data after the top-level value is ignored. FuzzDockerProjection checks +// this against encoding/json. + +// Docker body limits. Measured on a host with 31 containers: inspect bodies +// 6.8-13.7 KB, labels at most 638 B, /containers/json 78 KB (~2.5 KB per +// container). Documented in docs/security-hardening/focused-container- +// hardening.md (C5). +const ( + // maxInspectBody bounds one GET /containers/{id}/json: ~300x the largest + // measured. Over it, the container is skipped. + maxInspectBody = 4 << 20 + // maxListEntry bounds one container's entry in GET /containers/json, the + // same as an inspect body. Over it, that entry is dropped, so a few + // padded containers cannot fail the whole list. + maxListEntry = maxInspectBody + // The list has no total byte limit: a total would let a few padded + // containers (16 at 4 MiB) fail every re-list. Memory is constant, the + // tenant-driven CPU is bounded per entry, and requestTimeout stops a + // body that never ends. + // maxWalkDepth is encoding/json's nesting limit. + maxWalkDepth = 10000 + // maxKeyRaw is the longest key kept for matching; the longest wanted key, + // NetworkSettings, is 90 bytes with every rune \u-escaped. + maxKeyRaw = 256 + // maxTextRaw caps a kept Name or Image: at least 682 decoded bytes, so + // strpolicy.Clean's 256-byte result is the same as for the full string. + maxTextRaw = 4 << 10 + // maxIDRaw caps the daemon-set ID and SandboxKey; longer is an error. + maxIDRaw = 4 << 10 + // maxNumberRaw caps an int token; a valid int is at most 20 bytes. + maxNumberRaw = 64 +) + +var ( + errWalkSyntax = errors.New("json syntax error") + errWalkType = errors.New("json type mismatch") + errWalkDepth = errors.New("json nesting too deep") + errFieldTooLong = errors.New("daemon-set field over its cap") +) + +// walker reads one JSON value from r, keeping only what its callers ask for. +type walker struct { + r *bufio.Reader + c *capReader + depth int +} + +// noLimit is the limit for a body bounded only by requestTimeout. +const noLimit = 0 + +// capReader counts the bytes read and, with a limit, fails with +// errBodyTooLarge once more than limit are read. +type capReader struct { + r io.Reader + read int64 + limit int64 // noLimit: count only +} + +func (c *capReader) Read(p []byte) (int, error) { + if c.limit == noLimit { + k, err := c.r.Read(p) + c.read += int64(k) + return k, err + } + if c.read > c.limit { + return 0, errBodyTooLarge + } + if room := c.limit - c.read + 1; int64(len(p)) > room { + p = p[:room] + } + k, err := c.r.Read(p) + c.read += int64(k) + if c.read > c.limit { + return k, errBodyTooLarge + } + return k, err +} + +func newWalker(r io.Reader, limit int64) *walker { + c := &capReader{r: r, limit: limit} + return &walker{r: bufio.NewReaderSize(c, 32<<10), c: c} +} + +// overLimit reports that the walk consumed more than the limit. capReader's +// error can trail the last bytes it hands over, which a walk may finish on. +func (w *walker) overLimit() bool { + return w.c.limit != noLimit && w.pos() > w.c.limit +} + +// pos is how many body bytes the walk has consumed. +func (w *walker) pos() int64 { + return w.c.read - int64(w.r.Buffered()) +} + +// next skips whitespace and returns the next byte without consuming it. +func (w *walker) next() (byte, error) { + for { + b, err := w.r.ReadByte() + if err != nil { + if errors.Is(err, io.EOF) { + return 0, io.ErrUnexpectedEOF + } + return 0, err + } + switch b { + case ' ', '\t', '\n', '\r': + continue + } + return b, w.r.UnreadByte() + } +} + +func (w *walker) expect(want byte) error { + b, err := w.r.ReadByte() + if err != nil { + return eofIsSyntax(err) + } + if b != want { + return fmt.Errorf("%w: %q, expected %q", errWalkSyntax, b, want) + } + return nil +} + +func eofIsSyntax(err error) error { + if errors.Is(err, io.EOF) { + return io.ErrUnexpectedEOF + } + return err +} + +func (w *walker) push() error { + w.depth++ + if w.depth > maxWalkDepth { + return errWalkDepth + } + return nil +} + +// skip consumes and validates one value of any type. +func (w *walker) skip() error { + b, err := w.next() + if err != nil { + return err + } + switch { + case b == '{': + return w.object(func(string) error { return w.skip() }) + case b == '[': + return w.array(w.skip) + case b == '"': + _, _, err := w.str(0) + return err + case b == '-' || (b >= '0' && b <= '9'): + _, _, err := w.number(0) + return err + case b == 't': + return w.literal("true") + case b == 'f': + return w.literal("false") + case b == 'n': + return w.literal("null") + } + return fmt.Errorf("%w: %q starts no value", errWalkSyntax, b) +} + +func (w *walker) literal(lit string) error { + for i := 0; i < len(lit); i++ { + if err := w.expect(lit[i]); err != nil { + return err + } + } + return nil +} + +// object walks {"k":v,...}, calling field for each key with the reader at +// the value; field must consume the value. The opening brace must be next. +func (w *walker) object(field func(key string) error) error { + if err := w.expect('{'); err != nil { + return err + } + if err := w.push(); err != nil { + return err + } + b, err := w.next() + if err != nil { + return err + } + if b == '}' { + w.depth-- + return w.expect('}') + } + for { + if b != '"' { + return fmt.Errorf("%w: %q, expected a key", errWalkSyntax, b) + } + key, over, err := w.str(maxKeyRaw) + if err != nil { + return err + } + if over { + key = "" // too long to be a wanted key + } + if _, err = w.next(); err != nil { + return err + } + if err := w.expect(':'); err != nil { + return err + } + if err := field(key); err != nil { + return err + } + if b, err = w.next(); err != nil { + return err + } + if b == '}' { + w.depth-- + return w.expect('}') + } + if err := w.expect(','); err != nil { + return err + } + if b, err = w.next(); err != nil { + return err + } + } +} + +// array walks [v,...], calling elem for each element. The opening bracket +// must be next. +func (w *walker) array(elem func() error) error { + if err := w.expect('['); err != nil { + return err + } + if err := w.push(); err != nil { + return err + } + b, err := w.next() + if err != nil { + return err + } + if b == ']' { + w.depth-- + return w.expect(']') + } + for { + if err := elem(); err != nil { + return err + } + if b, err = w.next(); err != nil { + return err + } + if b == ']' { + w.depth-- + return w.expect(']') + } + if err := w.expect(','); err != nil { + return err + } + } +} + +func isHex(b byte) bool { + return (b >= '0' && b <= '9') || (b >= 'a' && b <= 'f') || (b >= 'A' && b <= 'F') +} + +// str consumes a string (the opening quote must be next), validating it, and +// returns its decoded value from at most keep raw bytes; over reports that +// the raw string was longer. The cut falls between escapes, never inside one. +// keep 0 decodes nothing. +func (w *walker) str(keep int) (string, bool, error) { + if err := w.expect('"'); err != nil { + return "", false, err + } + raw := make([]byte, 0, min(keep, 64)+2) + raw = append(raw, '"') + over := false + for { + b, err := w.r.ReadByte() + if err != nil { + return "", false, eofIsSyntax(err) + } + seq := [6]byte{b} + n := 1 + switch { + case b == '"': + if keep == 0 { + return "", over, nil + } + raw = append(raw, '"') + var s string + if err := json.Unmarshal(raw, &s); err != nil { + return "", false, fmt.Errorf("%w: %v", errWalkSyntax, err) + } + return s, over, nil + case b < 0x20: + return "", false, fmt.Errorf("%w: control byte %#x in string", errWalkSyntax, b) + case b == '\\': + e, err := w.r.ReadByte() + if err != nil { + return "", false, eofIsSyntax(err) + } + seq[1], n = e, 2 + switch e { + case '"', '\\', '/', 'b', 'f', 'n', 'r', 't': + case 'u': + for i := 0; i < 4; i++ { + h, err := w.r.ReadByte() + if err != nil { + return "", false, eofIsSyntax(err) + } + if !isHex(h) { + return "", false, fmt.Errorf("%w: bad \\u escape", errWalkSyntax) + } + seq[n] = h + n++ + } + default: + return "", false, fmt.Errorf("%w: bad escape \\%c", errWalkSyntax, e) + } + } + if !over && len(raw)-1+n <= keep { + raw = append(raw, seq[:n]...) + } else { + over = true + } + } +} + +// Number states: JSON's number grammar as a DFA. numFinal marks the states +// a number may end in. +const ( + numStart = iota + numMinus + numZero + numInt + numDot + numFrac + numExp + numExpSign + numExpDigits +) + +var numFinal = [...]bool{numZero: true, numInt: true, numFrac: true, numExpDigits: true} + +// numNext is the state after byte b in state st, or -1 when b ends the token. +func numNext(st int, b byte) int { + digit := b >= '0' && b <= '9' + switch st { + case numStart: + switch { + case b == '-': + return numMinus + case b == '0': + return numZero + case digit: + return numInt + } + case numMinus: + switch { + case b == '0': + return numZero + case digit: + return numInt + } + case numZero, numInt: + switch { + case st == numInt && digit: + return numInt + case b == '.': + return numDot + case b == 'e' || b == 'E': + return numExp + } + case numDot, numFrac: + switch { + case digit: + return numFrac + case st == numFrac && (b == 'e' || b == 'E'): + return numExp + } + case numExp: + switch { + case b == '+' || b == '-': + return numExpSign + case digit: + return numExpDigits + } + case numExpSign, numExpDigits: + if digit { + return numExpDigits + } + } + return -1 +} + +// number consumes a number token, validating JSON's grammar, and returns up +// to keep bytes of it; over reports a longer token. +func (w *walker) number(keep int) (string, bool, error) { + var tok []byte + over := false + st := numStart + for { + b, err := w.r.ReadByte() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return "", false, err + } + next := numNext(st, b) + if next < 0 { + if err := w.r.UnreadByte(); err != nil { + return "", false, err + } + break + } + st = next + if len(tok) < keep { + tok = append(tok, b) + } else { + over = true + } + } + if !numFinal[st] { + return "", false, fmt.Errorf("%w: bad number", errWalkSyntax) + } + return string(tok), over, nil +} + +// keptString reads a string field into *dst (null leaves it unchanged). A +// raw string over keep is cut, or, when tooLong is non-nil, left out of *dst +// and flagged there; the walk goes on either way. +func (w *walker) keptString(dst *string, keep int, tooLong *bool) error { + b, err := w.next() + if err != nil { + return err + } + switch b { + case 'n': + return w.literal("null") + case '"': + s, over, err := w.str(keep) + if err != nil { + return err + } + if over && tooLong != nil { + *tooLong = true + return nil + } + *dst = s + return nil + } + if err := w.skip(); err != nil { + return err + } + return errWalkType +} + +// keptInt reads an int field into *dst (null leaves it unchanged). +func (w *walker) keptInt(dst *int) error { + b, err := w.next() + if err != nil { + return err + } + if b == 'n' { + return w.literal("null") + } + if b != '-' && (b < '0' || b > '9') { + if err := w.skip(); err != nil { + return err + } + return errWalkType + } + tok, over, err := w.number(maxNumberRaw) + if err != nil { + return err + } + if over { + return errWalkType // no int is that long + } + var n int + if err := json.Unmarshal([]byte(tok), &n); err != nil { + return errWalkType + } + *dst = n + return nil +} + +// keptObject walks an object field (null leaves it unchanged). +func (w *walker) keptObject(field func(key string) error) error { + b, err := w.next() + if err != nil { + return err + } + switch b { + case 'n': + return w.literal("null") + case '{': + return w.object(field) + } + if err := w.skip(); err != nil { + return err + } + return errWalkType +} + +// decodeInspect walks a GET /containers/{id}/json body into the inspect +// projection. An ID or SandboxKey over maxIDRaw is errFieldTooLong. +func decodeInspect(r io.Reader, limit int64) (inspect, error) { + var in inspect + tooLong := false + w := newWalker(r, limit) + err := w.keptObject(func(key string) error { + switch { + case strings.EqualFold(key, "Id"): + return w.keptString(&in.ID, maxIDRaw, &tooLong) + case strings.EqualFold(key, "Name"): + return w.keptString(&in.Name, maxTextRaw, nil) + case strings.EqualFold(key, "Image"): + return w.keptString(&in.Image, maxTextRaw, nil) + case strings.EqualFold(key, "Config"): + return w.keptObject(func(k string) error { + if strings.EqualFold(k, "Image") { + return w.keptString(&in.Config.Image, maxTextRaw, nil) + } + return w.skip() + }) + case strings.EqualFold(key, "State"): + return w.keptObject(func(k string) error { + if strings.EqualFold(k, "Pid") { + return w.keptInt(&in.State.Pid) + } + return w.skip() + }) + case strings.EqualFold(key, "NetworkSettings"): + return w.keptObject(func(k string) error { + if strings.EqualFold(k, "SandboxKey") { + return w.keptString(&in.NetworkSettings.SandboxKey, maxIDRaw, &tooLong) + } + return w.skip() + }) + } + return w.skip() + }) + switch { + case err == nil && w.overLimit(): + err = errBodyTooLarge + case err == nil && tooLong: + err = errFieldTooLong + } + return in, err +} + +// decodeIDs walks a GET /containers/json body (limit noLimit: none) and +// returns each container's +// Id, and how many entries it dropped: those over entryLimit bytes, and those +// whose Id is over maxIDRaw. A wrong type anywhere fails the list, as +// encoding/json would. +func decodeIDs(r io.Reader, limit, entryLimit int64) ([]string, int, error) { + var ids []string + dropped := 0 + w := newWalker(r, limit) + b, err := w.next() + if err != nil { + return nil, 0, err + } + switch b { + case 'n': + return nil, 0, w.literal("null") + case '[': + default: + if err := w.skip(); err != nil { + return nil, 0, err + } + return nil, 0, errWalkType + } + err = w.array(func() error { + var id string + tooLong := false + if _, err := w.next(); err != nil { + return err + } + start := w.pos() + err := w.keptObject(func(key string) error { + if strings.EqualFold(key, "Id") { + return w.keptString(&id, maxIDRaw, &tooLong) + } + return w.skip() + }) + switch { + case err != nil: + case tooLong || w.pos()-start > entryLimit: + dropped++ + default: + ids = append(ids, id) + } + return err + }) + return ids, dropped, err +} diff --git a/pkg/dockermeta/jsonwalk_test.go b/pkg/dockermeta/jsonwalk_test.go new file mode 100644 index 000000000..0059a5dc0 --- /dev/null +++ b/pkg/dockermeta/jsonwalk_test.go @@ -0,0 +1,222 @@ +package dockermeta + +import ( + "bytes" + "encoding/json" + "errors" + "strings" + "testing" +) + +// containerRef is one entry of GET /containers/json, the reference decode +// decodeIDs is checked against. +type containerRef struct { + ID string `json:"Id"` +} + +// refInspect is what encoding/json makes of body, the behavior decodeInspect +// must match. +func refInspect(body []byte) (inspect, error) { + var in inspect + err := json.NewDecoder(bytes.NewReader(body)).Decode(&in) + return in, err +} + +// checkInspectParity fails if decodeInspect and encoding/json disagree on +// body: both must accept or both reject, and accepted bodies must project +// to the same Container. An over-long daemon-set field is the one +// deliberate difference. +func checkInspectParity(t *testing.T, body []byte) (inspect, error) { + t.Helper() + got, werr := decodeInspect(bytes.NewReader(body), maxInspectBody) + if errors.Is(werr, errFieldTooLong) { + return got, werr + } + want, jerr := refInspect(body) + if (werr == nil) != (jerr == nil) { + t.Fatalf("walker err %v, encoding/json err %v, on %q", werr, jerr, clip(body)) + } + if werr != nil { + return got, werr + } + gc, gok := project(got, fuzzStat) + wc, wok := project(want, fuzzStat) + if gc != wc || gok != wok { + t.Fatalf("walker %+v/%v, encoding/json %+v/%v, on %q", gc, gok, wc, wok, clip(body)) + } + return got, nil +} + +func clip(b []byte) []byte { + if len(b) > 200 { + return b[:200] + } + return b +} + +func TestDecodeInspect(t *testing.T) { + type want struct { + err bool + name, image string + pid int + sandbox, cImg string + } + deep := strings.Repeat(`{"a":`, maxWalkDepth) + "1" + strings.Repeat("}", maxWalkDepth) + cases := []struct { + name string + cat string + description string + body string + expected want + }{ + {"basic", "P", "every kept field", + `{"Id":"i","Name":"/n","Image":"img","Config":{"Image":"c"},"State":{"Pid":7},"NetworkSettings":{"SandboxKey":"/k"}}`, + want{name: "/n", image: "img", cImg: "c", pid: 7, sandbox: "/k"}}, + {"skips_unknown", "P", "unknown fields of every type are skipped", + `{"A":[1,-2.5e+3,true,false,null,{"b":[{}]}],"Name":"n","Z":"é\n"}`, want{name: "n"}}, + {"case_insensitive", "C", "keys match case-insensitively, as encoding/json does", + `{"name":"a","STATE":{"pid":3}}`, want{name: "a", pid: 3}}, + {"escaped_key", "C", `"Name" is the key Name`, + `{"Name":"a"}`, want{name: "a"}}, + {"kelvin_key", "C", "U+212A KELVIN SIGN folds to k in SandboxKey (parity row)", + `{"NetworkSettings":{"SandboxKey":"/k"}}`, want{sandbox: "/k"}}, + {"duplicate_last_wins", "C", "the last duplicate key wins", + `{"Name":"a","Name":"b"}`, want{name: "b"}}, + {"null_keeps", "C", "a later null leaves an object field as it was", + `{"Config":{"Image":"c"},"Config":null,"Name":null}`, want{cImg: "c"}}, + {"top_null", "B", "a top-level null is the zero value", + `null`, want{}}, + {"trailing", "B", "data after the top-level value is ignored", + `{"Name":"a"} junk`, want{name: "a"}}, + {"depth_at_limit", "B", "nesting of exactly 10000 is accepted", + deep, want{}}, + {"depth_over_limit", "N", "nesting of 10001 is an error", + `{"a":` + deep + `}`, want{err: true}}, + {"pid_float", "N", "a fractional Pid is a type error", + `{"State":{"Pid":1.5}}`, want{err: true}}, + {"pid_exp", "N", "an exponent Pid is a type error", + `{"State":{"Pid":1e3}}`, want{err: true}}, + {"pid_overflow", "N", "a Pid past int64 is a type error", + `{"State":{"Pid":99999999999999999999}}`, want{err: true}}, + {"pid_string", "N", "a string Pid is a type error", + `{"State":{"Pid":"1"}}`, want{err: true}}, + {"leading_zero", "N", "01 is not JSON, even in a skipped field", + `{"X":01}`, want{err: true}}, + {"bad_escape", "N", `\x is not a JSON escape`, + `{"X":"\x"}`, want{err: true}}, + {"raw_control", "N", "a raw control byte in a skipped string is an error", + "{\"X\":\"a\x01b\"}", want{err: true}}, + {"bad_literal", "N", "tru is not a literal", + `{"X":tru}`, want{err: true}}, + {"wrong_top", "N", "a top-level array is a type error", + `[1]`, want{err: true}}, + {"config_string", "N", "Config as a string is a type error", + `{"Config":"x"}`, want{err: true}}, + {"truncated", "N", "a body cut mid-object", + `{"Name":"a"`, want{err: true}}, + {"empty", "B", "an empty body", + ``, want{err: true}}, + {"invalid_utf8_name", "C", "invalid UTF-8 becomes U+FFFD, as encoding/json does", + "{\"Name\":\"a\xffb\"}", want{name: "a�b"}}, + {"lone_surrogate", "C", `a lone \ud800 becomes U+FFFD`, + `{"Name":"\ud800"}`, want{name: "�"}}, + {"long_name_cut", "B", "a 1 MiB name is cut to maxTextRaw raw bytes; Clean's result is unchanged", + `{"Name":"` + strings.Repeat("n", 1<<20) + `"}`, want{name: strings.Repeat("n", maxTextRaw)}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + in, err := checkInspectParity(t, []byte(tc.body)) + got := want{err: err != nil, name: in.Name, image: in.Image, pid: in.State.Pid, + sandbox: in.NetworkSettings.SandboxKey, cImg: in.Config.Image} + if err != nil { + got = want{err: true} + } + if got != tc.expected { + t.Fatalf("%s: got %+v (err %v), expected %+v", tc.description, got, err, tc.expected) + } + }) + } +} + +// idCases drive TestDecodeIDs and seed FuzzDecodeIDs. +func idCases() []struct { + name, cat, description, body string + expected []string // nil with err + err bool +} { + long := strings.Repeat("a", maxIDRaw+1) + return []struct { + name, cat, description, body string + expected []string + err bool + }{ + {"two", "P", "two entries with labels", `[{"Id":"a","Labels":{"k":"v"}},{"Id":"b"}]`, []string{"a", "b"}, false}, + {"empty_array", "B", "no containers", `[]`, nil, false}, + {"null", "B", "a null list", `null`, nil, false}, + {"null_entry", "C", "a null entry is an empty Id, as encoding/json makes it", `[null,{"Id":"b"}]`, []string{"", "b"}, false}, + {"no_id", "C", "an entry without Id", `[{"Names":["/x"]}]`, []string{""}, false}, + {"long_id_dropped", "C", "an Id over maxIDRaw drops that entry only", `[{"Id":"` + long + `"},{"Id":"b"}]`, []string{"b"}, false}, + {"object_top", "N", "an object is not a list", `{"Id":"a"}`, nil, true}, + {"number_entry", "N", "a number entry is a type error", `[1]`, nil, true}, + {"id_number", "N", "a numeric Id is a type error", `[{"Id":1}]`, nil, true}, + {"truncated", "N", "a list cut mid-entry", `[{"Id":"a"},{"Id"`, nil, true}, + } +} + +// checkIDsParity compares decodeIDs with encoding/json on body, except for +// the entries decodeIDs drops for an over-long Id. +func checkIDsParity(t *testing.T, body []byte) ([]string, error) { + t.Helper() + got, _, werr := decodeIDs(bytes.NewReader(body), noLimit, maxListEntry) + var refs []containerRef + jerr := json.NewDecoder(bytes.NewReader(body)).Decode(&refs) + if (werr == nil) != (jerr == nil) { + t.Fatalf("walker err %v, encoding/json err %v, on %q", werr, jerr, clip(body)) + } + if werr != nil { + return nil, werr + } + // Walk both in step: every Id must match, except that decodeIDs may + // drop one whose raw form was over maxIDRaw (so its decoded form is over + // maxIDRaw/6 bytes). + i := 0 + for _, r := range refs { + if i < len(got) && got[i] == r.ID { + i++ + continue + } + if len(r.ID) <= maxIDRaw/6 { + t.Fatalf("walker %q dropped or changed %q, on %q", got, r.ID, clip(body)) + } + } + if i != len(got) { + t.Fatalf("walker %q has Ids encoding/json does not, on %q", got[i:], clip(body)) + } + return got, nil +} + +func TestDecodeIDs(t *testing.T) { + for _, tc := range idCases() { + t.Run(tc.name, func(t *testing.T) { + got, err := checkIDsParity(t, []byte(tc.body)) + if (err != nil) != tc.err { + t.Fatalf("%s: err %v, expected err %v", tc.description, err, tc.err) + } + if strings.Join(got, ",") != strings.Join(tc.expected, ",") || len(got) != len(tc.expected) { + t.Fatalf("%s: got %q, expected %q", tc.description, got, tc.expected) + } + }) + } +} + +// FuzzDecodeIDs holds decodeIDs to encoding/json on arbitrary list bodies. +// +// go test -run '^$' -fuzz '^FuzzDecodeIDs$' -fuzztime=30s ./pkg/dockermeta/ +func FuzzDecodeIDs(f *testing.F) { + for _, tc := range idCases() { + f.Add([]byte(tc.body)) + } + f.Fuzz(func(t *testing.T, data []byte) { + _, _ = checkIDsParity(t, data) + }) +}