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/central.mjs
1// Zoo Central readiness verification: contract, domain portability, customer/internal separation, metadata-only events, super-admin visibility.2// States are asserted honestly: nothing may report "live" because no Central endpoint is documented or reachable.3import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import crypto from "node:crypto"; import https from "node:https"; import pg from "pg";4import { request } from "playwright";5import { buildContract, sanitizeEvent, ADAPTERS, adapterState, orgRef } from "../src/lib/central-core.mjs";6const BASE = process.argv[2] || "https://127.0.0.1:8443"; const O = { origin: BASE }; const 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 app = new pg.Pool({ connectionString: `postgres://studio_app:${encodeURIComponent(rd("pg-app-password"))}@127.0.0.1:5432/studio`, max: 1 });9const results = []; const rec = (n, ok, d = "") => { results.push({ name: n, ok: !!ok }); console.log((ok ? "PASS " : "FAIL ") + n + (ok ? "" : " -> " + d)); };10const q = async (t, p) => (await owner.query(t, p)).rows; const fails = async f => { try { await f(); return false; } catch (e) { return String(e.message); } };11const ts = Date.now(), now = new Date().toISOString(); const sleep = ms => new Promise(r => setTimeout(r, ms));12const getHost = (host) => new Promise(res => { const rq = https.request({ host: "127.0.0.1", port: 8443, path: "/.well-known/zoo-cloud-registration.json", headers: { host }, rejectUnauthorized: false }, r => { let s = ""; r.on("data", d => s += d); r.on("end", () => res({ status: r.statusCode, body: s })); }); rq.end(); });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 A = "org_cenA" + ts, B = "org_cenB" + ts, UA = "usr_cenA" + ts, UB = "usr_cenB" + ts, tokA = "zcu_" + crypto.randomBytes(24).toString("hex"); const hash = t => crypto.createHash("sha256").update(t).digest("hex");15let prevDev = null;16try {17 // ---- contract + portability ----18 const c1 = await getHost("cloud.zoobd.com:8443"), c2 = await getHost("brand-new-domain.example"); const j1 = JSON.parse(c1.body), j2 = JSON.parse(c2.body);19 rec("registration contract is served publicly and declares schema zoo.cloud.registration/v1", c1.status === 200 && j1.schema === "zoo.cloud.registration/v1");20 rec("contract: dedicated client zoo-cloud-studio, code+PKCE, identity key (iss,sub), e-mail is not identity, no admin-by-email", j1.identity.clientId === "zoo-cloud-studio" && /pkce/.test(j1.identity.flow) && j1.identity.subjectKey === "(iss, sub)" && j1.identity.emailIsIdentity === false && j1.identity.autoAssignAdminByEmail === false);21 rec("domain portability: the same application id and identity under a different host name", /^zca_[0-9a-f]{24}$/.test(j1.application.id) && j1.application.id === j2.application.id && j1.identity.clientId === j2.identity.clientId && j1.identity.subjectKey === j2.identity.subjectKey);22 rec("a request Host header never writes endpoint history (public, unauthenticated input)", (await q("SELECT value FROM settings WHERE key IN ('central.endpoint_history','central.last_base')")).every(r => !/brand-new-domain|evil|example\.(test|invalid)/.test(r.value)));23 rec("domain portability: every endpoint follows the configured/derived domain (nothing hard-coded)", j1.endpoints.public !== j2.endpoints.public && JSON.stringify(j2.endpoints).includes("brand-new-domain.example") && !JSON.stringify(j2).includes("zoobd.com/console"));24 const p1 = buildContract("zca_x", { PUBLIC_BASE_URL: "https://cloud.zoobd.com", CONSOLE_BASE_URL: "a", API_BASE_URL: "b", GATEWAY_BASE_URL: "c", PACKAGE_BASE_URL: "d", OIDC_ISSUER: "https://iam.zoobd.com/realms/zoo", OIDC_REDIRECT_URI: "https://cloud.zoobd.com/auth/callback" }); const p2 = buildContract("zca_x", { ...{ PUBLIC_BASE_URL: "https://zoocloud.example", CONSOLE_BASE_URL: "a", API_BASE_URL: "b", GATEWAY_BASE_URL: "c", PACKAGE_BASE_URL: "d", OIDC_ISSUER: "https://iam.zoobd.com/realms/zoo", OIDC_REDIRECT_URI: "https://zoocloud.example/auth/callback" } }, ["https://cloud.zoobd.com"]);25 rec("domain migration keeps identity/tenancy fields identical and records the previous endpoint", p1.application.id === p2.application.id && JSON.stringify(p1.tenancy) === JSON.stringify(p2.tenancy) && p2.portability.previousEndpoints[0] === "https://cloud.zoobd.com" && p1.endpoints.public !== p2.endpoints.public);26 rec("org references sent to Central are opaque and domain-independent (hash or explicit mapping, never a host)", orgRef("zca_x", "org_1") === orgRef("zca_x", "org_1") && !/zoobd|http/.test(orgRef("zca_x", "org_1")) && orgRef("zca_x", "org_1", "central:org:42") === "central:org:42");27 const live = await q("SELECT id,instance_id FROM nodes LIMIT 50"); rec("gateway node identities do not embed any domain", live.every(n => !/\./.test(n.id)));28 rec("contract states what is NEVER synchronized (secrets, source, terminal, AI conversations)", ["secrets", "source", "terminal", "AI conversations"].every(w => j1.dataPolicy.neverSynchronized.join(" ").includes(w)));29 rec("contract exposes no secret material", !/(master\.key|BEGIN [A-Z ]*PRIVATE|zce_|zcu_|node_[0-9a-f]{16}\.)/.test(c1.body));30 // ---- sanitizer ----31 const when = now;32 rec("outbox accepts only allowlisted metadata", Object.keys(sanitizeEvent("audit.activity", { action: "node.revoke", resourceType: "node", orgRef: "zc_abc", at: when })).length === 4);33 for (const [name, kind, data] of [["a free-text field", "notification.request", { template: "node.offline", severity: "info", orgRef: "zc_a", at: when, message: "hello" }], ["a secret-looking key", "audit.activity", { action: "x", resourceType: "y", orgRef: "z", at: when, token: "abc" }], ["terminal content", "service.health", { component: "web", state: "operational", at: when, stdout: "ls" }], ["source code", "audit.activity", { action: "x", resourceType: "y", orgRef: "z", at: when, source: "code" }], ["an unknown template", "notification.request", { template: "free.text", severity: "info", orgRef: "z", at: when }], ["an unknown event kind", "chat.transcript", {}], ["an over-long value", "audit.activity", { action: "a".repeat(300), resourceType: "y", orgRef: "z", at: when }], ["a prompt / conversation field", "approval.request", { kind: "quota-increase", requestId: "r1", orgRef: "z", at: when, prompt: "secret plan" }]])34 rec(`outbox rejects ${name}`, !!(await fails(() => sanitizeEvent(kind, data))));35 // ---- adapter states ----36 const st = ADAPTERS.map(a => ({ id: a.id, s: adapterState(a, { endpoint: "", probeOk: false, secretPresent: false }) }));37 rec("catalogue covers all ten Central integrations plus the Nexus client", ADAPTERS.length === 11 && ADAPTERS.some(a => a.id === "nexus"));38 rec("with no Central endpoint nothing is reported live; IAM is blocked, the rest 'contract prepared'", st.every(x => x.s !== "live") && st.find(x => x.id === "iam").s === "blocked" && st.filter(x => x.id !== "iam").every(x => x.s === "contract-prepared"));39 rec("an endpoint alone never makes an adapter 'live' (a successful probe is required)", adapterState(ADAPTERS[2], { endpoint: "", probeOk: false }) === "contract-prepared" && adapterState(ADAPTERS[2], { endpoint: "https://x.example", probeOk: false }) === "ready-untested");40 // ---- DB-level customer / internal separation ----41 const mkOrg = (id, cls) => owner.query("INSERT INTO organizations(id,slug,name,created_at,org_class) VALUES($1,$2,$3,$4,$5)", [id, id.toLowerCase(), id, now, cls]);42 await mkOrg(A, "customer"); await mkOrg(B, "customer");43 for (const [u, o] of [[UA, A], [UB, B]]) { await owner.query("INSERT INTO users(id,email,name,token_hash,created_at) VALUES($1,$2,'u',$3,$4)", [u, u + "@example.test", u === UA ? hash(tokA) : null, now]); await owner.query("INSERT INTO memberships(org_id,user_id,role,created_at) VALUES($1,$2,'owner',$3)", [o, u, now]); }44 rec("DB trigger: a CUSTOMER organization cannot hold an internal-application entitlement", /internal/.test(await fails(() => owner.query("INSERT INTO app_entitlements(id,org_id,user_id,app_key,created_at) VALUES('e1',$1,$2,'zoo-connect',$3)", [A, UA, now]))));45 rec("DB trigger: the runtime role cannot bypass it either", /internal|row-level/.test(await fails(async () => { const c = await app.connect(); try { await c.query("BEGIN"); await c.query("SELECT set_config('app.mode','system',true)"); await c.query("INSERT INTO app_entitlements(id,org_id,user_id,app_key,created_at) VALUES('e2',$1,$2,'zoo-connect',$3)", [A, UA, now]); } finally { await c.query("ROLLBACK"); c.release(); } })));46 const prevDevRow = await q("SELECT value FROM settings WHERE key='security.dev_customer_ops'"); prevDev = prevDevRow[0]?.value ?? null;47 await owner.query("INSERT INTO settings(key,value) VALUES('security.dev_customer_ops','1') ON CONFLICT(key) DO UPDATE SET value='1'");48 const cust = await request.newContext({ baseURL: BASE, ignoreHTTPSErrors: true }); const lr = await login(cust, tokA); rec("customer fixture signs in (dev override on for this test only)", lr.ok());49 const my = await (await cust.get("/api/myapps")).json(); rec("My Apps: a customer sees NO internal applications, only Zloud itself", my.orgClass === "customer" && my.internalApps.length === 0 && my.cloud.key === "zoo-cloud");50 rec("a customer cannot read or change Central integration (platform only)", [401, 403].includes((await cust.get("/api/central")).status()) && [401, 403].includes((await cust.post("/api/central", { data: { action: "setOrgClass", orgId: A, class: "internal", confirm: "MARK INTERNAL" }, headers: O })).status()));51 rec("a customer cannot open the Central admin page content", !(await (await cust.get("/superadmin/central")).text()).includes("Application Registry"));52 rec("customer organization is still customer after the attempt", (await q("SELECT org_class FROM organizations WHERE id=$1", [A]))[0].org_class === "customer");53 // ---- tenant isolation of the new tables (direct, runtime role) ----54 await owner.query("INSERT INTO org_mappings(id,org_id,central_ref,created_at) VALUES('m_a',$1,$3,$4),('m_b',$2,$5,$4)", [A, B, "ref-a-" + ts, now, "ref-b-" + ts]);55 const as = async (org, mode, sql, p) => { const c = await app.connect(); try { await c.query("BEGIN"); await c.query("SELECT set_config('app.org_id',$1,true),set_config('app.mode',$2,true)", [org, mode]); return (await c.query(sql, p)).rows; } finally { await c.query("ROLLBACK"); c.release(); } };56 rec("RLS: tenant A reads only its own Central mapping", JSON.stringify((await as(A, "tenant", "SELECT central_ref FROM org_mappings")).map(r => r.central_ref)) === JSON.stringify(["ref-a-" + ts]));57 rec("RLS: no tenant context -> no mappings, no outbox, no external identities", (await as("", "none", "SELECT 1 FROM org_mappings UNION ALL SELECT 1 FROM central_outbox UNION ALL SELECT 1 FROM external_identities")).length === 0);58 rec("RLS: tenants cannot read external identities, OIDC requests or the outbox", (await as(A, "tenant", "SELECT 1 FROM external_identities UNION ALL SELECT 1 FROM oidc_requests UNION ALL SELECT 1 FROM central_outbox")).length === 0);59 // ---- platform administration ----60 const own = await request.newContext({ baseURL: BASE, ignoreHTTPSErrors: true }); await login(own, rd("admin-token"));61 const post = d => own.post("/api/central", { data: d, headers: O }); const j = async r => r.json().catch(() => ({}));62 const stt = await j(await own.get("/api/central")); rec("Super Admin API lists 11 integrations, none live, IAM blocked", stt.integrations?.length === 11 && stt.integrations.every(i => i.state !== "live") && stt.integrations.find(i => i.id === "iam").state === "blocked");63 rec("Super Admin Central page renders honest states", await (async () => { const t = await (await own.get("/superadmin/central")).text(); return /Blocked/.test(t) && /Cloud side prepared/.test(t) && !/>Live</.test(t) && /No Zoo Central API is documented/.test(t); })());64 rec("marking an organization internal requires the typed phrase", (await post({ action: "setOrgClass", orgId: B, class: "internal" })).status() === 422);65 rec("platform admin can map an org to an opaque Central reference (audited)", (await post({ action: "mapOrg", orgId: A, centralRef: "central:org:" + ts })).ok() && (await q("SELECT 1 FROM org_mappings WHERE central_ref=$1", ["central:org:" + ts])).length === 1);66 rec("a Central reference cannot be reused by two organizations", (await post({ action: "mapOrg", orgId: B, centralRef: "central:org:" + ts })).status() === 409);67 rec("granting an internal-app entitlement to a customer org is rejected end-to-end", (await post({ action: "grant", orgId: A, userId: UA, appKey: "zoo-connect" })).status() === 409);68 rec("the protected Zoo organization is internal and cannot be marked customer", (await q("SELECT org_class FROM organizations WHERE id='org_owner'"))[0].org_class === "internal" && (await post({ action: "setOrgClass", orgId: "org_owner", class: "customer" })).status() === 409);69 rec("internal org + member: an explicit entitlement is stored; non-members are refused", (await post({ action: "setOrgClass", orgId: B, class: "internal", confirm: "MARK INTERNAL" })).ok() && (await post({ action: "grant", orgId: B, userId: UB, appKey: "zoo-connect" })).ok() && (await post({ action: "grant", orgId: B, userId: UA, appKey: "zoo-connect" })).status() === 409);70 rec("reverting an org to customer removes its internal entitlements", (await post({ action: "setOrgClass", orgId: B, class: "customer" })).ok() && (await q("SELECT 1 FROM app_entitlements WHERE org_id=$1", [B])).length === 0);71 rec("Central endpoint setting accepts https only", (await post({ action: "endpoint", adapter: "notifications", url: "http://x.example/api" })).status() === 422 && (await post({ action: "endpoint", adapter: "notifications", url: "https://central.example/notify" })).ok());72 const st2 = await j(await own.get("/api/central")); rec("after an endpoint is set the adapter is 'ready, untested' — never live", st2.integrations.find(i => i.id === "notifications").state === "ready-untested");73 await post({ action: "endpoint", adapter: "notifications", url: "" });74 const aud = (await q("SELECT action FROM audit_log WHERE action LIKE 'central.%' ORDER BY seq DESC LIMIT 50")).map(r => r.action); rec("Central administration is audited", ["central.map_org", "central.org_class", "central.endpoint"].every(x => aud.includes(x)));75 rec("audit hash chain still verifies", await (async () => { const rows = await q("SELECT * FROM audit_log ORDER BY seq"); let prev = "GENESIS"; 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) return false; prev = r.hash; } return true; })());76} catch (e) { console.error("TEST ERROR", e); rec("test harness completed without error", false, String(e.message)); }77finally {78 await owner.query("DELETE FROM organizations WHERE id = ANY($1)", [[A, B]]).catch(() => {}); await owner.query("DELETE FROM users WHERE id = ANY($1)", [[UA, UB]]).catch(() => {});79 await owner.query(prevDev === null ? "DELETE FROM settings WHERE key='security.dev_customer_ops'" : "UPDATE settings SET value=$1 WHERE key='security.dev_customer_ops'", prevDev === null ? [] : [prevDev]).catch(() => {});80 await owner.query("DELETE FROM sessions WHERE user_id = ANY($1)", [[UA, UB]]).catch(() => {}); await owner.end(); await app.end();81}82const f = results.filter(r => !r.ok); console.log(`\n${results.length - f.length}/${results.length} Central integration checks passed`);83fs.mkdirSync("../design/verification", { recursive: true }); fs.writeFileSync("../design/verification/central.json", JSON.stringify({ at: new Date().toISOString(), scope: "Cloud-side contracts/adapters; no Zoo Central endpoint exists or was contacted", total: results.length, passed: results.length - f.length, results }, null, 1));84process.exit(f.length ? 1 : 0);85
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 0eebc42 on master.
Approval requests
None pending.