Personal Telegram developer console for GitHub

fix: verify active Worker version commit evidence before delivery success

Codex committed Oct 25, 2026 at 07:26 UTC ace882ccefff4b13b983ac4bf6ec36b44b66f803
9 files changed +387 -17
.github/workflows/deploy.yml
+4 -3
@@ -49,11 +49,12 @@ jobs:
49 shell: bash
50 run: |
51 set -euo pipefail
52 - printf '%s' "$CLOUDFLARE_API_TOKEN" | npx --yes wrangler@4 secret put CLOUDFLARE_API_TOKEN
53 - printf '%s' "$CLOUDFLARE_ACCOUNT_ID" | npx --yes wrangler@4 secret put CLOUDFLARE_ACCOUNT_ID
52 + printf '%s' "$CLOUDFLARE_API_TOKEN" | npx --yes wrangler@4.152.0 secret put CLOUDFLARE_API_TOKEN
53 + printf '%s' "$CLOUDFLARE_ACCOUNT_ID" | npx --yes wrangler@4.152.0 secret put CLOUDFLARE_ACCOUNT_ID
54
55 - name: Deploy verified commit to Cloudflare Workers
56 env:
57 CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
58 CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
59 - run: npx --yes wrangler@4 deploy
59 + DEPLOY_COMMIT_SHA: ${{ github.event.workflow_run.head_sha }}
60 + run: npx --yes wrangler@4.152.0 deploy --tag "$DEPLOY_COMMIT_SHA"
src/core/cicd-control-plane.js
+36 -3
@@ -1,6 +1,6 @@
1 const fullSha = (value) =>
2 - /^[a-f0-9]{40}$/i.test(String(value || ''))
3 - ? String(value).toLowerCase()
2 + typeof value === 'string' && /^[a-f0-9]{40}$/i.test(value)
3 + ? value.toLowerCase()
4 : '';
5
6 export function correlateDeliveryState({
@@ -51,9 +51,42 @@ export function correlateDeliveryState({
51 };
52 }
53
54 + const activeVersion = runtime?.version;
55 + if (!activeVersion?.id) {
56 + return {
57 + state: 'unknown',
58 + reason: 'Active runtime version SHA evidence is unavailable'
59 + };
60 + }
61 + if (activeVersion.id !== versions[0].versionId) {
62 + return {
63 + state: 'mismatch',
64 + reason: 'Runtime version evidence does not match the active version'
65 + };
66 + }
67 +
68 + // Cloudflare documents commit_sha as CI metadata and tag as an operator
69 + // identifier. Our deploy workflow sets the tag to its verified commit SHA.
70 + // These authenticated provider markers are not source-content attestations.
71 + const annotations = activeVersion.annotations;
72 + const commitSha = fullSha(annotations?.['workers/commit_sha']);
73 + const tagSha = fullSha(annotations?.['workers/tag']);
74 + if (!commitSha && !tagSha) {
75 + return {
76 + state: 'unknown',
77 + reason: 'Active runtime version has no validated full SHA metadata'
78 + };
79 + }
80 + if ((commitSha && commitSha !== target) || (tagSha && tagSha !== target)) {
81 + return {
82 + state: 'mismatch',
83 + reason: 'Active runtime version SHA does not match target'
84 + };
85 + }
86 +
87 return {
88 state: 'success',
56 - reason: 'Exact SHA CI/deploy evidence and runtime traffic agree',
89 + reason: 'Exact SHA CI/deploy and active runtime version metadata agree',
90 sha: target,
91 deploymentId: String(runtime?.deployment?.id || ''),
92 versionId: String(versions[0].versionId)
src/plugins/cloudflare/plugin.js
+2 -2
@@ -174,8 +174,8 @@ export function createCloudflarePlugin({ cloudflare, github } = {}) {
174 ) || null;
175 const state = correlateDeliveryState({
176 targetSha,
177 - ci,
178 - deploy,
177 + ci: ci ? { ...ci, sha: ci.fullSha } : null,
178 + deploy: deploy ? { ...deploy, sha: deploy.fullSha } : null,
179 runtime
180 });
181 const label =
src/plugins/cloudflare/service.js
+36 -5
@@ -188,7 +188,29 @@ export class CloudflareService {
188 : [];
189
190 const latestDeployment = deployments[0] || null;
191 - const latestVersion = versions[0] || null;
191 + const traffic = Array.isArray(latestDeployment?.versions)
192 + ? latestDeployment.versions
193 + : [];
194 + const activeVersionId =
195 + traffic.length === 1 && Number(traffic[0]?.percentage) === 100
196 + ? clean(traffic[0]?.version_id)
197 + : '';
198 + let activeVersion = activeVersionId
199 + ? versions.find((version) => clean(version?.id) === activeVersionId)
200 + : null;
201 + // The versions list can omit annotations or the deployed version itself.
202 + // Read that exact version's detail; an unrelated latest upload is no proof.
203 + if (
204 + activeVersionId &&
205 + activeVersion?.annotations?.['workers/commit_sha'] === undefined &&
206 + activeVersion?.annotations?.['workers/tag'] === undefined
207 + ) {
208 + const detail = await this.requestJson(
209 + `/versions/${safe(activeVersionId)}`,
210 + 'Cloudflare active version'
211 + );
212 + activeVersion = clean(detail?.id) === activeVersionId ? detail : null;
213 + }
214 const bindings = Array.isArray(settingsResult?.bindings)
215 ? settingsResult.bindings
216 .map((binding) => ({
@@ -216,12 +238,21 @@ export class CloudflareService {
238 }))
239 }
240 : null,
219 - version: latestVersion
241 + version: activeVersion
242 ? {
221 - id: clean(latestVersion.id),
222 - createdOn: clean(latestVersion.created_on),
243 + id: clean(activeVersion.id),
244 + createdOn: clean(
245 + activeVersion.metadata?.created_on || activeVersion.created_on
246 + ),
247 triggeredBy: clean(
224 - latestVersion.annotations?.['workers/triggered_by']
248 + activeVersion.annotations?.['workers/triggered_by']
249 + ),
250 + annotations: Object.fromEntries(
251 + ['workers/commit_sha', 'workers/tag']
252 + .filter(
253 + (key) => typeof activeVersion.annotations?.[key] === 'string'
254 + )
255 + .map((key) => [key, activeVersion.annotations[key]])
256 )
257 }
258 : null,
test/cicd-control-plane.test.js
+4 -3
@@ -4,7 +4,8 @@ import { correlateDeliveryState } from '../src/core/cicd-control-plane.js';
4
5 const sha = 'a'.repeat(40);
6 const active = {
7 - deployment: { id: 'dep', versions: [{ versionId: 'v1', percentage: 100 }] }
7 + deployment: { id: 'dep', versions: [{ versionId: 'v1', percentage: 100 }] },
8 + version: { id: 'v1', annotations: { 'workers/tag': sha } }
9 };
10
11 test('CP5 correlates exact SHA across CI and deploy before declaring success', () => {
@@ -134,7 +135,7 @@ test('CP5 Cloudflare plugin exposes owner delivery view from live provider evide
135 id: 'dep',
136 versions: [{ versionId: 'v1', percentage: 100 }]
137 },
137 - version: { id: 'v1' },
138 + version: { id: 'v1', annotations: { 'workers/tag': target } },
139 bindings: [],
140 observability: {}
141 };
@@ -144,6 +145,6 @@ test('CP5 Cloudflare plugin exposes owner delivery view from live provider evide
145 const route = plugin.resolveCallback('cf:delivery');
146 assert.equal(route.actionId, 'cloudflare.delivery.status');
147 const view = await route.execute();
147 - assert.match(view.text, /SUCCESS|موفق/i);
148 + assert.match(view.text, /State: <b>SUCCESS \/ موفق<\/b>/);
149 assert.match(view.text, new RegExp(target.slice(0, 12)));
150 });
test/cloudflare-ops-completion.test.js
+5
@@ -46,6 +46,11 @@ test('CP4 service lists versions and deploys exact known version at 100 percent
46 return cf({
47 items: [{ id: uuid, created_on: '2026-10-04T00:00:00Z' }]
48 });
49 + if (String(url).endsWith(`/versions/${uuid}`))
50 + return cf({
51 + id: uuid,
52 + metadata: { created_on: '2026-10-04T00:00:00Z' }
53 + });
54 if (String(url).endsWith('/settings'))
55 return cf({
56 bindings: [{ name: 'SECRET', type: 'secret_text' }],
test/cloudflare-service.test.js
+10 -1
@@ -75,6 +75,15 @@ test('CloudflareService normalizes deployment, version, bindings and observabili
75 }
76 }
77 });
78 + if (value.endsWith('/versions/ver-1'))
79 + return response({
80 + success: true,
81 + result: {
82 + id: 'ver-1',
83 + metadata: { created_on: '2026-10-04T19:34:01Z' },
84 + annotations: { 'workers/triggered_by': 'upload' }
85 + }
86 + });
87 return response(
88 { success: false, errors: [{ message: 'Not Found' }] },
89 404
@@ -105,7 +114,7 @@ test('CloudflareService normalizes deployment, version, bindings and observabili
114 invocationLogs: true,
115 tracesEnabled: false
116 });
108 - assert.equal(calls.length, 3);
117 + assert.equal(calls.length, 4);
118 for (const call of calls) {
119 assert.equal(call.options.headers.Authorization, `Bearer ${token}`);
120 assert.equal(call.options.headers['Content-Type'], 'application/json');
test/delivery-evidence.test.js new
+289
@@ -0,0 +1,289 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { readFileSync } from 'node:fs';
4 +import { correlateDeliveryState } from '../src/core/cicd-control-plane.js';
5 +import { CloudflareService } from '../src/plugins/cloudflare/service.js';
6 +import { createCloudflarePlugin } from '../src/plugins/cloudflare/plugin.js';
7 +
8 +const sha = 'a'.repeat(40);
9 +const otherSha = 'b'.repeat(40);
10 +const activeId = '11111111-1111-4111-8111-111111111111';
11 +const latestId = '22222222-2222-4222-8222-222222222222';
12 +const deployment = {
13 + id: 'dep-active',
14 + versions: [{ versionId: activeId, percentage: 100 }]
15 +};
16 +const runs = {
17 + targetSha: sha,
18 + ci: { sha, status: 'completed', conclusion: 'success' },
19 + deploy: { sha, status: 'completed', conclusion: 'success' }
20 +};
21 +const version = (annotations = { 'workers/tag': sha }, id = activeId) => ({
22 + id,
23 + annotations
24 +});
25 +
26 +test('delivery requires explicit SHA metadata for the version receiving traffic', () => {
27 + for (const runtime of [
28 + { deployment },
29 + { deployment, version: { id: activeId } },
30 + { deployment, version: { id: activeId, sha } },
31 + { deployment, version: version({ 'workers/message': sha }) },
32 + { deployment, version: version({ 'workers/sha': sha }) },
33 + { deployment, version: version({ 'workers/tag': sha.slice(0, 12) }) },
34 + { deployment, version: version({ 'workers/commit_sha': 'invalid' }) },
35 + { deployment, version: version({ 'workers/tag': [sha] }) }
36 + ]) {
37 + const state = correlateDeliveryState({ ...runs, runtime });
38 + assert.equal(state.state, 'unknown', JSON.stringify(runtime));
39 + assert.match(state.reason, /SHA|evidence/i);
40 + }
41 +});
42 +
43 +test('delivery rejects another version metadata even when its SHA matches', () => {
44 + const state = correlateDeliveryState({
45 + ...runs,
46 + runtime: { deployment, version: version(undefined, latestId) }
47 + });
48 + assert.equal(state.state, 'mismatch');
49 +});
50 +
51 +test('delivery rejects an active version whose explicit SHA differs from target', () => {
52 + for (const annotations of [
53 + { 'workers/tag': otherSha },
54 + { 'workers/commit_sha': otherSha },
55 + { 'workers/commit_sha': otherSha, 'workers/tag': sha }
56 + ]) {
57 + const state = correlateDeliveryState({
58 + ...runs,
59 + runtime: { deployment, version: version(annotations) }
60 + });
61 + assert.equal(state.state, 'mismatch');
62 + assert.match(state.reason, /SHA/i);
63 + }
64 +});
65 +
66 +test('delivery accepts only full matching SHA markers tied to the active version', () => {
67 + for (const annotations of [
68 + { 'workers/tag': sha },
69 + { 'workers/commit_sha': sha },
70 + { 'workers/tag': sha.toUpperCase(), 'workers/commit_sha': sha },
71 + { 'workers/commit_sha': sha, 'workers/tag': 'release-1' }
72 + ]) {
73 + const state = correlateDeliveryState({
74 + ...runs,
75 + runtime: { deployment, version: version(annotations) }
76 + });
77 + assert.equal(state.state, 'success');
78 + assert.equal(state.sha, sha);
79 + assert.equal(state.versionId, activeId);
80 + assert.equal(state.deploymentId, deployment.id);
81 + }
82 +});
83 +
84 +function serviceFor({ items = [], active = deployment.versions, detail } = {}) {
85 + const calls = [];
86 + const service = new CloudflareService({
87 + token: 'cf-token',
88 + accountId: 'account',
89 + workerName: 'nexa-dev-bot',
90 + async fetchImpl(url, options) {
91 + const path = new URL(url).pathname;
92 + calls.push({ path, method: options.method });
93 + let result;
94 + if (path.endsWith('/deployments')) {
95 + result = {
96 + deployments: [
97 + {
98 + id: deployment.id,
99 + versions: active.map(({ versionId, percentage }) => ({
100 + version_id: versionId,
101 + percentage
102 + }))
103 + }
104 + ]
105 + };
106 + } else if (path.endsWith('/versions')) result = { items };
107 + else if (path.endsWith(`/versions/${activeId}`)) result = detail;
108 + else if (path.endsWith('/settings')) result = {};
109 + else throw new Error('Unexpected Cloudflare path');
110 + return new Response(JSON.stringify({ success: true, result }));
111 + }
112 + });
113 + return { service, calls };
114 +}
115 +
116 +test('snapshot selects deployed version metadata instead of a newer unused upload', async () => {
117 + const { service, calls } = serviceFor({
118 + items: [
119 + version({ 'workers/tag': sha }, latestId),
120 + {
121 + ...version({ 'workers/commit_sha': otherSha }),
122 + metadata: { created_on: '2026-10-24T00:00:00Z' }
123 + }
124 + ]
125 + });
126 + const snapshot = await service.getWorkerSnapshot();
127 + assert.equal(snapshot.version.id, activeId);
128 + assert.equal(snapshot.version.createdOn, '2026-10-24T00:00:00Z');
129 + assert.deepEqual(snapshot.version.annotations, {
130 + 'workers/commit_sha': otherSha
131 + });
132 + assert.equal(
133 + correlateDeliveryState({ ...runs, runtime: snapshot }).state,
134 + 'mismatch'
135 + );
136 + assert.equal(calls.length, 3);
137 +});
138 +
139 +test('snapshot fetches deployed version when it is absent from the latest versions page', async () => {
140 + const { service, calls } = serviceFor({
141 + items: [version({ 'workers/tag': otherSha }, latestId)],
142 + detail: version()
143 + });
144 + const snapshot = await service.getWorkerSnapshot();
145 + assert.equal(snapshot.version.id, activeId);
146 + assert.deepEqual(snapshot.version.annotations, { 'workers/tag': sha });
147 + assert.equal(
148 + correlateDeliveryState({ ...runs, runtime: snapshot }).state,
149 + 'success'
150 + );
151 + assert.ok(calls.some(({ path }) => path.endsWith(`/versions/${activeId}`)));
152 + assert.ok(calls.every(({ method }) => method === 'GET'));
153 +});
154 +
155 +test('snapshot fetches SHA annotations absent from the minimal deployed version listing', async () => {
156 + const { service, calls } = serviceFor({
157 + items: [{ id: activeId, metadata: { source: 'wrangler' } }],
158 + detail: version({ 'workers/commit_sha': sha })
159 + });
160 + const snapshot = await service.getWorkerSnapshot();
161 + assert.equal(
162 + correlateDeliveryState({ ...runs, runtime: snapshot }).state,
163 + 'success'
164 + );
165 + assert.ok(calls.some(({ path }) => path.endsWith(`/versions/${activeId}`)));
166 +});
167 +
168 +test('snapshot stays unverified when deployed version detail lacks SHA annotations', async () => {
169 + const { service } = serviceFor({
170 + items: [{ id: activeId }],
171 + detail: { id: activeId }
172 + });
173 + const snapshot = await service.getWorkerSnapshot();
174 + assert.equal(snapshot.version.id, activeId);
175 + assert.equal(
176 + correlateDeliveryState({ ...runs, runtime: snapshot }).state,
177 + 'unknown'
178 + );
179 +});
180 +
181 +test('snapshot detail errors propagate through the existing redacted provider boundary', async () => {
182 + const service = new CloudflareService({
183 + token: 'cf-token',
184 + accountId: 'account',
185 + workerName: 'nexa-dev-bot',
186 + async fetchImpl(url) {
187 + let result;
188 + if (String(url).endsWith('/deployments')) {
189 + result = {
190 + deployments: [
191 + { versions: [{ version_id: activeId, percentage: 100 }] }
192 + ]
193 + };
194 + } else if (String(url).endsWith('/versions')) result = { items: [] };
195 + else if (String(url).endsWith('/settings')) result = {};
196 + else
197 + return new Response(
198 + JSON.stringify({
199 + success: false,
200 + errors: [{ message: 'bad credential cf-token' }]
201 + }),
202 + { status: 403 }
203 + );
204 + return new Response(JSON.stringify({ success: true, result }));
205 + }
206 + });
207 + await assert.rejects(service.getWorkerSnapshot(), (error) => {
208 + assert.match(error.message, /403.*\[REDACTED\]/);
209 + assert.doesNotMatch(error.message, /cf-token/);
210 + return true;
211 + });
212 +});
213 +
214 +test('snapshot never substitutes unrelated metadata returned by a version detail read', async () => {
215 + const { service } = serviceFor({
216 + items: [version(undefined, latestId)],
217 + detail: version(undefined, latestId)
218 + });
219 + const snapshot = await service.getWorkerSnapshot();
220 + assert.equal(snapshot.version, null);
221 + assert.equal(
222 + correlateDeliveryState({ ...runs, runtime: snapshot }).state,
223 + 'unknown'
224 + );
225 +});
226 +
227 +test('snapshot has no single active version for absent or split traffic', async () => {
228 + for (const active of [
229 + [],
230 + [
231 + { versionId: activeId, percentage: 50 },
232 + { versionId: latestId, percentage: 50 }
233 + ]
234 + ]) {
235 + const { service } = serviceFor({ items: [version()], active });
236 + const snapshot = await service.getWorkerSnapshot();
237 + assert.equal(snapshot.version, null);
238 + assert.equal(
239 + correlateDeliveryState({ ...runs, runtime: snapshot }).state,
240 + 'mismatch'
241 + );
242 + }
243 +});
244 +
245 +test('delivery view reports unknown when workflow success has no runtime SHA evidence', async () => {
246 + const plugin = createCloudflarePlugin({
247 + cloudflare: {
248 + workerName: 'nexa-dev-bot',
249 + isConfigured: () => true,
250 + getWorkerSnapshot: async () => ({ deployment, version: { id: activeId } })
251 + },
252 + github: {
253 + listRepositories: async () => [
254 + { id: '123', name: 'nexa-dev-bot', defaultBranch: 'main' }
255 + ],
256 + listCommits: async () => [{ fullSha: sha }],
257 + listWorkflowRuns: async () =>
258 + ['CI', 'Deploy Cloudflare Worker'].map((name) => ({
259 + name,
260 + branch: 'main',
261 + fullSha: sha,
262 + ...runs.ci
263 + }))
264 + }
265 + });
266 + const view = await plugin.resolveCallback('cf:delivery').execute();
267 + assert.match(view.text, /UNKNOWN/);
268 + assert.doesNotMatch(view.text, /SUCCESS|موفق/);
269 +});
270 +
271 +test('production deployment pins Wrangler and tags the checked out verified commit', () => {
272 + const workflow = readFileSync(
273 + new URL('../.github/workflows/deploy.yml', import.meta.url),
274 + 'utf8'
275 + );
276 + assert.match(
277 + workflow,
278 + /ref: \$\{\{ github\.event\.workflow_run\.head_sha \}\}/
279 + );
280 + assert.match(
281 + workflow,
282 + /DEPLOY_COMMIT_SHA: \$\{\{ github\.event\.workflow_run\.head_sha \}\}/
283 + );
284 + assert.match(
285 + workflow,
286 + /wrangler@4\.152\.0 deploy --tag "\$DEPLOY_COMMIT_SHA"/
287 + );
288 + assert.doesNotMatch(workflow, /wrangler@4\s/);
289 +});
test/g0-bot-regressions.test.js
+1
@@ -55,6 +55,7 @@ function installProviders(t, { githubFailure = false } = {}) {
55 ]
56 },
57 versions: { items: [{ id: versionId }] },
58 + [versionId]: { id: versionId },
59 settings: { bindings: [], observability: {} }
60 }[resource];
61 if (result) return Response.json({ success: true, result });