Files

195 lines
7.9 KiB
JavaScript

"use strict";
// Real Chromium -> original Login V2 -> real ZITADEL -> unmodified Auth.js.
// No mock authorization, fabricated JWT, injected session, or token exfiltration.
const assert = require("node:assert/strict");
const fs = require("node:fs");
const { spawn } = require("node:child_process");
const { chromium } = require("playwright");
const ACCOUNT = "http://localhost:3000";
const ISSUER = "http://localhost:8080";
let stage = "BROWSER_PREFLIGHT";
let server;
let browser;
function pass(marker) {
process.stdout.write(marker + "\n");
}
function fixture() {
const data = JSON.parse(fs.readFileSync("/ci/secret/oidc.json", "utf8"));
for (const key of ["authSecret", "clientId", "clientSecret", "userId", "loginName", "password"]) {
assert.equal(typeof data[key], "string", "Missing temporary fixture field");
assert.ok(data[key].length > 0, "Empty temporary fixture field");
}
assert.equal(data.issuer, ISSUER);
return data;
}
async function waitForPortal(maxMs = 180000) {
const deadline = Date.now() + maxMs;
while (Date.now() < deadline) {
if (server.exitCode !== null) throw Error("Disposable Account Portal exited early");
try {
const controller = new AbortController();
const abort = setTimeout(() => controller.abort(), 3000);
try {
const res = await fetch(ACCOUNT + "/signin", { redirect: "manual", signal: controller.signal });
if (res.status === 200 || res.status === 303 || res.status === 307) return;
} finally {
clearTimeout(abort);
}
} catch (_) {}
await new Promise(resolve => setTimeout(resolve, 1500));
}
throw Error("Disposable Account Portal was not HTTP-ready");
}
function assertAuthorization(requestUrl, expectedId) {
assert.ok(requestUrl, "No genuine OIDC authorization navigation observed");
const u = new URL(requestUrl);
assert.equal(u.origin, ISSUER);
assert.equal(u.pathname, "/oauth/v2/authorize");
assert.equal(u.searchParams.get("client_id"), expectedId);
assert.equal(u.searchParams.get("response_type"), "code");
assert.equal(u.searchParams.get("code_challenge_method"), "S256");
assert.ok((u.searchParams.get("code_challenge") || "").length >= 43);
assert.ok((u.searchParams.get("state") || "").length >= 16);
assert.ok((u.searchParams.get("nonce") || "").length >= 16);
assert.equal(u.searchParams.get("redirect_uri"), ACCOUNT + "/api/auth/callback/zitadel");
}
async function verifyAnonymous(context) {
const reply = await context.request.get(ACCOUNT + "/api/account/me");
assert.equal(reply.status(), 401, "Anonymous Account API must be denied");
const cache = reply.headers()["cache-control"] || "";
assert.ok(cache.includes("no-store"), "Anonymous identity response may be cached");
const page = await context.newPage();
await page.goto(ACCOUNT + "/account", { waitUntil: "domcontentloaded", timeout: 90000 });
await page.waitForURL(url => url.pathname === "/signin", { timeout: 60000 });
await page.close();
pass("ZITPLANE_OIDC_ANONYMOUS_API_AND_PAGE_REJECTED_PASS");
}
async function verifyInvalidCallback(context) {
const page = await context.newPage();
await page.goto(ACCOUNT + "/api/auth/callback/zitadel?code=invalid&state=invalid", {
waitUntil: "domcontentloaded",
timeout: 60000
}).catch(() => {});
const reply = await context.request.get(ACCOUNT + "/api/account/me");
assert.equal(reply.status(), 401, "Tampered callback established an identity");
await page.close();
pass("ZITPLANE_OIDC_INVALID_CALLBACK_FAIL_CLOSED_PASS");
}
async function main() {
const data = fixture();
stage = "ACCOUNT_SERVER_START";
// Only this isolated CI namespace uses HTTP loopback; production Auth.js
// configuration (including its HTTPS requirement) stays untouched.
const outFd = fs.openSync("/tmp/oidc-portal-server.log", "w", 0o600);
server = spawn("npm", ["run", "dev", "--", "--hostname", "127.0.0.1", "--port", "3000"], {
cwd: "/tmp/ui",
detached: true,
stdio: ["ignore", outFd, outFd],
env: {
...process.env,
NODE_ENV: "development",
AUTH_URL: ACCOUNT,
AUTH_TRUST_HOST: "true",
AUTH_SECRET: data.authSecret,
ZITADEL_ISSUER: ISSUER,
ZITADEL_CLIENT_ID: data.clientId,
ZITADEL_CLIENT_SECRET: data.clientSecret,
NO_PROXY: "localhost,127.0.0.1"
}
});
fs.closeSync(outFd);
await waitForPortal();
pass("ZITPLANE_OIDC_DISPOSABLE_ACCOUNT_HTTP_READY_PASS");
stage = "PLAYWRIGHT_CHROMIUM_START";
browser = await chromium.launch({ headless: true, args: ["--no-sandbox"] });
const anonymous = await browser.newContext();
const signed = await browser.newContext();
anonymous.setDefaultTimeout(70000);
signed.setDefaultTimeout(70000);
stage = "ANONYMOUS_NEGATIVE";
await verifyAnonymous(anonymous);
stage = "INVALID_CALLBACK_NEGATIVE";
await verifyInvalidCallback(anonymous);
stage = "REAL_OIDC_AUTH_REDIRECT";
const page = await signed.newPage();
let authorizeUrl = null;
page.on("request", request => {
try {
const url = new URL(request.url());
if (url.origin === ISSUER && url.pathname === "/oauth/v2/authorize") {
// Captured in memory ONLY. Never print code challenge, state or nonce.
authorizeUrl = request.url();
}
} catch (_) {}
});
await page.goto(ACCOUNT + "/signin", { waitUntil: "domcontentloaded", timeout: 90000 });
await page.getByRole("button", { name: "Continue with ZITADEL" }).click();
await page.getByTestId("username-text-input").waitFor({ state: "visible", timeout: 110000 });
assertAuthorization(authorizeUrl, data.clientId);
pass("ZITPLANE_OIDC_REAL_AUTHORIZE_PKCE_STATE_NONCE_PASS");
stage = "ORIGINAL_LOGIN_USERNAME";
await page.getByTestId("username-text-input").fill(data.loginName);
await page.getByTestId("submit-button").click();
stage = "ORIGINAL_LOGIN_PASSWORD";
await page.getByTestId("password-text-input").waitFor({ state: "visible", timeout: 80000 });
await page.getByTestId("password-text-input").fill(data.password);
await page.getByTestId("submit-button").click();
stage = "OIDC_CODE_CALLBACK";
await page.waitForURL(url => url.origin === ACCOUNT && url.pathname === "/account", {
timeout: 105000
});
pass("ZITPLANE_OIDC_REAL_PASSWORD_AND_CALLBACK_PASS");
stage = "AUTHENTICATED_SESSION_IDENTITY";
const response = await signed.request.get(ACCOUNT + "/api/account/me");
assert.equal(response.status(), 200, "Authenticated API did not return HTTP 200");
assert.ok((response.headers()["cache-control"] || "").includes("no-store"));
const identity = await response.json();
assert.equal(identity?.user?.id, data.userId, "Authenticated subject mismatch");
const cookies = await signed.cookies(ACCOUNT);
assert.ok(cookies.some(c => c.name.includes("session-token") && c.httpOnly), "No HttpOnly Auth.js session cookie");
await page.goto(ACCOUNT + "/account/security", { waitUntil: "domcontentloaded" });
assert.equal(new URL(page.url()).pathname, "/account/security", "Protected Account page denied valid session");
pass("ZITPLANE_OIDC_REAL_SESSION_PROTECTED_PAGE_AND_API_PASS");
stage = "LOCAL_SESSION_LOGOUT";
await page.getByRole("button", { name: "Sign out of portal" }).click();
await page.waitForURL(url => url.pathname === "/signin", { timeout: 90000 });
const afterLogout = await signed.request.get(ACCOUNT + "/api/account/me");
assert.equal(afterLogout.status(), 401, "Local sign out left Account API authenticated");
pass("ZITPLANE_OIDC_PORTAL_LOGOUT_SESSION_REVOKED_PASS");
await anonymous.close();
await signed.close();
pass("ZITPLANE_OIDC_REAL_BROWSER_COMPLETE_PASS");
}
(async () => {
try {
await main();
} catch (_) {
// Never log browser URL/query, cookies, API bodies, passwords or client key.
process.stderr.write("ZITPLANE_OIDC_BROWSER_BLOCKED_AT=" + stage + "\n");
process.exitCode = 1;
} finally {
if (browser) await browser.close().catch(() => {});
if (server?.pid) {
try { process.kill(-server.pid, "SIGTERM"); } catch (_) {}
}
}
})();