Skip to content
  1. Home
  2. workspace
Checking…
Demo view — sanitized data only. Sign in over HTTPS to create projects and manage the workspace.

AI Engineering Workspace

Partial

Chat, 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

app/qa/gates.mjs

1// Customer-activation security gates, against the live HTTPS edge with the real agent (same-host: LOCAL test).
2import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import crypto from "node:crypto"; import { spawn, spawnSync } from "node:child_process"; import { fileURLToPath } from "node:url";
3import { request } from "playwright"; import pg from "pg";
4const 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 };
5const TOKEN = fs.readFileSync(path.join(os.homedir(), ".config/zoo-cloud-studio/admin-token"), "utf8").trim();
6const results = []; const rec = (n, ok, d = "") => { results.push({ n, ok: !!ok }); console.log(`${ok ? "PASS" : "FAIL"} ${n}${d ? " — " + d : ""}`); };
7const sleep = ms => new Promise(r => setTimeout(r, ms)); const ts = Date.now(); const J = async r => r.json().catch(() => ({}));
8const 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;
9const ctxOf = () => request.newContext({ baseURL: BASE, ignoreHTTPSErrors: true }); const post = (c, u, b) => c.post(u, { data: b, headers: O });
10async 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"); }
11const fp = new crypto.X509Certificate(fs.readFileSync(path.join(os.homedir(), ".config/zoo-cloud-studio/tls/cert.pem"))).fingerprint256.replace(/:/g, "");
12const AGENT = path.join(ROOT, "agent/zoo-cloud-agent.mjs"); const get = async (url) => { try { const r = await fetch(url, { signal: AbortSignal.timeout(3000) }); return { s: r.status, t: await r.text() }; } catch { return { s: 0, t: "" }; } };
13async 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; }
14const created = { orgs: [], users: [] }; let agentProc = null; const D = fs.mkdtempSync(path.join(os.tmpdir(), "zcs-gt-"));
15const owner = await ctxOf(); await login(owner, TOKEN); const sec0 = (await J(await owner.get("/api/super"))).security; const trusted0 = await q("SELECT value FROM settings WHERE key='security.trusted_tls'"); const act0 = await q("SELECT value FROM settings WHERE key='security.activation_orgs'");
16const 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 }; };
17const 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 });
18const A = await ctxOf(), B = await ctxOf(); await login(A, TA.token); await login(B, TB.token);
19const stopWait = async () => { await until(async () => (await q("SELECT COUNT(*) n FROM node_jobs WHERE org_id=$1 AND status IN ('queued','delivered')", [TA.org]))[0].n == 0, 90000, 700); };
20const run = async () => {
21 const iA = await J(await post(A, "/api/cloud/instances", { name: "gt", target: "external" })); const eA = await J(await post(A, "/api/cloud/servers", { action: "enroll", instanceId: iA.id, label: "gt-vps" })); const nodeA = eA.id;
22 const en = spawnSync(process.execPath, [AGENT, "enroll", "--url", BASE, "--token", eA.token, "--pin", fp, "--public-host", "127.0.0.1"], { env: { ...process.env, ZOO_AGENT_HOME: D }, encoding: "utf8" }); rec("agent enrols", en.status === 0, en.stderr);
23 agentProc = spawn(process.execPath, [AGENT, "run"], { env: { ...process.env, ZOO_AGENT_HOME: D }, stdio: "ignore" });
24 await until(async () => (await J(await A.get("/api/cloud/apps"))).nodes?.find(n => n.id === nodeA && n.state === "online" && n.caps), 40000);
25 const dep = (b) => post(A, "/api/cloud/apps", { action: "deploy", nodeId: nodeA, template: "static-site", ...b });
26 // ---- per-node execution authorization ----
27 rec("authorization: an enrolled but NOT authorized server refuses deployments (409)", (await dep({ name: "gt-one", params: {} })).status() === 409);
28 const jid = `job_gt${ts}`; await q("INSERT INTO node_jobs(id,org_id,node_id,kind,payload,status,created_at) VALUES($1,$2,$3,'app.stop','{\"deploymentId\":\"app_00000000\"}','queued',$4)", [jid, TA.org, nodeA, new Date().toISOString()]); await sleep(18000);
29 rec("authorization: app jobs are NOT delivered to an unauthorized server (even if forced into the queue)", (await q("SELECT status FROM node_jobs WHERE id=$1", [jid]))[0].status === "queued"); await q("DELETE FROM node_jobs WHERE id=$1", [jid]);
30 rec("authorization: only an admin can authorize execution; unknown node cannot be authorized by another tenant", (await post(B, "/api/cloud/servers", { action: "authorize", nodeId: nodeA })).status() === 404 && (await post(A, "/api/cloud/servers", { action: "authorize", nodeId: nodeA })).ok());
31 // ---- quotas ----
32 const lim = async o => owner.post("/api/super", { data: { action: "updateOrg", orgId: TA.org, ...o }, headers: O });
33 await lim({ maxApps: 1 }); const first = await J(await dep({ name: "gt-one", params: { html: "<h1>one</h1>" } })); const second = await dep({ name: "gt-two", params: {} });
34 rec("spending/quota: per-tenant application quota enforced (429 over the limit)", !!first.id && second.status() === 429 && /quota/.test((await J(second)).error ?? ""));
35 await until(async () => (await J(await A.get("/api/cloud/apps"))).deployments.find(x => x.id === first.id && x.status === "running"), 60000); await stopWait();
36 await lim({ maxApps: 5, maxDeploysPerDay: 1 }); rec("spending/quota: daily deployment limit enforced (429)", (await post(A, "/api/cloud/apps", { action: "redeploy", deploymentId: first.id, params: { html: "x" } })).status() === 429); await lim({ maxDeploysPerDay: 20 });
37 // ---- serialization (one active job per node) ----
38 const r2 = await post(A, "/api/cloud/apps", { action: "redeploy", deploymentId: first.id, params: { html: "<h1>two</h1>" } }); const dd = await J(await post(A, "/api/cloud/apps", { action: "deploy", nodeId: nodeA, template: "static-site", name: "gt-b", params: { html: "<h1>b</h1>" } })); await stopWait();
39 const jobs = await q("SELECT id,delivered_at,finished_at FROM node_jobs WHERE org_id=$1 AND kind='app.deploy' ORDER BY delivered_at DESC LIMIT 2", [TA.org]);
40 rec("job isolation: jobs on one node run strictly one at a time (next delivered only after the previous finished)", jobs.length === 2 && new Date(jobs[0].delivered_at) >= new Date(jobs[1].finished_at), JSON.stringify(jobs));
41 // ---- secrets ----
42 const SECRET = `s3cr3t-${crypto.randomBytes(8).toString("hex")}`;
43 const code = "const http=require('http');http.createServer((q,s)=>s.end('v:'+process.env.API_KEY)).listen(process.env.PORT,'0.0.0.0')";
44 const sd = await J(await dep({ name: "gt-secret", template: "node-app", params: { code, env: `API_KEY=${SECRET}` } })); await until(async () => (await J(await A.get("/api/cloud/apps"))).deployments.find(x => x.id === sd.id && x.status === "running"), 60000);
45 const port = sd.port; rec("secrets: the value reaches the running application (injected at delivery)", (await get(`http://127.0.0.1:${port}/`)).t === `v:${SECRET}`);
46 const rel = await q("SELECT params FROM app_releases WHERE deployment_id=$1", [sd.id]); const jobsAll = await q("SELECT payload,result,log FROM node_jobs WHERE org_id=$1", [TA.org]); const aud = await q("SELECT detail FROM audit_log ORDER BY seq DESC LIMIT 300");
47 rec("secrets: encrypted at rest; plaintext absent from release rows, job payloads/results/logs and the audit log", rel.every(r => !r.params.includes(SECRET) && r.params.includes("envEnc")) && JSON.stringify(jobsAll).indexOf(SECRET) < 0 && JSON.stringify(aud).indexOf(SECRET) < 0);
48 rec("secrets: never returned by any API (list, detail, logs)", JSON.stringify(await J(await A.get("/api/cloud/apps"))).indexOf(SECRET) < 0 && JSON.stringify(await J(await A.get(`/api/cloud/apps?id=${sd.id}`))).indexOf(SECRET) < 0);
49 rec("secrets: not stored in job rows even AFTER delivery (payload carries no environment)", jobsAll.every(j => { const pl = JSON.parse(j.payload); return !pl.params || pl.params.env === undefined && pl.params.envEnc === undefined; }));
50 const leak = `const http=require('http');console.log('boot '+process.env.API_KEY);process.exit(1)`; await post(A, "/api/cloud/apps", { action: "redeploy", deploymentId: sd.id, params: { code: leak, env: `API_KEY=${SECRET}` } }); await stopWait();
51 const dl = await J(await A.get(`/api/cloud/apps?id=${sd.id}`)); const logs = dl.jobs.map(j => j.log).join("\n"); rec("redaction: application output containing the secret is redacted (***) in the stored and returned job log", /health check FAILED/.test(logs) && logs.indexOf(SECRET) < 0 && /boot \*\*\*/.test(logs), logs.slice(-200).replace(/\n/g, " | "));
52 rec("secrets: environment of a retry/restart still works (values come from the encrypted release)", (await post(A, "/api/cloud/apps", { action: "restart", deploymentId: sd.id })).ok() && !!(await until(async () => { await stopWait(); return (await get(`http://127.0.0.1:${port}/`)).t === `v:${SECRET}`; }, 60000, 1500)));
53 // ---- emergency stop ----
54 const e1 = await post(owner, "/api/estop", { on: true }); rec("emergency stop: engaged by the platform owner", e1.ok());
55 const blocked = [await dep({ name: "gt-es", params: {} }), await post(A, "/api/cloud/apps", { action: "redeploy", deploymentId: first.id, params: { html: "z" } }), await post(A, "/api/cloud/apps", { action: "restart", deploymentId: first.id }), await post(A, "/api/cloud/domains", { action: "apply", nodeId: nodeA })].map(r => r.status());
56 rec("emergency stop: new deployments, redeploys, restarts and proxy updates are refused (503)", blocked.every(s => s === 503), blocked.join(","));
57 const jq = `job_es${ts}`; await q("INSERT INTO node_jobs(id,org_id,node_id,kind,payload,status,created_at) VALUES($1,$2,$3,'echo','{\"text\":\"x\"}','queued',$4)", [jq, TA.org, nodeA, new Date().toISOString()]); await sleep(18000);
58 rec("emergency stop: no job (even a safe one) is delivered to any agent while engaged", (await q("SELECT status FROM node_jobs WHERE id=$1", [jq]))[0].status === "queued");
59 rec("emergency stop: customers can still stop and remove (wind down)", (await post(A, "/api/cloud/apps", { action: "stop", deploymentId: sd.id })).ok());
60 await post(owner, "/api/estop", { on: false }); await stopWait(); rec("emergency stop: released; queued work resumes", !!(await until(async () => (await q("SELECT status FROM node_jobs WHERE id=$1", [jq]))[0].status === "done", 60000)) );
61 // ---- resource limits ----
62 const st = JSON.parse(fs.readFileSync(path.join(D, "apps", first.id, "state.json"), "utf8")); const envp = fs.readFileSync(`/proc/${st.pid}/environ`, "utf8"); const meta = fs.readFileSync(path.join(D, "apps", first.id, "releases", String(st.release), "release.json"));
63 rec("resource limits: applications start with a V8 heap cap (soft limit) and a private 0600 release file; honestly NOT cgroup isolation", /NODE_OPTIONS=--max-old-space-size=256/.test(envp) && (fs.statSync(path.join(D, "apps", first.id, "releases", String(st.release), "release.json")).mode & 0o777) === 0o600);
64 // ---- controlled activation ----
65 const rep = (await J(await owner.get("/api/super"))); rec("activation: gate report is computed (10 gates) with live audit-chain verification", rep.gates.gates.length === 10 && rep.gates.gates.find(g => g.id === "audit").pass === true);
66 await owner.post("/api/super", { data: { action: "updateOrg", orgId: TB.org, aiCap: 0 }, headers: O }); const att = await post(owner, "/api/super", { action: "security", trustedTls: true, confirm: "I ATTEST TRUSTED TLS" }); const aj = await J(att);
67 rec("activation: attestation is REFUSED (409) while any mandatory gate fails (a tenant without a spend limit)", att.status() === 409 && aj.failing?.includes("spending")); await owner.post("/api/super", { data: { action: "updateOrg", orgId: TB.org, aiCap: 2 }, headers: O });
68 rec("activation: allowlist needs the typed phrase and refuses the protected owner organization", (await post(owner, "/api/super", { action: "activation", orgIds: [TA.org] })).status() === 400 && (await post(owner, "/api/super", { action: "activation", orgIds: ["org_owner"], confirm: "ACTIVATE AUTHORIZED CUSTOMERS" })).status() === 422);
69 await owner.post("/api/super", { data: { action: "security", devCustomerOps: false }, headers: O }); await post(owner, "/api/super", { action: "activation", orgIds: [TA.org], confirm: "ACTIVATE AUTHORIZED CUSTOMERS" });
70 await q("INSERT INTO settings(key,value) VALUES('security.trusted_tls','1') ON CONFLICT(key) DO UPDATE SET value='1'"); // admission logic test only; restored below
71 const A2 = await ctxOf(), B2 = await ctxOf(); const la = await login(A2, TA.token), lb = await login(B2, TB.token);
72 rec("activation: only the explicitly listed test customer can sign in; every other customer is refused (403); no public registration", la.ok() && lb.status() === 403);
73};
74try { await run(); } catch (e) { rec("flow aborted", false, String(e.stack ?? e).slice(0, 500)); }
75try { agentProc?.kill("SIGKILL"); } catch {} try { await post(owner, "/api/estop", { on: false }); } catch {}
76try { for (const a of fs.existsSync(path.join(D, "apps")) ? fs.readdirSync(path.join(D, "apps")) : []) { try { { const pid = JSON.parse(fs.readFileSync(path.join(D, "apps", a, "state.json"), "utf8")).pid; if (pid > 0) process.kill(-pid, "SIGKILL"); }; } catch {} }
77 if (trusted0[0]) await q("UPDATE settings SET value=$1 WHERE key='security.trusted_tls'", [trusted0[0].value]); else await q("DELETE FROM settings WHERE key='security.trusted_tls'"); if (act0[0]) await q("UPDATE settings SET value=$1 WHERE key='security.activation_orgs'", [act0[0].value]); else await q("DELETE FROM settings WHERE key='security.activation_orgs'");
78 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 memberships WHERE org_id = ANY($1)", [created.orgs]); await q("DELETE FROM organizations WHERE id = ANY($1)", [created.orgs]); await q("DELETE FROM users WHERE id = ANY($1) OR email LIKE 'qa-%@example.test'", [created.users]); fs.rmSync(D, { recursive: true, force: true });
79 rec("cleanup: fixtures, processes and temporary settings restored", 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)); }
80await owner.post("/api/super", { data: { action: "security", devCustomerOps: false }, headers: O }); rec("customer gate restored to its prior state (still CLOSED)", (await J(await owner.get("/api/super"))).security.mode === sec0.mode);
81await 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} gate checks passed (local same-host)`);
82fs.writeFileSync(path.join(ROOT, "design/verification/gates.json"), JSON.stringify({ finished: new Date().toISOString(), scope: "local same-host agent; NOT independent external-VPS verification", passed: results.length - f, failed: f, results }, null, 2)); process.exit(f ? 1 : 0);
83

Conversation

Partial
Sign in to start AI sessions.

Task checklist

  • Application shell deployed
  • Persistent projects
  • Agent runtime
  • Sandboxed terminal

Execution activity

No agent sessions. Git HEAD fb22adb on master.

Approval requests

None pending.