AI Engineering Workspace
PartialChat, files, terminal and preview in one place. Chat sessions run on a durable Postgres-backed queue (chat only: no tools or shell). Live models need an API key; the terminal is unavailable.
Project files
read-onlyapp/qa/oidc-flow.mjs
1// End-to-end OIDC flow test: a TEST instance of the app (loopback :3100, mock IdP on loopback :4400 — never the public edge) talks to a mock IdP that2import https from "node:https";3// enforces PKCE like a real one. Verifies state/nonce/PKCE/signature handling, identity=(iss,sub), no e-mail linking, invitations, fixation, back-channel logout.4// NOT a test against live Zoo IAM (no client credentials exist).5import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import http from "node:http"; import crypto from "node:crypto"; import { spawn } from "node:child_process"; import pg from "pg";6const CFG = path.join(os.homedir(), ".config/zoo-cloud-studio"); const rd = f => fs.readFileSync(path.join(CFG, f), "utf8").trim();7const owner = new pg.Pool({ connectionString: `postgres://studio:${encodeURIComponent(rd("pg-password"))}@127.0.0.1:5432/studio`, max: 2 });8const results = []; const rec = (n, ok, d = "") => { results.push({ name: n, ok: !!ok }); console.log((ok ? "PASS " : "FAIL ") + n + (ok ? "" : " -> " + d)); };9const q = async (t, p) => (await owner.query(t, p)).rows; const ts = Date.now(); const sleep = ms => new Promise(r => setTimeout(r, ms));10const ISS = "http://127.0.0.1:4400/realms/zoo"; const SECRET = "test-secret-" + ts; const b64 = o => Buffer.from(JSON.stringify(o)).toString("base64url");11const good = crypto.generateKeyPairSync("rsa", { modulusLength: 2048 }), evil = crypto.generateKeyPairSync("rsa", { modulusLength: 2048 });12const jwks = { keys: [{ ...good.publicKey.export({ format: "jwk" }), kid: "k1", use: "sig", alg: "RS256" }] };13const codes = new Map(); let lastTokenReq = null;14const sign = (claims, key = good.privateKey) => { const si = b64({ alg: "RS256", kid: "k1", typ: "JWT" }) + "." + b64(claims); return si + "." + crypto.sign("sha256", Buffer.from(si), key).toString("base64url"); };15const idp = http.createServer((req, res) => {16 const u = new URL(req.url, "http://x"); const send = (c, o) => { res.writeHead(c, { "content-type": "application/json" }); res.end(JSON.stringify(o)); };17 if (u.pathname.endsWith("/.well-known/openid-configuration")) return send(200, { issuer: ISS, authorization_endpoint: ISS + "/protocol/openid-connect/auth", token_endpoint: ISS + "/protocol/openid-connect/token", jwks_uri: ISS + "/protocol/openid-connect/certs", code_challenge_methods_supported: ["S256"] });18 if (u.pathname.endsWith("/certs")) return send(200, jwks);19 if (u.pathname.endsWith("/token") && req.method === "POST") { let body = ""; req.on("data", d => body += d); req.on("end", () => {20 const f = new URLSearchParams(body); const auth = req.headers.authorization ?? ""; const c = codes.get(f.get("code")); codes.delete(f.get("code"));21 const basicOk = auth === "Basic " + Buffer.from(`zoo-cloud-studio:${SECRET}`).toString("base64");22 lastTokenReq = { basicOk, grant: f.get("grant_type"), redirect: f.get("redirect_uri"), pkceOk: !!c && crypto.createHash("sha256").update(f.get("code_verifier") ?? "").digest("base64url") === c.challenge };23 if (!basicOk || !c || !lastTokenReq.pkceOk) return send(400, { error: "invalid_grant" });24 send(200, { id_token: sign(c.claims, c.key), access_token: "x", token_type: "Bearer" }); }); return; }25 send(404, {});26}); await new Promise(r => idp.listen(4400, "127.0.0.1", r));27// ---- test app instance (loopback only) ----28const env = { ...process.env, PORT: "3100", ZCS_OIDC_ALLOW_HTTP_LOOPBACK: "1", OIDC_ISSUER: ISS, OIDC_CLIENT_SECRET: SECRET, OIDC_REDIRECT_URI: "https://127.0.0.1:8443/auth/callback", PUBLIC_BASE_URL: "https://127.0.0.1:8443" };29const app = spawn(process.execPath, ["node_modules/next/dist/bin/next", "start", "-p", "3100", "-H", "127.0.0.1"], { env, stdio: "ignore", detached: true });30const T = "http://127.0.0.1:3100"; for (let i = 0; i < 60; i++) { try { if ((await fetch(T + "/auth/backchannel-logout", { method: "GET" })).status) break; } catch { await sleep(500); } }31const jar = () => { const m = new Map(); return { set(r) { for (const c of r.headers.getSetCookie?.() ?? []) { const [kv] = c.split(";"); const [k, ...v] = kv.split("="); if (/max-age=0|expires=thu, 01 jan 1970/i.test(c)) m.delete(k); else m.set(k, v.join("=")); } }, header() { return [...m].map(([k, v]) => `${k}=${v}`).join("; "); }, get: k => m.get(k), m }; };32const call = async (path, { cookies, method = "GET", body, headers = {} } = {}) => { const r = await fetch(T + path, { method, redirect: "manual", body, headers: { "x-zcs-proto": "https", host: "127.0.0.1:8443", ...(cookies ? { cookie: cookies.header() } : {}), ...headers } }); cookies?.set(r); return r; };33async function signIn({ sub, email, emailVerified = false, claims = {}, key = good.privateKey, cookies = jar(), tamper, replayCookie, dropCookie }) {34 const l = await call("/auth/login", { cookies }); if (l.status !== 302) return { login: l };35 const au = new URL(l.headers.get("location")); const state = au.searchParams.get("state"), nonce = au.searchParams.get("nonce"), ch = au.searchParams.get("code_challenge");36 const code = "c_" + crypto.randomBytes(8).toString("hex"); const t = Math.floor(Date.now() / 1000);37 codes.set(code, { challenge: ch, key, claims: { iss: ISS, aud: "zoo-cloud-studio", sub, exp: t + 300, iat: t, nonce: tamper === "nonce" ? "wrong" : nonce, sid: "sid-" + sub, email, email_verified: emailVerified, name: "QA " + sub, ...claims } });38 if (dropCookie) cookies.m.delete("zcs_oidc"); if (replayCookie) cookies.m.set("zcs_oidc", replayCookie);39 const cb = await call(`/auth/callback?code=${code}&state=${tamper === "state" ? "forged" : state}`, { cookies }); return { login: l, cb, state, au, cookies, code };40}41const created = { users: [], orgs: [] }; const prev = {}; let ok = true;42try {43 // ---- live instance must refuse (no secret provisioned) ----44 const live = await new Promise(res => { const rq = (https).request({ host: "127.0.0.1", port: 8443, path: "/auth/login", rejectUnauthorized: false }, r => { r.resume(); res(r.statusCode); }); rq.on("error", () => res(0)); rq.end(); });45 rec("live deployment: /auth/login answers 503 'not configured' (no client secret provisioned; IAM not contacted)", live === 503, String(live));46 const unauth = await call("/auth/login", { headers: { "x-zcs-proto": "http" } }); rec("sign-in over plain HTTP refused", unauth.status === 403);47 prev.dev = (await q("SELECT value FROM settings WHERE key='security.dev_customer_ops'"))[0]?.value ?? null; prev.acr = (await q("SELECT value FROM settings WHERE key='oidc.required_acr'"))[0]?.value ?? null;48 const setS = (k, v) => owner.query(v === null ? "DELETE FROM settings WHERE key=$1" : "INSERT INTO settings(key,value) VALUES($1,$2) ON CONFLICT(key) DO UPDATE SET value=excluded.value", v === null ? [k] : [k, v]);49 // ---- gate closed ----50 await setS("security.dev_customer_ops", "0");51 const g = await signIn({ sub: "gate-" + ts, email: `gate-${ts}@example.test` });52 rec("authorization request is code+PKCE S256 with state and nonce; token exchange used client auth + verifier", g.au.searchParams.get("code_challenge_method") === "S256" && g.au.searchParams.get("response_type") === "code" && lastTokenReq?.basicOk && lastTokenReq?.pkceOk && lastTokenReq?.redirect === env.OIDC_REDIRECT_URI);53 rec("customer gate: IAM sign-in creates NO session while trusted HTTPS is not attested", g.cb.status === 403 && !g.cookies.get("zcs_session"));54 await setS("security.dev_customer_ops", "1");55 // ---- new identity ----56 const a = await signIn({ sub: "alice-" + ts, email: `alice-${ts}@example.test`, emailVerified: true });57 const ua = (await q("SELECT u.id,u.platform_admin,u.email FROM external_identities e JOIN users u ON u.id=e.user_id WHERE e.issuer=$1 AND e.subject=$2", [ISS, "alice-" + ts]))[0]; created.users.push(ua?.id);58 rec("first login: session issued and redirected to the console", a.cb.status === 302 && !!a.cookies.get("zcs_session"));59 rec("new external identity: not a platform admin, no organization, placeholder e-mail (never the IdP address)", ua && ua.platform_admin === 0 && !/alice/.test(ua.email) && (await q("SELECT 1 FROM memberships WHERE user_id=$1", [ua.id])).length === 0);60 rec("identity without membership cannot reach any tenant API", (await call("/api/cloud/overview", { cookies: a.cookies })).status === 401);61 const a2 = await signIn({ sub: "alice-" + ts, email: `alice-${ts}@example.test`, emailVerified: true });62 rec("same (iss,sub) logs into the SAME user; no duplicate identity rows", (await q("SELECT count(*)::int n FROM external_identities WHERE issuer=$1 AND subject=$2", [ISS, "alice-" + ts]))[0].n === 1 && (await q("SELECT user_id FROM external_identities WHERE subject=$1", ["alice-" + ts]))[0].user_id === ua.id && a2.cb.status === 302);63 // ---- e-mail never links ----64 const F = "org_oidc" + ts; created.orgs.push(F);65 await owner.query("INSERT INTO organizations(id,slug,name,created_at) VALUES($1,$2,'OIDC fixture',$3)", [F, F.toLowerCase(), new Date().toISOString()]);66 const vid = "usr_victim" + ts; created.users.push(vid); await owner.query("INSERT INTO users(id,email,name,created_at) VALUES($1,$2,'victim',$3)", [vid, `victim-${ts}@example.test`, new Date().toISOString()]);67 await owner.query("INSERT INTO memberships(org_id,user_id,role,created_at) VALUES($1,$2,'owner',$3)", [F, vid, new Date().toISOString()]);68 const m = await signIn({ sub: "mallory-" + ts, email: `victim-${ts}@example.test`, emailVerified: true }); const um = (await q("SELECT user_id FROM external_identities WHERE subject=$1", ["mallory-" + ts]))[0]?.user_id; created.users.push(um);69 rec("an IdP identity claiming an existing user's e-mail is NOT linked to that account and gets no access to its organization", um && um !== vid && (await q("SELECT 1 FROM memberships WHERE user_id=$1", [um])).length === 0);70 // ---- invitations ----71 const mk = (e, role) => owner.query("INSERT INTO invitations(id,org_id,email,role,created_by,created_at,expires_at) VALUES($1,$2,$3,$4,'qa',$5,$6)", ["inv_" + crypto.randomBytes(6).toString("hex"), F, e, role, new Date().toISOString(), Date.now() + 3600_000]);72 await mk(`inv-${ts}@example.test`, "developer"); await mk(`unv-${ts}@example.test`, "admin");73 await signIn({ sub: "inv-" + ts, email: `inv-${ts}@example.test`, emailVerified: true }); const ui = (await q("SELECT user_id FROM external_identities WHERE subject=$1", ["inv-" + ts]))[0]?.user_id; created.users.push(ui);74 rec("invitation to a VERIFIED e-mail grants exactly the invited role in the inviting org only", (await q("SELECT role FROM memberships WHERE user_id=$1 AND org_id=$2", [ui, F]))[0]?.role === "developer" && (await q("SELECT count(*)::int n FROM memberships WHERE user_id=$1", [ui]))[0].n === 1);75 await signIn({ sub: "unv-" + ts, email: `unv-${ts}@example.test`, emailVerified: false }); const uu = (await q("SELECT user_id FROM external_identities WHERE subject=$1", ["unv-" + ts]))[0]?.user_id; created.users.push(uu);76 rec("invitation is NOT accepted for an UNVERIFIED e-mail", (await q("SELECT 1 FROM memberships WHERE user_id=$1", [uu])).length === 0);77 rec("no IAM-created user is ever a platform administrator", (await q("SELECT count(*)::int n FROM users u JOIN external_identities e ON e.user_id=u.id WHERE u.platform_admin<>0"))[0].n === 0);78 // ---- state / nonce / signature ----79 rec("replaying a consumed callback is refused (state is single use)", (await call(`/auth/callback?code=x&state=${a.state}`, { cookies: (() => { const c = jar(); c.m.set("zcs_oidc", a.state); return c; })() })).status === 400);80 const noCookie = await signIn({ sub: "nc-" + ts, email: "nc@example.test", dropCookie: true }); rec("callback without the browser-bound state cookie is refused (login CSRF)", noCookie.cb.status === 400);81 const wrongCookie = await signIn({ sub: "wc-" + ts, email: "wc@example.test", replayCookie: "attacker-state" }); rec("callback whose state does not match the cookie is refused", wrongCookie.cb.status === 400);82 const forged = await signIn({ sub: "fs-" + ts, email: "fs@example.test", tamper: "state" }); rec("forged state parameter is refused", forged.cb.status === 400);83 const badNonce = await signIn({ sub: "bn-" + ts, email: "bn@example.test", tamper: "nonce" }); rec("ID token with the wrong nonce is refused (no session)", badNonce.cb.status === 401 && !badNonce.cookies.get("zcs_session"));84 const badSig = await signIn({ sub: "sg-" + ts, email: "sg@example.test", key: evil.privateKey }); rec("ID token signed by an unknown key is refused (no session, no user)", badSig.cb.status === 401 && !badSig.cookies.get("zcs_session") && (await q("SELECT 1 FROM external_identities WHERE subject=$1", ["sg-" + ts])).length === 0);85 const badAud = await signIn({ sub: "au-" + ts, email: "au@example.test", claims: { aud: "zoo-connect" } }); rec("ID token for another client (audience) is refused", badAud.cb.status === 401);86 const expired = await signIn({ sub: "ex-" + ts, email: "ex@example.test", claims: { exp: Math.floor(Date.now() / 1000) - 600, iat: Math.floor(Date.now() / 1000) - 900 } }); rec("expired ID token is refused", expired.cb.status === 401);87 const badIss = await signIn({ sub: "bi-" + ts, email: "bi@example.test", claims: { iss: "https://evil.example/realms/zoo" } }); rec("ID token from a different issuer is refused", badIss.cb.status === 401);88 // ---- MFA / acr ----89 await setS("oidc.required_acr", "mfa");90 const noAcr = await signIn({ sub: "na-" + ts, email: "na@example.test" }); rec("MFA policy: a login without the required acr is refused", noAcr.cb.status === 401 && new URL(noAcr.login.headers.get("location")).searchParams.get("acr_values") === "mfa");91 const yesAcr = await signIn({ sub: "ya-" + ts, email: "ya@example.test", claims: { acr: "mfa" } }); created.users.push((await q("SELECT user_id FROM external_identities WHERE subject=$1", ["ya-" + ts]))[0]?.user_id); rec("MFA policy: a login asserting the required acr succeeds", yesAcr.cb.status === 302);92 await setS("oidc.required_acr", prev.acr);93 // ---- fixation ----94 await owner.query("INSERT INTO sessions(id,created_at,expires_at,user_id,org_id) VALUES('attacker-fixed',$1,$2,'usr_owner','org_owner')", [Date.now(), Date.now() + 600_000]);95 const fx = jar(); fx.m.set("zcs_session", "attacker-fixed"); const f = await signIn({ sub: "alice-" + ts, email: `alice-${ts}@example.test`, emailVerified: true, cookies: fx });96 rec("session fixation: the pre-login session id is destroyed and a NEW id is issued", (await q("SELECT 1 FROM sessions WHERE id='attacker-fixed'")).length === 0 && f.cookies.get("zcs_session") && f.cookies.get("zcs_session") !== "attacker-fixed" && f.cb.status === 302);97 rec("the session cookie is httpOnly, secure and SameSite", (await (async () => { const c = jar(); const s = await signIn({ sub: "alice-" + ts, email: `alice-${ts}@example.test`, emailVerified: true, cookies: c }); return (s.cb.headers.getSetCookie?.() ?? []).some(x => /zcs_session=/.test(x) && /httponly/i.test(x) && /secure/i.test(x) && /samesite=/i.test(x)); })()));98 // ---- back-channel logout ----99 const sessN = async () => (await q("SELECT count(*)::int n FROM sessions WHERE idp_iss=$1 AND idp_sid=$2", [ISS, "sid-alice-" + ts]))[0].n;100 const now = Math.floor(Date.now() / 1000); const LT = (c, key = good.privateKey) => sign({ iss: ISS, aud: "zoo-cloud-studio", iat: now, jti: crypto.randomUUID(), events: { "http://schemas.openid.net/event/backchannel-logout": {} }, ...c }, key);101 const post = tok => call("/auth/backchannel-logout", { method: "POST", body: new URLSearchParams({ logout_token: tok }), headers: { "content-type": "application/x-www-form-urlencoded" } });102 const before = await sessN();103 rec("back-channel logout: a forged token is refused and sessions survive", (await post(LT({ sid: "sid-alice-" + ts }, evil.privateKey))).status === 400 && (await sessN()) === before && before > 0);104 rec("back-channel logout: an ID token cannot be replayed as a logout token", (await post(sign({ iss: ISS, aud: "zoo-cloud-studio", sub: "alice-" + ts, exp: now + 60, iat: now, nonce: "n" }))).status === 400 && (await sessN()) === before);105 rec("back-channel logout: a valid token revokes every session of that IdP session", (await post(LT({ sid: "sid-alice-" + ts }))).status === 200 && (await sessN()) === 0);106 await signIn({ sub: "alice-" + ts, email: `alice-${ts}@example.test`, emailVerified: true }); const nb = (await q("SELECT count(*)::int n FROM sessions WHERE user_id=$1", [ua.id]))[0].n;107 rec("back-channel logout by subject revokes all sessions of that user", (await post(LT({ sub: "alice-" + ts }))).status === 200 && nb > 0 && (await q("SELECT count(*)::int n FROM sessions WHERE user_id=$1", [ua.id]))[0].n === 0);108 const aud = (await q("SELECT action FROM audit_log WHERE action LIKE 'auth.oidc.%' ORDER BY seq DESC LIMIT 200")).map(r => r.action);109 rec("OIDC events are audited (login, registered, failed, back-channel logout)", ["auth.oidc.login", "auth.oidc.registered", "auth.oidc.failed", "auth.oidc.backchannel_logout"].every(x => aud.includes(x)));110 await setS("security.dev_customer_ops", prev.dev);111} catch (e) { ok = false; console.error("TEST ERROR", e); rec("test harness completed without error", false, String(e.message)); }112finally {113 try { process.kill(-app.pid, "SIGTERM"); } catch {} idp.close();114 await owner.query("DELETE FROM sessions WHERE id='attacker-fixed' OR user_id = ANY($1)", [created.users.filter(Boolean)]).catch(() => {});115 await owner.query("DELETE FROM invitations WHERE org_id = ANY($1)", [created.orgs]).catch(() => {});116 await owner.query("DELETE FROM users WHERE id = ANY($1)", [created.users.filter(Boolean)]).catch(() => {});117 await owner.query("DELETE FROM users WHERE id IN (SELECT user_id FROM external_identities WHERE subject LIKE ANY($1))", [[ `%-${ts}` ]]).catch(() => {});118 await owner.query("DELETE FROM organizations WHERE id = ANY($1)", [created.orgs]).catch(() => {});119 await owner.query("DELETE FROM oidc_requests WHERE created_at > $1", [ts - 1000]).catch(() => {}); await owner.end();120}121122const f = results.filter(r => !r.ok); console.log(`\n${results.length - f.length}/${results.length} OIDC flow checks passed`);123fs.mkdirSync("../design/verification", { recursive: true }); fs.writeFileSync("../design/verification/oidc-flow.json", JSON.stringify({ at: new Date().toISOString(), scope: "test instance on loopback + mock IdP; NOT live Zoo IAM", total: results.length, passed: results.length - f.length, results }, null, 1));124process.exit(f.length ? 1 : 0);125
Conversation
PartialSign in to start AI sessions.
Task checklist
- Application shell deployed
- Persistent projects
- Agent runtime
- Sandboxed terminal
Execution activity
No agent sessions. Git HEAD 1c27633 on master.
Approval requests
None pending.