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/proxy.mjs
1// Reverse-proxy / domains suite. HONEST SCOPE: Caddy is NOT installed on this host, so the agent is driven against a STUB `caddy` (validate/reload exit codes + an admin endpoint)2// to verify the agent's validate -> reload -> health-check -> rollback logic. Real certificate issuance and real Caddy behaviour are UNVERIFIED. DNS positive verification is3// unit-tested (pure evaluator); live DNS is only exercised for the negative path because no customer domain is under our control.4import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import crypto from "node:crypto"; import http from "node:http"; import { spawn, spawnSync } from "node:child_process"; import { fileURLToPath } from "node:url";5import { chromium, request } from "playwright"; import pg from "pg";6import { checkHostname, dnsInstructions, evaluateDns, renderCaddyfile } from "../src/lib/proxy-core.mjs";7const here = path.dirname(fileURLToPath(import.meta.url)); const ROOT = path.resolve(here, "../.."); const BASE = process.argv[2] || "https://127.0.0.1:8443"; const O = { origin: BASE };8const TOKEN = fs.readFileSync(path.join(os.homedir(), ".config/zoo-cloud-studio/admin-token"), "utf8").trim();9const results = []; const rec = (n, ok, d = "") => { results.push({ n, ok: !!ok }); console.log(`${ok ? "PASS" : "FAIL"} ${n}${d ? " — " + d : ""}`); };10const sleep = ms => new Promise(r => setTimeout(r, ms)); const ts = Date.now(); const J = async r => r.json().catch(() => ({}));11const pw = fs.readFileSync(path.join(os.homedir(), ".config/zoo-cloud-studio/pg-password"), "utf8").trim(); const pool = new pg.Pool({ connectionString: `postgres://studio:${encodeURIComponent(pw)}@127.0.0.1:5432/studio`, max: 3 }); const q = async (t, p) => (await pool.query(t, p)).rows;12const ctxOf = () => request.newContext({ baseURL: BASE, ignoreHTTPSErrors: true });13async function login(c, token) { for (let i = 0; i < 8; i++) { const r = await c.post("/api/auth/login", { data: { token }, headers: O }); if (r.status() !== 429) return r; await sleep(15000); } throw new Error("rate-limited"); }14const fp = new crypto.X509Certificate(fs.readFileSync(path.join(os.homedir(), ".config/zoo-cloud-studio/tls/cert.pem"))).fingerprint256.replace(/:/g, "");15const AGENT = path.join(ROOT, "agent/zoo-cloud-agent.mjs"); const post = (c, u, b) => c.post(u, { data: b, headers: O });16const get = async (url, ms = 3000) => { try { const r = await fetch(url, { signal: AbortSignal.timeout(ms) }); return { s: r.status, t: await r.text() }; } catch (e) { return { s: 0, t: "" }; } };17async function until(fn, ms = 60000, step = 700) { const end = Date.now() + ms; while (Date.now() < end) { const v = await fn(); if (v) return v; await sleep(step); } return null; }18// ---------- unit: pure logic ----------19rec("hostnames: valid accepted, invalid/IP/internal/wildcard/scheme/port rejected", checkHostname("App.Example.com").hostname === "app.example.com" && ["http://a.example.com", "a.example.com:8080", "*.example.com", "1.2.3.4", "intranet.local", "nodot", "a_b.example.com", "x.example.com/path"].every(h => !checkHostname(h).ok));20rec("hostnames: platform and third-party domains cannot be connected (cloud.zoobd.com, zloud.io, gpt.com)", ["cloud.zoobd.com", "zoobd.com", "x.zloud.io", "cloud.gpt.com"].every(h => !checkHostname(h).ok));21const iA = dnsInstructions("app.example.com", "zlv_x", "203.0.113.7"), iC = dnsInstructions("app.example.com", "zlv_x", "vps.example.net"), iAp = dnsInstructions("example.com", "zlv_x", "vps.example.net"), iN = dnsInstructions("a.example.com", "t", null);22rec("DNS instructions derive from the real target: A for an IP, CNAME for a hostname, A for an apex, TXT ownership record always, clear note when no address known", iA.records[0].type === "A" && iA.records[0].value === "203.0.113.7" && iC.records[0].type === "CNAME" && iAp.records[0].type === "A" && iA.records[1].type === "TXT" && iA.records[1].name === "_zloud-verify.app.example.com" && iN.records.length === 0 && /public-host/.test(iN.note));23const e1 = evaluateDns({ txt: ["zlv_x"], a: ["203.0.113.7"] }, "zlv_x", "203.0.113.7"), e2 = evaluateDns({ txt: ["other"], a: ["203.0.113.7"] }, "zlv_x", "203.0.113.7"), e3 = evaluateDns({ txt: ["zlv_x"], a: ["198.51.100.1"] }, "zlv_x", "203.0.113.7"), e4 = evaluateDns({ txt: ["zlv_x"], cname: ["VPS.example.net."] }, "zlv_x", "vps.example.net"), e5 = evaluateDns({ txt: ["zlv_x"] }, "zlv_x", "203.0.113.7");24rec("DNS evaluation: ownership needs the exact TXT token; routing needs the target; wrong target and missing records are distinguished (positive path is unit-level)", e1.dns === "ok" && !e2.owned && e2.dns === "ownership-not-proven" && e3.dns === "wrong-target" && e4.dns === "ok" && e5.dns === "no-route-record");25let bad = 0; for (const s of [[{ hostname: "a.example.com", port: 22 }], [{ hostname: "a.example.com", port: 5432 }], [{ hostname: "a.example.com", port: 19999 }], [{ hostname: "bad host", port: 20000 }], [{ hostname: "a.example.com", redirectTo: "x y" }]]) { try { renderCaddyfile(s); } catch { bad++; } }26rec("renderer: databases/admin/system ports, out-of-range ports, malformed hosts and redirect targets are refused (never publicly routed)", bad === 5);27// ---------- fixtures ----------28const homes = []; const created = { orgs: [], users: [] }; let agentProc = null, adminSrv = null; const D = fs.mkdtempSync(path.join(os.tmpdir(), "zcs-px-")); homes.push(D);29const owner = await ctxOf(); await login(owner, TOKEN); const mode0 = (await J(await owner.get("/api/super"))).security.mode;30const mk = async l => { const email = `qa-${l.toLowerCase()}-${ts}@example.test`; const r = await J(await owner.post("/api/super", { data: { action: "createOrg", name: `QA-T${l} ${ts}`, ownerEmail: email, ownerName: `Owner ${l}` }, headers: O })); created.orgs.push(r.id); created.users.push(r.ownerId); return { ...r, org: r.id }; };31const TA = await mk("A"), TB = await mk("B"); await owner.post("/api/super", { data: { action: "security", devCustomerOps: true, confirm: "ENABLE DEV CUSTOMER OPS" }, headers: O });32const A = await ctxOf(), B = await ctxOf(); await login(A, TA.token); await login(B, TB.token);33const stubDir = path.join(D, "bin"); fs.mkdirSync(stubDir); const log = path.join(D, "caddy.log"); const ADMINPORT = 29555;34fs.writeFileSync(path.join(stubDir, "caddy"), `#!/bin/sh\necho "$@" >> "${log}"\ncase "$1" in\n version) echo v2.8.4-stub;;\n validate) [ -f "${D}/fail-validate" ] && { echo "stub: invalid config" >&2; exit 1; }; exit 0;;\n reload) [ -f "${D}/fail-reload" ] && { echo "stub: reload refused" >&2; exit 1; }; cp "$3" "${D}/active.caddyfile"; exit 0;;\nesac\n`, { mode: 0o755 });35adminSrv = http.createServer((q2, s) => { s.writeHead(200); s.end("{}"); }).listen(ADMINPORT, "127.0.0.1");36const AGENVS = { ...process.env, ZOO_AGENT_HOME: D + "/home", PATH: `${stubDir}:${process.env.PATH}`, ZOO_CADDY_ADMIN: `127.0.0.1:${ADMINPORT}`, ZOO_PROXY_HTTPS_PORT: "29443" };37const run = async () => {38 const iA2 = await J(await post(A, "/api/cloud/instances", { name: "px-ext", target: "external" })); const eA = await J(await post(A, "/api/cloud/servers", { action: "enroll", instanceId: iA2.id, label: "px-vps" }));39 const en = spawnSync(process.execPath, [AGENT, "enroll", "--url", BASE, "--token", eA.token, "--pin", fp, "--public-host", "203.0.113.7"], { env: AGENVS, encoding: "utf8" }); rec("agent 0.3.0 enrols with a public address", en.status === 0, en.stderr);40 agentProc = spawn(process.execPath, [AGENT, "run"], { env: AGENVS, stdio: "ignore" }); const nodeA = eA.id; await until(async () => (await post(A, "/api/cloud/servers", { action: "authorize", nodeId: nodeA })).ok(), 30000);41 const on = await until(async () => (await J(await A.get("/api/cloud/domains"))).servers?.find(s => s.id === nodeA && s.state === "online" && s.caddy), 40000); rec("node reports the proxy (Caddy) as installed via capabilities", !!on);42 const dep = await J(await post(A, "/api/cloud/apps", { action: "deploy", nodeId: nodeA, template: "static-site", name: "px-site", params: { html: "<h1>px</h1>" } })); const up = await until(async () => (await J(await A.get("/api/cloud/apps"))).deployments.find(x => x.id === dep.id && x.status === "running"), 60000);43 const dep2 = await J(await post(A, "/api/cloud/apps", { action: "deploy", nodeId: nodeA, template: "static-site", name: "px-site2", params: { html: "<h1>px2</h1>" } })); await until(async () => (await J(await A.get("/api/cloud/apps"))).deployments.find(x => x.id === dep2.id && x.status === "running"), 60000);44 rec("two websites run on one VPS on different internal ports (multi-site port conflict avoided)", !!up && dep.port !== dep2.port && dep.port >= 20000);45 const H1 = `www-${ts}.example.org`, H2 = `shop-${ts}.example.org`;46 // ---- API: add / validation / tenancy ----47 const add = await post(A, "/api/cloud/domains", { action: "add", hostname: H1, nodeId: nodeA, deploymentId: dep.id }); const aj = await J(add); const dA = aj.id;48 rec("domain: add returns accurate DNS records derived from the server's public address", add.status() === 201 && aj.instructions.records[0].type === "A" && aj.instructions.records[0].value === "203.0.113.7" && aj.instructions.records[1].type === "TXT" && /^zlv_[0-9a-f]{32}$/.test(aj.instructions.records[1].value));49 rec("domain: platform domains, IPs and bad names refused (422)", (await post(A, "/api/cloud/domains", { action: "add", hostname: "cloud.zoobd.com", nodeId: nodeA })).status() === 422 && (await post(A, "/api/cloud/domains", { action: "add", hostname: "10.0.0.1", nodeId: nodeA })).status() === 422);50 rec("domain: the same hostname cannot be connected twice or by another tenant (409, no owner disclosed)", (await post(A, "/api/cloud/domains", { action: "add", hostname: H1, nodeId: nodeA })).status() === 409);51 const iB = await J(await post(B, "/api/cloud/instances", { name: "pxb", target: "external" })); const eB = await J(await post(B, "/api/cloud/servers", { action: "enroll", instanceId: iB.id, label: "pxb-vps" })); const hB = path.join(D, "homeB");52 spawnSync(process.execPath, [AGENT, "enroll", "--url", BASE, "--token", eB.token, "--pin", fp, "--public-host", "203.0.113.9"], { env: { ...AGENVS, ZOO_AGENT_HOME: hB }, encoding: "utf8" });53 const bDup = await post(B, "/api/cloud/domains", { action: "add", hostname: H1, nodeId: eB.id }); rec("wrong tenant: B cannot claim A's hostname (409) and cannot attach to A's node (404)", bDup.status() === 409 && !(await bDup.text()).includes(TA.org) && (await post(B, "/api/cloud/domains", { action: "add", hostname: `b-${ts}.example.org`, nodeId: nodeA })).status() === 404);54 rec("wrong tenant: B cannot see, verify, map, apply or remove A's domain", !JSON.stringify(await J(await B.get("/api/cloud/domains"))).includes(H1) && (await post(B, "/api/cloud/domains", { action: "verify", id: dA })).status() === 404 && (await post(B, "/api/cloud/domains", { action: "remove", id: dA })).status() === 404 && (await post(B, "/api/cloud/domains", { action: "apply", nodeId: nodeA })).status() === 404);55 const vf = await J(await post(A, "/api/cloud/domains", { action: "verify", id: dA })); rec("verification (LIVE DNS, negative path): an unconfigured domain is NOT verified", vf.ok && vf.owned === false && vf.dns === "ownership-not-proven");56 const ap0 = await J(await post(A, "/api/cloud/domains", { action: "apply", nodeId: nodeA })); await until(async () => (await q("SELECT status FROM node_jobs WHERE id=$1", [ap0.jobId]))[0]?.status === "done", 30000);57 rec("unverified domains are never applied to the proxy (empty site list)", ap0.sites === 0 && !fs.existsSync(path.join(D, "active.caddyfile")) || !/example\.org/.test(fs.readFileSync(path.join(D, "active.caddyfile"), "utf8")));58 // positive DNS path is simulated through the database (no control of any customer domain): marked as simulated59 await q("UPDATE domains SET status='verified', dns_status='ok', verified_at=$2 WHERE id=$1", [dA, new Date().toISOString()]);60 const sites1 = [{ hostname: H1, port: dep.port, deploymentId: dep.id }]; const fx = path.join(D, "sites.json"); fs.writeFileSync(fx, JSON.stringify([...sites1, { hostname: H2, redirectTo: H1 }]));61 const rc = spawnSync(process.execPath, [AGENT, "proxy-render", "--sites", fx], { encoding: "utf8" }).stdout; rec("agent and control plane render byte-identical Caddyfiles", rc.trimEnd() === renderCaddyfile([...sites1, { hostname: H2, redirectTo: H1 }]).trimEnd());62 const ap1 = await J(await post(A, "/api/cloud/domains", { action: "apply", nodeId: nodeA })); const j1 = await until(async () => { const r = (await q("SELECT status,result,log FROM node_jobs WHERE id=$1", [ap1.jobId]))[0]; return r?.status === "done" ? r : null; }, 40000);63 const act = fs.existsSync(path.join(D, "active.caddyfile")) ? fs.readFileSync(path.join(D, "active.caddyfile"), "utf8") : ""; const res1 = JSON.parse(j1?.result ?? "{}");64 rec("apply: config validated, reloaded safely, active config routes the hostname to the internal port", res1.ok === true && act.includes(`${H1} {`) && act.includes(`reverse_proxy 127.0.0.1:${dep.port}`) && /validate/.test(fs.readFileSync(log, "utf8")) && /reloaded safely/.test(j1.log));65 await until(async () => (await q("SELECT proxy_status FROM domains WHERE id=$1", [dA]))[0].proxy_status === "applied", 8000, 300); const row = (await q("SELECT proxy_status,tls_status FROM domains WHERE id=$1", [dA]))[0]; rec("apply: status recorded; certificate honestly reported as pending (no live Caddy/ACME here)", row.proxy_status === "applied" && row.tls_status === "pending", JSON.stringify(row) + " " + j1?.result);66 const before = fs.readFileSync(path.join(D, "home/proxy/Caddyfile"), "utf8");67 // ---- failure + rollback ----68 fs.writeFileSync(path.join(D, "fail-validate"), ""); await post(A, "/api/cloud/domains", { action: "map", id: dA, deploymentId: dep.id }); await q("UPDATE domains SET status='verified' WHERE id=$1", [dA]); const apv = await J(await post(A, "/api/cloud/domains", { action: "apply", nodeId: nodeA })); const jv = await until(async () => { const r = (await q("SELECT status,result,log FROM node_jobs WHERE id=$1", [apv.jobId]))[0]; return r?.status === "done" ? r : null; }, 40000);69 rec("safe reload: a configuration that fails validation is rejected and the active configuration is untouched", JSON.parse(jv?.result ?? "{}").ok === false && /REJECTED/.test(jv.log) && fs.readFileSync(path.join(D, "home/proxy/Caddyfile"), "utf8") === before); fs.rmSync(path.join(D, "fail-validate"));70 fs.writeFileSync(path.join(D, "fail-reload"), ""); const arl = await J(await post(A, "/api/cloud/domains", { action: "apply", nodeId: nodeA })); const jr = await until(async () => { const r = (await q("SELECT status,result,log FROM node_jobs WHERE id=$1", [arl.jobId]))[0]; return r?.status === "done" ? r : null; }, 40000); fs.rmSync(path.join(D, "fail-reload"));71 rec("rollback: when the reload fails the previous configuration file is restored", JSON.parse(jr?.result ?? "{}").reverted === true && /previous configuration restored/.test(jr.log) && fs.readFileSync(path.join(D, "home/proxy/Caddyfile"), "utf8") === before);72 const stA = JSON.parse(fs.readFileSync(path.join(D, "home/apps", dep.id, "state.json"), "utf8")); try { process.kill(-stA.pid, "SIGKILL"); } catch {} await sleep(800);73 await q("UPDATE app_deployments SET status='running' WHERE id=$1", [dep.id]); const ah = await J(await post(A, "/api/cloud/domains", { action: "apply", nodeId: nodeA })); const jh = await until(async () => { const r = (await q("SELECT status,result,log FROM node_jobs WHERE id=$1", [ah.jobId]))[0]; return r?.status === "done" ? r : null; }, 40000);74 rec("health check: if the upstream application is down the new configuration is rolled back", JSON.parse(jh?.result ?? "{}").reverted === true && /health check of/.test(jh.log) && fs.readFileSync(path.join(D, "home/proxy/Caddyfile"), "utf8") === before);75 // ---- agent refuses unmanaged upstreams (defence in depth against a forged job) ----76 const jid = `job_px${ts}`; await q("INSERT INTO node_jobs(id,org_id,node_id,kind,payload,status,created_at) VALUES($1,$2,$3,'proxy.apply',$4,'queued',$5)", [jid, TA.org, nodeA, JSON.stringify({ sites: [{ hostname: H1, port: 22, deploymentId: dep.id }] }), new Date().toISOString()]);77 const jf = await until(async () => { const r = (await q("SELECT status,result,log FROM node_jobs WHERE id=$1", [jid]))[0]; return r?.status === "done" ? r : null; }, 40000); rec("agent refuses to route a hostname to an unmanaged port (22) even if the control plane asks", /not a managed application/.test(jf?.log ?? "") && JSON.parse(jf?.result ?? "{}").ok === false);78 // ---- second site, primary, redirect ----79 const dB = (await J(await post(A, "/api/cloud/domains", { action: "add", hostname: H2, nodeId: nodeA, deploymentId: dep.id }))).id; await q("UPDATE domains SET status='verified' WHERE id=$1", [dB]);80 await q("UPDATE app_deployments SET status='stopped' WHERE id=$1", [dep.id]); const stopped = await J(await post(A, "/api/cloud/domains", { action: "apply", nodeId: nodeA })); await until(async () => (await q("SELECT status FROM node_jobs WHERE id=$1", [stopped.jobId]))[0]?.status === "done", 30000);81 rec("a domain mapped to a stopped application is skipped with an explanation, not routed", (stopped.skipped ?? []).some(s => /not running/.test(s)));82 await post(A, "/api/cloud/apps", { action: "start", deploymentId: dep.id }); await until(async () => (await J(await A.get("/api/cloud/apps"))).deployments.find(x => x.id === dep.id && x.status === "running"), 60000, 1000);83 rec("primary domain and redirect: only a verified primary can be a redirect target", (await post(A, "/api/cloud/domains", { action: "redirect", id: dB })).status() === 409 && (await post(A, "/api/cloud/domains", { action: "primary", id: dA })).ok() && (await post(A, "/api/cloud/domains", { action: "redirect", id: dB })).ok());84 const prev = (await J(await A.get("/api/cloud/domains"))).preview[nodeA]; rec("preview shows redirect site + proxied site (no port visible to visitors)", prev.includes(`redir https://${H1}{uri} permanent`) && prev.includes(`${H1} {`) && !/:\d{2,5} \{/.test(prev));85 // ---- remove ----86 rec("remove: viewer-level cannot remove; admin owner can; domain disappears", (await post(A, "/api/cloud/domains", { action: "remove", id: dB })).ok() && !JSON.stringify(await J(await A.get("/api/cloud/domains"))).includes(H2));87 // ---- UI ----88 try { process.env.LD_LIBRARY_PATH = `${os.homedir()}/.local/chromelibs/usr/lib/x86_64-linux-gnu`; const br = await chromium.launch(); const st = await A.storageState();89 for (const [nm, vp] of [["desktop", { width: 1366, height: 900 }], ["mobile", { width: 390, height: 844 }]]) { const c = await br.newContext({ viewport: vp, ignoreHTTPSErrors: true, storageState: st }); const pg2 = await c.newPage(); await pg2.goto(`${BASE}/console/domains`); await pg2.locator('section[aria-label="Domains"]').waitFor({ timeout: 15000 }); await pg2.getByText(H1).first().waitFor({ timeout: 10000 });90 const over = await pg2.evaluate(() => document.documentElement.scrollWidth > innerWidth + 1); rec(`ui: domains dashboard at ${nm} shows DNS records, status and controls without horizontal overflow`, !over && await pg2.getByText("_zloud-verify").first().isVisible()); await pg2.screenshot({ path: path.join(ROOT, `design/screenshots/customer-domains-${nm}.png`), fullPage: true }); await c.close(); } await br.close(); } catch (e) { rec("ui: domains screenshots", false, e.message.slice(0, 160)); }91};92try { await run(); } catch (e) { rec("flow aborted", false, String(e.stack ?? e).slice(0, 400)); }93try { agentProc?.kill("SIGKILL"); } catch {} adminSrv?.close();94try { for (const h of [path.join(D, "home"), path.join(D, "homeB")]) for (const a of fs.existsSync(path.join(h, "apps")) ? fs.readdirSync(path.join(h, "apps")) : []) { try { { const pid = JSON.parse(fs.readFileSync(path.join(h, "apps", a, "state.json"), "utf8")).pid; if (pid > 0) process.kill(-pid, "SIGKILL"); }; } catch {} }95 for (const t of ["domains", "app_releases", "app_deployments", "node_jobs", "usage_records"]) await q(`DELETE FROM ${t} WHERE org_id = ANY($1)`, [created.orgs]); await q("DELETE FROM sessions WHERE org_id = ANY($1) OR user_id = ANY($2)", [created.orgs, created.users]); await q("DELETE FROM organizations WHERE id = ANY($1)", [created.orgs]); await q("DELETE FROM users WHERE id = ANY($1)", [created.users]); for (const h of homes) fs.rmSync(h, { recursive: true, force: true });96 rec("cleanup: fixtures and app processes removed", Number((await q("SELECT COUNT(*) n FROM organizations WHERE name LIKE $1", [`QA-T% ${ts}`]))[0].n) === 0); } catch (e) { rec("cleanup", false, String(e.message)); }97await owner.post("/api/super", { data: { action: "security", devCustomerOps: false, trustedTls: false }, headers: O }); if (mode0 === "trusted-tls") await owner.post("/api/super", { data: { action: "security", trustedTls: true, confirm: "I ATTEST TRUSTED TLS" }, headers: O });98rec("customer gate restored to CLOSED", (await J(await owner.get("/api/super"))).security.mode === mode0);99await owner.post("/api/design/rebuild", { headers: O }); await pool.end(); const f = results.filter(r => !r.ok).length; console.log(`\n${results.length - f}/${results.length} proxy checks passed (stub Caddy; real Caddy/ACME unverified)`);100fs.writeFileSync(path.join(ROOT, "design/verification/proxy.json"), JSON.stringify({ finished: new Date().toISOString(), scope: "stub caddy; positive DNS simulated; NOT live Caddy/ACME; NOT independent VPS", passed: results.length - f, failed: f, results }, null, 2)); process.exit(f ? 1 : 0);101
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 692573d on master.
Approval requests
None pending.