From 9ec679d9bea22e348ea30e24de18ed49c709c1a3 Mon Sep 17 00:00:00 2001 From: Harlan Wilton Date: Tue, 24 Nov 2026 10:27:30 +1100 Subject: [PATCH] fix(checkin): read Cloudflare through cf, not wrangler Wrangler is retired for operator work. The collector also inherited the checkout's .env token: on 2026-11-24 a stale one there shadowed a valid cf login and left deploy, D1, Workers, analytics, and the report check blind. cf now runs from the home directory, pinned to the production account. Worker outcomes still need an environment token, because cf has no GraphQL command; the check names that token when it is missing. --- checks/_helpers/collectors.mjs | 36 ++++++++--- docs/runbooks/checkin.md | 10 +++ test/unit/daily-checkin-data.test.ts | 2 +- test/unit/external-checkin-collectors.test.ts | 63 +++++++++++++++---- 4 files changed, 89 insertions(+), 22 deletions(-) diff --git a/checks/_helpers/collectors.mjs b/checks/_helpers/collectors.mjs index 2360abbc..c35893ee 100644 --- a/checks/_helpers/collectors.mjs +++ b/checks/_helpers/collectors.mjs @@ -1,5 +1,6 @@ import { readFileSync } from 'node:fs' import { readdir, readFile } from 'node:fs/promises' +import { homedir } from 'node:os' import { basename, join } from 'node:path' import { readBoundedResponseText, runCheckCommand } from '@harlan-zw/nuxt-checkin/external' import { ANALYTICS_ACCOUNT_TAG, buildCopyQuery, buildCopyTotalsQuery, buildWorkersQuery, collectWorkflowRuns, parseAnalyticsEngineResponse, parseWorkersResponse, parseWorkflowName, runListArgs, summarizeCopies, summarizeWorkflowRuns, workersWindow } from './observability.mjs' @@ -36,6 +37,22 @@ async function run(context, command, args) { async function commandJson(context, command, args) { return JSON.parse(await run(context, command, args)) } + +// Production identities, as `wrangler.jsonc` names them. +const PRODUCTION_WORKER = 'skilld-dev' +const PRODUCTION_D1_DATABASE_ID = 'a5e53f35-f5e5-4987-8c67-c0175addc7cc' + +/** + * Read Cloudflare through the `cf` CLI, pinned to the production account. + * + * `cf` loads `.env` from its working directory, and this checkout's `.env` + * carries a deploy-time CLOUDFLARE_API_TOKEN. On 2026-11-24 a stale one there + * shadowed a valid `cf` login and blinded five checks, so `cf` runs from the + * home directory. A check-in token still reaches it through the environment. + */ +function cloudflare(context, args) { + return run({ ...context, rootDir: context.env.HOME || homedir(), env: { ...context.env, CLOUDFLARE_ACCOUNT_ID: ANALYTICS_ACCOUNT_TAG } }, 'cf', args) +} export function collectProduction(context) { return collect(context, 'production-ref', async (context) => { await run(context, 'git', ['fetch', 'origin', 'main']) @@ -55,7 +72,7 @@ export function collectGit(context) { export function collectDeploy(context) { return collect(context, 'deploy', async (context) => { const production = await collectProduction(context) - const deployments = await commandJson(context, join(context.rootDir, 'node_modules/.bin/wrangler'), ['deployments', 'list', '--json', '--config', 'wrangler.jsonc']) + const { deployments } = JSON.parse(await cloudflare(context, ['workers', 'deployments', 'list', '--worker', PRODUCTION_WORKER])) const latest = [...deployments].sort((a, b) => String(b.created_on).localeCompare(String(a.created_on)))[0] return { latest: latest ? { id: latest.id, createdOn: latest.created_on, versionId: latest.versions?.find(version => version.percentage === 100)?.version_id ?? latest.versions?.[0]?.version_id ?? null, message: latest.annotations?.['workers/message'] ?? null, approxDeployedSha: latest.created_on ? await run(context, 'git', ['rev-list', '-1', `--before=${latest.created_on}`, production.ref]) : null } : null } }) @@ -111,7 +128,7 @@ export function collectD1(context) { const dayAgoSec = nowSec - 24 * 60 * 60 const utcDay = now.toISOString().slice(0, 10) async function d1Query(sql) { - const output = await commandJson(context, join(root, 'node_modules/.bin/wrangler'), ['d1', 'execute', 'DB', '--remote', '--json', '--config', 'wrangler.jsonc', '--command', sql]) + const output = JSON.parse(await cloudflare(context, ['d1', 'query', PRODUCTION_D1_DATABASE_ID, '--sql', sql])) if (!output[0]?.success) throw new Error('D1 query did not succeed.') return output[0].results ?? [] @@ -318,9 +335,11 @@ export function collectD1(context) { } export function collectWorkers(context) { return collect(context, 'workers', async (context) => { - const token = context.env.CLOUDFLARE_USAGE_TOKEN || context.env.CLOUDFLARE_API_TOKEN || context.env.CF_API_TOKEN || (await commandJson(context, join(context.rootDir, 'node_modules/.bin/wrangler'), ['auth', 'token', '--json'])).token + // The `cf` CLI has no GraphQL command, so Worker outcomes need a token in + // the environment. The `cf` login cannot stand in for it. + const token = context.env.CLOUDFLARE_USAGE_TOKEN || context.env.CLOUDFLARE_API_TOKEN || context.env.CF_API_TOKEN if (!token) - throw new Error('Cloudflare token is unavailable.') + throw new Error('Worker analytics needs CLOUDFLARE_USAGE_TOKEN. The cf CLI cannot read GraphQL.') const window = workersWindow(context.since.toISOString(), context.now.toISOString()) const response = await fetch('https://api.cloudflare.com/client/v4/graphql', { method: 'POST', redirect: 'error', signal: context.signal, headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ query: buildWorkersQuery(window.since, window.until) }) }) const parsed = parseWorkersResponse(response.status, await readBoundedResponseText(response, 2_097_152)) @@ -328,7 +347,7 @@ export function collectWorkers(context) { throw new Error(parsed.reason) const outcomes = {} for (const row of parsed.rows) { - if (row.dimensions.scriptName === 'skilld-dev') + if (row.dimensions.scriptName === PRODUCTION_WORKER) outcomes[row.dimensions.status] = (outcomes[row.dimensions.status] ?? 0) + row.sum.requests } return { window, outcomes, nonOk: Object.entries(outcomes).filter(([status]) => !['success', 'clientDisconnected', 'responseStreamDisconnected'].includes(status)).map(([status, requests]) => ({ status, requests })) } @@ -347,12 +366,9 @@ export function collectWorkers(context) { */ export function collectAnalytics(context) { return collect(context, 'analytics', async (context) => { - const token = context.env.CLOUDFLARE_USAGE_TOKEN || context.env.CLOUDFLARE_API_TOKEN || context.env.CF_API_TOKEN || (await commandJson(context, join(context.rootDir, 'node_modules/.bin/wrangler'), ['auth', 'token', '--json'])).token - if (!token) - throw new Error('Cloudflare token is unavailable.') const readRows = async (query) => { - const response = await fetch(`https://api.cloudflare.com/client/v4/accounts/${ANALYTICS_ACCOUNT_TAG}/analytics_engine/sql`, { method: 'POST', redirect: 'error', signal: context.signal, headers: { Authorization: `Bearer ${token}` }, body: query }) - const parsed = parseAnalyticsEngineResponse(response.status, await readBoundedResponseText(response, 2_097_152)) + // `cf` exits non-zero on an HTTP failure, so a body that reaches here succeeded. + const parsed = parseAnalyticsEngineResponse(200, await cloudflare(context, ['analytics-engine', 'sql', 'query', '--body', query])) if (parsed._tag === 'Err') throw new Error(parsed.reason) return parsed.rows diff --git a/docs/runbooks/checkin.md b/docs/runbooks/checkin.md index f4b38f20..fb755ec6 100644 --- a/docs/runbooks/checkin.md +++ b/docs/runbooks/checkin.md @@ -60,6 +60,16 @@ The report must match the deployed Worker and be less than five minutes old. The daily health email cron and X API failure emails are removed. Customer digests remain unchanged. Historical email records stay in D1, but checks no longer depend on them. +## Cloudflare reads + +The collector reads [Cloudflare](https://cloudflare.com) through the `cf` CLI, never wrangler. +It runs `cf` from the home directory, pinned to the production account. +The checkout's `.env` token therefore cannot shadow the `cf` login. +A `CLOUDFLARE_API_TOKEN` in the check-in environment still takes precedence. +The `cf` CLI has no [GraphQL](https://graphql.org) command, so `skilld.workers` needs an environment token. +If `CLOUDFLARE_USAGE_TOKEN` is absent, `skilld.workers` reads Unavailable. +Give that token Account Analytics read access. + ## Artifact signing key The `skilld.signing-key` check reads the signer key windows from `workers/artifact-signer/wrangler.jsonc` and the live trusted root. diff --git a/test/unit/daily-checkin-data.test.ts b/test/unit/daily-checkin-data.test.ts index 424ff779..6a763b8d 100644 --- a/test/unit/daily-checkin-data.test.ts +++ b/test/unit/daily-checkin-data.test.ts @@ -55,7 +55,7 @@ it('archives the identities behind the skill sync failure count', async () => { output = args[0] === 'ls-tree' ? 'migrations/001.sql' : args[0] === 'branch' ? 'main' : args[0] === 'rev-parse' ? 'abc' : '' return { _tag: 'Ok', stdout: output, stderr: '' } } - const sql = args[args.indexOf('--command') + 1]! + const sql = args[args.indexOf('--sql') + 1]! let rows: unknown[] = [] if (sql.includes('sqlite_master')) rows = ['skills', 'repos', 'owners', 'users', 'activity', 'sync_jobs', 'jobs', 'failed_jobs', 'd1_migrations'].map(name => ({ name })) diff --git a/test/unit/external-checkin-collectors.test.ts b/test/unit/external-checkin-collectors.test.ts index a947c0df..da74a596 100644 --- a/test/unit/external-checkin-collectors.test.ts +++ b/test/unit/external-checkin-collectors.test.ts @@ -43,11 +43,11 @@ it.each([ output = args[0] === 'ls-tree' ? 'migrations/001.sql' : args[0] === 'branch' ? 'main' : args[0] === 'rev-parse' ? 'abc' : '' return { _tag: 'Ok', stdout: output, stderr: '' } } - if (args[0] === 'deployments') { - output = [{ id: 'deployment', created_on: now.toISOString(), versions: [{ percentage: 100, version_id: 'release-1' }] }] + if (args[1] === 'deployments') { + output = { deployments: [{ id: 'deployment', created_on: now.toISOString(), versions: [{ percentage: 100, version_id: 'release-1' }] }] } } else { - const sql = args[args.indexOf('--command') + 1]! + const sql = args[args.indexOf('--sql') + 1]! let rows: unknown[] = [] if (sql.includes('sqlite_master')) rows = ['skills', 'repos', 'owners', 'users', 'activity', 'install_events', 'sync_jobs', 'jobs', 'failed_jobs', 'daily_health_checks', 'd1_migrations'].map(name => ({ name })) @@ -100,7 +100,7 @@ it('counts only X Posts observed within the UTC day at the check time', async () boundary.command.mockImplementation(async (_context, command: string, args: string[]) => { if (command === 'git') return { _tag: 'Ok', stdout: args[0] === 'rev-parse' ? 'abc' : '', stderr: '' } - const sql = args[args.indexOf('--command') + 1]! + const sql = args[args.indexOf('--sql') + 1]! const rows = db.prepare(sql).all() return { _tag: 'Ok', stdout: JSON.stringify([{ success: true, results: rows }]), stderr: '' } }) @@ -136,7 +136,7 @@ it.each(['2026-10-05T09:00:00Z', '2026-10-03T10:00:00Z'])('keeps rolling X day t boundary.command.mockImplementation(async (_context, command: string, args: string[]) => { if (command === 'git') return { _tag: 'Ok', stdout: args[0] === 'rev-parse' ? 'abc' : '', stderr: '' } - const sql = args[args.indexOf('--command') + 1]! + const sql = args[args.indexOf('--sql') + 1]! return { _tag: 'Ok', stdout: JSON.stringify([{ success: true, results: db.prepare(sql).all() }]), stderr: '' } }) @@ -204,7 +204,7 @@ it.each([ boundary.command.mockImplementation(async (_context, command: string, args: string[]) => { if (command === 'git') return { _tag: 'Ok', stdout: args[0] === 'rev-parse' ? 'abc' : '', stderr: '' } - const sql = args[args.indexOf('--command') + 1]! + const sql = args[args.indexOf('--sql') + 1]! return { _tag: 'Ok', stdout: JSON.stringify([{ success: true, results: db.prepare(sql).all() }]), stderr: '' } }) @@ -214,6 +214,44 @@ it.each([ expect(report.results[0]?.result).toMatchObject({ evidence: { pipeline: { embeddings_stuck: expected } } }) }) +// A repository `.env` can carry a deploy-time CLOUDFLARE_API_TOKEN, and `cf` +// loads `.env` from its working directory. Run inside the checkout, a stale +// token there shadowed the operator's valid `cf` login (2026-11-24). +it('reads Cloudflare through cf from the home directory, not the checkout', async () => { + const now = new Date('2026-11-24T00:00:00Z') + const root = await mkdtemp(join(tmpdir(), 'skilld-checkin-cf-')) + roots.push(root) + await mkdir(join(root, 'shared/server'), { recursive: true }) + await mkdir(join(root, 'migrations')) + await writeFile(join(root, 'shared/server/x-ingest.ts'), 'export const DAILY_DISCOVERY_READ_BUDGET = 400\nconst MIN_SEARCH_PAGE_SIZE = 10') + const cloudflareCalls: { command: string, cwd: string }[] = [] + boundary.command.mockImplementation(async (context: { rootDir: string }, command: string, args: string[]) => { + if (command === 'git') + return { _tag: 'Ok', stdout: args[0] === 'rev-parse' ? 'abc' : '', stderr: '' } + cloudflareCalls.push({ command, cwd: context.rootDir }) + if (args[1] === 'deployments') + return { _tag: 'Ok', stdout: JSON.stringify({ deployments: [{ id: 'deployment', created_on: now.toISOString(), versions: [{ percentage: 100, version_id: 'release-1' }] }] }), stderr: '' } + return { _tag: 'Ok', stdout: JSON.stringify([{ success: true, results: [] }]), stderr: '' } + }) + + const { report } = await runExternalChecks([deployCheck, databaseCheck], { required: [deployCheck.id, databaseCheck.id] }, { rootDir: root, env: { HOME: '/home/operator' }, clock: () => now }) + + expect(report.results.find(check => check.id === 'skilld.deploy')?.result).toMatchObject({ evidence: { latest: { versionId: 'release-1' } } }) + expect(cloudflareCalls.length).toBeGreaterThan(1) + expect(cloudflareCalls.every(call => call.command === 'cf' && call.cwd === '/home/operator')).toBe(true) +}) + +it('names the missing Worker analytics token instead of falling back to another CLI', async () => { + const fetch = vi.fn() + vi.stubGlobal('fetch', fetch) + + const { report } = await runExternalChecks([workersCheck], { required: [workersCheck.id] }, { env: {} }) + + expect(report.results[0]?.result).toMatchObject({ _tag: 'Unavailable', reason: expect.stringContaining('CLOUDFLARE_USAGE_TOKEN') }) + expect(boundary.command).not.toHaveBeenCalled() + expect(fetch).not.toHaveBeenCalled() +}) + it('rejects oversized Worker analytics evidence', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue(Response.json({ data: { viewer: { accounts: [{ workersInvocationsAdaptive: [] }] } }, padding: 'x'.repeat(2_097_153) }))) const { report } = await runExternalChecks([workersCheck], { required: [workersCheck.id] }, { env: { CLOUDFLARE_USAGE_TOKEN: 'test-token' } }) @@ -236,13 +274,16 @@ it('archives the collector failure cause instead of the generic throw message', it('totals command copies from an untruncated rollup, not the capped top page', async () => { const topRows = Array.from({ length: 50 }, (_, index) => ({ mode: 'run', kind: 'skill', slug: `owner/skill-${index}`, copies: 1 })) const totalsRows = [{ mode: 'run', copies: 50 }, { mode: 'install', copies: 10 }] - vi.stubGlobal('fetch', vi.fn(async (_url: string | URL, init?: { body?: string }) => { - return Response.json({ data: init?.body?.includes('blob3 = \'signup\'') + boundary.command.mockImplementation(async (_context, command: string, args: string[]) => { + if (command !== 'cf' || args.slice(0, 3).join(' ') !== 'analytics-engine sql query') + return { _tag: 'Err', reason: 'Unexpected command.' } + const body = args[args.indexOf('--body') + 1]! + return { _tag: 'Ok', stdout: JSON.stringify({ data: body.includes('blob3 = \'signup\'') ? [{ stage: 'email', outcome: 'failed', entry: 'onboarding', choice: '', events: '2' }] - : init?.body?.includes('LIMIT 50') ? topRows : totalsRows }) - })) + : body.includes('LIMIT 50') ? topRows : totalsRows }), stderr: '' } + }) - const { report } = await runExternalChecks([analyticsCheck], { required: [analyticsCheck.id] }, { env: { CLOUDFLARE_USAGE_TOKEN: 'test-token' } }) + const { report } = await runExternalChecks([analyticsCheck], { required: [analyticsCheck.id] }, { env: { HOME: '/home/operator' } }) expect(report.results.find(check => check.id === 'skilld.analytics')?.result).toMatchObject({ _tag: 'Pass',