From bbeddf2edd0df4bf5d4220416daecf01726d3737 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Tue, 3 Nov 2026 06:08:33 -0600 Subject: [PATCH] fix(cloudflare-export): fail-closed paginated R2 bucket enumeration (#2574) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GET /accounts/{id}/r2/buckets was read once with `result?.buckets ?? []`, so a 500 or malformed answer published r2Buckets: [] inside a status: "ok" document, and buckets past the first page were silently dropped. - listR2Buckets() follows result_info.cursor (List Buckets cursor form) then result_info.total_pages (page form) to completion; a short page without metadata still proves completeness; 1000-page safety cap. - Non-200 (except the 401/403 token-scope path), a missing/malformed result.buckets, or a nameless entry throws ExportError("unparseable", 6) so no status:ok document is written for a failed enumeration. - Unextinguishable pagination (full page, no metadata, or safety cap) keeps the collected names and marks the document r2BucketsTruncated: true + r2BucketsDetail — the r2-storage lowerBound discipline. - Tests: buckets 500, four malformed bodies, nameless entry, failed later page, page-round pagination, cursor pagination, truncation marker, known-empty list, 401/403 preservation, cross-page dedupe. 36/36 pass via `node --test pm-stack/cloudflare-export/cloudflare-quota-export.test.mjs`. Builds on the pagination work abandoned on queue/5387-2574-r2-bucket-enumeration (task 5387, done without a PR) but keeps the packet's fail-closed contract. --- pm-stack/cloudflare-export/README.md | 17 +- .../cloudflare-quota-export.mjs | 119 ++++++++++++- .../cloudflare-quota-export.test.mjs | 164 ++++++++++++++++++ 3 files changed, 294 insertions(+), 6 deletions(-) diff --git a/pm-stack/cloudflare-export/README.md b/pm-stack/cloudflare-export/README.md index dc731d1895..e5ac7c3fb9 100644 --- a/pm-stack/cloudflare-export/README.md +++ b/pm-stack/cloudflare-export/README.md @@ -26,7 +26,7 @@ One GraphQL analytics POST (`/client/v4/graphql`) plus REST probes: | `d1-rows-read`, `d1-rows-written` | `d1AnalyticsAdaptiveGroups` sum | | `queues-ops` | `queueMessageOperationsAdaptiveGroups` sum billableOperations | | `r2-class-a`, `r2-class-b` | `r2OperationsAdaptiveGroups` by actionType, classified per Cloudflare's published pricing classes (deletes free; unknown actions reported in `r2UnclassifiedActions`, never guessed) | -| `r2-storage` | `r2StorageAdaptiveGroups` max payloadSize → GB; bucket names enumerated directly via `GET /accounts/{id}/r2/buckets` | +| `r2-storage` | `r2StorageAdaptiveGroups` max payloadSize → GB; bucket names enumerated directly via paginated `GET /accounts/{id}/r2/buckets` (fail-closed, #2574) | | `workers-ai-neurons` | `aiInferenceAdaptiveGroups` sum totalNeurons, as a per-day average over the cycle to date (cycle total in the metric's `detail`) | | neurons/day alert | `aiInferenceAdaptiveGroups` grouped by `date` + `modelId` (limit 10000, sized for cycle-days × models) — see the alert section below | @@ -110,6 +110,19 @@ append-only `history.jsonl`: } ``` +`r2Buckets` is the complete bucket-name enumeration: every page +reported by `result_info` is followed (cursor form, then `total_pages` +page form), so accounts with more than 100 buckets list all of them. +Enumeration is **fail-closed** (#2574): a non-200 answer other than the +401/403 token-scope case, a missing/malformed `result.buckets`, or a +nameless entry aborts the run with an `unparseable` failure document +(exit 6) — a failed enumeration is never published as `r2Buckets: []` +inside a `status: "ok"` document. If pagination cannot be proven +complete (a full page with no usable metadata, or the 1000-page safety +cap), the document keeps the collected names and adds +`"r2BucketsTruncated": true` plus `r2BucketsDetail`, so the list reads +as a lower bound instead of a complete enumeration. + ## Failure states (fail-closed) A failed tick writes a failure document with `status`, @@ -119,7 +132,7 @@ A failed tick writes a failure document with `status`, | -------------- | ------------------------------------------------------------- | ---- | | `no-token` | token not in environment (wrapper/bws problem) | 2 | | `token-scope` | API answered 401/403; `missingScopes` names the scopes needed | 3 | -| `unparseable` | an endpoint answered an unrecognised shape | 6 | +| `unparseable` | an endpoint answered an unrecognised shape (includes a failed R2 bucket enumeration — #2574) | 6 | | `fetch-failed` | network/other error | 7 | ## Install / schedule (laptop) diff --git a/pm-stack/cloudflare-export/cloudflare-quota-export.mjs b/pm-stack/cloudflare-export/cloudflare-quota-export.mjs index 1b6cc37325..dbef43471b 100755 --- a/pm-stack/cloudflare-export/cloudflare-quota-export.mjs +++ b/pm-stack/cloudflare-export/cloudflare-quota-export.mjs @@ -361,7 +361,16 @@ export function classifyBilling(probes) { }; } -export function successDocument({ measuredAt, cycleStart, accountId, billing, parsed, r2Buckets }) { +export function successDocument({ + measuredAt, + cycleStart, + accountId, + billing, + parsed, + r2Buckets, + r2BucketsTruncated = false, + r2BucketsDetail = null, +}) { return { service: "cloudflare", source: SOURCE, @@ -371,6 +380,12 @@ export function successDocument({ measuredAt, cycleStart, accountId, billing, pa accountId, billing, r2Buckets, + // #2574: present ONLY when pagination could not be proven complete, + // so a partial list can never be mistaken for the full bucket set — + // the r2-storage lowerBound discipline, applied to the list itself. + ...(r2BucketsTruncated + ? { r2BucketsTruncated: true, ...(r2BucketsDetail ? { r2BucketsDetail } : {}) } + : {}), ...(parsed.r2Unclassified?.length ? { r2UnclassifiedActions: parsed.r2Unclassified } : {}), // #2287: the alerts array is present ONLY when a day is firing, so // consumers can key on its presence; saturation of the grouped @@ -494,9 +509,11 @@ export async function run({ token, accountId, now = new Date() } = {}) { // R2 bucket enumeration directly (names only) — the storage figure // itself comes from the analytics dataset, not the tracker prose. - const buckets = await apiJson(`/accounts/${acct}/r2/buckets?per_page=100`, token); - if (buckets.status === 401 || buckets.status === 403) throw scopeError("GET r2/buckets", buckets.status); - const r2Buckets = (buckets.body?.result?.buckets ?? []).map((b) => b.name).filter(Boolean); + // Fail-closed (#2574): a failed or malformed answer throws; a list the + // pages cannot prove complete is published with an explicit truncation + // marker. Neither is ever silently rendered as []. + const r2Enumeration = await listR2Buckets(acct, token); + const r2Buckets = r2Enumeration.buckets; const start = cycleStartUtc(now); const gql = await apiJson("/graphql", token, { @@ -541,9 +558,103 @@ export async function run({ token, accountId, now = new Date() } = {}) { billing, parsed, r2Buckets, + r2BucketsTruncated: r2Enumeration.truncated, + r2BucketsDetail: r2Enumeration.detail, }); } +// R2 bucket enumeration, fail-closed and paginated (#2574). +// +// The old call made one request (`per_page=100`) and read +// `result?.buckets ?? []`, so a 500/malformed answer published an empty +// list and anything past the first 100 buckets vanished — both inside a +// `status: "ok"` document that also reported R2 storage usage. +// +// Contract: +// * 401/403 keep the token-scope contract (scopeError, exit 3). +// * Any other non-200, a missing/malformed `result.buckets`, or a +// nameless entry throws ExportError("unparseable", 6): enumeration +// is not knowable, so no document is published at all. +// * Pages are followed to completion — `result_info.cursor` (List +// Buckets cursor form) or `result_info.total_pages` (page form) — +// and a short page without metadata proves completeness. +// * If a full page arrives with no usable pagination metadata, or the +// safety cap is hit, the accumulated names are returned with +// `{ truncated: true }` so successDocument() marks the list as a +// LOWER BOUND instead of passing it off as complete. +export const R2_BUCKETS_PER_PAGE = 100; +// Safety cap: a server that never stops handing out pages must not spin. +export const R2_BUCKETS_PAGE_LIMIT = 1000; + +export async function listR2Buckets(acct, token) { + const names = []; + const seen = new Set(); + let page = 1; + let cursor = null; + for (;;) { + const query = new URLSearchParams({ per_page: String(R2_BUCKETS_PER_PAGE) }); + if (cursor) query.set("cursor", cursor); + else if (page > 1) query.set("page", String(page)); + const res = await apiJson(`/accounts/${acct}/r2/buckets?${query}`, token); + const where = `GET r2/buckets page ${page}`; + if (res.status === 401 || res.status === 403) throw scopeError("GET r2/buckets", res.status); + if (res.status !== 200) { + throw new ExportError( + "unparseable", + 6, + `${where}: HTTP ${res.status} — bucket enumeration failed, refusing to publish an empty or partial list (#2574)`, + ); + } + const list = res.body?.result?.buckets; + if (!Array.isArray(list)) { + throw new ExportError( + "unparseable", + 6, + `${where}: result.buckets missing or malformed — bucket enumeration failed (#2574)`, + ); + } + for (const b of list) { + if (typeof b?.name !== "string" || !b.name) { + throw new ExportError( + "unparseable", + 6, + `${where}: bucket entry without a name — enumeration shape unknown (#2574)`, + ); + } + if (!seen.has(b.name)) { + seen.add(b.name); + names.push(b.name); + } + } + const info = res.body?.result_info ?? {}; + const nextCursor = typeof info.cursor === "string" && info.cursor ? info.cursor : null; + const totalPages = Number.isInteger(info.total_pages) && info.total_pages >= 1 ? info.total_pages : null; + if (page >= R2_BUCKETS_PAGE_LIMIT) { + return { + buckets: names, + truncated: true, + detail: `${where}: stopped at the ${R2_BUCKETS_PAGE_LIMIT}-page safety limit — bucket list is a LOWER BOUND`, + }; + } + if (nextCursor && nextCursor !== cursor) { + cursor = nextCursor; + page += 1; + continue; + } + if (totalPages !== null) { + if (page >= totalPages) return { buckets: names, truncated: false, detail: null }; + page += 1; + continue; + } + if (list.length < R2_BUCKETS_PER_PAGE) return { buckets: names, truncated: false, detail: null }; + return { + buckets: names, + truncated: true, + detail: `${where}: full page with no result_info cursor or total_pages — the list may continue and is a LOWER BOUND`, + }; + } +} + async function writeOutputs(outDir, doc) { await mkdir(outDir, { recursive: true }); const latest = join(outDir, "latest.json"); diff --git a/pm-stack/cloudflare-export/cloudflare-quota-export.test.mjs b/pm-stack/cloudflare-export/cloudflare-quota-export.test.mjs index 5c55b3f085..71950c75a1 100755 --- a/pm-stack/cloudflare-export/cloudflare-quota-export.test.mjs +++ b/pm-stack/cloudflare-export/cloudflare-quota-export.test.mjs @@ -14,7 +14,9 @@ import { ExportError, failureDocument, foldKv, + listR2Buckets, parseGraphqlUsage, + R2_BUCKETS_PER_PAGE, R2_STORAGE_GROUP_LIMIT, run, successDocument, @@ -492,3 +494,165 @@ test("measurement strings use plain decimals; request counts remain integers (#2 ); } }); + +// #2574: R2 bucket enumeration is fail-closed and paginated. A failed or +// malformed answer must abort the export (never publish r2Buckets: [] in a +// status:ok document), and every page must be followed so >100 buckets are +// listed rather than silently dropped. +function bucketPage(names, { totalPages, cursor, count } = {}) { + return { + status: 200, + body: { + result: { buckets: names.map((name) => ({ name })) }, + ...(totalPages === undefined && cursor === undefined && count === undefined + ? {} + : { + result_info: { + page: 1, + per_page: R2_BUCKETS_PER_PAGE, + count: count ?? names.length, + ...(totalPages === undefined ? {} : { total_pages: totalPages }), + ...(cursor === undefined ? {} : { cursor }), + }, + }), + }, + }; +} + +// Billing probes and GraphQL answer benignly, so any r2Buckets outcome +// proves the enumeration path is isolated from the rest of the run. +async function runWithBucketPages(pages) { + let i = 0; + const prev = globalThis.fetch; + globalThis.fetch = async (url) => { + const u = String(url); + if (u.includes("/r2/buckets")) { + const p = pages[Math.min(i, pages.length - 1)]; + i += 1; + return { status: p.status, json: async () => p.body }; + } + if (u.includes("/graphql")) { + return { status: 200, json: async () => ({ data: { viewer: { accounts: [ACCOUNT] } } }) }; + } + return { status: 200, json: async () => ({}) }; + }; + try { + return await run({ token: "tok", accountId: "acct", now: NOW }); + } finally { + globalThis.fetch = prev; + } +} + +async function expectBucketExportError(pages, status, exitCode, messagePart) { + await assert.rejects(runWithBucketPages(pages), (e) => { + assert.ok(e instanceof ExportError, `expected ExportError, got ${e}`); + assert.equal(e.status, status); + assert.equal(e.exitCode, exitCode); + if (messagePart) assert.match(e.message, messagePart); + return true; + }); +} + +test("run: an HTTP 500 on buckets fails closed as unparseable, not an empty list (#2574)", async () => { + await expectBucketExportError([{ status: 500, body: {} }], "unparseable", 6, /HTTP 500/); +}); + +test("run: a malformed result.buckets body fails closed as unparseable (#2574)", async () => { + for (const body of [{}, { result: {} }, { result: { buckets: "nope" } }, { result: { buckets: null } }]) { + await expectBucketExportError([{ status: 200, body }], "unparseable", 6, /missing or malformed/); + } +}); + +test("run: a nameless bucket entry fails closed as unparseable (#2574)", async () => { + await expectBucketExportError( + [{ status: 200, body: { result: { buckets: [{ name: "ok" }, { id: "no-name" }] } } }], + "unparseable", + 6, + /without a name/, + ); +}); + +test("run: a failed later page fails closed instead of publishing the partial list (#2574)", async () => { + const first = Array.from({ length: R2_BUCKETS_PER_PAGE }, (_, i) => `b${i}`); + await expectBucketExportError( + [bucketPage(first, { totalPages: 2 }), { status: 500, body: {} }], + "unparseable", + 6, + /page 2/, + ); +}); + +test("run: page-based pagination follows every page to completion (#2574)", async () => { + const first = Array.from({ length: R2_BUCKETS_PER_PAGE }, (_, i) => `b${i}`); + const rest = Array.from({ length: 50 }, (_, i) => `b${R2_BUCKETS_PER_PAGE + i}`); + const doc = await runWithBucketPages([ + bucketPage(first, { totalPages: 2 }), + bucketPage(rest, { totalPages: 2 }), + ]); + assert.equal(doc.status, "ok"); + assert.equal(doc.metrics.length, 11); // GraphQL metrics untouched + assert.equal(doc.r2Buckets.length, 150); + assert.equal(doc.r2Buckets[0], "b0"); + assert.equal(doc.r2Buckets[149], "b149"); + assert.equal("r2BucketsTruncated" in doc, false); + assert.equal("r2BucketsDetail" in doc, false); +}); + +test("run: cursor pagination follows result_info.cursor to completion (#2574)", async () => { + const first = Array.from({ length: R2_BUCKETS_PER_PAGE }, (_, i) => `b${i}`); + const rest = ["c1", "c2"]; + const doc = await runWithBucketPages([ + bucketPage(first, { cursor: "next-page" }), + bucketPage(rest, { count: rest.length }), + ]); + assert.equal(doc.r2Buckets.length, R2_BUCKETS_PER_PAGE + rest.length); + assert.equal(doc.r2Buckets.at(-1), "c2"); + assert.equal("r2BucketsTruncated" in doc, false); +}); + +test("run: a full page with no pagination metadata is flagged as a lower bound (#2574)", async () => { + const full = Array.from({ length: R2_BUCKETS_PER_PAGE }, (_, i) => `b${i}`); + const doc = await runWithBucketPages([bucketPage(full)]); + assert.equal(doc.status, "ok"); + assert.equal(doc.r2Buckets.length, R2_BUCKETS_PER_PAGE); + assert.equal(doc.r2BucketsTruncated, true); + assert.match(doc.r2BucketsDetail, /LOWER BOUND/); + // A short page without metadata is still provably complete. + const short = await runWithBucketPages([bucketPage(["only"])]); + assert.deepEqual(short.r2Buckets, ["only"]); + assert.equal("r2BucketsTruncated" in short, false); +}); + +test("run: a genuinely empty bucket page stays a known empty list (#2574)", async () => { + const doc = await runWithBucketPages([bucketPage([])]); + assert.deepEqual(doc.r2Buckets, []); + assert.equal("r2BucketsTruncated" in doc, false); +}); + +test("run: 401/403 on buckets keep the token-scope contract (#2574)", async () => { + await expectBucketExportError([{ status: 403, body: {} }], "token-scope", 3, /lacks a scope/); + await expectBucketExportError([{ status: 401, body: {} }], "token-scope", 3); +}); + +test("listR2Buckets: duplicate names across pages are reported once (#2574)", async () => { + const prev = globalThis.fetch; + let i = 0; + const pages = [ + { status: 200, body: { result: { buckets: [{ name: "a" }, { name: "b" }] }, result_info: { total_pages: 2 } } }, + { status: 200, body: { result: { buckets: [{ name: "b" }, { name: "c" }] }, result_info: { total_pages: 2 } } }, + ]; + globalThis.fetch = async (url) => { + if (String(url).includes("/r2/buckets")) { + const p = pages[Math.min(i, pages.length - 1)]; + i += 1; + return { status: p.status, json: async () => p.body }; + } + return { status: 200, json: async () => ({}) }; + }; + try { + const out = await listR2Buckets("acct", "tok"); + assert.deepEqual(out, { buckets: ["a", "b", "c"], truncated: false, detail: null }); + } finally { + globalThis.fetch = prev; + } +});