Skip to content

Commit 4a6f9ec

Browse files
yetvalvincentkoc
andauthored
fix(dashboard): normalize exact-review queue failures (#1240)
Normalize rejected and malformed exact-review queue 5xx responses at the dashboard Worker boundary, while preserving intentional 4xx and valid JSON 5xx responses. Keep Durable Object storage errors rejecting so transaction rollback remains atomic. Preserve the proof harness collision-refusal guards. Validated on head 0e6ef72 with four boundary tests, six rollback regression controls, host-local Wrangler/SQLite failure and recovery proof, green CI and CodeQL, and clean independent Codex review. Co-authored-by: yetval <[email protected]> Co-authored-by: Vincent Koc <[email protected]>
1 parent a8b2deb commit 4a6f9ec

4 files changed

Lines changed: 466 additions & 7 deletions

File tree

‎dashboard/worker.ts‎

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import {
2828
githubAppJsonAsPlainError as githubAppJson,
2929
signGithubAppJwt,
3030
} from "./github-api.ts";
31+
import { sanitizedServerError } from "./error-safety.ts";
3132
import {
3233
HEALTH_HISTORY_RETENTION_DAYS,
3334
HEALTH_HISTORY_SAMPLE_MS,
@@ -4422,13 +4423,25 @@ async function exactReviewQueueRequest(env, path, request?: Request) {
44224423
const queue = exactReviewQueueStub(env);
44234424
if (!queue) return json({ error: "exact_review_queue_not_configured" }, 503);
44244425
const body = request ? await request.text() : undefined;
4425-
return queue.fetch(
4426-
new Request(`https://clawsweeper-exact-review-queue${path}`, {
4427-
method: request?.method || "GET",
4428-
headers: body ? { "content-type": "application/json" } : undefined,
4429-
...(body ? { body } : {}),
4430-
}),
4431-
);
4426+
try {
4427+
const response = await queue.fetch(
4428+
new Request(`https://clawsweeper-exact-review-queue${path}`, {
4429+
method: request?.method || "GET",
4430+
headers: body ? { "content-type": "application/json" } : undefined,
4431+
...(body ? { body } : {}),
4432+
}),
4433+
);
4434+
if (response.status < 500) return response;
4435+
const responseBody = await response.clone().text();
4436+
try {
4437+
JSON.parse(responseBody);
4438+
return response;
4439+
} catch {
4440+
return json({ error: sanitizedServerError(responseBody) }, response.status);
4441+
}
4442+
} catch (error) {
4443+
return json({ error: sanitizedServerError(error) }, 500);
4444+
}
44324445
}
44334446

44344447
const PUBLIC_QUEUE_COUNT_LIMIT = 1_000_000;
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Exact-review Worker sanitized JSON error proof
2+
3+
This proof starts the actual local Wrangler Worker and its ExactReviewQueue
4+
Durable Object, then drives the signed internal
5+
`/internal/exact-review/publications/list` route through the real Workers
6+
Durable Object boundary. A proof-only entry module re-exports the production
7+
`ExactReviewQueue` with its real SQLite `storage.sql.exec` wrapped so one
8+
marked request fails the `SELECT item_key, item_json` state read with an
9+
error message carrying a planted GitHub token. The production route code,
10+
worker forwarding, HMAC verification, storage initialization, and every other
11+
request run unmodified.
12+
13+
The scenario sends three identical-shape signed requests: a baseline list
14+
(expect 200), the marked failing request, and a recovery list (expect 200).
15+
The script detects whether the checked-out tree contains the fix and asserts
16+
accordingly:
17+
18+
- before (base tree): the injected Durable Object failure escapes the Worker,
19+
and the client receives a non-JSON 500 with no sanitized error contract; in
20+
the local dev runtime the error page also exposes the planted token to the
21+
client.
22+
- after (fixed tree): the Durable Object still rejects so its transaction
23+
remains fail closed, while the Worker converts that rejected stub call into
24+
HTTP 500 with
25+
`content-type: application/json` and body
26+
`{"error":"injected sqlite read failure exposing GH_TOKEN=[REDACTED]"}`;
27+
the planted token never reaches the client.
28+
29+
Run from the repository root of the tree under test:
30+
31+
```bash
32+
crabbox run \
33+
--provider local-container \
34+
--local-container-image node:24-bookworm \
35+
--no-hydrate \
36+
--timing-json \
37+
--script docs/proof/exact-review-do-json-errors/run-proof.sh \
38+
--require-artifact '.artifacts/exact-review-do-json-errors/proof-summary.json' \
39+
--artifact-glob '.artifacts/exact-review-do-json-errors/**'
40+
```
41+
42+
Limits: the before-mode HTML error page is the local dev runtime's rendering
43+
of the escaped exception; deployed workerd returns its generic internal-error
44+
response instead. The invariant proven is the Worker-facing failure contract:
45+
an escaped Durable Object rejection becomes a sanitized JSON 500 without
46+
changing the Durable Object transaction boundary.
Lines changed: 284 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,284 @@
1+
#!/usr/bin/env bash
2+
set -euo pipefail
3+
4+
export CI=1
5+
export WRANGLER_SEND_METRICS=false
6+
7+
root_dir=$PWD
8+
output_dir="${EXACT_REVIEW_DO_PROOF_OUTPUT:-.artifacts/exact-review-do-json-errors}"
9+
port="${EXACT_REVIEW_DO_PROOF_PORT:-8794}"
10+
runtime_dir=$(mktemp -d "${TMPDIR:-/tmp}/clawsweeper-do-json-errors.XXXXXX")
11+
vars_file="$runtime_dir/.dev.vars"
12+
wrangler_log="$runtime_dir/wrangler.log"
13+
proof_entry="dashboard/proof-entry-do-error.ts"
14+
proof_config="dashboard/wrangler.proof.toml"
15+
16+
if [ -e "$proof_entry" ] || [ -e "$proof_config" ]; then
17+
echo "Refusing to overwrite existing proof injection files" >&2
18+
exit 1
19+
fi
20+
21+
cleanup() {
22+
if [ -n "${wrangler_pid:-}" ]; then
23+
kill "$wrangler_pid" >/dev/null 2>&1 || true
24+
wait "$wrangler_pid" >/dev/null 2>&1 || true
25+
fi
26+
rm -f "$proof_entry" "$proof_config"
27+
rm -rf "$runtime_dir"
28+
}
29+
trap cleanup EXIT
30+
31+
if [ -e "$output_dir" ]; then
32+
echo "Refusing to overwrite existing proof output: $output_dir" >&2
33+
exit 1
34+
fi
35+
mkdir -p "$output_dir"
36+
37+
if grep -q 'sanitizedServerError(responseBody)' dashboard/worker.ts; then
38+
proof_mode=after
39+
else
40+
proof_mode=before
41+
fi
42+
head_sha=$(git rev-parse HEAD 2>/dev/null || echo unknown)
43+
44+
secret=$(node --input-type=module -e 'import { randomBytes } from "node:crypto"; process.stdout.write(randomBytes(32).toString("hex"));')
45+
umask 077
46+
printf '%s\n' \
47+
"CLAWSWEEPER_WEBHOOK_SECRET=$secret" \
48+
"INGEST_TOKEN=$secret" \
49+
"GITHUB_API_URL=http://127.0.0.1:9" \
50+
"CACHE_TTL_SECONDS=0" \
51+
"STALE_CACHE_TTL_SECONDS=0" \
52+
"INCLUDE_CI_STATUS=0" \
53+
"EXACT_REVIEW_DISPATCH_DEBOUNCE_MS=900000" \
54+
"EXACT_REVIEW_DISPATCH_DEBOUNCE_MAX_MS=900000" \
55+
>"$vars_file"
56+
57+
cat >"$proof_entry" <<'PROOF_ENTRY'
58+
import baseWorker, {
59+
StatusStore as WorkerStatusStore,
60+
ExactReviewQueue as BaseExactReviewQueue,
61+
} from "./worker.ts";
62+
63+
const PROOF_FAILURE_MESSAGE =
64+
"injected sqlite read failure exposing GH_TOKEN=ghp_examplesecrettoken0123456789abcd";
65+
66+
function bindingProxy(target: any, overrides: Record<PropertyKey, unknown>) {
67+
return new Proxy(target, {
68+
get(source, property) {
69+
if (Object.prototype.hasOwnProperty.call(overrides, property)) return overrides[property];
70+
const value = source[property];
71+
return typeof value === "function" ? value.bind(source) : value;
72+
},
73+
});
74+
}
75+
76+
export class ExactReviewQueue extends BaseExactReviewQueue {
77+
constructor(state: any, env: any) {
78+
let armedPattern: RegExp | null = null;
79+
const realStorage = state.storage;
80+
const sqlProxy = bindingProxy(realStorage.sql, {
81+
exec: (query: string, ...args: unknown[]) => {
82+
if (armedPattern && armedPattern.test(String(query))) {
83+
armedPattern = null;
84+
throw new Error(PROOF_FAILURE_MESSAGE);
85+
}
86+
return realStorage.sql.exec(query, ...args);
87+
},
88+
});
89+
const storageProxy = bindingProxy(realStorage, { sql: sqlProxy });
90+
const stateProxy = bindingProxy(state, { storage: storageProxy });
91+
super(stateProxy, env);
92+
Object.defineProperty(this, "armProofSqlFailure", {
93+
value: (pattern: RegExp) => {
94+
armedPattern = pattern;
95+
},
96+
});
97+
}
98+
99+
async fetch(request: Request) {
100+
if (request.method !== "POST") return super.fetch(request);
101+
const bodyText = await request.text();
102+
let marker: unknown = null;
103+
try {
104+
marker = (JSON.parse(bodyText) as { proof_fail_sql?: unknown }).proof_fail_sql;
105+
} catch {
106+
marker = null;
107+
}
108+
if (typeof marker === "string" && marker) {
109+
(this as { armProofSqlFailure?: (pattern: RegExp) => void }).armProofSqlFailure?.(
110+
new RegExp(marker),
111+
);
112+
}
113+
return super.fetch(
114+
new Request(request.url, { method: "POST", headers: request.headers, body: bodyText }),
115+
);
116+
}
117+
}
118+
119+
export { WorkerStatusStore as StatusStore };
120+
export default baseWorker;
121+
PROOF_ENTRY
122+
123+
sed 's|^main = "worker.ts"$|main = "proof-entry-do-error.ts"|' dashboard/wrangler.toml >"$proof_config"
124+
grep -q 'proof-entry-do-error.ts' "$proof_config"
125+
126+
driver="$runtime_dir/drive-proof.mjs"
127+
cat >"$driver" <<'PROOF_DRIVER'
128+
import { createHmac } from "node:crypto";
129+
import { mkdir, writeFile } from "node:fs/promises";
130+
import path from "node:path";
131+
132+
const origin = String(process.env.EXACT_REVIEW_DO_PROOF_ORIGIN || "").replace(/\/+$/, "");
133+
const secret = String(process.env.EXACT_REVIEW_DO_PROOF_SECRET || "");
134+
const outputDir = path.resolve(
135+
process.env.EXACT_REVIEW_DO_PROOF_OUTPUT || ".artifacts/exact-review-do-json-errors",
136+
);
137+
const mode = process.env.EXACT_REVIEW_DO_PROOF_MODE === "before" ? "before" : "after";
138+
const headSha = String(process.env.EXACT_REVIEW_DO_PROOF_HEAD || "unknown");
139+
if (!origin || !secret) throw new Error("proof origin and secret are required");
140+
141+
const plantedToken = "ghp_examplesecrettoken0123456789abcd";
142+
const routePath = "/internal/exact-review/publications/list";
143+
const assertions = [];
144+
const transcript = [];
145+
146+
function assertProof(name, condition, details = {}) {
147+
if (!condition) throw new Error(`Proof assertion failed: ${name} ${JSON.stringify(details)}`);
148+
assertions.push({ name, status: "PASS", ...details });
149+
}
150+
151+
function redact(value) {
152+
return String(value).split(plantedToken).join("ghp_[PLANTED_TOKEN_REDACTED]");
153+
}
154+
155+
async function signedPost(label, value) {
156+
const body = JSON.stringify(value);
157+
const signature = `sha256=${createHmac("sha256", secret).update(body).digest("hex")}`;
158+
const response = await fetch(`${origin}${routePath}`, {
159+
method: "POST",
160+
headers: {
161+
"content-type": "application/json",
162+
"x-clawsweeper-exact-review-signature": signature,
163+
},
164+
body,
165+
});
166+
const text = await response.text();
167+
transcript.push({
168+
label,
169+
request_body: body,
170+
status: response.status,
171+
content_type: response.headers.get("content-type") || "",
172+
response_body: redact(text),
173+
});
174+
return { status: response.status, contentType: response.headers.get("content-type") || "", text };
175+
}
176+
177+
await mkdir(outputDir, { recursive: true });
178+
179+
const baseline = await signedPost("baseline-list", { limit: 100 });
180+
assertProof("baseline_list_ok", baseline.status === 200, { http_status: baseline.status });
181+
182+
const failing = await signedPost("injected-storage-failure", {
183+
limit: 100,
184+
proof_fail_sql: "SELECT item_key, item_json",
185+
});
186+
187+
const recovery = await signedPost("recovery-list", { limit: 100 });
188+
assertProof("recovery_list_ok", recovery.status === 200, { http_status: recovery.status });
189+
190+
let parsedFailing = null;
191+
try {
192+
parsedFailing = JSON.parse(failing.text);
193+
} catch {
194+
parsedFailing = null;
195+
}
196+
const jsonContract =
197+
failing.contentType.includes("application/json") &&
198+
parsedFailing !== null &&
199+
typeof parsedFailing.error === "string";
200+
const tokenLeaked = failing.text.includes(plantedToken);
201+
202+
assertProof("failure_status_500", failing.status === 500, { http_status: failing.status });
203+
if (mode === "before") {
204+
assertProof("broken_failure_contract_on_base", !jsonContract || tokenLeaked, {
205+
json_contract: jsonContract,
206+
token_leaked: tokenLeaked,
207+
});
208+
} else {
209+
assertProof("worker_sanitized_json_contract", jsonContract, {
210+
content_type: failing.contentType,
211+
});
212+
assertProof("planted_token_redacted", !tokenLeaked && failing.text.includes("[REDACTED"), {
213+
response_body: redact(failing.text).slice(0, 300),
214+
});
215+
}
216+
217+
const summary = {
218+
mode,
219+
head_sha: headSha,
220+
route: routePath,
221+
planted_token: "ghp_[PLANTED_TOKEN_REDACTED]",
222+
failure_response: {
223+
status: failing.status,
224+
content_type: failing.contentType,
225+
body: redact(failing.text).slice(0, 2000),
226+
json_contract: jsonContract,
227+
token_leaked: tokenLeaked,
228+
},
229+
assertions,
230+
};
231+
await writeFile(
232+
path.join(outputDir, "proof-summary.json"),
233+
`${JSON.stringify(summary, null, 2)}\n`,
234+
);
235+
await writeFile(
236+
path.join(outputDir, "transcript.md"),
237+
[
238+
"# exact-review Worker JSON error proof",
239+
`mode: ${mode}`,
240+
`head: ${headSha}`,
241+
"",
242+
...transcript.map((entry) =>
243+
[
244+
`## ${entry.label}`,
245+
"```",
246+
`POST ${routePath}`,
247+
entry.request_body,
248+
`-> ${entry.status} ${entry.content_type}`,
249+
entry.response_body,
250+
"```",
251+
"",
252+
].join("\n"),
253+
),
254+
].join("\n"),
255+
);
256+
console.log(JSON.stringify({ mode, head: headSha, assertions }, null, 2));
257+
PROOF_DRIVER
258+
259+
if [ "${EXACT_REVIEW_DO_PROOF_SKIP_INSTALL:-0}" != "1" ]; then
260+
corepack pnpm install --frozen-lockfile
261+
fi
262+
npx --yes [email protected] dev --config "$proof_config" --local --ip 127.0.0.1 --port "$port" --env-file "$vars_file" --persist-to "$runtime_dir/state" >"$wrangler_log" 2>&1 &
263+
wrangler_pid=$!
264+
265+
for _ in $(seq 1 120); do
266+
if curl --fail --silent "http://127.0.0.1:${port}/api/health" >/dev/null 2>&1; then
267+
break
268+
fi
269+
if ! kill -0 "$wrangler_pid" >/dev/null 2>&1; then
270+
tail -n 100 "$wrangler_log" >&2
271+
exit 1
272+
fi
273+
sleep 1
274+
done
275+
276+
curl --fail --silent --show-error "http://127.0.0.1:${port}/api/health" >/dev/null
277+
EXACT_REVIEW_DO_PROOF_ORIGIN="http://127.0.0.1:${port}" \
278+
EXACT_REVIEW_DO_PROOF_SECRET="$secret" \
279+
EXACT_REVIEW_DO_PROOF_OUTPUT="$output_dir" \
280+
EXACT_REVIEW_DO_PROOF_MODE="$proof_mode" \
281+
EXACT_REVIEW_DO_PROOF_HEAD="$head_sha" \
282+
node "$driver"
283+
284+
test -s "$output_dir/proof-summary.json"

0 commit comments

Comments
 (0)