Diffinery

codician/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

800 lines · 54.9 KBRaw History
1name: Live test
2
3# End-to-end checks against the real diffinery.com after each deploy: email
4# sending, web UI features (syntax highlighting, settings pages, view transitions, milestones, variables), hosted Actions jobs in Cloudflare Containers (with Docker builds and services), the container registry, agent sandboxes,
5# webhooks, scheduled workflows, Git LFS, imports from GitHub, that tokens can't mint tokens, and pull requests (test merge commits, pull_request_target and the merge
6# queue). Each run works in a throwaway private repository that it
7# deletes at the end.
8#
9# Needs DIFFINERY_LIVE_TOKEN in the production environment: a write-scope token
10# (Settings -> Tokens) with access to all repositories, for a dedicated account that isn't
11# a site administrator (give it a quota override). The checks that need a site
12# administrator are skipped with a notice when the token isn't one's.
13on:
14 workflow_dispatch:
15 workflow_run:
16 workflows: [Deploy]
17 types: [completed]
18 branches: [main]
19
20permissions:
21 contents: read
22
23concurrency:
24 group: live-test
25 cancel-in-progress: false
26
27jobs:
28 live:
29 name: Containers, registry, sandboxes, webhooks, schedules, LFS and pull requests
30 # Runs on the host that deploys production (see the gate in deploy.yml).
31 if: ${{ github.event_name == 'workflow_dispatch' || (github.server_url == 'https://diffinery.com' && github.event.workflow_run.conclusion == 'success') }}
32 runs-on: ubuntu-latest
33 timeout-minutes: 45
34 environment: production
35 env:
36 DIFFINERY: https://diffinery.com
37 TOKEN: ${{ secrets.DIFFINERY_LIVE_TOKEN }}
38 REPO: live-${{ github.run_id }}-${{ github.run_attempt }}
39 HEAD_SHA: ${{ github.event.workflow_run.head_sha || github.sha }}
40 steps:
41 - name: Check the token
42 id: token
43 run: |
44 if [ -z "$TOKEN" ]; then
45 # After a deploy of diffinery.com a missing token is an error: a green run would mean nothing was tested.
46 if [ "$GITHUB_EVENT_NAME" = workflow_run ]; then
47 echo "::error::DIFFINERY_LIVE_TOKEN is not set in the production environment, so nothing was tested. Create a write token at $DIFFINERY/settings/tokens and save it as a production environment secret."
48 exit 1
49 fi
50 echo "::warning::DIFFINERY_LIVE_TOKEN is not set, so the live test is skipped. Create a write token at $DIFFINERY/settings/tokens and save it as a production environment secret."
51 echo "skip=true" >> "$GITHUB_OUTPUT"
52 exit 0
53 fi
54 login=$(curl -fsS "$DIFFINERY/api/v3/user" -H "Authorization: Bearer $TOKEN" | jq -r .login)
55 echo "OWNER=$login" >> "$GITHUB_ENV"
56 echo "testing as $login in $login/$REPO"
57
58 - name: Choose the registry check's image sizes
59 if: steps.token.outputs.skip != 'true'
60 run: |
61 set -euo pipefail
62 # Layers over Cloudflare's 100 MB request limit (which hosted runners push through
63 # the registry relay) take minutes to push and pull. They're pushed on manual runs and
64 # whenever the registry, the runner image or this test changed since the last
65 # successful live test; other deploys push small images through the same path.
66 full=true
67 if [ "$GITHUB_EVENT_NAME" = workflow_run ]; then
68 api() { curl -fsS "$DIFFINERY/api/v3/repos/$GITHUB_REPOSITORY$1" -H "Authorization: Bearer $TOKEN"; }
69 last=$(api "/actions/runs?workflow=live-test.yml&status=success&per_page=1" | jq -r '.workflow_runs[0].head_sha // empty' || true)
70 if [ -n "$last" ] && files=$(api "/compare/$last...$HEAD_SHA" | jq -r '.files[].filename'); then
71 grep -qE '^(apps/diffinery/src/registry/|containers/runner/|\.github/workflows/live-test\.yml$)' <<<"$files" || full=false
72 echo "changed since $last: $(wc -l <<<"$files") files"
73 fi
74 fi
75 if [ "$full" = true ]; then
76 echo "BIG=150000000" >> "$GITHUB_ENV"
77 echo "BUILDX=120000000" >> "$GITHUB_ENV"
78 else
79 echo "BIG=5000000" >> "$GITHUB_ENV"
80 echo "BUILDX=4000000" >> "$GITHUB_ENV"
81 fi
82 echo "registry check: full=$full"
83
84 - name: Profile picture upload (WASM resize in the Worker)
85 if: steps.token.outputs.skip != 'true'
86 run: |
87 set -euo pipefail
88 av="$DIFFINERY/api/avatars/$OWNER"
89 # Keep the account's current picture, if it has one, to put it back afterwards.
90 had=$(curl -fsS -o before.webp -w '%{content_type}' "$av?s=256&v=1")
91 restore() {
92 if [ "$had" = image/webp ]; then
93 curl -fsS -X PUT "$DIFFINERY/api/v3/user/avatar" -H "Authorization: Bearer $TOKEN" -H "content-type: image/webp" --data-binary @before.webp | jq -r '"restored the previous picture: \(.avatar_url)"'
94 else
95 curl -fsS -o /dev/null -X DELETE "$DIFFINERY/api/v3/user/avatar" -H "Authorization: Bearer $TOKEN"
96 fi
97 }
98 trap restore EXIT
99 # A 600×400 PNG gradient; the server crops it to a square and makes small WebPs.
100 python3 - <<'EOF'
101 import struct, zlib
102 w, h = 600, 400
103 rows = b"".join(b"\0" + bytes(c for x in range(w) for c in (x * 255 // w, y * 255 // h, 128)) for y in range(h))
104 chunk = lambda t, d: struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d))
105 open("avatar.png", "wb").write(b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b""))
106 EOF
107 url=$(curl -fsS -X PUT "$DIFFINERY/api/v3/user/avatar" -H "Authorization: Bearer $TOKEN" -H "content-type: image/png" --data-binary @avatar.png | jq -r .avatar_url)
108 echo "uploaded: $url"
109 v=${url##*v=}
110 type=$(curl -fsS -o small.webp -w '%{content_type}' "$av?s=64&v=$v")
111 [ "$type" = image/webp ] || { echo "::error::expected image/webp, got $type"; exit 1; }
112 python3 - <<'EOF'
113 import struct, sys
114 b = open("small.webp", "rb").read()
115 ok = b[:4] == b"RIFF" and b[8:12] == b"WEBP"
116 if b[12:16] == b"VP8 ":
117 size = (struct.unpack("<H", b[26:28])[0] & 0x3FFF, struct.unpack("<H", b[28:30])[0] & 0x3FFF)
118 elif b[12:16] == b"VP8X":
119 size = (int.from_bytes(b[24:27], "little") + 1, int.from_bytes(b[27:30], "little") + 1)
120 else:
121 size = None
122 print(f"64 px avatar: {len(b)} bytes, {size}")
123 if not ok or size != (64, 64) or len(b) > 5000:
124 print("::error::the 64 px avatar is not a 64x64 WebP under 5 KB"); sys.exit(1)
125 EOF
126 curl -fsS -X DELETE "$DIFFINERY/api/v3/user/avatar" -H "Authorization: Bearer $TOKEN" >/dev/null
127 # A `v` that is not current bypasses the edge cache, so this sees the removal from any colo.
128 type=$(curl -fsS -o /dev/null -w '%{content_type}' "$av?s=64&v=1")
129 [[ "$type" == image/svg+xml* ]] || { echo "::error::after removal expected the initials SVG, got $type"; exit 1; }
130 echo "removed: initials again ($type)"
131
132 - name: Public docs are served without signing in
133 run: |
134 set -euo pipefail
135 check() { # path, content type, text it must contain
136 body=$(curl -fsS -D /tmp/h "$DIFFINERY$1")
137 grep -qi "content-type: $2" /tmp/h || { echo "::error::$1 is not $2"; exit 1; }
138 grep -qF -- "$3" <<<"$body" || { echo "::error::$1 doesn't contain: $3"; exit 1; }
139 echo "$1 ok ($(wc -c <<<"$body") bytes)"
140 }
141 check /docs "text/html" "Overview"
142 check /docs/actions/workflow-syntax "text/html" "View as Markdown"
143 check /docs/quickstart.md "text/markdown" "# Quickstart"
144 check /llms.txt "text/plain" "/docs/actions/workflow-syntax.md"
145 check /llms-full.txt "text/plain" "# REST API reference"
146 check /docs/api/openapi.json "application/json" '"openapi": "3.1.0"'
147 check /-/cli/diffinery.mjs "text/javascript" "#!/usr/bin/env node"
148 md=$(curl -fsS -H "Accept: text/markdown" "$DIFFINERY/docs/agents/mcp")
149 grep -q "^# MCP" <<<"$md" || { echo "::error::Accept: text/markdown didn't return Markdown"; exit 1; }
150 curl -fsS "$DIFFINERY/-/cli/diffinery.mjs" -o /tmp/diffinery.mjs && node /tmp/diffinery.mjs --version
151
152 - name: Email sending is configured
153 if: steps.token.outputs.skip != 'true'
154 run: |
155 set -euo pipefail
156 s=$(curl -sS -w '\n%{http_code}' "$DIFFINERY/api/v3/diffinery/admin/email" -H "Authorization: Bearer $TOKEN")
157 code=${s##*$'\n'}; s=${s%$'\n'*}
158 # Only a site administrator's token reads the email settings, and the live-test account isn't one.
159 if [ "$code" = 403 ]; then echo "::notice::skipped: the live-test token isn't a site administrator's"; exit 0; fi
160 [ "$code" = 200 ] || { echo "::error::/diffinery/admin/email answered $code"; exit 1; }
161 echo "$s" | jq '{sending, queue, from, last_24h}'
162 [ "$(jq -r .sending <<<"$s")" = true ] || { echo "::error::the Worker has no Email Sending binding"; exit 1; }
163 [ "$(jq -r .queue <<<"$s")" = true ] || { echo "::error::the Worker has no mail queue binding"; exit 1; }
164 failed=$(jq -r .last_24h.failed <<<"$s")
165 [ "$failed" = 0 ] || echo "::warning::$failed emails failed in the last 24 hours; see Settings -> Email in site administration"
166
167 - name: Create a throwaway repository with a webhook
168 if: steps.token.outputs.skip != 'true'
169 run: |
170 set -euo pipefail
171 api() { curl -fsS -X "$1" "$DIFFINERY/api/v3$2" -H "Authorization: Bearer $TOKEN" -H "content-type: application/json" ${3:+--data "$3"}; }
172 api POST /user/repos "{\"name\":\"$REPO\",\"private\":true}" >/dev/null
173 # Webhooks may only reach public hosts other than Diffinery itself; the push's delivery goes to example.com.
174 code=$(curl -sS -o /dev/null -w '%{http_code}' -X POST "$DIFFINERY/api/v3/repos/$OWNER/$REPO/hooks" -H "Authorization: Bearer $TOKEN" -H "content-type: application/json" --data "{\"config\":{\"url\":\"$DIFFINERY/healthz\"},\"events\":[\"push\"]}")
175 [ "$code" = 422 ] || { echo "::error::a webhook to Diffinery itself answered $code, not 422"; exit 1; }
176 api POST "/repos/$OWNER/$REPO/hooks" "{\"config\":{\"url\":\"https://example.com/diffinery-live-test\"},\"events\":[\"push\"]}" >/dev/null
177 echo "created $OWNER/$REPO"
178
179 - name: Wait for jobs to start on the deployed runner image
180 if: steps.token.outputs.skip != 'true'
181 run: |
182 set -euo pipefail
183 # A deploy's container rollout updates instances over a while after it starts, and an
184 # instance not yet updated starts jobs on the previous runner image. Jobs report their
185 # image (`runner.image`), so a probe workflow runs until three jobs in a row land on the
186 # image the deploy set (/meta's runner_image) before the Docker and registry checks.
187 api() { curl -fsS -X "$1" "$DIFFINERY/api/v3$2" -H "Authorization: Bearer $TOKEN" -H "content-type: application/json" ${3:+--data "$3"}; }
188 expected=$(api GET /meta | jq -r '.runner_image // empty')
189 if [ -z "$expected" ]; then
190 echo "::warning::/meta doesn't name the deployed runner image, so jobs aren't checked against it"
191 exit 0
192 fi
193 echo "DEPLOYED_RUNNER_IMAGE=$expected" >> "$GITHUB_ENV"
194 mkdir -p src/.github/workflows && cd src
195 git init -q -b main
196 git config user.name "Live test" && git config user.email "live-test@diffinery.com"
197 cat > .github/workflows/probe.yml <<'EOF'
198 on: workflow_dispatch
199 jobs:
200 probe:
201 runs-on: ubuntu-latest
202 strategy:
203 matrix:
204 n: [1, 2, 3]
205 steps:
206 - run: echo "probe ok"
207 EOF
208 git add -A && git commit -q -m "Runner image probe"
209 git push -q "https://x-token:${TOKEN}@${DIFFINERY#https://}/$OWNER/$REPO.git" main
210 deadline=$(( $(date +%s) + 15 * 60 ))
211 while :; do
212 before=$(api GET "/repos/$OWNER/$REPO/actions/runs?event=workflow_dispatch" | jq '.workflow_runs | length')
213 api POST "/repos/$OWNER/$REPO/actions/workflows/probe.yml/dispatches" '{"ref":"main"}' >/dev/null
214 run=""
215 # Up to 10 minutes: a job turned away from a replaced image starts again after 30 s, 1, 2 and 4 minutes.
216 for i in $(seq 1 120); do
217 runs=$(api GET "/repos/$OWNER/$REPO/actions/runs?event=workflow_dispatch")
218 if [ "$(jq '.workflow_runs | length' <<<"$runs")" -gt "$before" ]; then
219 run=$(jq -c '.workflow_runs[0]' <<<"$runs")
220 [ "$(jq -r .status <<<"$run")" = completed ] && break
221 fi
222 sleep 5
223 done
224 [ -n "$run" ] || { echo "::error::the probe workflow didn't start"; exit 1; }
225 probe=$(api GET "/repos/$OWNER/$REPO/actions/runs/$(jq -r .id <<<"$run")/jobs")
226 images=$(jq -r '.jobs[] | .runner.image // "no image reported"' <<<"$probe")
227 echo "probe jobs ran on: $(sort <<<"$images" | uniq -c | sed 's/^ *//' | paste -sd ','), started again $(jq '[.jobs[].placementTries // 0] | add // 0' <<<"$probe") time(s) in all"
228 [ "$(grep -cxF "$expected" <<<"$images" || true)" = 3 ] && { echo "jobs start on $expected"; exit 0; }
229 if [ "$(date +%s)" -ge "$deadline" ]; then
230 echo "::error::15 minutes after the deploy, jobs still start on a runner image other than the deployed $expected"
231 exit 1
232 fi
233 sleep 20
234 done
235
236 - name: Push workflows and an LFS file
237 id: push
238 if: steps.token.outputs.skip != 'true'
239 run: |
240 set -euo pipefail
241 mkdir -p src/.github/workflows && cd src
242 git init -q -b main
243 git config user.name "Live test" && git config user.email "live-test@diffinery.com"
244 git lfs install --local >/dev/null
245 git lfs track "*.bin" >/dev/null
246 head -c 3145728 /dev/urandom > blob.bin
247 sha256sum blob.bin | cut -d' ' -f1 > ../blob.sha
248 echo "# $REPO" > README.md
249 cat > .github/workflows/ci.yml <<'EOF'
250 on: push
251 jobs:
252 hosted:
253 runs-on: ubuntu-latest
254 strategy:
255 matrix:
256 n: [1, 2]
257 steps:
258 - uses: actions/checkout@v4
259 - run: echo "live ok ${{ '${{' }} matrix.n }} $(cat README.md)"
260 # Passwordless sudo, as on GitHub's runners (`sudo apt-get install ...` is common).
261 - run: sudo -n true && echo "sudo ok $(sudo -n id -u)"
262 docker:
263 runs-on: ubuntu-latest
264 services:
265 cache:
266 image: redis:7-alpine
267 ports: ["6379"]
268 options: --health-cmd "redis-cli ping" --health-interval 1s --health-retries 30
269 steps:
270 - run: |
271 printf 'FROM alpine:3.20\nRUN echo built > /msg\nCMD ["cat", "/msg"]\n' > Dockerfile
272 docker build -q -t live-image .
273 echo "docker ok $(docker run --rm live-image)"
274 exec 3<>/dev/tcp/127.0.0.1/${{ '${{' }} job.services.cache.ports['6379'] }}
275 printf 'PING\r\n' >&3
276 read -r line <&3
277 echo "service ok ${line%$'\r'}"
278 # Container registry: a layer pushed with the job's GITHUB_TOKEN (over Cloudflare's
279 # 100 MB request limit on full runs), plus the docker/*-action route most ghcr.io
280 # workflows use. __BIG__ and __BUILDX__ are the layer sizes.
281 publish:
282 runs-on: ubuntu-latest
283 permissions:
284 packages: write
285 steps:
286 - run: |
287 image="diffinery.com/${GITHUB_REPOSITORY,,}"
288 echo "${{ '${{' }} secrets.GITHUB_TOKEN }}" | docker login diffinery.com -u "${{ '${{' }} github.actor }}" --password-stdin
289 head -c __BIG__ /dev/urandom > big.bin
290 sha256sum big.bin | cut -d' ' -f1 > big.sha
291 printf 'FROM scratch\nCOPY big.bin big.sha /\n' > Dockerfile
292 docker build -q -t "$image:live" .
293 docker push "$image:live"
294 echo "pushed $(cat big.sha)"
295 buildx:
296 runs-on: ubuntu-latest
297 permissions:
298 packages: write
299 steps:
300 - run: |
301 echo "IMAGE=diffinery.com/${GITHUB_REPOSITORY,,}" >> "$GITHUB_ENV"
302 head -c __BUILDX__ /dev/urandom > big.bin
303 printf 'FROM scratch\nCOPY big.bin /\n' > Dockerfile
304 - uses: docker/setup-buildx-action@v3
305 - uses: docker/login-action@v3
306 with:
307 registry: diffinery.com
308 username: ${{ '${{' }} github.actor }}
309 password: ${{ '${{' }} secrets.GITHUB_TOKEN }}
310 - uses: docker/build-push-action@v6
311 with:
312 context: .
313 push: true
314 tags: ${{ '${{' }} env.IMAGE }}:buildx
315 pull:
316 needs: [publish, buildx]
317 runs-on: ubuntu-latest
318 permissions:
319 packages: read
320 steps:
321 - run: |
322 image="diffinery.com/${GITHUB_REPOSITORY,,}"
323 echo "${{ '${{' }} secrets.GITHUB_TOKEN }}" | docker login diffinery.com -u "${{ '${{' }} github.actor }}" --password-stdin
324 docker pull -q "$image:live"
325 id=$(docker create "$image:live" true)
326 docker cp "$id:/big.bin" big.bin && docker cp "$id:/big.sha" big.sha
327 [ "$(sha256sum big.bin | cut -d' ' -f1)" = "$(cat big.sha)" ] && echo "registry ok $(stat -c %s big.bin) bytes"
328 docker pull -q "$image:buildx"
329 id=$(docker create "$image:buildx" true)
330 docker cp "$id:/big.bin" buildx.bin
331 echo "buildx ok $(stat -c %s buildx.bin) bytes"
332 EOF
333 cat > .github/workflows/tick.yml <<'EOF'
334 on:
335 schedule:
336 - cron: "*/5 * * * *"
337 jobs:
338 tick:
339 runs-on: ubuntu-latest
340 steps:
341 - run: echo "scheduled ok"
342 EOF
343 sed -i "s/__BIG__/$BIG/g; s/__BUILDX__/$BUILDX/g" .github/workflows/ci.yml
344 git add -A && git commit -q -m "Live test"
345 git push -q "https://x-token:${TOKEN}@${DIFFINERY#https://}/$OWNER/$REPO.git" main
346 git lfs ls-files
347
348 - name: Web UI features (highlighting, settings pages, view transitions, base permission, invitations)
349 if: steps.token.outputs.skip != 'true'
350 run: |
351 set -euo pipefail
352 page() { curl -fsS "$DIFFINERY$1" -H "Authorization: Bearer $TOKEN"; }
353 has() { grep -qF -- "$2" <<<"$1" || { echo "::error::$3"; exit 1; }; }
354 html=$(page "/$OWNER/$REPO/blob/main/.github/workflows/ci.yml")
355 has "$html" '<td class="sh">' "the workflow file is not syntax highlighted"
356 has "$html" "--shiki-dark" "highlighted code has no dark theme colours"
357 has "$html" "@view-transition{navigation:auto}" "pages don't opt in to view transitions"
358 has "$html" "prefers-reduced-motion:no-preference" "view transitions ignore reduced motion"
359 has "$(page /settings/appearance)" 'name="appearance"' "Settings -> Appearance has no theme choice"
360 has "$(page /notifications)" 'href="/settings/notifications"' "the notifications page doesn't link to notification settings"
361 code=$(curl -sS -o /tmp/out -w '%{http_code}' -X POST "$DIFFINERY/api/v3/user/repos" -H "Authorization: Bearer $TOKEN" -H "content-type: application/json" --data "{\"name\":\"$REPO-internal\",\"visibility\":\"internal\"}")
362 [ "$code" = 422 ] || { echo "::error::visibility internal got $code, expected 422"; curl -sS -o /dev/null -X DELETE "$DIFFINERY/api/v3/repos/$OWNER/$REPO-internal" -H "Authorization: Bearer $TOKEN"; exit 1; }
363 org=$(page /api/v3/user/orgs | jq -r '.[0].login // empty')
364 if [ -n "$org" ]; then
365 perm=$(page "/api/v3/orgs/$org" | jq -r '.default_repository_permission // empty')
366 case "$perm" in none|read|write|admin) echo "$org's base permission: $perm" ;; *) echo "::error::GET /orgs/$org has no default_repository_permission"; exit 1 ;; esac
367 # A malformed rename is refused before anything is written (422 for owners, 403 for everyone else).
368 code=$(curl -sS -o /tmp/out -w '%{http_code}' -X PATCH "$DIFFINERY/api/v3/orgs/$org" -H "Authorization: Bearer $TOKEN" -H "content-type: application/json" --data '{"name":123}')
369 case "$code" in 422|403) ;; *) echo "::error::PATCH /orgs/$org with a numeric name got $code"; cat /tmp/out; exit 1 ;; esac
370 fi
371 page "/api/v3/repos/$OWNER/$REPO/invitations" | jq -e 'type == "array"' >/dev/null || { echo "::error::GET /repos/$OWNER/$REPO/invitations doesn't list pending invitations"; exit 1; }
372 tools=$(curl -fsS -X POST "$DIFFINERY/mcp" -H "Authorization: Bearer $TOKEN" -H "content-type: application/json" -H "accept: application/json, text/event-stream" --data '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | jq -r '.result.tools[].name')
373 for t in get_organization list_invitations revoke_invitation; do grep -qx "$t" <<<"$tools" || { echo "::error::the MCP server has no $t tool"; exit 1; }; done
374 echo "highlighting, Appearance, notification settings link, view transitions, visibility, organization and invitation checks passed"
375
376 - name: Diffy placeholders, Actions settings, milestones and variables
377 if: steps.token.outputs.skip != 'true'
378 run: |
379 set -euo pipefail
380 page() { curl -fsS "$DIFFINERY$1" -H "Authorization: Bearer $TOKEN"; }
381 api() { curl -fsS -X "$1" "$DIFFINERY/api/v3$2" -H "Authorization: Bearer $TOKEN" -H "content-type: application/json" ${3:+--data "$3"}; }
382 code() { curl -sS -o /tmp/out -w '%{http_code}' -X "$1" "$DIFFINERY/api/v3$2" -H "Authorization: Bearer $TOKEN" -H "content-type: application/json" ${3:+--data "$3"}; }
383 fail() { echo "::error::$1"; cat /tmp/out 2>/dev/null || true; exit 1; }
384 has() { grep -qF -- "$2" <<<"$1" || fail "$3"; }
385 R="/repos/$OWNER/$REPO"
386 has "$(page /new/import)" 'diffy/hello-world' "the importer's placeholder isn't Diffy"
387 has "$(page "/$OWNER/$REPO/settings/actions")" 'Allow GitHub Actions to create and approve pull requests' "repository settings have no Actions page"
388 # Milestones: created closed, checked before an issue edit is saved, shown in the response, and filterable.
389 [ "$(api POST "$R/milestones" '{"title":"Shipped","state":"closed"}' | jq -r .state)" = closed ] || fail "POST milestones ignored state"
390 ms=$(api POST "$R/milestones" '{"title":"Live v1"}' | jq -r .number)
391 n=$(api POST "$R/issues" '{"title":"Planned"}' | jq -r .number)
392 [ "$(code PATCH "$R/issues/$n" '{"title":"Renamed","milestone":999999}')" = 422 ] || fail "an unknown milestone wasn't refused with 422"
393 [ "$(api GET "$R/issues/$n" | jq -r .title)" = Planned ] || fail "a refused milestone edit saved the title"
394 [ "$(api PATCH "$R/issues/$n" "{\"milestone\":$ms}" | jq -r .milestone.number)" = "$ms" ] || fail "PATCH issue doesn't return the new milestone"
395 [ "$(api GET "$R/issues?milestone=$ms&state=all" | jq -r '[.[].number] | join(",")')" = "$n" ] || fail "issues aren't filtered by milestone"
396 loc=$(curl -sS -o /dev/null -w '%{redirect_url}' "$DIFFINERY/$OWNER/$REPO/milestone/$ms" -H "Authorization: Bearer $TOKEN")
397 has "$loc" "/issues?milestone=$ms" "the milestone link doesn't open its issue list"
398 # Repository variable deletes ignore letter case.
399 [ "$(code PUT "$R/actions/variables/LIVE_CASE" '{"value":"x"}')" = 204 ] || fail "couldn't set a repository variable"
400 [ "$(code DELETE "$R/actions/variables/live_case")" = 204 ] || fail "couldn't delete a repository variable"
401 [ "$(code GET "$R/actions/variables/LIVE_CASE")" = 404 ] || fail "deleting a variable in lower case left it in place"
402 org=$(page /api/v3/user/orgs | jq -r '.[0].login // empty')
403 if [ -n "$org" ]; then
404 # Deleting an organization variable or secret that doesn't exist is a 404 (403 for someone who isn't an admin).
405 for path in variables secrets; do
406 c=$(code DELETE "/orgs/$org/actions/$path/LIVE_NEVER_SET_$GITHUB_RUN_ID")
407 case "$c" in 404|403) ;; *) fail "DELETE of a missing organization $path entry got $c" ;; esac
408 done
409 fi
410 echo "Diffy placeholders, Actions settings page, milestone and variable checks passed"
411
412 - name: Hosted Actions jobs (and Docker) run in Cloudflare Containers
413 if: steps.token.outputs.skip != 'true'
414 run: |
415 set -euo pipefail
416 api() { curl -fsS "$DIFFINERY/api/v3$1" -H "Authorization: Bearer $TOKEN"; }
417 for i in $(seq 1 90); do
418 run=$(api "/repos/$OWNER/$REPO/actions/runs?event=push" | jq -c '.workflow_runs[0] // empty')
419 [ -n "$run" ] && [ "$(jq -r .status <<<"$run")" = completed ] && break
420 sleep 10
421 done
422 echo "$run" | jq '{id, status, conclusion}'
423 id=$(jq -r .id <<<"$run")
424 jobs=$(api "/repos/$OWNER/$REPO/actions/runs/$id/jobs")
425 # placementTries: times a job went back in line (no machine, or a runner on a replaced image turned away).
426 # restarts: times it started over because the platform replaced its runner before its steps ran.
427 jq -r '.jobs[] | " \(.name): \(.conclusion)\(if .failure then " - " + (.failure.message // "") else "" end)\(try " (\((.completed_at | fromdateiso8601) - (.started_at | fromdateiso8601))s)" catch "")\(if (.placementTries // 0) > 0 then ", started again \(.placementTries) time(s)" else "" end)\(if (.restarts // 0) > 0 then ", restarted \(.restarts) time(s) after its runner was replaced" else "" end)"' <<<"$jobs"
428 if [ "$(jq -r .conclusion <<<"$run")" != success ]; then
429 for job in $(jq -r '.jobs[] | select(.conclusion == "failure" or .conclusion == "timed_out") | .id' <<<"$jobs"); do
430 echo "::group::Last log lines of job $job"
431 api "/repos/$OWNER/$REPO/actions/jobs/$job/logs" | tail -n 80 || true
432 echo "::endgroup::"
433 done
434 echo "::error::the push run did not succeed"
435 exit 1
436 fi
437 if [ -n "${DEPLOYED_RUNNER_IMAGE:-}" ]; then
438 # Every job ran the deployed runner, so these checks test what was just deployed.
439 stale=$(jq -r --arg want "$DEPLOYED_RUNNER_IMAGE" '.jobs[] | select(.runner.image != $want) | "\(.name) on \(.runner.image // "no image reported")"' <<<"$jobs")
440 [ -z "$stale" ] || { echo "::error::jobs ran on a runner image other than the deployed $DEPLOYED_RUNNER_IMAGE: $(paste -sd ';' <<<"$stale")"; exit 1; }
441 echo "every job ran on $DEPLOYED_RUNNER_IMAGE"
442 fi
443 for job in $(jq -r '.jobs[] | select(.name | startswith("hosted")) | .id' <<<"$jobs"); do
444 log=$(api "/repos/$OWNER/$REPO/actions/jobs/$job/logs")
445 grep -F "live ok" <<<"$log" | grep -F "# $REPO" || { echo "::error::job $job did not print its line (checkout or run step failed)"; exit 1; }
446 grep -F "sudo ok 0" <<<"$log" || { echo "::error::job $job could not run sudo without a password"; exit 1; }
447 done
448 job=$(jq -r '.jobs[] | select(.name == "docker") | .id' <<<"$jobs")
449 log=$(api "/repos/$OWNER/$REPO/actions/jobs/$job/logs")
450 grep -F "docker ok built" <<<"$log" || { echo "::error::docker build or run failed on a hosted runner"; exit 1; }
451 grep -F "service ok +PONG" <<<"$log" || { echo "::error::the redis service container was not reachable"; exit 1; }
452 job=$(jq -r '.jobs[] | select(.name == "pull") | .id' <<<"$jobs")
453 log=$(api "/repos/$OWNER/$REPO/actions/jobs/$job/logs")
454 grep -F "registry ok $BIG bytes" <<<"$log" || { echo "::error::the image pushed with a $BIG-byte layer did not come back intact from the registry"; exit 1; }
455 grep -F "buildx ok $BUILDX bytes" <<<"$log" || { echo "::error::the image pushed by docker/build-push-action did not come back from the registry"; exit 1; }
456 api "/users/$OWNER/packages/container/${REPO,,}/versions" | jq -c '.[] | {tags: .metadata.container.tags, size, platforms}'
457
458 - name: An organization's packages page keeps its tabs
459 if: steps.token.outputs.skip != 'true'
460 run: |
461 set -euo pipefail
462 org=$(curl -fsS "$DIFFINERY/api/v3/user/orgs" -H "Authorization: Bearer $TOKEN" | jq -r '.[0].login // empty')
463 [ -n "$org" ] || { echo "$OWNER is in no organization; skipped"; exit 0; }
464 html=$(curl -fsS "$DIFFINERY/$org/-/packages" -H "Authorization: Bearer $TOKEN")
465 grep -qF "<a href=\"/$org/-/packages\" class=\"on\">" <<<"$html" || { echo "::error::$org's packages page lost the organization's tab bar"; exit 1; }
466 grep -qF "href=\"/$org?tab=repositories\"" <<<"$html" || { echo "::error::$org's packages page has no Repositories tab"; exit 1; }
467 echo "$org's packages page shows the organization's tabs with Packages selected"
468
469 - name: Git LFS round trip
470 if: steps.token.outputs.skip != 'true'
471 run: |
472 set -euo pipefail
473 git clone -q "https://x-token:${TOKEN}@${DIFFINERY#https://}/$OWNER/$REPO.git" clone
474 [ "$(sha256sum clone/blob.bin | cut -d' ' -f1)" = "$(cat blob.sha)" ] || { echo "::error::the LFS file came back different"; exit 1; }
475 echo "LFS file matches ($(stat -c %s clone/blob.bin) bytes)"
476
477 - name: Webhook delivered
478 if: steps.token.outputs.skip != 'true'
479 run: |
480 set -euo pipefail
481 for i in $(seq 1 30); do
482 hook=$(curl -fsS "$DIFFINERY/api/v3/repos/$OWNER/$REPO/hooks" -H "Authorization: Bearer $TOKEN" | jq -c '.[0]')
483 # GitHub's hook shape: the target is config.url, the last delivery's status last_response.code.
484 [ "$(jq -r '.last_response.code // empty' <<<"$hook")" != "" ] && break
485 sleep 5
486 done
487 echo "$hook" | jq '{target: .config.url, last_response, updated_at}'
488 [ "$(jq -r '.last_response.code // empty' <<<"$hook")" != "" ] || { echo "::error::the push webhook was never delivered"; exit 1; }
489
490 - name: Tokens can't mint tokens (API or web forms)
491 if: steps.token.outputs.skip != 'true'
492 run: |
493 set -euo pipefail
494 # Revokes anything a failed check minted, then fails.
495 minted() { echo "::error::$1"; curl -fsS "$DIFFINERY/api/v3/diffinery/tokens" -H "Authorization: Bearer $TOKEN" | jq -r '.[] | select(.name == "live-test escalation") | .id' | while read -r id; do curl -sS -o /dev/null -X DELETE "$DIFFINERY/api/v3/diffinery/tokens/$id" -H "Authorization: Bearer $TOKEN"; done; exit 1; }
496 code=$(curl -sS -o /tmp/out -w '%{http_code}' -X POST "$DIFFINERY/api/v3/diffinery/tokens" -H "Authorization: Bearer $TOKEN" -H "content-type: application/json" --data '{"name":"live-test escalation","scopes":["read"],"expires_in_days":1}')
497 [ "$code" = 403 ] || minted "an admin token minted a token through the API ($code)"
498 grep -q "browser session" /tmp/out || minted "unexpected refusal: $(cat /tmp/out)"
499 code=$(curl -sS -o /dev/null -w '%{http_code}' -X POST "$DIFFINERY/api/v3/diffinery/agents" -H "Authorization: Bearer $TOKEN" -H "content-type: application/json" --data '{"login":"live-test-escalation"}')
500 [ "$code" = 403 ] || { echo "::error::an admin token created an agent ($code); disable live-test-escalation by hand"; exit 1; }
501 # A web form with a token and a forged double-submit CSRF pair.
502 code=$(curl -sS -o /dev/null -w '%{http_code}' -X POST "$DIFFINERY/settings/tokens" -H "Authorization: Bearer $TOKEN" -H "cookie: dfy_csrf=forged" --data "_csrf=forged&name=live-test%20escalation&scope=read&days=1")
503 [ "$code" = 403 ] || minted "a token submitted the web token form ($code)"
504 echo "tokens can't mint tokens or agents, through the API or the web forms"
505
506 - name: Agent sandbox
507 if: steps.token.outputs.skip != 'true'
508 run: |
509 set -euo pipefail
510 base="$DIFFINERY/api/v3/repos/$OWNER/$REPO/diffinery/sandboxes"
511 id=$(curl -fsS --retry 1 --retry-delay 15 -X POST "$base" -H "Authorization: Bearer $TOKEN" -H "content-type: application/json" --data '{}' | jq -r .id)
512 echo "sandbox $id"
513 for i in $(seq 1 40); do
514 out=$(curl -sS -X POST "$base/$id/exec" -H "Authorization: Bearer $TOKEN" -H "content-type: application/json" --data '{"cmd":"cat README.md && git lfs ls-files | wc -l"}' || true)
515 jq -e '.exitCode == 0' >/dev/null 2>&1 <<<"$out" && break
516 sleep 6
517 done
518 echo "$out" | jq '{exitCode, stdout}'
519 curl -sS -X POST "$base/$id/close" -H "Authorization: Bearer $TOKEN" >/dev/null || true
520 jq -e --arg r "# $REPO" '.exitCode == 0 and (.stdout | contains($r))' >/dev/null <<<"$out" || { echo "::error::the sandbox did not run the command in the repository"; exit 1; }
521
522 # Owned by the agentic thread: proves the agent jails (containers/runner/src/jail.ts) on Cloudflare: a terminal
523 # task's, and a headless run's (phase 5d), which reaches Diffinery only at its model endpoints.
524 - name: Agent jails (bubblewrap, no network but the allowlist proxy and the model proxy)
525 if: steps.token.outputs.skip != 'true'
526 run: |
527 set -euo pipefail
528 base="$DIFFINERY/api/v3/repos/$OWNER/$REPO/diffinery/sandboxes"
529 id=""
530 close() { if [ -n "$id" ]; then curl -sS --max-time 60 -X POST "$base/$id/close" -H "Authorization: Bearer $TOKEN" >/dev/null || true; fi; id=""; }
531 trap close EXIT
532 run() { curl -sS --max-time "${2:-240}" -X POST "$base/$id/exec" -H "Authorization: Bearer $TOKEN" -H "content-type: application/json" --data "$(jq -n --arg c "$1" '{cmd: $c, timeoutMs: 180000}')"; }
533 # One create (no retry: a retried POST could open a second sandbox nothing closes), then wait for it to answer.
534 open() {
535 close
536 id=$(curl -sS --max-time 240 -X POST "$base" -H "Authorization: Bearer $TOKEN" -H "content-type: application/json" --data '{}' | jq -r '.id // empty' || true)
537 [ -n "$id" ] || { echo "::error::could not open a sandbox for the jail check"; exit 1; }
538 for i in $(seq 1 30); do
539 jq -e '.exitCode == 0' >/dev/null 2>&1 <<<"$(run true 20 || true)" && return 0
540 sleep 6
541 done
542 echo "::error::the sandbox never became ready"
543 exit 1
544 }
545 # Sandboxes roll out on their own: one opened right after a deploy can still be on the previous image.
546 jail=no
547 for attempt in 1 2 3 4 5; do
548 open
549 # A runner with headless jails asks for the run's model token; an older one ignores --egress.
550 has=$(run 'mkdir -p ../probe ../probe.out; [ -n "${DIFFINERY_JAIL:-}" ] && [ -x "$DIFFINERY_JAIL" ] && "$DIFFINERY_JAIL" agent --dir ../probe --out ../probe.out --egress model -- true 2>&1 | grep -q DIFFINERY_MODEL_TOKEN && echo yes || echo no' 20 | jq -r '.stdout // empty' || true)
551 if [ "$has" = yes ]; then jail=yes; break; fi
552 echo "sandbox $id is on a runner image without the jail; trying another in a minute"
553 close
554 sleep 60
555 done
556 [ "$jail" = yes ] || { echo "::error::the sandbox started on a runner image without the jail (rollout not finished?)"; exit 1; }
557 inside='echo "direct=$(node -e "require(\"net\").connect(443, \"1.1.1.1\").on(\"connect\", () => (console.log(\"open\"), process.exit())).on(\"error\", (e) => (console.log(e.code), process.exit()))")"
558 echo "other=$(curl -sS -m 20 -o /dev/null -w "%{http_connect}" https://example.com 2>/dev/null || true)"
559 echo "sni=$(curl -sS -m 20 -o /dev/null -w "%{http_code}" --connect-to example.com:443:registry.npmjs.org:443 https://example.com 2>/dev/null; true)"
560 echo "checkout=$(ls -A /workspace/repo | paste -sd,)"
561 echo "credential=$(cat /workspace/repo/.git/config 2>/dev/null || echo hidden)"
562 v=$(npm view left-pad version --no-update-notifier --loglevel=error 2>/tmp/npm.err)
563 echo "npm=$(printf "%s\n" "$v" | grep -E "^[0-9]+\.[0-9]+\.[0-9]+$" | tail -1)"
564 echo "npmerr=$(tail -3 /tmp/npm.err | paste -sd" " -)"'
565 out=$(run "mkdir -p ../jail-check ../jail-check.out && \"\$DIFFINERY_JAIL\" agent --dir ../jail-check --out ../jail-check.out -- sh -c $(printf '%q' "$inside")")
566 echo "$out" | jq -r '"exit \(.exitCode)", .stdout, .stderr'
567 o=$(jq -r .stdout <<<"$out")
568 fail=0
569 jq -e '.exitCode == 0' >/dev/null <<<"$out" || { echo "::error::the jail didn't run (exit $(jq -r .exitCode <<<"$out"))"; fail=1; }
570 grep -qE '^direct=(ENETUNREACH|EHOSTUNREACH|ECONNREFUSED|EACCES)$' <<<"$o" || { echo "::error::the jail has a route out of its own"; fail=1; }
571 grep -qx 'other=403' <<<"$o" || { echo "::error::the proxy didn't refuse example.com"; fail=1; }
572 grep -qx 'checkout=.git' <<<"$o" || { echo "::error::the jail sees the person's checkout"; fail=1; }
573 grep -qx 'credential=hidden' <<<"$o" || { echo "::error::the jail sees the checkout's git config"; fail=1; }
574 grep -qE '^npm=[0-9]+\.[0-9]+' <<<"$o" || { echo "::error::npm view left-pad didn't work through the proxy"; fail=1; }
575 grep -qx 'sni=000' <<<"$o" || { echo "::error::the proxy let TLS for example.com through a tunnel to registry.npmjs.org"; fail=1; }
576
577 # A headless run's jail: registries only, and Diffinery only at /-/model/ through the model proxy outside,
578 # which adds the run's token (a stand-in here, so Diffinery answers 401) and drops whatever the agent sends.
579 host=${DIFFINERY#https://}
580 headless='echo "model=$(curl -s -o /dev/null -w "%{http_code}" -X POST "$ANTHROPIC_BASE_URL/v1/messages" -H "x-api-key: $ANTHROPIC_API_KEY" -H "content-type: application/json" -d "{}")"
581 echo "api=$(curl -s -o /dev/null -w "%{http_code}" --path-as-is "$ANTHROPIC_BASE_URL/../../api/v3/user")"
582 echo "connect=$(curl -sS -m 20 -o /dev/null -w "%{http_connect}" https://'"$host"'/api/v3/user 2>/dev/null || true)"
583 echo "vendor=$(curl -sS -m 20 -o /dev/null -w "%{http_connect}" https://api.anthropic.com 2>/dev/null || true)"
584 echo "token=$(env | grep -c dmt_ || true)"
585 echo "credential=$(cat /workspace/repo/.git/config 2>/dev/null || echo hidden)"
586 v=$(npm view left-pad version --no-update-notifier --loglevel=error 2>/dev/null)
587 echo "npm=$(printf "%s\n" "$v" | grep -E "^[0-9]+\.[0-9]+\.[0-9]+$" | tail -1)"'
588 out=$(run "mkdir -p ../headless-check ../headless-check.out && DIFFINERY_MODEL_TOKEN=dmt_livetest_standin DIFFINERY_MODEL_ORIGIN=$(printf '%q' "$DIFFINERY") ANTHROPIC_BASE_URL=http://127.0.0.1:3129/-/model/anthropic ANTHROPIC_API_KEY=diffinery-jail \"\$DIFFINERY_JAIL\" agent --dir ../headless-check --out ../headless-check.out --egress model -- sh -c $(printf '%q' "$headless")")
589 echo "$out" | jq -r '"exit \(.exitCode)", .stdout, .stderr'
590 o=$(jq -r .stdout <<<"$out")
591 jq -e '.exitCode == 0' >/dev/null <<<"$out" || { echo "::error::the headless jail didn't run (exit $(jq -r .exitCode <<<"$out"))"; fail=1; }
592 grep -qx 'model=401' <<<"$o" || { echo "::error::the model proxy didn't reach Diffinery's model endpoint with the run's token"; fail=1; }
593 grep -qx 'api=403' <<<"$o" || { echo "::error::the model proxy forwarded a path outside /-/model/"; fail=1; }
594 grep -qx 'connect=403' <<<"$o" || { echo "::error::the headless jail could open a tunnel to Diffinery"; fail=1; }
595 grep -qx 'vendor=403' <<<"$o" || { echo "::error::the headless jail could reach a CLI vendor"; fail=1; }
596 grep -qx 'token=0' <<<"$o" || { echo "::error::the run's token is inside the headless jail"; fail=1; }
597 grep -qx 'credential=hidden' <<<"$o" || { echo "::error::the headless jail sees the checkout's git config"; fail=1; }
598 grep -qE '^npm=[0-9]+\.[0-9]+' <<<"$o" || { echo "::error::npm view left-pad didn't work in the headless jail"; fail=1; }
599 exit $fail
600
601 - name: Pull requests and the merge queue
602 if: steps.token.outputs.skip != 'true'
603 run: |
604 set -euo pipefail
605 Q="$REPO-pr"
606 api() { curl -fsS -X "$1" "$DIFFINERY/api/v3$2" -H "Authorization: Bearer $TOKEN" -H "content-type: application/json" ${3:+--data "$3"}; }
607 api POST /user/repos "{\"name\":\"$Q\",\"private\":true}" >/dev/null
608 echo "PR_REPO=$Q" >> "$GITHUB_ENV"
609 api PUT "/repos/$OWNER/$Q/actions/secrets/TOPSECRET" '{"value":"s3cret"}' >/dev/null
610 remote="https://x-token:${TOKEN}@${DIFFINERY#https://}/$OWNER/$Q.git"
611 mkdir -p pr/.github/workflows && cd pr
612 git init -q -b main
613 git config user.name "Live test" && git config user.email "live-test@diffinery.com"
614 printf 'a\nb\nc\n' > app.txt
615 cat > .github/workflows/ci.yml <<'EOF'
616 name: CI
617 on:
618 pull_request:
619 merge_group:
620 jobs:
621 test:
622 runs-on: ubuntu-latest
623 steps:
624 - uses: actions/checkout@v4
625 - run: echo "pr ok event=${{ '${{' }} github.event_name }} ref=${{ '${{' }} github.ref }} sha=${{ '${{' }} github.sha }} head=$(git rev-parse HEAD) app=$(tr '\n' ' ' < app.txt)"
626 EOF
627 cat > .github/workflows/target.yml <<'EOF'
628 name: Target
629 on: pull_request_target
630 jobs:
631 t:
632 runs-on: ubuntu-latest
633 steps:
634 - run: echo "target ok secret=${{ '${{' }} secrets.TOPSECRET == 's3cret' }} ref=${{ '${{' }} github.ref }}"
635 EOF
636 git add -A && git commit -q -m "PR test" && git push -q "$remote" main
637 # The pull request changes app.txt and tries to rewrite the pull_request_target workflow.
638 git checkout -q -b change
639 printf 'A\nb\nc\n' > app.txt
640 sed -i 's/target ok/PWNED/' .github/workflows/target.yml
641 git commit -q -am "Change" && git push -q "$remote" change
642 head=$(git rev-parse HEAD)
643 # Main moves on, so the test merge commit holds both sides.
644 git checkout -q main
645 printf 'a\nb\nC\n' > app.txt
646 git commit -q -am "Main moves" && git push -q "$remote" main
647 n=$(api POST "/repos/$OWNER/$Q/pulls" '{"title":"Change","head":"change","base":"main"}' | jq -r .number)
648 echo "opened pull request #$n (head $head)"
649
650 wait_run() { # event -> the completed run JSON
651 for i in $(seq 1 60); do
652 run=$(api GET "/repos/$OWNER/$Q/actions/runs?event=$1" | jq -c '.workflow_runs[0] // empty')
653 [ -n "$run" ] && [ "$(jq -r .status <<<"$run")" = completed ] && { echo "$run"; return; }
654 sleep 10
655 done
656 echo "::error::no completed $1 run" >&2; exit 1
657 }
658 log_of() { for job in $(api GET "/repos/$OWNER/$Q/actions/runs/$1/jobs" | jq -r '.jobs[].id'); do api GET "/repos/$OWNER/$Q/actions/jobs/$job/logs"; done; }
659 pr=$(wait_run pull_request)
660 echo "$pr" | jq '{event, ref, sha, head_sha, conclusion}'
661 [ "$(jq -r .conclusion <<<"$pr")" = success ] || { echo "::error::the pull_request run failed"; exit 1; }
662 [ "$(jq -r .ref <<<"$pr")" = "refs/pull/$n/merge" ] && [ "$(jq -r .head_sha <<<"$pr")" = "$head" ] && [ "$(jq -r .sha <<<"$pr")" != "$head" ] || { echo "::error::the pull_request run did not use the test merge commit"; exit 1; }
663 log_of "$(jq -r .id <<<"$pr")" | grep -F "pr ok event=pull_request ref=refs/pull/$n/merge" | grep -F "app=A b C" || { echo "::error::the pull_request job did not check out the merged code"; exit 1; }
664 target=$(wait_run pull_request_target)
665 echo "$target" | jq '{event, ref, sha, head_sha, conclusion}'
666 tlog=$(log_of "$(jq -r .id <<<"$target")")
667 grep -F "target ok secret=true ref=refs/heads/main" <<<"$tlog" || { echo "::error::pull_request_target did not run the base workflow with secrets"; exit 1; }
668 ! grep -q PWNED <<<"$tlog" || { echo "::error::pull_request_target ran the pull request's workflow"; exit 1; }
669
670 api PUT "/repos/$OWNER/$Q/branches/main/protection" '{"requirePullRequest":true,"requiredChecks":["CI / test"],"mergeQueue":{"method":"squash","checkTimeoutMinutes":20}}' >/dev/null
671 code=$(curl -sS -o /dev/null -w '%{http_code}' -X PUT "$DIFFINERY/api/v3/repos/$OWNER/$Q/pulls/$n/merge" -H "Authorization: Bearer $TOKEN" -H "content-type: application/json" --data '{}')
672 [ "$code" = 405 ] || { echo "::error::a direct merge into a merge queue branch returned $code"; exit 1; }
673 api PUT "/repos/$OWNER/$Q/pulls/$n/merge-queue" '{"delete_branch":true}' | jq '{state, position: .entry.position, merge_group: .entry.merge_group}'
674 for i in $(seq 1 60); do
675 merged=$(api GET "/repos/$OWNER/$Q/pulls/$n" | jq -r .merged)
676 [ "$merged" = true ] && break
677 sleep 10
678 done
679 [ "$merged" = true ] || { echo "::error::the merge queue did not merge #$n"; api GET "/repos/$OWNER/$Q/merge-queue/main" | jq .; exit 1; }
680 group=$(wait_run merge_group)
681 echo "$group" | jq '{event, ref, sha, conclusion}'
682 [[ "$(jq -r .ref <<<"$group")" == refs/heads/gh-readonly-queue/main/pr-$n-* ]] || { echo "::error::the merge_group run is not on a queue branch"; exit 1; }
683 sha=$(api GET "/repos/$OWNER/$Q/branches/main" | jq -r .commit.sha)
684 [ "$sha" = "$(jq -r .sha <<<"$group")" ] || { echo "::error::main ($sha) is not the tested merge group"; exit 1; }
685 git fetch -q "$remote" main && [ "$(git show FETCH_HEAD:app.txt | tr '\n' ' ')" = "A b C " ] || { echo "::error::main does not hold the merged change"; exit 1; }
686 echo "pull request #$n merged through the queue as $sha"
687
688 - name: Import a public GitHub repository
689 if: steps.token.outputs.skip != 'true'
690 env:
691 # A small public repository with issues and pull requests; a repository variable can change it.
692 SOURCE: ${{ vars.LIVE_IMPORT_SOURCE || 'octocat/git-consortium' }}
693 # A read-only GitHub token (copied here by the sync), so GitHub's rate limit doesn't skip the check. Never printed.
694 GITHUB_TOKEN_FOR_IMPORT: ${{ secrets.IMPORT_GITHUB_TOKEN }}
695 run: |
696 set -euo pipefail
697 api() { curl -fsS -X "$1" "$DIFFINERY/api/v3$2" -H "Authorization: Bearer $TOKEN" -H "content-type: application/json" ${3:+--data "$3"}; }
698 name="$REPO-import"
699 body=$(jq -nc --arg s "$SOURCE" --arg o "$OWNER" --arg n "$name" --arg t "${GITHUB_TOKEN_FOR_IMPORT:-}" \
700 '{source: $s, owner: $o, name: $n, visibility: "private"} + (if $t == "" then {} else {github_token: $t} end)')
701 if [ -n "${GITHUB_TOKEN_FOR_IMPORT:-}" ]; then echo "importing with IMPORT_GITHUB_TOKEN"; else echo "::warning::IMPORT_GITHUB_TOKEN is not set, so the import runs token-free"; fi
702 # Token-free, GitHub allows 60 requests an hour per address: a rate limit skips this check with a warning.
703 # Starting the import reads the repository from GitHub; a GitHub outage (502 "could not reach GitHub")
704 # is retried, and skips this check with a warning if it outlasts the retries. While other imports hold
705 # every slot (an import campaign), it waits up to 15 minutes for one, so a busy account doesn't hide this check.
706 tries=0 waits=0
707 while :; do
708 code=$(curl -sS -o import.json -w '%{http_code}' -X POST "$DIFFINERY/api/v3/diffinery/imports" -H "Authorization: Bearer $TOKEN" -H "content-type: application/json" \
709 --data-binary @- <<<"$body" || true)
710 unreachable=$(jq -r '.message // "" | startswith("could not reach GitHub")' import.json 2>/dev/null || echo false)
711 busy=$(jq -r '.message // "" | startswith("too many repository imports are already running")' import.json 2>/dev/null || echo false)
712 if [ "$code" = 429 ] && [ "$busy" = true ]; then
713 waits=$((waits + 1))
714 [ "$waits" -le 30 ] || break
715 [ "$waits" -gt 1 ] || echo "every import slot is taken ($(jq -r .message import.json)); waiting for one, up to 15 minutes"
716 sleep 30
717 continue
718 fi
719 { [ "$code" = 502 ] && [ "$unreachable" = true ]; } || [ "$code" = 000 ] || break
720 tries=$((tries + 1))
721 [ "$tries" -lt 4 ] || break
722 echo "starting the import returned $code ($(jq -r .message import.json 2>/dev/null)); trying again in 30 seconds"
723 sleep 30
724 done
725 if [ "$code" = 429 ] && [ "$busy" = true ]; then echo "::warning::no import slot came free in 15 minutes, so the import check is skipped: $(jq -r .message import.json)"; exit 0; fi
726 if [ "$code" = 429 ]; then echo "::warning::GitHub's rate limit stopped the import check: $(jq -r .message import.json)"; exit 0; fi
727 if [ "$code" = 502 ] && [ "$unreachable" = true ]; then echo "::warning::GitHub could not be reached, so the import check is skipped: $(jq -r .message import.json)"; exit 0; fi
728 [ "$code" = 201 ] || { echo "::error::starting the import returned $code: $(cat import.json)"; exit 1; }
729 echo "IMPORT_REPO=$name" >> "$GITHUB_ENV"
730 id=$(jq -r .id import.json)
731 echo "import $id: $SOURCE -> $OWNER/$name"
732 for i in $(seq 1 90); do
733 imp=$(api GET "/diffinery/imports/$id")
734 status=$(jq -r .status <<<"$imp")
735 case "$status" in succeeded|failed|cancelled) break ;; esac
736 if jq -e '[.steps[].message // ""] | any(test("rate limit"))' >/dev/null <<<"$imp"; then
737 api POST "/diffinery/imports/$id/cancel" >/dev/null || true
738 echo "::warning::GitHub's rate limit paused the import, so the import check is skipped: $(jq -r '[.steps[].message // ""] | map(select(test("rate limit")))[0]' <<<"$imp")"
739 exit 0
740 fi
741 sleep 10
742 done
743 jq '{status, error, warnings, steps: [.steps[] | "\(.name): \(.status) \(.message // "")"], git}' <<<"$imp"
744 [ "$status" = succeeded ] || { echo "::error::the import ended $status"; exit 1; }
745
746 # The same refs, issue and pull request numbers as on GitHub (when GitHub still answers this runner).
747 R="/repos/$OWNER/$name"
748 [ "$(api GET "$R" | jq -r .private)" = true ] || { echo "::error::the imported repository is not private"; exit 1; }
749 gh() { curl -fsS "https://api.github.com/repos/$SOURCE$1" -H "Accept: application/vnd.github+json" ${GITHUB_TOKEN_FOR_IMPORT:+-H "Authorization: Bearer $GITHUB_TOKEN_FOR_IMPORT"}; }
750 if src=$(gh "") && branches=$(gh "/branches?per_page=100") && items=$(gh "/issues?state=all&per_page=30&sort=created&direction=asc"); then
751 def=$(jq -r .default_branch <<<"$src")
752 want=$(jq -r --arg b "$def" '.[] | select(.name == $b) | .commit.sha' <<<"$branches")
753 got=$(api GET "$R/branches/$def" | jq -r .commit.sha)
754 [ "$got" = "$want" ] || { echo "::error::$def is $got on Diffinery, $want on GitHub"; exit 1; }
755 diff <(jq -r '.[].name' <<<"$branches" | sort) <(api GET "$R/branches?per_page=100" | jq -r '.[].name' | sort) || { echo "::error::the branches differ"; exit 1; }
756 n=0
757 for row in $(jq -r '.[] | "\(.number):\(if .pull_request then "pulls" else "issues" end)"' <<<"$items"); do
758 num=${row%%:*} kind=${row#*:}
759 want=$(jq -r --argjson n "$num" '.[] | select(.number == $n) | .title' <<<"$items")
760 got=$(api GET "$R/$kind/$num" | jq -r .title)
761 [ "$got" = "$want" ] || { echo "::error::$kind #$num is \"$got\" on Diffinery, \"$want\" on GitHub"; exit 1; }
762 n=$((n + 1))
763 done
764 echo "$def at $got, $(jq length <<<"$branches") branches and $n issues and pull requests match GitHub"
765 else
766 echo "::warning::GitHub did not answer this runner (rate limit?), so the import is checked without comparing to GitHub"
767 fi
768 # No side effects: importing runs no workflows and sends no notifications.
769 runs=$(api GET "$R/actions/runs" | jq .total_count)
770 [ "$runs" = 0 ] || { echo "::error::the import started $runs workflow runs"; exit 1; }
771
772 - name: Scheduled workflow
773 # Runs even when the import check failed: the two are independent. It needs the scheduled
774 # workflow pushed, though, so a failed setup doesn't add a 13-minute wait for a run that can't come.
775 if: ${{ !cancelled() && steps.token.outputs.skip != 'true' && steps.push.outcome == 'success' }}
776 run: |
777 set -euo pipefail
778 # The cron trigger fires every 5 minutes, so allow two windows.
779 for i in $(seq 1 75); do
780 run=$(curl -fsS "$DIFFINERY/api/v3/repos/$OWNER/$REPO/actions/runs?event=schedule" -H "Authorization: Bearer $TOKEN" | jq -c '.workflow_runs[0] // empty')
781 [ -n "$run" ] && [ "$(jq -r .status <<<"$run")" = completed ] && break
782 sleep 10
783 done
784 if [ -z "$run" ]; then
785 # Whether the scheduler stopped ticking (last_tick_at is old) or ticked without starting the run
786 # (site administrators only: another token prints the 403).
787 echo "scheduler: $(curl -sS "$DIFFINERY/api/v3/diffinery/admin/scheduler" -H "Authorization: Bearer $TOKEN") (now $(date -u +%FT%TZ))"
788 echo "::error::no scheduled run started"
789 exit 1
790 fi
791 echo "$run" | jq '{id, event, status, conclusion}'
792 [ "$(jq -r .conclusion <<<"$run")" = success ] || { echo "::error::the scheduled run did not succeed"; exit 1; }
793
794 - name: Delete the throwaway repositories
795 if: always() && steps.token.outputs.skip != 'true'
796 run: |
797 curl -sS -o /dev/null -w 'package %{http_code}\n' -X DELETE "$DIFFINERY/api/v3/users/$OWNER/packages/container/${REPO,,}" -H "Authorization: Bearer $TOKEN"
798 curl -sS -o /dev/null -w '%{http_code}\n' -X DELETE "$DIFFINERY/api/v3/repos/$OWNER/$REPO" -H "Authorization: Bearer $TOKEN"
799 [ -z "${PR_REPO:-}" ] || curl -sS -o /dev/null -w '%{http_code}\n' -X DELETE "$DIFFINERY/api/v3/repos/$OWNER/$PR_REPO" -H "Authorization: Bearer $TOKEN"
800 [ -z "${IMPORT_REPO:-}" ] || curl -sS -o /dev/null -w '%{http_code}\n' -X DELETE "$DIFFINERY/api/v3/repos/$OWNER/$IMPORT_REPO" -H "Authorization: Bearer $TOKEN"