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-only- ..
- apple-touch-icon.png
- brand-guidelines-v2.md
- brand-manifest-v2.json
- favicon-16.png
- favicon-32.png
- favicon-48.png
- favicon.ico
- icon-192.png
- icon-512.png
- maskable-192.png
- maskable-512.png
- source-brand-board.png
- source-crop-icon-fullcolor.png
- source-crop-lockup-dark.png
- source-crop-wordmark-light.png
- zloud-app-icon-1024.png
- zloud-app-icon.svg
- zloud-favicon.svg
- zloud-mark-1024.png
- zloud-mark-512.png
- zloud-mark-mono-512.png
- zloud-mark-mono.svg
- zloud-mark-reversed.svg
- zloud-mark-white-512.png
- zloud-mark-white.svg
- zloud-mark.svg
- zloud-maskable.svg
- zloud-wordmark-dark.svg
- zloud-wordmark-light.svg
- zloud-wordmark-mono.svg
app/qa/tenant-isolation.mjs
1// Tenant isolation, RBAC, agent enrollment and gate verification against the live HTTPS edge.2// Creates two customer tenants (A, B) via the Super Admin API, drives the REAL agent binary as a subprocess, then removes ONLY the fixtures it created.3// Honest scope: the agent runs on this same host. This is NOT verification on a separate, independent server.4import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import crypto from "node:crypto"; import { spawnSync } from "node:child_process"; import { fileURLToPath } from "node:url";5import { chromium, request } from "playwright"; import pg from "pg";6const 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 };7const TOKEN = fs.readFileSync(path.join(os.homedir(), ".config/zoo-cloud-studio/admin-token"), "utf8").trim();8const SHOTS = path.join(ROOT, "design/screenshots"); fs.mkdirSync(SHOTS, { recursive: true });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();11const pw = fs.readFileSync(path.join(os.homedir(), ".config/zoo-cloud-studio/pg-password"), "utf8").trim();12const pool = new pg.Pool({ connectionString: `postgres://studio:${encodeURIComponent(pw)}@127.0.0.1:5432/studio`, max: 3 });13const q = async (t, p) => (await pool.query(t, p)).rows;14const ctxOf = async () => request.newContext({ baseURL: BASE, ignoreHTTPSErrors: true });15async 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("login rate-limited"); }16const J = async r => r.json().catch(() => ({}));17const fp = new crypto.X509Certificate(fs.readFileSync(path.join(os.homedir(), ".config/zoo-cloud-studio/tls/cert.pem"))).fingerprint256.replace(/:/g, "");18const AGENT = path.join(ROOT, "agent/zoo-cloud-agent.mjs");19const agent = (home, args) => spawnSync(process.execPath, [AGENT, ...args], { env: { ...process.env, ZOO_AGENT_HOME: home }, encoding: "utf8", timeout: 40000 });20const created = { orgs: [], users: [], projects: [] }; const homes = [];21const prevSecurity = {};2223// ---------------- setup ----------------24const owner = await ctxOf(); await login(owner, TOKEN);25const sec0 = (await J(await owner.get("/api/super"))).security; prevSecurity.mode = sec0.mode;26// gate must be CLOSED by default: a customer token cannot sign in until trusted HTTPS (or the explicit dev override) exists27await owner.post("/api/super", { data: { action: "security", trustedTls: false, devCustomerOps: false }, headers: O });28const mk = async (label) => { const email = `qa-${label.toLowerCase()}-${ts}@example.test`; const r = await J(await owner.post("/api/super", { data: { action: "createOrg", name: `QA-T${label} ${ts}`, ownerEmail: email, ownerName: `Owner ${label}` }, headers: O })); created.orgs.push(r.id); created.users.push(r.ownerId); return { org: r.id, token: r.token, email, ownerId: r.ownerId }; };29const TA = await mk("A"), TB = await mk("B");30rec("setup: two customer tenants created by the platform admin (token shown once)", /^org_/.test(TA.org) && /^org_/.test(TB.org) && /^zcu_/.test(TA.token ?? ""));31const gate = await ctxOf(); const gl = await login(gate, TA.token);32rec("gate: customer sign-in REFUSED while trusted HTTPS is not attested (default)", gl.status() === 403 && /trusted HTTPS/i.test((await J(gl)).error ?? ""));33const ownerStillIn = await owner.get("/api/cloud/overview"); rec("gate: platform owner is unaffected by the customer gate", ownerStillIn.ok());34await gate.dispose();35rec("gate: dev override requires the typed phrase", (await owner.post("/api/super", { data: { action: "security", devCustomerOps: true }, headers: O })).status() === 400);36await owner.post("/api/super", { data: { action: "security", devCustomerOps: true, confirm: "ENABLE DEV CUSTOMER OPS" }, headers: O });37const A = await ctxOf(), B = await ctxOf(); const la = await login(A, TA.token), lb = await login(B, TB.token);38rec("gate: with the dev override on, each tenant owner signs in", la.ok() && lb.ok());39const nobody = await ctxOf();40const post = (c, u, b) => c.post(u, { data: b, headers: O }); const put = (c, u, b) => c.put(u, { data: b, headers: O }); const patch = (c, u, b) => c.patch(u, { data: b, headers: O });4142// ---------------- tenant A resources ----------------43const iA = await J(await post(A, "/api/cloud/instances", { name: "a-prod", target: "external" })); const iAm = await J(await post(A, "/api/cloud/instances", { name: "a-managed", target: "managed" }));44const pA = (await J(await post(A, "/api/projects", { name: "A secret project" }))).id; created.projects.push(pA);45await put(A, `/api/workspace/${pA}/files`, { path: "secrets.txt", content: "tenant-A-confidential-content" });46const sA = (await J(await post(A, "/api/ai/sessions", { provider: "mock", model: "mock-1", budget_usd: 1, title: "A chat", project_id: pA }))).id;47await post(A, `/api/ai/sessions/${sA}/messages`, { content: "A private prompt TENANT-A-PROMPT" });48for (let i = 0; i < 30; i++) { const s = await J(await A.get(`/api/ai/sessions/${sA}`)); if (s.runs?.[0]?.status === "succeeded") break; await sleep(500); }49const pB = (await J(await post(B, "/api/projects", { name: "B project" }))).id; created.projects.push(pB);50const iB = await J(await post(B, "/api/cloud/instances", { name: "b-prod", target: "external" }));51// provider credential for A (dummy ciphertext inserted directly: no external network call is made with a fake key)52await pool.query("INSERT INTO credentials(id,provider,ciphertext,iv,tag,hint,status,updated_at,org_id) VALUES($1,'anthropic','AAAA','AAAA','AAAA','sk-a…zzzz','verified',$2,$3) ON CONFLICT DO NOTHING", [`cred_${TA.org}_anthropic`, new Date().toISOString(), TA.org]);53rec("A resources created (instance, managed instance, project, file, AI session with reply)", !!iA.id && !!iAm.id && !!pA && !!sA);5455// ---------------- cross-tenant denial: B using A's ids ----------------56const proj = await J(await B.get("/api/projects")); rec("isolation: B's project list excludes A's project", !proj.projects.some(p => p.id === pA) && proj.projects.some(p => p.id === pB));57rec("isolation: B cannot PATCH A's project (404, existence not leaked)", (await patch(B, `/api/projects/${pA}`, { name: "hijack" })).status() === 404);58rec("isolation: B cannot add tasks/milestones to A's project", (await post(B, `/api/projects/${pA}/tasks`, { title: "x" })).status() === 404 && (await post(B, `/api/projects/${pA}/milestones`, { title: "x" })).status() === 404);59rec("isolation: B cannot read A's workspace file", (await B.get(`/api/workspace/${pA}/files?file=secrets.txt`)).status() === 404 && !(await (await B.get(`/api/workspace/${pA}/files`)).text()).includes("secrets.txt"));60rec("isolation: B cannot write/upload/git in A's workspace", (await put(B, `/api/workspace/${pA}/files`, { path: "x.txt", content: "x" })).status() === 404 && (await post(B, `/api/workspace/${pA}/git`, { op: "status" })).status() === 404 && (await B.post(`/api/workspace/${pA}/upload`, { headers: O, multipart: { dir: "", file: { name: "n.txt", mimeType: "text/plain", buffer: Buffer.from("x") } } })).status() === 404);61rec("isolation: workspace path traversal into another tenant's directory rejected", [400, 403, 404].includes((await put(B, `/api/workspace/${pB}/files`, { path: `../${pA}/secrets.txt`, content: "x" })).status()));62rec("isolation: A's file content never changed", fs.readFileSync(path.join(ROOT, "app/data/workspaces", pA, "secrets.txt"), "utf8") === "tenant-A-confidential-content");63rec("isolation: B's AI session list excludes A's", !(await J(await B.get("/api/ai/sessions"))).some?.(s => s.id === sA) );64rec("isolation: B cannot read/message/control/stream A's AI session", (await B.get(`/api/ai/sessions/${sA}`)).status() === 404 && (await post(B, `/api/ai/sessions/${sA}/messages`, { content: "x" })).status() === 404 && (await post(B, `/api/ai/sessions/${sA}/control`, { action: "cancel" })).status() === 404);65const sse = await B.get(`/api/ai/sessions/${sA}/stream`, { timeout: 8000 }).catch(() => null); rec("isolation: B cannot subscribe to A's event stream (SSE 404)", sse?.status() === 404);66rec("isolation: B cannot create an AI session in A's project", (await post(B, "/api/ai/sessions", { provider: "mock", model: "mock-1", budget_usd: 1, project_id: pA })).status() === 404);67rec("isolation: B cannot modify/see A's instances", (await patch(B, `/api/cloud/instances/${iA.id}`, { status: "active" })).status() === 404 && !(await (await B.get("/api/cloud/instances")).text()).includes(iA.id));68rec("isolation: B cannot request provisioning or enroll against A's instances", (await post(B, "/api/cloud/provision", { instanceId: iAm.id, planId: "x" })).status() === 404 && (await post(B, "/api/cloud/servers", { action: "enroll", instanceId: iA.id, label: "evil-node" })).status() === 404);69const tm = await J(await B.get("/api/cloud/team")); rec("isolation: B's team list shows only B members", tm.members.length === 1 && tm.members[0].email === TB.email);70rec("isolation: B cannot change A's member role (membership is org-scoped)", (await patch(B, "/api/cloud/team", { userId: TA.ownerId, role: "viewer" })).status() === 404);71rec("isolation: B cannot switch into A's organization", (await post(B, "/api/cloud/org", { orgId: TA.org })).status() === 403);72rec("isolation: client-supplied org ids are ignored (no orgId parameter exists on tenant APIs)", (await post(B, "/api/projects", { name: "spoof", org_id: TA.org, orgId: TA.org })).ok() && (await q("SELECT org_id FROM projects WHERE name='spoof' ORDER BY created_at DESC LIMIT 1"))[0].org_id === TB.org);73await q("DELETE FROM projects WHERE name='spoof'");74// credentials75const intB = await (await B.get("/integrations")).text(); rec("credentials: B's integrations page shows nothing of A's key", !intB.includes("sk-a…zzzz"));76rec("credentials: A's integrations page shows A's key hint", (await (await A.get("/integrations")).text()).includes("sk-a…zzzz"));77await B.delete("/api/integrations/anthropic", { headers: O }); rec("credentials: B deleting 'anthropic' cannot remove A's credential", Number((await q("SELECT COUNT(*) n FROM credentials WHERE org_id=$1 AND provider='anthropic'", [TA.org]))[0].n) === 1);78const sB = (await J(await post(B, "/api/ai/sessions", { provider: "anthropic", model: "claude-haiku-5-5", budget_usd: 1 }))).id;79const noKey = await post(B, `/api/ai/sessions/${sB}/messages`, { content: "hi" }); rec("credentials: B's real-provider session reports 'awaiting credentials' despite A having a key", noKey.status() === 409 && /Awaiting credentials/.test((await J(noKey)).error));80// worker routing: force a run for B's anthropic session straight into the queue; the worker must NOT use A's credential81const runB = `run_iso_${ts}`; await pool.query("INSERT INTO ai_messages(session_id,role,content,created_at) VALUES($1,'user','route test',$2)", [sB, new Date().toISOString()]); await pool.query("INSERT INTO ai_runs(id,session_id,created_at,updated_at) VALUES($1,$2,$3,$3)", [runB, sB, new Date().toISOString()]);82let rb = null; for (let i = 0; i < 30; i++) { rb = (await q("SELECT status,error FROM ai_runs WHERE id=$1", [runB]))[0]; if (rb.status === "failed") break; await sleep(500); }83rec("job routing: worker refuses to run B's job with A's credential (own-org key only)", rb?.status === "failed" && /Awaiting credentials/.test(rb.error ?? ""), rb?.error);84// usage + spending limits85const uA = await J(await A.get("/api/cloud/usage")), uB = await J(await B.get("/api/cloud/usage"));86rec("usage: A's AI usage recorded under A only; B's usage is separate", uA.summary.ai.calls >= 1 && uB.summary.ai.calls === 0 && (await q("SELECT COUNT(*) n FROM usage_ledger WHERE org_id=$1", [TB.org]))[0].n == 0);87// per-organization spend caps (price raised so the worst-case cost trips A's cap but not B's)88await owner.post("/api/settings", { data: { "ai.pricing": { "mock-1": { in: 500, out: 500 } } }, headers: O });89await post(owner, "/api/super", { action: "updateOrg", orgId: TA.org, aiCap: 0.5 });90const waitRun = async (c, sid, ms = 20000) => { const t = Date.now(); while (Date.now() - t < ms) { const j = await J(await c.get(`/api/ai/sessions/${sid}`)); const r = j.runs?.[0]; if (r && ["succeeded", "failed", "cancelled"].includes(r.status)) return r; await sleep(400); } return null; };91const sA2 = (await J(await post(A, "/api/ai/sessions", { provider: "mock", model: "mock-1", budget_usd: 5, title: "A capped" }))).id; await post(A, `/api/ai/sessions/${sA2}/messages`, { content: "cap test A" });92const sB2 = (await J(await post(B, "/api/ai/sessions", { provider: "mock", model: "mock-1", budget_usd: 5, title: "B uncapped" }))).id; await post(B, `/api/ai/sessions/${sB2}/messages`, { content: "cap test B" });93const rA = await waitRun(A, sA2), rB = await waitRun(B, sB2);94rec("spending limits: A's per-organization cap blocks the call before it is made", rA?.status === "failed" && /organization monthly cap/.test(rA.error ?? ""), rA?.error?.slice(0, 80));95rec("spending limits: B (own cap) is unaffected by A's cap", rB?.status === "succeeded", rB?.error);96await owner.post("/api/settings", { data: { "ai.pricing": {} }, headers: O }); await post(owner, "/api/super", { action: "updateOrg", orgId: TA.org, aiCap: 2 });9798// ---------------- RBAC ----------------99const addMember = async (C, role, label) => { const email = `qa-${label}-${ts}@example.test`; const r = await J(await post(C, "/api/cloud/team", { email, name: label, role })); created.users.push(r.id); return { id: r.id, token: r.token, email }; };100const V = await addMember(A, "viewer", "viewer"), D = await addMember(A, "developer", "dev"), AD = await addMember(A, "admin", "admin");101const cV = await ctxOf(), cD = await ctxOf(), cAD = await ctxOf(); await login(cV, V.token); await login(cD, D.token); await login(cAD, AD.token);102rec("rbac: viewer reads but cannot create projects/instances/AI sessions/files", (await cV.get("/api/projects")).ok() && (await post(cV, "/api/projects", { name: "v-proj" })).status() === 403 && (await post(cV, "/api/cloud/instances", { name: "v-inst", target: "external" })).status() === 403 && (await post(cV, "/api/ai/sessions", { provider: "mock", model: "mock-1", budget_usd: 1 })).status() === 403 && (await put(cV, `/api/workspace/${pA}/files`, { path: "v.txt", content: "x" })).status() === 403);103const dp = await post(cD, "/api/projects", { name: "dev-project" }); if (dp.ok()) created.projects.push((await J(dp)).id);104rec("rbac: developer can build (projects/files) but cannot manage instances, servers, credentials or team", dp.ok() && (await put(cD, `/api/workspace/${pA}/files`, { path: "d.txt", content: "x" })).ok() && (await post(cD, "/api/cloud/instances", { name: "d-inst", target: "external" })).status() === 403 && (await post(cD, "/api/cloud/servers", { action: "enroll", instanceId: iA.id, label: "dev-node" })).status() === 403 && (await put(cD, "/api/integrations/openai", { key: "x".repeat(24) })).status() === 403 && (await post(cD, "/api/cloud/team", { email: "z@example.test", role: "viewer" })).status() === 403);105rec("rbac: admin cannot grant a role above its own", (await post(cAD, "/api/cloud/team", { email: `qa-esc-${ts}@example.test`, role: "owner" })).status() === 403);106rec("rbac: the last owner cannot be demoted or removed", (await patch(A, "/api/cloud/team", { userId: TA.ownerId, role: "viewer" })).status() === 409 && (await patch(A, "/api/cloud/team", { userId: TA.ownerId, remove: true })).status() === 409);107rec("rbac: removing a member revokes their sessions", (await patch(A, "/api/cloud/team", { userId: V.id, remove: true })).ok() && (await cV.get("/api/cloud/overview")).status() === 401);108// quotas109await post(owner, "/api/super", { action: "updateOrg", orgId: TB.org, maxProjects: 1 }); const q2 = await post(B, "/api/projects", { name: "B second" }); rec("quota: project quota enforced per organization (409)", q2.status() === 409 && /quota/.test((await J(q2)).error));110await post(owner, "/api/super", { action: "updateOrg", orgId: TB.org, maxInstances: 1 }); rec("quota: instance quota enforced", (await post(B, "/api/cloud/instances", { name: "b-two", target: "external" })).status() === 409);111await post(owner, "/api/super", { action: "updateOrg", orgId: TB.org, maxProjects: 20, maxInstances: 3 });112// tenant switching113const ex = await J(await post(B, "/api/cloud/team", { email: TA.email, name: "A owner", role: "viewer" })); rec("switching: existing account can be added to a second organization (no new token)", !!ex.id && !ex.token);114await post(A, "/api/cloud/org", { orgId: TB.org }); const sw = await J(await A.get("/api/cloud/org")); const swProj = await J(await A.get("/api/projects"));115rec("switching: after switching, A's owner sees only B's data and acts with the viewer role there", sw.current === TB.org && swProj.projects.every(p => p.id !== pA) && (await post(A, "/api/projects", { name: "x-in-b" })).status() === 403);116await post(A, "/api/cloud/org", { orgId: TA.org }); rec("switching: switching back restores A's data", (await J(await A.get("/api/projects"))).projects.some(p => p.id === pA));117await patch(B, "/api/cloud/team", { userId: TA.ownerId, remove: true });118// platform vs customer administration119rec("separation: customer owner cannot use Super Admin / platform APIs", (await A.get("/api/super")).status() === 403 && (await post(A, "/api/super", { action: "createOrg", name: "Evil", ownerEmail: "e@e.test" })).status() === 403 && (await A.get("/api/config")).status() === 403 && (await post(A, "/api/engines", { consent: true, confirm: "I CONSENT" })).status() === 403 && (await post(A, "/api/estop", { on: true })).status() === 403);120rec("separation: customer cannot open platform pages", /Platform administrators only/.test(await (await A.get("/superadmin/platform")).text()) && /Platform administrators only/.test(await (await A.get("/infrastructure")).text()) && /Platform administrators only/.test(await (await A.get("/deployments")).text()));121const superJson = await (await owner.get("/api/super")).text(); const superHtml = await (await owner.get("/superadmin/platform")).text();122rec("separation: Super Admin data contains no customer secrets, files or AI content", !/ciphertext|token_hash|secret_hash|tenant-A-confidential|TENANT-A-PROMPT|A secret project/.test(superJson + superHtml));123rec("separation: platform admin sees customer tenants only as metadata (orgs, counts)", superJson.includes(TA.org) && superJson.includes("max_projects"));124rec("separation: platform admin cannot silently read customer files / AI sessions (scoped to its own tenant)", (await owner.get(`/api/workspace/${pA}/files?file=secrets.txt`)).status() === 404 && (await owner.get(`/api/ai/sessions/${sA}`)).status() === 404 && (await post(owner, `/api/ai/sessions/${sA}/messages`, { content: "x" })).status() === 404 && !(await (await owner.get("/api/ai/sessions")).text()).includes(sA));125rec("separation: no terminal or shell endpoint exists for anyone", (await owner.get("/api/terminal")).status() === 404 && (await (await owner.get("/terminal")).text()).includes("Unavailable"));126// audit scoping127const monA = await (await A.get("/monitoring")).text(); const monB = await (await B.get("/monitoring")).text(); const monO = await (await owner.get("/monitoring")).text();128rec("audit: each tenant sees only its own activity; platform sees all", monA.includes(pA) && !monA.includes(pB) && monB.includes(pB) && !monB.includes(pA) && monO.includes(pA) && monO.includes(pB));129// managed infrastructure workflow130const plan = await J(await post(owner, "/api/super", { action: "addPlan", name: `QA plan ${ts}`, cpu: 2, ramGb: 4, diskGb: 80 })); const inv = await J(await post(owner, "/api/super", { action: "addInventory", label: `qa-server-${ts}`, region: "test", cpu: 4, ramGb: 8, diskGb: 160 }));131const prv = await J(await post(A, "/api/cloud/provision", { instanceId: iAm.id, planId: plan.id })); rec("managed: customer requests provisioning (instance -> pending_provisioning)", !!prv.id && (await q("SELECT status FROM instances WHERE id=$1", [iAm.id]))[0].status === "pending_provisioning");132rec("managed: B cannot see A's request, nor activate a managed instance without a server", !(await (await B.get("/api/cloud/provision")).text()).includes(prv.id) && (await patch(A, `/api/cloud/instances/${iAm.id}`, { status: "active" })).status() === 409);133rec("managed: only a platform admin can decide requests", (await post(A, "/api/super", { action: "decide", id: prv.id, decision: "approve", inventoryId: inv.id })).status() === 403);134rec("managed: approval assigns inventory and activates the instance; no second assignment", (await post(owner, "/api/super", { action: "decide", id: prv.id, decision: "approve", inventoryId: inv.id })).ok() && (await q("SELECT status FROM instances WHERE id=$1", [iAm.id]))[0].status === "active" && (await post(owner, "/api/super", { action: "decide", id: prv.id, decision: "approve", inventoryId: inv.id })).status() === 404);135rec("managed: assigned server visible to A only", (await (await A.get("/api/cloud/servers")).text()).includes(`qa-server-${ts}`) && !(await (await B.get("/api/cloud/servers")).text()).includes(`qa-server-${ts}`));136rec("managed: lifecycle transitions validated (terminated is final)", (await patch(A, `/api/cloud/instances/${iAm.id}`, { status: "terminated" })).ok() && (await patch(A, `/api/cloud/instances/${iAm.id}`, { status: "active" })).status() === 409);137138// ---------------- package signature (independent key) ----------------139const man = await J(await nobody.get("/packages/manifest.json")); const pk = man.packages[0];140const repoKey = /public key: (\S+)/.exec(fs.readFileSync(path.join(ROOT, "agent/SIGNING-KEY.txt"), "utf8"))[1]; const tmpd = fs.mkdtempSync(path.join(os.tmpdir(), "zcs-pkg-")); homes.push(tmpd);141const pkgBuf = Buffer.from(await (await nobody.get(`/packages/${pk.file}`)).body()); const sigTxt = await (await nobody.get(`/packages/${pk.signature}`)).text();142fs.writeFileSync(path.join(tmpd, pk.file), pkgBuf); fs.writeFileSync(path.join(tmpd, "p.sig"), sigTxt); fs.writeFileSync(path.join(tmpd, "bad.mjs"), Buffer.concat([pkgBuf, Buffer.from("\n// tampered\n")]));143rec("package: manifest signing key equals the key committed in the repository (independent trust anchor)", man.signing.publicKey === repoKey);144rec("package: downloaded package matches manifest SHA-256", crypto.createHash("sha256").update(pkgBuf).digest("hex") === pk.sha256);145rec("package: signature VALID against the repository key", agent(tmpd, ["verify", "--file", path.join(tmpd, pk.file), "--sig", path.join(tmpd, "p.sig"), "--pubkey", repoKey]).stdout.includes("VALID") && agent(tmpd, ["verify", "--file", path.join(tmpd, pk.file), "--sig", path.join(tmpd, "p.sig"), "--pubkey", repoKey]).status === 0);146const tam = agent(tmpd, ["verify", "--file", path.join(tmpd, "bad.mjs"), "--sig", path.join(tmpd, "p.sig"), "--pubkey", repoKey]); rec("package: tampered package is rejected (INVALID, exit 1)", tam.status === 1 && /INVALID/.test(tam.stdout));147rec("package: only manifest-listed files are downloadable", (await nobody.get("/packages/..%2Fmanifest.json")).status() === 404 && (await nobody.get("/packages/node.json")).status() === 404);148149// ---------------- agent enrollment (real agent, same host) ----------------150const hA = fs.mkdtempSync(path.join(os.tmpdir(), "zcs-agA-")), hB = fs.mkdtempSync(path.join(os.tmpdir(), "zcs-agB-")); homes.push(hA, hB);151const enr = async (C, inst, label) => J(await post(C, "/api/cloud/servers", { action: "enroll", instanceId: inst, label }));152const eA = await enr(A, iA.id, "a-node-1"); const eB = await enr(B, iB.id, "b-node-1");153rec("enroll: token is tenant-bound, single-use, short-lived (15 min) and shown once", /^zce_[0-9a-f]{48}$/.test(eA.token) && eA.singleUse === true && Math.abs(new Date(eA.expires) - Date.now() - 900000) < 30000 && !(await (await A.get("/api/cloud/servers")).text()).includes(eA.token));154rec("enroll: managed-target instance cannot take an external enrollment", (await post(A, "/api/cloud/servers", { action: "enroll", instanceId: iAm.id, label: "nope" })).status() === 409);155const noPin = agent(hA, ["enroll", "--url", BASE, "--token", eA.token]); rec("enroll: verified TLS by default — a self-signed server is refused without --pin", noPin.status === 1 && /self.signed|certificate|unable to verify/i.test(noPin.stderr), noPin.stderr.trim().slice(0, 70));156const badPin = agent(hA, ["enroll", "--url", BASE, "--token", eA.token, "--pin", "00".repeat(32)]); rec("enroll: wrong TLS pin is refused (token not consumed)", badPin.status === 1 && /pin mismatch/i.test(badPin.stderr));157const enrolled = agent(hA, ["enroll", "--url", BASE, "--token", eA.token, "--pin", fp]); rec("enroll: agent enrolls with the correct pin", enrolled.status === 0 && /enrolled as node_/.test(enrolled.stdout), enrolled.stderr.trim());158const replay = agent(hB, ["enroll", "--url", BASE, "--token", eA.token, "--pin", fp]); rec("enroll: replay of a used token is rejected", replay.status === 1 && /already used|invalid/i.test(replay.stderr) && !fs.existsSync(path.join(hB, "node.json")));159const eX = await enr(A, iA.id, "a-expired"); await q("UPDATE nodes SET enroll_expires=$2 WHERE id=$1", [eX.id, Date.now() - 1000]); const exp = agent(fs.mkdtempSync(path.join(os.tmpdir(), "zcs-agX-")), ["enroll", "--url", BASE, "--token", eX.token, "--pin", fp]); rec("enroll: expired token is rejected", exp.status === 1 && /expired/i.test(exp.stderr));160const enB = agent(hB, ["enroll", "--url", BASE, "--token", eB.token, "--pin", fp]); rec("enroll: tenant B enrolls its own node", enB.status === 0);161const nA = (await q("SELECT id,org_id,instance_id,secret_hash FROM nodes WHERE id=$1", [eA.id]))[0], nB = (await q("SELECT id,org_id FROM nodes WHERE id=$1", [eB.id]))[0];162rec("enroll: node identities are unique and bound to the issuing tenant", nA.org_id === TA.org && nB.org_id === TB.org && nA.id !== nB.id && !!nA.secret_hash && nA.secret_hash.length === 64);163rec("enroll: only a hash of the node secret is stored", !JSON.stringify(await q("SELECT * FROM nodes WHERE id=$1", [eA.id])).includes(JSON.parse(fs.readFileSync(path.join(hA, "node.json"), "utf8")).credential.split(".")[1]));164rec("enroll: agent config file is private (0600)", (fs.statSync(path.join(hA, "node.json")).mode & 0o777) === 0o600);165const hbA = agent(hA, ["run", "--once"]), hbB = agent(hB, ["run", "--once"]); rec("connect: heartbeats succeed", hbA.status === 0 && hbB.status === 0, hbA.stderr.trim());166const srvA = (await J(await A.get("/api/cloud/servers"))).nodes.find(n => n.id === eA.id); rec("connect: server appears ONLINE with node metrics and agent info", srvA?.state === "online" && !!srvA.hostname && srvA.metrics?.memTotalMb > 0 && srvA.agent_version === pk.version);167rec("connect: B cannot see A's node and A cannot see B's", !(await (await B.get("/api/cloud/servers")).text()).includes(eA.id) && !(await (await A.get("/api/cloud/servers")).text()).includes(eB.id));168// job routing169const jobA = await J(await post(A, "/api/cloud/servers", { action: "job", nodeId: eA.id, kind: "collect-info" })); rec("jobs: only safe kinds exist (no command execution)", (await post(A, "/api/cloud/servers", { action: "job", nodeId: eA.id, kind: "shell", text: "id" })).status() === 422 && !!jobA.id);170rec("jobs: B cannot enqueue a job for A's node", (await post(B, "/api/cloud/servers", { action: "job", nodeId: eA.id, kind: "echo", text: "x" })).status() === 404);171agent(hB, ["run", "--once"]); rec("jobs: B's agent heartbeat does NOT receive A's queued job (routing is node + org bound)", (await q("SELECT status FROM node_jobs WHERE id=$1", [jobA.id]))[0].status === "queued");172const credB = JSON.parse(fs.readFileSync(path.join(hB, "node.json"), "utf8")).credential, credA = JSON.parse(fs.readFileSync(path.join(hA, "node.json"), "utf8")).credential;173const gw = await ctxOf(); const bear = c => ({ headers: { authorization: `Bearer ${c}`, "content-type": "application/json" }, data: { result: { stolen: true } } });174agent(hA, ["run", "--once"]); const jr = (await q("SELECT status,result FROM node_jobs WHERE id=$1", [jobA.id]))[0]; rec("jobs: A's own agent receives and completes the job", jr.status === "done" && /hostname/.test(jr.result));175const jobA2 = await J(await post(A, "/api/cloud/servers", { action: "job", nodeId: eA.id, kind: "echo", text: "hello" })); await gw.post("/gateway/api/heartbeat", { ...bear(credA), data: {} });176rec("jobs: another tenant's node cannot post a result for A's job", (await gw.post(`/gateway/api/jobs/${jobA2.id}`, bear(credB))).status() === 404);177rec("jobs: a node id paired with another node's secret is rejected", (await gw.post("/gateway/api/heartbeat", bear(`${eB.id}.${credA.split(".")[1]}`))).status() === 401);178rec("gateway: unauthenticated / malformed requests rejected", (await gw.post("/gateway/api/heartbeat", { data: {} })).status() === 401 && (await gw.post("/gateway/api/enroll", { data: { token: "zce_bad" } })).status() === 400 && (await gw.post("/gateway/api/enroll", { data: { token: "zce_" + "0".repeat(48) } })).status() === 401);179rec("gateway: plain HTTP is refused", (await (await request.newContext({ baseURL: "http://127.0.0.1:8080" })).post("/gateway/api/enroll", { data: { token: "zce_" + "0".repeat(48) } })).status() === 403);180// domain migration / reconnection181await q("UPDATE nodes SET last_seen=$2 WHERE id=$1", [eA.id, Date.now() - 600000]); const offState = (await J(await A.get("/api/cloud/servers"))).nodes.find(n => n.id === eA.id).state;182agent(hA, ["run", "--once"]); const onState = (await J(await A.get("/api/cloud/servers"))).nodes.find(n => n.id === eA.id).state; rec("reconnect: node goes offline when silent and returns online on reconnect", offState === "offline" && onState === "online");183await post(owner, "/api/config", { values: { GATEWAY_BASE_URL: "https://localhost:8443/gateway" } }); agent(hA, ["run", "--once"]); const adopted = JSON.parse(fs.readFileSync(path.join(hA, "node.json"), "utf8")).url; await post(owner, "/api/config", { values: { GATEWAY_BASE_URL: "" } });184rec("domain migration: an enrolled agent adopts a changed gateway URL announced by the authenticated server and keeps working", adopted === "https://localhost:8443/gateway" && agent(hA, ["run", "--once"]).status === 0);185// revocation186rec("revoke: customer developer cannot revoke; admin can", (await post(cD, "/api/cloud/servers", { action: "revoke", nodeId: eA.id })).status() === 403 && (await post(A, "/api/cloud/servers", { action: "revoke", nodeId: eA.id })).ok());187const rv = agent(hA, ["run", "--once"]); rec("revoke: a revoked node cannot reconnect (agent exits 3 on 'credential rejected')", rv.status === 3 && /revoked|rejected/i.test(rv.stderr));188rec("revoke: raw heartbeat with the old credential is refused (403)", (await gw.post("/gateway/api/heartbeat", bear(credA))).status() === 403 && (await J(await A.get("/api/cloud/servers"))).nodes.find(n => n.id === eA.id).state === "revoked");189rec("revoke: the used token cannot be replayed to re-enroll a revoked node", agent(fs.mkdtempSync(path.join(os.tmpdir(), "zcs-agR-")), ["enroll", "--url", BASE, "--token", eA.token, "--pin", fp]).status === 1);190rec("revoke: another tenant cannot revoke A's node", (await post(B, "/api/cloud/servers", { action: "revoke", nodeId: eB.id.replace(eB.id, eA.id) })).status() === 404);191192// ---------------- UI: customer console screenshots + layout checks (as tenant A's owner) ----------------193{ const b = await chromium.launch(); const errs = [];194 async function uiLogin(pg, token) { for (let i = 0; i < 6; i++) { await pg.goto(BASE + "/login"); await pg.fill("#tok", token); await pg.click("button:has-text('Sign in')"); try { await pg.waitForURL(BASE + "/console", { timeout: 8000 }); return; } catch { await sleep(15000); } } throw new Error("UI login failed"); }195 const PAGES = [["/console", "overview"], ["/console/instances", "instances"], ["/console/managed", "managed"], ["/console/servers", "servers"], ["/console/hosting", "hosting"], ["/console/databases", "databases"], ["/console/deployments", "deployments"], ["/console/billing", "billing"], ["/console/team", "team"], ["/console/settings", "settings"], ["/projects", "applications"], ["/workspace", "ai-studio"], ["/terminal", "terminal"], ["/domains", "domains"], ["/integrations", "integrations"]];196 for (const [vpn, w, h] of [["desktop", 1440, 900], ["mobile", 390, 844]]) {197 const ctx = await b.newContext({ ignoreHTTPSErrors: true, viewport: { width: w, height: h } }); const pg = await ctx.newPage(); pg.on("pageerror", e => errs.push(String(e))); await uiLogin(pg, TA.token); const bad = [];198 for (const [route, slug] of PAGES) { await pg.goto(BASE + route); await pg.waitForTimeout(900); if (await pg.evaluate(() => document.documentElement.scrollWidth > window.innerWidth + 1)) bad.push(route); if ((await pg.locator("h1").count()) !== 1) bad.push(route + " h1"); await pg.screenshot({ path: path.join(SHOTS, `cc-${slug}-${vpn}.png`) }); }199 rec(`UI ${vpn}: all ${PAGES.length} customer console pages render with one h1 and no horizontal overflow`, bad.length === 0, bad.join(", "));200 if (vpn === "desktop") { await pg.goto(BASE + "/console/servers"); await pg.getByRole("button", { name: /Generate enrollment token/ }).waitFor(); await pg.getByLabel("Server label").fill("ui-node"); await pg.getByRole("button", { name: /Generate enrollment token/ }).click(); await pg.waitForSelector("[data-testid=enroll-token]"); rec("UI: customer generates an enrollment token and sees install instructions", /zce_[0-9a-f]{48}/.test(await pg.locator("[data-testid=enroll-token]").innerText()) && (await pg.locator("pre").first().innerText()).includes("--pin")); await pg.screenshot({ path: path.join(SHOTS, "cc-servers-enrollment-desktop.png") });201 await pg.goto(BASE + "/console/team"); rec("UI: team page lists members with roles", (await pg.locator("[data-testid=member-list] li").count()) >= 2); await pg.getByRole("button", { name: /Zoo Cloud Studio|^.*$/ }).first(); const sw = pg.locator("[data-testid=org-name]"); rec("UI: organization name shown in the tenant switcher", (await sw.innerText()).includes("QA-TA")); }202 await ctx.close(); }203 const octx = await b.newContext({ ignoreHTTPSErrors: true, viewport: { width: 1440, height: 900 } }); const op = await octx.newPage(); op.on("pageerror", e => errs.push(String(e))); await uiLogin(op, TOKEN);204 for (const [route, slug, w] of [["/superadmin/platform", "super-admin", 1440], ["/superadmin", "command-center", 1440], ["/console", "owner-overview", 1440], ["/packages", "packages", 1440]]) { await op.setViewportSize({ width: w, height: 900 }); await op.goto(BASE + route); await op.waitForTimeout(1000); await op.screenshot({ path: path.join(SHOTS, `cc-${slug}-desktop.png`), fullPage: slug === "super-admin" }); }205 await op.setViewportSize({ width: 390, height: 844 }); await op.goto(BASE + "/superadmin/platform"); await op.waitForTimeout(800); rec("UI mobile: Super Admin has no horizontal overflow", await op.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1)); await op.screenshot({ path: path.join(SHOTS, "cc-super-admin-mobile.png") });206 rec("UI: no page errors across customer and super-admin pages", errs.length === 0, errs[0]); await b.close(); }207208// ---------------- gate re-closed: customer operations stop, platform owner continues ----------------209await owner.post("/api/super", { data: { action: "security", trustedTls: false, devCustomerOps: false }, headers: O });210rec("gate: closing it ends customer sessions immediately (401)", (await A.get("/api/cloud/overview")).status() === 401 && (await B.get("/api/cloud/overview")).status() === 401 && (await B.get("/api/ai/sessions")).status() === 401);211const eG = null; const nodeLive = (await q("SELECT id FROM nodes WHERE id=$1", [eB.id]))[0]; rec("gate: customer agents are refused at the gateway while the gate is closed (403)", (await gw.post("/gateway/api/heartbeat", bear(credB))).status() === 403 && !!nodeLive);212rec("gate: platform owner still operates normally", (await owner.get("/api/cloud/overview")).ok() && (await owner.get("/api/super")).ok());213// ---------------- existing owner data preserved ----------------214const own = (await q("SELECT COUNT(*) n FROM projects WHERE org_id='org_owner'"))[0].n, dep = (await q("SELECT COUNT(*) n FROM deployments"))[0].n, au = (await q("SELECT COUNT(*) n FROM audit_log"))[0].n;215const orphans = (await q("SELECT (SELECT COUNT(*) FROM projects WHERE org_id IS NULL) + (SELECT COUNT(*) FROM ai_sessions WHERE org_id IS NULL) + (SELECT COUNT(*) FROM credentials WHERE org_id IS NULL) n"))[0].n;216rec("owner data: pre-existing projects live in the protected owner tenant, none orphaned", Number(own) >= 7 && Number(orphans) === 0, `owner projects=${own}`);217rec("owner data: deployment history and audit log preserved", Number(dep) >= 7 && Number(au) >= 51);218const rows = await q("SELECT * FROM audit_log ORDER BY seq"); let prev = "GENESIS", chain = true; for (const r of rows) { const h = crypto.createHash("sha256").update([prev, r.ts, r.actor, r.action, r.resource, r.detail].join("|")).digest("hex"); if (r.prev_hash !== prev || r.hash !== h) { chain = false; break; } prev = r.hash; } rec("owner data: audit hash chain verifies after all tenant activity", chain, `${rows.length} entries`);219rec("owner tenant is protected (cannot be suspended)", (await post(owner, "/api/super", { action: "updateOrg", orgId: "org_owner", status: "suspended" })).status() === 409);220221// ---------------- cleanup: only the fixtures this run created ----------------222try {223 await q("DELETE FROM node_jobs WHERE org_id = ANY($1)", [created.orgs]); await q("DELETE FROM provisioning_requests WHERE org_id = ANY($1)", [created.orgs]); await q("UPDATE managed_inventory SET status='available', assigned_org_id=NULL, assigned_instance_id=NULL WHERE assigned_org_id = ANY($1)", [created.orgs]);224 await q("DELETE FROM managed_inventory WHERE label LIKE $1", [`qa-server-${ts}`]); await q("DELETE FROM resource_plans WHERE name=$1", [`QA plan ${ts}`]);225 await q("DELETE FROM ai_sessions WHERE org_id = ANY($1)", [created.orgs]); await q("DELETE FROM projects WHERE org_id = ANY($1)", [created.orgs]); await q("DELETE FROM credentials WHERE org_id = ANY($1)", [created.orgs]);226 await q("DELETE FROM usage_ledger WHERE org_id = ANY($1)", [created.orgs]); await q("DELETE FROM usage_records 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]);227 await q("DELETE FROM organizations WHERE id = ANY($1)", [created.orgs]); await q("DELETE FROM users WHERE id = ANY($1)", [created.users]);228 for (const p of created.projects) fs.rmSync(path.join(ROOT, "app/data/workspaces", p), { recursive: true, force: true }); for (const h of homes) fs.rmSync(h, { recursive: true, force: true });229 rec("cleanup: test fixtures removed; no QA tenants remain", Number((await q("SELECT COUNT(*) n FROM organizations WHERE name LIKE $1", [`QA-T% ${ts}`]))[0].n) === 0);230} catch (e) { rec("cleanup: test fixtures removed", false, String(e.message)); }231// restore the owner's gate state232if (prevSecurity.mode === "trusted-tls") await owner.post("/api/super", { data: { action: "security", trustedTls: true, confirm: "I ATTEST TRUSTED TLS" }, headers: O });233await owner.post("/api/design/rebuild", { headers: O });234await pool.end(); const f = results.filter(r => !r.ok).length; console.log(`\n${results.length - f}/${results.length} tenant-isolation checks passed`); fs.writeFileSync(path.join(ROOT, "design/verification/tenant-isolation.json"), JSON.stringify({ finished: new Date().toISOString(), passed: results.length - f, total: results.length, checks: results }, null, 2)); process.exit(f ? 1 : 0);235
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.