Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion .github/workflows/live-readonly-verify.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,16 @@ on:
type: boolean
required: false
default: false
reject_login_redirect:
description: Fail verification if a non-login page redirects to /login or /auth/
type: boolean
required: false
default: true
upload_summary:
description: Upload sanitized JSON summary artifact (metadata counts only; safe for public repos)
type: boolean
required: false
default: true
secrets:
VERIFY_SESSION_SECRET:
required: true
Expand All @@ -49,7 +59,7 @@ permissions: {}

jobs:
verify-live:
if: ${{ github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' }}
if: ${{ github.ref == 'refs/heads/main' && (github.event_name == 'workflow_dispatch' || github.event_name == 'push') }}
name: Live Read-Only Playwright Verification
runs-on: ubuntu-latest
timeout-minutes: 15
Expand Down Expand Up @@ -99,6 +109,8 @@ jobs:
VERIFY_WRITE_GUARD_PATH: ${{ inputs.write_guard_path }}
TTL_SECONDS: ${{ inputs.ttl_seconds }}
UPLOAD_SCREENSHOTS: ${{ inputs.upload_screenshots }}
VERIFY_REJECT_LOGIN_REDIRECT: ${{ inputs.reject_login_redirect }}
VERIFY_SUMMARY_PATH: ${{ runner.temp }}/verify-summary.json
NODE_PATH: ${{ runner.temp }}/pw-tools/node_modules
run: |
set -euo pipefail
Expand All @@ -111,6 +123,15 @@ jobs:
fi
node scripts/playwright_readonly_verify.mjs

- name: Upload verification summary (sanitized JSON)
if: ${{ always() && inputs.upload_summary }}
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: live-readonly-verify-summary-${{ github.run_id }}-${{ github.run_attempt }}
path: ${{ runner.temp }}/verify-summary.json
if-no-files-found: ignore
retention-days: 7

- name: Upload verification screenshots (private repos only)
if: ${{ always() && inputs.upload_screenshots }}
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
Expand Down
222 changes: 148 additions & 74 deletions scripts/playwright_readonly_verify.mjs
Original file line number Diff line number Diff line change
@@ -1,99 +1,173 @@
#!/usr/bin/env node
/**
* Headless Playwright verifier for live sites using an ephemeral read-only session cookie.
* Never logs the cookie value; fails on HTTP >= 400, console errors, uncaught page errors,
* or missing required selectors.
* Never logs the cookie value; fails on HTTP >= 400, unexpected login redirects, console errors,
* uncaught page errors, or missing required selectors.
*/
import fs from "node:fs";
import path from "node:path";
import { chromium } from "playwright";
import { pathToFileURL } from "node:url";

const baseUrl = (process.env.VERIFY_BASE_URL || "").trim().replace(/\/+$/, "");
const cookieName = (process.env.VERIFY_COOKIE_NAME || "__readonly_verify").trim();
const cookieValue = (process.env.VERIFY_SESSION_TOKEN || "").trim();
const pagesJson = process.env.VERIFY_PAGES_JSON || '[{"path":"/"}]';
const writeGuardPath = (process.env.VERIFY_WRITE_GUARD_PATH || "").trim();
const screenshotDir = (process.env.VERIFY_SCREENSHOT_DIR || "").trim();

if (!baseUrl.startsWith("https://")) {
console.error("VERIFY_BASE_URL must be an HTTPS URL");
process.exit(1);
export function isUnexpectedLoginRedirect(requestedPath, finalUrl) {
let finalPath;
try {
finalPath = new URL(finalUrl).pathname;
} catch {
return false;
}
const reqNorm = String(requestedPath || "/").split("?")[0];
const reqIsLogin = reqNorm === "/login" || reqNorm.startsWith("/auth/");
if (reqIsLogin) return false;
return finalPath === "/login" || finalPath.startsWith("/auth/");
}
if (!cookieValue) {
console.error("Missing VERIFY_SESSION_TOKEN");
process.exit(1);

export function sanitizePathName(relPath) {
return String(relPath || "")
.replace(/[^a-zA-Z0-9_-]+/g, "_")
.replace(/^_+|_+$/g, "") || "home";
}

const origin = new URL(baseUrl);
const pages = JSON.parse(pagesJson);
if (!Array.isArray(pages) || !pages.length) {
console.error("VERIFY_PAGES_JSON must be a non-empty JSON array");
process.exit(1);
export function buildSummaryPayload({ baseUrl, writeGuard, results, passed }) {
return {
base_url: String(baseUrl || ""),
write_guard: writeGuard || null,
pages: Array.isArray(results) ? results : [],
passed: Boolean(passed),
};
}

const browser = await chromium.launch({ headless: true });
try {
const context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
await context.addCookies([
{
name: cookieName,
value: cookieValue,
domain: origin.hostname,
path: "/",
httpOnly: true,
secure: true,
sameSite: "Lax",
},
]);
export async function runLiveVerify() {
const { chromium } = await import("playwright");
const baseUrl = (process.env.VERIFY_BASE_URL || "").trim().replace(/\/+$/, "");
const cookieName = (process.env.VERIFY_COOKIE_NAME || "__readonly_verify").trim();
const cookieValue = (process.env.VERIFY_SESSION_TOKEN || "").trim();
const pagesJson = process.env.VERIFY_PAGES_JSON || '[{"path":"/"}]';
const writeGuardPath = (process.env.VERIFY_WRITE_GUARD_PATH || "").trim();
const screenshotDir = (process.env.VERIFY_SCREENSHOT_DIR || "").trim();
const summaryPath = (process.env.VERIFY_SUMMARY_PATH || "").trim();
const rejectLoginRedirect = (process.env.VERIFY_REJECT_LOGIN_REDIRECT || "true").trim().toLowerCase() !== "false";

if (writeGuardPath) {
const target = `${baseUrl}${writeGuardPath.startsWith("/") ? writeGuardPath : "/" + writeGuardPath}`;
const res = await context.request.post(target, { data: {} });
console.log(`Write-guard POST ${writeGuardPath} -> ${res.status()} (expected 403)`);
if (res.status() !== 403) {
throw new Error(`Read-only write guard failed on ${writeGuardPath}: got ${res.status()}, expected 403`);
}
if (!baseUrl.startsWith("https://")) {
throw new Error("VERIFY_BASE_URL must be an HTTPS URL");
}
if (!cookieValue) {
throw new Error("Missing VERIFY_SESSION_TOKEN");
}

if (screenshotDir) {
fs.mkdirSync(screenshotDir, { recursive: true });
const origin = new URL(baseUrl);
const pages = JSON.parse(pagesJson);
if (!Array.isArray(pages) || !pages.length) {
throw new Error("VERIFY_PAGES_JSON must be a non-empty JSON array");
}

const page = await context.newPage();
for (let i = 0; i < pages.length; i += 1) {
const spec = pages[i];
const rel = String(spec.path || "/");
const url = `${baseUrl}${rel.startsWith("/") ? rel : "/" + rel}`;
const errors = [];
const onPageError = (err) => errors.push(`pageerror: ${err.message}`);
const onConsole = (msg) => {
if (msg.type() === "error") errors.push(`console.error: ${msg.text()}`);
};
page.on("pageerror", onPageError);
page.on("console", onConsole);
const browser = await chromium.launch({ headless: true });
const results = [];
let writeGuard = null;
let passed = false;
try {
const context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
await context.addCookies([
{
name: cookieName,
value: cookieValue,
domain: origin.hostname,
path: "/",
httpOnly: true,
secure: true,
sameSite: "Lax",
},
]);

const response = await page.goto(url, { waitUntil: "networkidle", timeout: 30000 });
const status = response ? response.status() : 0;
console.log(`Live UI ${rel} -> HTTP ${status}`);
if (status < 200 || status >= 400) {
throw new Error(`Unexpected HTTP status ${status} for ${rel}`);
}
if (spec.selector) {
await page.waitForSelector(String(spec.selector), { timeout: 15000 });
console.log(` selector ok: ${spec.selector}`);
if (writeGuardPath) {
const target = `${baseUrl}${writeGuardPath.startsWith("/") ? writeGuardPath : "/" + writeGuardPath}`;
const res = await context.request.post(target, { data: {} });
writeGuard = { path: writeGuardPath, status: res.status(), expected: 403, ok: res.status() === 403 };
console.log(`Write-guard POST ${writeGuardPath} -> ${res.status()} (expected 403)`);
if (res.status() !== 403) {
throw new Error(`Read-only write guard failed on ${writeGuardPath}: got ${res.status()}, expected 403`);
}
}

if (screenshotDir) {
const safeName = rel.replace(/[^a-zA-Z0-9_-]+/g, "_").replace(/^_+|_+$/g, "") || "home";
await page.screenshot({ path: path.join(screenshotDir, `${i + 1}-${safeName}.png`), fullPage: true });
fs.mkdirSync(screenshotDir, { recursive: true });
}
page.off("pageerror", onPageError);
page.off("console", onConsole);

if (errors.length) {
throw new Error(`Runtime errors on ${rel}:\n${errors.join("\n")}`);
const page = await context.newPage();
for (let i = 0; i < pages.length; i += 1) {
const spec = pages[i];
const rel = String(spec.path || "/");
const url = `${baseUrl}${rel.startsWith("/") ? rel : "/" + rel}`;
const pageErrors = [];
const consoleErrors = [];
const onPageError = (err) => pageErrors.push(`pageerror: ${err.message}`);
const onConsole = (msg) => {
if (msg.type() === "error") consoleErrors.push(`console.error: ${msg.text()}`);
};
page.on("pageerror", onPageError);
page.on("console", onConsole);

const started = Date.now();
const response = await page.goto(url, { waitUntil: "networkidle", timeout: 30000 });
const status = response ? response.status() : 0;
const finalUrl = page.url();
let finalPath = "";
try {
finalPath = new URL(finalUrl).pathname;
} catch {
finalPath = "";
}
console.log(`Live UI ${rel} -> HTTP ${status} (${finalPath})`);
if (status < 200 || status >= 400) {
throw new Error(`Unexpected HTTP status ${status} for ${rel}`);
}
if (rejectLoginRedirect && isUnexpectedLoginRedirect(rel, finalUrl)) {
throw new Error(`Unexpected login redirect for ${rel} -> ${finalPath}`);
}
let selectorOk = true;
if (spec.selector) {
await page.waitForSelector(String(spec.selector), { timeout: 15000 });
console.log(` selector ok: ${spec.selector}`);
}
if (screenshotDir) {
const safeName = sanitizePathName(rel);
await page.screenshot({ path: path.join(screenshotDir, `${i + 1}-${safeName}.png`), fullPage: true });
}
page.off("pageerror", onPageError);
page.off("console", onConsole);

results.push({
path: rel,
final_path: finalPath,
status,
selector: spec.selector ? String(spec.selector) : null,
selector_ok: selectorOk,
load_ms: Date.now() - started,
console_errors_count: consoleErrors.length,
page_errors_count: pageErrors.length,
});

const errors = [...pageErrors, ...consoleErrors];
if (errors.length) {
throw new Error(`Runtime errors on ${rel}:\n${errors.join("\n")}`);
}
}
passed = true;
console.log(`Live read-only verification passed (${pages.length} page(s)).`);
} finally {
if (summaryPath) {
fs.mkdirSync(path.dirname(summaryPath), { recursive: true });
fs.writeFileSync(
summaryPath,
JSON.stringify(buildSummaryPayload({ baseUrl, writeGuard, results, passed }), null, 2) + "\n",
);
}
await browser.close();
}
console.log(`Live read-only verification passed (${pages.length} page(s)).`);
} finally {
await browser.close();
}

if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
runLiveVerify().catch((err) => {
console.error(err?.stack || String(err));
process.exit(1);
});
}
10 changes: 9 additions & 1 deletion scripts/sign_readonly_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,16 @@ def verify_readonly_token(
if payload.get("role") != "readonly_verify" or payload.get("iss") != "cloud-deploy-kit":
raise ValueError("Token is not a valid readonly_verify session")
current = int(time.time() if now is None else now)
if int(payload.get("exp", 0)) <= current:
iat = payload.get("iat")
exp = payload.get("exp")
if not isinstance(iat, int) or isinstance(iat, bool) or not isinstance(exp, int) or isinstance(exp, bool):
raise ValueError("Invalid token timestamps")
if iat > current + 60:
raise ValueError("Token issued in the future")
if exp <= current:
raise ValueError("Token expired")
if exp - iat <= 0 or exp - iat > MAX_TTL_SECONDS:
raise ValueError("Token TTL out of bounds")
if expected_audience and payload.get("aud") != expected_audience:
raise ValueError("Token audience mismatch")
return payload
Expand Down
45 changes: 45 additions & 0 deletions tests/test_playwright_readonly_verify.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import test from "node:test";
import assert from "node:assert/strict";

import {
buildSummaryPayload,
isUnexpectedLoginRedirect,
sanitizePathName,
} from "../scripts/playwright_readonly_verify.mjs";

test("isUnexpectedLoginRedirect flags /login and /auth redirects on non-login paths", () => {
assert.equal(isUnexpectedLoginRedirect("/v2/", "https://example.workers.dev/login"), true);
assert.equal(isUnexpectedLoginRedirect("/desk/overview", "https://example.workers.dev/auth/github"), true);
assert.equal(isUnexpectedLoginRedirect("/v2/", "https://example.workers.dev/v2/"), false);
assert.equal(isUnexpectedLoginRedirect("/login", "https://example.workers.dev/login"), false);
});

test("sanitizePathName produces clean filename fragments", () => {
assert.equal(sanitizePathName("/"), "home");
assert.equal(sanitizePathName("/v2/desk?tab=overview"), "v2_desk_tab_overview");
});

test("buildSummaryPayload emits sanitized fields without cookies or body text", () => {
const payload = buildSummaryPayload({
baseUrl: "https://example.workers.dev",
writeGuard: { path: "/api/admin/kv-directory", status: 403, expected: 403, ok: true },
results: [
{
path: "/v2/",
final_path: "/",
status: 200,
selector: "#root",
selector_ok: true,
load_ms: 120,
console_errors_count: 0,
page_errors_count: 0,
},
],
passed: true,
});
const text = JSON.stringify(payload);
assert.equal(payload.passed, true);
assert.equal(payload.write_guard.ok, true);
assert.equal(payload.pages.length, 1);
assert.equal(text.includes("__readonly_verify"), false);
});
6 changes: 6 additions & 0 deletions tests/test_readonly_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ def test_rejects_excessive_ttl(self):
with self.assertRaisesRegex(ValueError, "ttl_seconds"):
issue_readonly_token("test-readonly-secret-key-32-bytes!", ttl_seconds=3600)

def test_rejects_future_iat(self):
secret = "test-readonly-secret-key-32-bytes!"
token = issue_readonly_token(secret, ttl_seconds=300, now=2000)
with self.assertRaisesRegex(ValueError, "future"):
verify_readonly_token(token, secret, now=1000)


if __name__ == "__main__":
unittest.main()