From 96721bc58fad4d64081b0c206bb450102057843a Mon Sep 17 00:00:00 2001 From: mapxn <16299874+mapxn@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:14:23 +0800 Subject: [PATCH] =?UTF-8?q?ci:=20=E6=9C=AA=E9=85=8D=E7=BD=AE=20APP=5FURL?= =?UTF-8?q?=20=E6=97=B6=E8=87=AA=E5=8A=A8=E6=8E=A8=E5=AF=BC=20workers.dev?= =?UTF-8?q?=20=E5=86=92=E7=83=9F=E5=9C=B0=E5=9D=80=20(ONE-513)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - smoke-test.sh:APP_URL 已配照旧探它;未配则用 CLOUDFLARE_API_TOKEN + ACCOUNT_ID 从 Cloudflare API 读取账户 workers.dev 子域名,拼出 https://..workers.dev 后探测;两者皆无才报错。 - 先查 Worker 的 workers.dev 开关,被关时明确报「workers.dev 未启用、 不是应用故障」,并提示改用 APP_URL。 - deploy.yml 的 Smoke 步补 ACCOUNT_ID 与 CLOUDFLARE_API_TOKEN;APP_URL 仍取 vars.APP_URL(可选,保留)。 - test-deploy-checks.mjs 新增 7 个用例(本地 mock curl,不调生产): 自动推导并探三路径、APP_URL 优先不调 API、workers.dev 关闭报错、 开关读不到仅警告、API 失败提示权限且不泄露 token、两者皆无报错、 Smoke 步 env 结构。 --- .github/scripts/smoke-test.sh | 86 +++++++++- .github/scripts/test-deploy-checks.mjs | 220 +++++++++++++++++++++++++ .github/workflows/deploy.yml | 6 + 3 files changed, 309 insertions(+), 3 deletions(-) diff --git a/.github/scripts/smoke-test.sh b/.github/scripts/smoke-test.sh index c936c00..a6bd2d3 100644 --- a/.github/scripts/smoke-test.sh +++ b/.github/scripts/smoke-test.sh @@ -2,13 +2,90 @@ # Public-hostname probes. A 403 with Cloudflare's documented challenge header is # inconclusive (warning), not an application failure. The separate control-plane # deployment check must succeed even if every HTTP probe is challenged. +# +# Target URL: `vars.APP_URL` when it is set — a custom domain is the real +# production entry point, so it is probed whenever it is configured. When it is +# not set, the Worker's workers.dev address is resolved instead. That address +# cannot be built from ACCOUNT_ID (the workers.dev subdomain is an account-level +# string), but it can be read from the Cloudflare API: +# +# https://..workers.dev +# +# Env: APP_URL — public entry point (optional) +# CLOUDFLARE_API_TOKEN — only needed when APP_URL is empty +# ACCOUNT_ID — only needed when APP_URL is empty set -euo pipefail -if [[ -z "${APP_URL:-}" ]]; then - echo "::error::Variable APP_URL is not set; cannot verify the deployment" +repo="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +api="https://api.cloudflare.com/client/v4" + +cf_get() { # cf_get — prints the response body + curl -sS --max-time 20 \ + -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \ + "$api$1" +} + +api_error() { # api_error — compact error list for messages + local detail + detail="$(jq -c 'if type == "object" then (.errors // empty) else empty end' \ + <<<"${1:-null}" 2>/dev/null || true)" + printf '%s' "${detail:-unknown error}" +} + +worker_name() { + local name="" + if [[ -f "$repo/apps/worker/wrangler.toml" ]]; then + name="$(sed -n 's/^name[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' \ + "$repo/apps/worker/wrangler.toml" | head -n 1)" + fi + if [[ -z "$name" ]]; then + echo "::error::Cannot read the Worker name from $repo/apps/worker/wrangler.toml" >&2 + return 1 + fi + printf '%s' "$name" +} + +resolve_workers_dev() { # prints the workers.dev URL of this Worker + local worker flags resp subdomain + worker="$(worker_name)" || return 1 + + # Whether the script is served on workers.dev at all. A disabled route + # resolves to a host that never answers, so say that plainly instead of + # letting it look like the application is broken. + flags="$(cf_get "/accounts/${ACCOUNT_ID}/workers/scripts/${worker}/subdomain" || true)" + if jq -e '.success == true' <<<"${flags:-null}" >/dev/null 2>&1; then + if [[ "$(jq -r '.result.enabled' <<<"$flags")" != "true" ]]; then + echo "::error::workers.dev is not enabled for Worker '${worker}' — the account or the script disabled its workers.dev route. That is a routing configuration problem, not an application failure. Set vars.APP_URL to a bound custom domain to smoke test it." >&2 + return 1 + fi + else + echo "::warning::Could not read whether Worker '${worker}' is served on workers.dev ($(api_error "$flags")); trying the workers.dev address anyway." >&2 + fi + + resp="$(cf_get "/accounts/${ACCOUNT_ID}/workers/subdomain" || true)" + if ! jq -e '.success == true' <<<"${resp:-null}" >/dev/null 2>&1; then + echo "::error::Cloudflare API GET /accounts/${ACCOUNT_ID}/workers/subdomain failed, so the workers.dev address cannot be resolved ($(api_error "$resp")). CLOUDFLARE_API_TOKEN needs Workers Scripts:Read; alternatively set vars.APP_URL to a bound custom domain." >&2 + return 1 + fi + subdomain="$(jq -r '.result.subdomain // empty' <<<"$resp")" + if [[ -z "$subdomain" ]]; then + echo "::error::The Cloudflare API returned no workers.dev subdomain for this account; set vars.APP_URL to a bound custom domain instead." >&2 + return 1 + fi + printf 'https://%s.%s.workers.dev' "$worker" "$subdomain" +} + +derived=false +if [[ -n "${APP_URL:-}" ]]; then + base="${APP_URL%/}" +elif [[ -z "${CLOUDFLARE_API_TOKEN:-}" || -z "${ACCOUNT_ID:-}" ]]; then + echo "::error::Neither vars.APP_URL nor CLOUDFLARE_API_TOKEN+ACCOUNT_ID are set; cannot work out which URL to smoke test. Set vars.APP_URL, or keep the credentials the deploy workflow passes so the workers.dev address can be resolved automatically." >&2 exit 1 +else + base="$(resolve_workers_dev)" || exit 1 + derived=true + echo "Resolved workers.dev address: $base" fi -base="${APP_URL%/}" tmp="$(mktemp -d)" trap 'rm -rf "$tmp"' EXIT @@ -38,6 +115,9 @@ probe() { # probe [jq filter the JSON body must satisfy] fi done echo "::error::GET $path -> HTTP $code (000 means transport failure)" + if [[ "$derived" == "true" ]]; then + echo "::warning::The target was resolved from this account's workers.dev subdomain. If the account or Worker has workers.dev disabled, that is a routing configuration problem, not an application failure — set vars.APP_URL to a bound custom domain." + fi return 1 } diff --git a/.github/scripts/test-deploy-checks.mjs b/.github/scripts/test-deploy-checks.mjs index 9bde13e..3d2a3b3 100644 --- a/.github/scripts/test-deploy-checks.mjs +++ b/.github/scripts/test-deploy-checks.mjs @@ -381,3 +381,223 @@ for (const scenario of [ assert.doesNotMatch(toml, /_PLACEHOLDER/); }); } + +// ─── 改动 E:未配置 APP_URL 时自动推导 workers.dev 地址 ─────────────────────── + +// 测试用 curl:本地 mock,不访问网络,两个 Cloudflare API 端点与冒烟探测都由 +// 它回答;请求 URL 记进 requests.log,测试据此断言真的请求了推导出的地址。 +function curlMock( + dir, + { + subdomain = 'demo-sub', + enabled = true, + scriptOk = true, + accountOk = true, + } = {}, +) { + const failure = JSON.stringify({ + success: false, + result: null, + errors: [{ code: 10000, message: 'Authentication error' }], + }); + const scriptBody = scriptOk + ? JSON.stringify({ + success: true, + result: { enabled, previews_enabled: false }, + errors: [], + }) + : failure; + const accountBody = accountOk + ? JSON.stringify({ success: true, result: { subdomain }, errors: [] }) + : failure; + writeFileSync( + join(dir, 'curl'), + `#!/bin/sh +out=""; hdr=""; url=""; prev="" +for a in "$@"; do + case "$prev" in + -o) out="$a" ;; + -D) hdr="$a" ;; + esac + case "$a" in + http*) url="$a" ;; + esac + prev="$a" +done +printf '%s\\n' "$url" >> ${join(dir, 'requests.log')} +case "$url" in + */accounts/*/workers/scripts/*/subdomain) body='${scriptBody}' ;; + */accounts/*/workers/subdomain) body='${accountBody}' ;; + */api/health) body='{"status":"ok"}' ;; + */api/config) body='{"appName":"Hop"}' ;; + *) body='Hop' ;; +esac +if [ -n "$out" ]; then + if [ -n "$hdr" ]; then : > "$hdr"; fi + printf '%s' "$body" > "$out" + printf '200' +else + printf '%s' "$body" +fi +`, + { mode: 0o755 }, + ); +} + +function requests(dir) { + try { + return readFileSync(join(dir, 'requests.log'), 'utf8') + .split('\n') + .filter(Boolean); + } catch { + return []; + } +} + +// 清掉真实环境里可能存在的部署变量,只保留用例显式给的值。 +async function runSmoke(f, extra) { + const env = { ...f.env }; + for (const name of [ + 'APP_URL', + 'ACCOUNT_ID', + 'CLOUDFLARE_API_TOKEN', + 'CHECK_DB', + ]) { + delete env[name]; + } + Object.assign(env, extra); + return exec('bash', [join(scripts, 'smoke-test.sh')], { env }).then( + (r) => ({ ok: true, output: r.stdout + r.stderr }), + (e) => ({ ok: false, output: `${e.stdout ?? ''}${e.stderr ?? ''}` }), + ); +} + +const creds = { + ACCOUNT_ID: 'a'.repeat(32), + CLOUDFLARE_API_TOKEN: 'not-a-real-token', +}; + +test('冒烟:未配置 APP_URL 时用 CF API 推导 workers.dev 地址并探测', async (t) => { + const f = fixture(t); + curlMock(f.dir); + const result = await runSmoke(f, { ...creds, CHECK_DB: 'true' }); + assert.equal(result.ok, true, result.output); + assert.match( + result.output, + /Resolved workers\.dev address: https:\/\/hop\.demo-sub\.workers\.dev/, + ); + const urls = requests(f.dir); + assert.deepEqual( + urls.filter((url) => url.startsWith('https://api.cloudflare.com/')), + [ + `https://api.cloudflare.com/client/v4/accounts/${creds.ACCOUNT_ID}/workers/scripts/hop/subdomain`, + `https://api.cloudflare.com/client/v4/accounts/${creds.ACCOUNT_ID}/workers/subdomain`, + ], + '两个 CF API 端点都应按同一 Worker 名与账户 ID 调用', + ); + assert.deepEqual( + urls.filter((url) => !url.startsWith('https://api.cloudflare.com/')), + [ + 'https://hop.demo-sub.workers.dev/api/health', + 'https://hop.demo-sub.workers.dev/', + 'https://hop.demo-sub.workers.dev/api/config', + ], + '探测必须打在推导出的 workers.dev 地址上', + ); + assert.doesNotMatch(result.output, /::warning::/); +}); + +test('冒烟:APP_URL 已配置时优先探测它,不调用 CF API', async (t) => { + const f = fixture(t); + curlMock(f.dir); + const result = await runSmoke(f, { + ...creds, + APP_URL: 'https://links.example.com/', + }); + assert.equal(result.ok, true, result.output); + const urls = requests(f.dir); + assert.deepEqual( + urls, + ['https://links.example.com/api/health', 'https://links.example.com/'], + '配了 APP_URL 就只探它(含去除尾部斜杠)', + ); + assert.doesNotMatch(result.output, /Resolved workers\.dev address/); +}); + +test('冒烟:workers.dev 被关闭时报「未启用」而不是应用故障', async (t) => { + const f = fixture(t); + curlMock(f.dir, { enabled: false }); + const result = await runSmoke(f, creds); + assert.equal(result.ok, false, result.output); + assert.match( + result.output, + /::error::workers\.dev is not enabled for Worker 'hop'/, + ); + assert.match(result.output, /not an application failure/); + // 未启用时不做无意义的探测。 + assert.deepEqual( + requests(f.dir).filter((url) => url.includes('workers.dev')), + [], + ); +}); + +test('冒烟:读不到 workers.dev 开关只警告,仍按推导地址探测', async (t) => { + const f = fixture(t); + curlMock(f.dir, { scriptOk: false }); + const result = await runSmoke(f, creds); + assert.equal(result.ok, true, result.output); + assert.match(result.output, /::warning::Could not read whether Worker/); + assert.deepEqual( + requests(f.dir).filter((url) => url.includes('/api/health')), + ['https://hop.demo-sub.workers.dev/api/health'], + ); +}); + +test('冒烟:CF API 取不到子域名时报错并提示所需权限', async (t) => { + const f = fixture(t); + curlMock(f.dir, { accountOk: false }); + const result = await runSmoke(f, creds); + assert.equal(result.ok, false, result.output); + assert.match(result.output, /workers\/subdomain failed/); + assert.match(result.output, /Workers Scripts:Read/); + assert.doesNotMatch(result.output, /not-a-real-token/); +}); + +test('冒烟:APP_URL 与凭证都没有时报错', async (t) => { + const f = fixture(t); + curlMock(f.dir); + const result = await runSmoke(f, {}); + assert.equal(result.ok, false, result.output); + assert.match(result.output, /Neither vars\.APP_URL nor/); + assert.deepEqual(requests(f.dir), [], '缺少凭证时不应发出任何请求'); +}); + +test('deploy.yml:Smoke 步给自动推导补上 token 与账户 ID', () => { + const lines = readFileSync( + join(repoRoot, '.github', 'workflows', 'deploy.yml'), + 'utf8', + ).split('\n'); + const start = lines.findIndex((line) => line.trim() === '- name: Smoke test'); + assert.notEqual(start, -1, 'deploy.yml 缺少 Smoke 步'); + // 到下一个步骤声明为止,就是 Smoke 步本身的整段内容。 + const end = lines.findIndex( + (line, i) => i > start && /^\s*- (name|uses):/.test(line), + ); + const smoke = lines.slice(start, end === -1 ? lines.length : end).join('\n'); + assert.match( + smoke, + /^ {10}APP_URL: \$\{\{ vars\.APP_URL \}\}$/m, + 'APP_URL 仍是可选变量,原样传入', + ); + assert.match( + smoke, + /^ {10}ACCOUNT_ID: \$\{\{ secrets\.[A-Z0-9_]+ \}\}$/m, + '自动推导需要账户 ID', + ); + assert.match( + smoke, + /^ {10}CLOUDFLARE_API_TOKEN: \$\{\{ secrets\.CLOUDFLARE_API_TOKEN \}\}$/m, + '自动推导需要 API token', + ); + assert.match(smoke, /^ {8}run: bash \.github\/scripts\/smoke-test\.sh$/m); +}); diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index bc55c80..54710f1 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -183,10 +183,16 @@ jobs: TABLE_PREFIX: ${{ steps.prefix.outputs.table_prefix }} run: bash ../../.github/scripts/verify-deployment.sh + # Probes vars.APP_URL when it is configured; otherwise resolves the + # Worker's workers.dev address through the Cloudflare API (the account's + # workers.dev subdomain cannot be derived from the account ID), so the + # smoke test no longer needs a configured APP_URL. - name: Smoke test id: smoke env: APP_URL: ${{ vars.APP_URL }} + ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} CHECK_DB: ${{ steps.d1.outputs.mode == 'apply' || steps.d1.outputs.mode == 'prefixed' }} run: bash .github/scripts/smoke-test.sh