diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8d66c369..e6c5ff6d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -58,6 +58,7 @@ jobs: run: go run github.com/rhysd/actionlint/cmd/actionlint@v1.7.12 -color=false - run: node --test scripts/ci-selection.test.mjs scripts/ci-results.test.mjs scripts/prepare-contract-report.test.mjs - run: node --test scripts/prepare-pages-reports.test.mjs + - run: node --test scripts/deployment-smoke.test.mjs - run: python3 -m unittest discover -s scripts -p railway_preview_qr_test.py railway-config: diff --git a/.github/workflows/deployment-smoke.yml b/.github/workflows/deployment-smoke.yml new file mode 100644 index 00000000..c16688a1 --- /dev/null +++ b/.github/workflows/deployment-smoke.yml @@ -0,0 +1,35 @@ +name: Public deployment smoke + +on: + workflow_dispatch: + +permissions: + contents: read + +jobs: + smoke: + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + timeout-minutes: 2 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: 22.20.0 + - name: Probe fixed public Lovat endpoints + run: | + set -o pipefail + { + echo "Smoke runner revision: $GITHUB_SHA" + node scripts/deployment-smoke.mjs + } | tee deployment-smoke.log + - name: Retain smoke evidence + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: deployment-smoke-${{ github.run_id }}-${{ github.run_attempt }} + path: deployment-smoke.log + retention-days: 14 + if-no-files-found: warn diff --git a/docs/deployment/README.md b/docs/deployment/README.md index 1e211c43..7faa2233 100644 --- a/docs/deployment/README.md +++ b/docs/deployment/README.md @@ -21,3 +21,29 @@ For Railway service roots and the plan/apply process, use [Railway configuration 4. Record the tested revision and verify a rollback path before promoting to production. [Test report hosting](../test-report-hosting.md) covers the separate GitHub Pages test site. + +## Public production smoke checks + +After a production deployment, run **Public deployment smoke** from the repository's +Actions tab on `main`, or run `node scripts/deployment-smoke.mjs` with Node 22.20.0. +It checks the deployed Website home, Learn root redirect and Welcome guide, +Dashboard shell and JavaScript entry point, and the public API `/status` and +`/version` contracts. The target domains and paths are fixed in the script. +It sends only bounded, anonymous GET requests, never follows redirects, and +retries timeouts, network errors, 429s and 5xx responses once for cold starts. +This is a manual check, not a periodic probe that could wake a sleeping service. + +Record the deployment SHA/ID separately from the smoke runner commit, and link +the Actions run to the release notes or incident. The run publishes a short log +as a 14-day artifact on success or probe failure. It logs the fixed endpoint, +status, elapsed time, retry count and failure category, not response contents or +arbitrary response headers. An overall failure is evidence to investigate, +not an automatic rollback: verify the deployed revision, check the provider and +service logs, and decide whether to repair or restore the last healthy release. + +`/status` is the current public **process** status, not dependency readiness. +This check does not establish PostgreSQL/Redis health, verify a deployed SHA, +exercise authenticated reads or submissions, or monitor production continuously. +Dependency readiness and shutdown remain in [LVT-339](https://linear.app/highlander-robotics/issue/LVT-339). +An authorized synthetic read, isolated test report, alerts, service metrics and +rollback rehearsal remain in [LVT-347](https://linear.app/highlander-robotics/issue/LVT-347). diff --git a/scripts/deployment-smoke.mjs b/scripts/deployment-smoke.mjs new file mode 100644 index 00000000..63d53c01 --- /dev/null +++ b/scripts/deployment-smoke.mjs @@ -0,0 +1,207 @@ +import { performance } from "node:perf_hooks"; +import { setTimeout as delay } from "node:timers/promises"; +import { pathToFileURL } from "node:url"; + +const timeoutMs = 12_000; +const bodyLimit = 32 * 1024; +const checks = [ + { + name: "Website home", + url: "https://lovat.app/", + mime: "text/html", + html: /\s*Lovat\s*(?:—|—|—)\s*Centralize your team/i, + }, + { + name: "Learn root redirect", + url: "https://learn.lovat.app/", + redirect: "https://learn.lovat.app/guides/welcome/", + }, + { + name: "Learn Welcome guide", + url: "https://learn.lovat.app/guides/welcome/", + mime: "text/html", + html: /<title>\s*Welcome\b/i, + }, + { + name: "Dashboard web shell", + url: "https://dashboard.lovat.app/", + mime: "text/html", + html: /<title>\s*Lovat\s*<\/title>/i, + }, + { + name: "Dashboard application script", + url: "https://dashboard.lovat.app/main.dart.js", + mime: ["text/javascript", "application/javascript", "application/x-javascript"], + }, + { + name: "API process status", + url: "https://api.lovat.app/status", + exact: "Server running", + }, + { + name: "API version contract", + url: "https://api.lovat.app/version", + mime: "application/json", + validate: (body) => { + const version = JSON.parse(body); + return ( + typeof version?.version === "string" && + /^\d+\.\d+\.\d+$/.test(version.version) && + typeof version.gitCommit === "string" && + version.gitCommit.length > 0 + ); + }, + }, +]; + +async function readPrefix(body, limit, pattern) { + if (!body) return { text: "", truncated: false }; + + const reader = body.getReader(); + const decoder = new TextDecoder(); + let text = ""; + let remaining = limit; + try { + for (;;) { + const { value, done } = await reader.read(); + if (done) return { text: text + decoder.decode(), truncated: false }; + + text += decoder.decode(value.subarray(0, remaining), { stream: true }); + if (pattern?.test(text)) return { text, truncated: false }; + + remaining -= value.length; + if (remaining <= 0) return { text, truncated: true }; + } + } finally { + // Cancelling prevents reading the full HTML or asset on a smoke request. + void reader.cancel().catch(() => {}); + } +} + +async function probe(check, fetcher, deadline) { + let response; + try { + response = await fetcher(check.url, { + method: "GET", + credentials: "omit", + redirect: "manual", + signal: deadline, + }); + + const { status } = response; + if (status >= 500 || status === 429) { + return { status, reason: "transient HTTP status", retryable: true }; + } + + if (check.redirect) { + let destination; + try { + const location = response.headers.get("location"); + if (location) destination = new URL(location, check.url).href; + } catch { + // Invalid redirect locations fail without logging response content. + } + return [302, 307].includes(status) && destination === check.redirect + ? { status } + : { status, reason: "unexpected redirect" }; + } + + if (status !== 200) return { status, reason: "unexpected HTTP status" }; + + if (check.mime) { + const mediaType = response.headers + .get("content-type") + ?.split(";")[0] + .trim() + .toLowerCase(); + if (![check.mime].flat().includes(mediaType)) { + return { status, reason: "unexpected content type" }; + } + } + + if (check.html || check.exact || check.validate) { + const { text, truncated } = await readPrefix( + response.body, + check.html ? bodyLimit : 4096, + check.html, + ); + try { + const valid = check.html + ? check.html.test(text) + : !truncated && (check.validate ? check.validate(text) : text.trim() === check.exact); + if (!valid) return { status, reason: "unexpected response content" }; + } catch { + return { status, reason: "unexpected response content" }; + } + } + return { status }; + } catch { + return { + status: response?.status ?? null, + reason: deadline.aborted ? "request timed out" : "network or response read error", + retryable: true, + }; + } finally { + if (response?.body && !response.body.locked) { + void response.body.cancel().catch(() => {}); + } + } +} + +export async function runDeploymentSmoke({ + fetcher = fetch, + pause = delay, + makeDeadline = () => AbortSignal.timeout(timeoutMs), +} = {}) { + return Promise.all( + checks.map(async (check) => { + const started = performance.now(); + const first = await probe(check, fetcher, makeDeadline()); + if (first.retryable) await pause(1000); + const last = first.retryable + ? await probe(check, fetcher, makeDeadline()) + : first; + + return { + name: check.name, + url: check.url, + ok: !last.reason, + status: last.status, + attempts: first.retryable ? 2 : 1, + durationMs: Math.round(performance.now() - started), + ...(first.retryable && { + firstAttempt: { status: first.status, reason: first.reason }, + }), + ...(last.reason && { reason: last.reason }), + }; + }), + ); +} + +async function main() { + if (process.argv.length !== 2) { + console.error("Usage: node scripts/deployment-smoke.mjs (no arguments)"); + process.exitCode = 2; + return; + } + + console.log(`Lovat public production smoke | ${new Date().toISOString()}`); + const results = await runDeploymentSmoke(); + for (const check of results) { + const status = check.status === null ? "no HTTP response" : `HTTP ${check.status}`; + const prior = check.firstAttempt + ? `; first attempt: ${check.firstAttempt.reason}${check.firstAttempt.status === null ? "" : ` (HTTP ${check.firstAttempt.status})`}` + : ""; + const problem = check.reason ? `; ${check.reason}` : ""; + console.log( + `${check.ok ? "PASS" : "FAIL"} ${check.name} [${check.url}]: ${status}, ${check.durationMs}ms, ${check.attempts} attempt(s)${prior}${problem}`, + ); + } + const passed = results.filter((check) => check.ok).length; + console.log(`${passed}/${results.length} public checks passed`); + if (passed !== results.length) process.exitCode = 1; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + await main(); +} diff --git a/scripts/deployment-smoke.test.mjs b/scripts/deployment-smoke.test.mjs new file mode 100644 index 00000000..f09ff76a --- /dev/null +++ b/scripts/deployment-smoke.test.mjs @@ -0,0 +1,145 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { runDeploymentSmoke } from "./deployment-smoke.mjs"; + +const expected = new Map([ + [ + "https://lovat.app/", + () => html("<title>Lovat — Centralize your team's strategy in minutes"), + ], + [ + "https://learn.lovat.app/", + () => new Response(null, { status: 307, headers: { location: "/guides/welcome/" } }), + ], + ["https://learn.lovat.app/guides/welcome/", () => html("Welcome | Lovat")], + ["https://dashboard.lovat.app/", () => html("Lovat")], + [ + "https://dashboard.lovat.app/main.dart.js", + () => new Response("compiled code", { headers: { "content-type": "application/javascript; charset=UTF-8" } }), + ], + ["https://api.lovat.app/status", () => new Response("Server running")], + ["https://api.lovat.app/version", () => Response.json({ version: "26.0.0", gitCommit: "no commit id" })], +]); +const html = (body) => new Response(body, { headers: { "content-type": "text/html; charset=utf-8" } }); +const testFetch = (url) => expected.get(url)(); +const noWait = async () => {}; + +test("fixed production probes use anonymous GET and no automatic redirects", async () => { + const calls = []; + const results = await runDeploymentSmoke({ + fetcher: (url, opts) => { + calls.push([url, opts]); + return testFetch(url); + }, + }); + + assert.deepEqual(calls.map(([url]) => url), [...expected.keys()]); + for (const [, opts] of calls) { + assert.equal(opts.method, "GET"); + assert.equal(opts.credentials, "omit"); + assert.equal(opts.redirect, "manual"); + assert.ok(opts.signal instanceof AbortSignal); + assert.equal(opts.headers, undefined); + assert.equal(opts.body, undefined); + } + assert.equal(results.length, expected.size); + assert.ok(results.every((result) => result.ok && result.attempts === 1)); +}); + +test("Learn accepts the two configured redirect statuses but rejects unrelated destinations", async () => { + async function check(location, status) { + const results = await runDeploymentSmoke({ + fetcher: (url) => + url === "https://learn.lovat.app/" + ? new Response(null, { status, headers: { location } }) + : testFetch(url), + }); + return results.find((entry) => entry.name === "Learn root redirect"); + } + + assert.ok((await check("https://learn.lovat.app/guides/welcome/", 302)).ok); + for (const [location, status] of [ + ["//external.invalid/guides/welcome/", 307], + ["/guides/welcome/?unexpected=1", 307], + ["/guides/welcome/", 301], + ]) { + const result = await check(location, status); + assert.equal(result.reason, "unexpected redirect"); + assert.equal(result.attempts, 1); + assert.ok(!("location" in result)); + } +}); + +test("a transient response retries once; deterministic contract failures do not", async () => { + let calls = 0; + let waits = 0; + const results = await runDeploymentSmoke({ + fetcher: (url) => { + if (url === "https://api.lovat.app/status" && ++calls === 1) { + return new Response("not ready", { status: 503 }); + } + if (url === "https://api.lovat.app/version") { + return Response.json({ error: "unrelated response text" }); + } + return testFetch(url); + }, + pause: () => { waits++; }, + }); + const status = results.find((r) => r.name === "API process status"); + const version = results.find((r) => r.name === "API version contract"); + assert.equal(waits, 1); + assert.equal(status.ok, true); + assert.equal(status.attempts, 2); + assert.equal(status.firstAttempt.status, 503); + assert.equal(version.reason, "unexpected response content"); + assert.equal(version.attempts, 1); + assert.doesNotMatch(JSON.stringify(results), /unrelated response text/); +}); + +test("timeout and retry exhaustion are bounded and do not log raw errors", async () => { + let calls = 0; + const results = await runDeploymentSmoke({ + fetcher: (url) => { + if (url === "https://lovat.app/") { + calls++; + throw new Error("unsafe arbitrary upstream text"); + } + return testFetch(url); + }, + pause: noWait, + makeDeadline: () => AbortSignal.abort(), + }); + const result = results.find((r) => r.name === "Website home"); + assert.equal(calls, 2); + assert.equal(result.ok, false); + assert.equal(result.status, null); + assert.equal(result.reason, "request timed out"); + assert.equal(result.attempts, 2); + assert.doesNotMatch(JSON.stringify(results), /unsafe arbitrary upstream text/); +}); + +test("wrong content types and over-budget bodies fail without dumping content", async () => { + const oversized = "x".repeat(36 * 1024); + const results = await runDeploymentSmoke({ + fetcher: (url) => { + if (url.endsWith("main.dart.js")) return html("not JavaScript"); + if (url.endsWith("/status")) return new Response("Server running" + oversized); + if (url === "https://lovat.app/") return html(oversized + "Lovat — Centralize your team"); + return testFetch(url); + }, + }); + assert.deepEqual(results.filter((r) => !r.ok).map((r) => r.reason), [ + "unexpected response content", + "unexpected content type", + "unexpected response content", + ]); +}); + +test("CLI rejects target arguments without making requests", () => { + const path = fileURLToPath(new URL("./deployment-smoke.mjs", import.meta.url)); + const run = spawnSync(process.execPath, [path, "https://external.invalid"], { encoding: "utf8" }); + assert.equal(run.status, 2); + assert.match(run.stderr, /no arguments/); +});