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/rls.mjs
1// Direct PostgreSQL row-level-security verification through the APPLICATION database role (studio_app) — not through HTTP.2// Fixtures are created with the owner role (outside RLS) and removed afterwards; real tenants/rows are never modified.3import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import pg from "pg";4const CFG = path.join(os.homedir(), ".config/zoo-cloud-studio"); const rd = f => fs.readFileSync(path.join(CFG, f), "utf8").trim();5const owner = new pg.Pool({ connectionString: `postgres://studio:${encodeURIComponent(rd("pg-password"))}@127.0.0.1:5432/studio`, max: 2 });6const app = new pg.Pool({ connectionString: `postgres://studio_app:${encodeURIComponent(rd("pg-app-password"))}@127.0.0.1:5432/studio`, max: 1 }); // max 1 => every query reuses the SAME connection7const results = []; const rec = (n, ok, d = "") => { results.push({ name: n, ok: !!ok, detail: d }); console.log((ok ? "PASS " : "FAIL ") + n + (ok || !d ? "" : " -> " + d)); };8async function as(scope, fn) { const c = await app.connect(); try { await c.query("BEGIN"); if (scope) await c.query("SELECT set_config('app.org_id',$1,true), set_config('app.mode',$2,true)", [scope.org ?? "", scope.mode]); const r = await fn(c); await c.query("COMMIT"); return r; } catch (e) { await c.query("ROLLBACK").catch(() => {}); throw e; } finally { c.release(); } }9const fails = async (fn) => { try { await fn(); return false; } catch (e) { return String(e.message); } };10const ts = Date.now(), A = "org_rlsA" + ts, B = "org_rlsB" + ts, now = new Date().toISOString();11const before = { audit: (await owner.query("SELECT count(*)::int n, max(seq) m FROM audit_log")).rows[0], proj: (await owner.query("SELECT count(*)::int n FROM projects WHERE org_id='org_owner'")).rows[0].n };12try {13 // ---- role hardening ----14 const role = (await owner.query("SELECT rolsuper, rolbypassrls, rolcreaterole, rolcreatedb FROM pg_roles WHERE rolname='studio_app'")).rows[0];15 rec("runtime role is not superuser, has no BYPASSRLS/CREATEROLE/CREATEDB", role && !role.rolsuper && !role.rolbypassrls && !role.rolcreaterole && !role.rolcreatedb);16 const owned = (await owner.query("SELECT count(*)::int n FROM pg_tables WHERE schemaname='public' AND tableowner='studio_app'")).rows[0].n;17 rec("runtime role owns no tables (policies cannot be bypassed as table owner)", owned === 0);18 const noRls = (await owner.query("SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public' AND c.relkind='r' AND NOT c.relrowsecurity")).rows.map(r => r.relname);19 rec("every public table has row-level security enabled", noRls.length === 0, noRls.join(","));20 rec("runtime role cannot alter schema", !!(await fails(() => app.query("CREATE TABLE zz_x(i int)"))));21 rec("runtime role cannot disable RLS", !!(await fails(() => app.query("ALTER TABLE projects DISABLE ROW LEVEL SECURITY"))));22 rec("runtime role cannot create roles / SET ROLE to the owner", !!(await fails(() => app.query("CREATE ROLE zz_evil"))) && !!(await fails(() => app.query("SET ROLE studio"))));2324 // ---- fixtures (owner role) ----25 for (const [o, n] of [[A, "RLS A"], [B, "RLS B"]]) {26 await owner.query("INSERT INTO organizations(id,slug,name,created_at) VALUES($1,$2,$3,$4)", [o, o.toLowerCase(), n, now]);27 await owner.query("INSERT INTO projects(id,slug,name,created_at,updated_at,org_id) VALUES($1,$2,$3,$4,$4,$5)", ["p_" + o, "s-" + o, "proj " + n, now, o]);28 await owner.query("INSERT INTO tasks(id,project_id,title,created_at) VALUES($1,$2,'t',$3)", ["t_" + o, "p_" + o, now]);29 await owner.query("INSERT INTO ai_sessions(id,project_id,title,provider,model,created_at,updated_at,org_id) VALUES($1,$2,'s','mock','m',$3,$3,$4)", ["s_" + o, "p_" + o, now, o]);30 await owner.query("INSERT INTO ai_messages(session_id,role,content,created_at) VALUES($1,'user','secret-' || $2,$3)", ["s_" + o, o, now]);31 await owner.query("INSERT INTO credentials(id,provider,ciphertext,iv,tag,updated_at,org_id) VALUES($1,'anthropic','c','i','t',$2,$3)", ["c_" + o, now, o]);32 await owner.query("INSERT INTO instances(id,org_id,name,kind,created_at) VALUES($1,$2,'inst','external',$3)", ["i_" + o, o, now]);33 await owner.query("INSERT INTO users(id,email,name,created_at) VALUES($1,$2,'u',$3)", ["u_" + o, o + "@example.test", now]);34 await owner.query("INSERT INTO memberships(org_id,user_id,role,created_at) VALUES($1,$2,'owner',$3)", [o, "u_" + o, now]);35 }36 // ---- fail closed ----37 const cnt = async (scope, t) => (await as(scope, c => c.query(`SELECT count(*)::int n FROM ${t}`))).rows[0].n;38 for (const t of ["projects", "ai_sessions", "credentials", "instances", "nodes", "users", "sessions", "memberships", "organizations", "tasks", "ai_messages", "audit_log"])39 rec(`no tenant context -> ${t} returns 0 rows (fail closed)`, (await app.query(`SELECT count(*)::int n FROM ${t}`)).rows[0].n === 0);40 rec("no tenant context -> INSERT rejected", !!(await fails(() => app.query("INSERT INTO projects(id,slug,name,created_at,updated_at,org_id) VALUES('x','x','x','x','x','org_owner')"))));41 rec("unknown mode value -> no rows", (await as({ org: A, mode: "root" }, c => c.query("SELECT count(*)::int n FROM projects"))).rows[0].n === 0);42 rec("mode set but empty org -> no tenant rows", (await as({ org: "", mode: "tenant" }, c => c.query("SELECT count(*)::int n FROM projects"))).rows[0].n === 0);43 // ---- isolation ----44 const ids = async (scope, t, col = "id") => (await as(scope, c => c.query(`SELECT ${col} v FROM ${t}`))).rows.map(r => r.v);45 rec("tenant A sees only its own project", JSON.stringify(await ids({ org: A, mode: "tenant" }, "projects")) === JSON.stringify(["p_" + A]));46 rec("tenant B sees only its own project", JSON.stringify(await ids({ org: B, mode: "tenant" }, "projects")) === JSON.stringify(["p_" + B]));47 rec("tenant A cannot read B's project by id", (await as({ org: A, mode: "tenant" }, c => c.query("SELECT 1 FROM projects WHERE id=$1", ["p_" + B]))).rowCount === 0);48 rec("tenant A cannot read B's tasks (child via parent)", (await as({ org: A, mode: "tenant" }, c => c.query("SELECT 1 FROM tasks WHERE id=$1", ["t_" + B]))).rowCount === 0);49 rec("tenant A cannot read B's AI sessions / messages", (await as({ org: A, mode: "tenant" }, c => c.query("SELECT 1 FROM ai_sessions WHERE id=$1 UNION ALL SELECT 1 FROM ai_messages WHERE content LIKE $2", ["s_" + B, "%" + B]))).rowCount === 0);50 rec("tenant A cannot read B's credentials", (await as({ org: A, mode: "tenant" }, c => c.query("SELECT 1 FROM credentials WHERE org_id=$1", [B]))).rowCount === 0);51 rec("tenant A cannot read B's instances", (await as({ org: A, mode: "tenant" }, c => c.query("SELECT 1 FROM instances WHERE org_id=$1", [B]))).rowCount === 0);52 rec("tenant A cannot UPDATE B's project (0 rows)", (await as({ org: A, mode: "tenant" }, c => c.query("UPDATE projects SET name='pwn' WHERE id=$1", ["p_" + B]))).rowCount === 0);53 rec("tenant A cannot DELETE B's project (0 rows)", (await as({ org: A, mode: "tenant" }, c => c.query("DELETE FROM projects WHERE id=$1", ["p_" + B]))).rowCount === 0);54 rec("B's project untouched after A's attempts", (await owner.query("SELECT name FROM projects WHERE id=$1", ["p_" + B])).rows[0].name === "proj RLS B");55 rec("tenant A cannot INSERT a row owned by B (WITH CHECK)", !!(await fails(() => as({ org: A, mode: "tenant" }, c => c.query("INSERT INTO projects(id,slug,name,created_at,updated_at,org_id) VALUES('zz1','zz1','z','x','x',$1)", [B])))));56 rec("tenant A cannot MOVE its row to B (UPDATE WITH CHECK)", !!(await fails(() => as({ org: A, mode: "tenant" }, c => c.query("UPDATE projects SET org_id=$1 WHERE id=$2", [B, "p_" + A])))));57 rec("tenant A cannot attach a task to B's project", !!(await fails(() => as({ org: A, mode: "tenant" }, c => c.query("INSERT INTO tasks(id,project_id,title,created_at) VALUES('zt','p_'||$1,'x','x')", [B])))));58 rec("tenant A can write inside its own scope", (await as({ org: A, mode: "tenant" }, c => c.query("UPDATE projects SET name='RLS A2' WHERE id=$1", ["p_" + A]))).rowCount === 1);59 rec("tenant sees only its own organization row and members", JSON.stringify(await ids({ org: A, mode: "tenant" }, "organizations")) === JSON.stringify([A]) && JSON.stringify(await ids({ org: A, mode: "tenant" }, "users")) === JSON.stringify(["u_" + A]));60 rec("tenant cannot read sessions table", (await cnt({ org: A, mode: "tenant" }, "sessions")) === 0);61 rec("tenant cannot read other tenants' audit rows", (await as({ org: A, mode: "tenant" }, c => c.query("SELECT 1 FROM audit_log WHERE org_id IS DISTINCT FROM $1", [A]))).rowCount === 0);62 rec("tenant cannot write the audit log directly", !!(await fails(() => as({ org: A, mode: "tenant" }, c => c.query("INSERT INTO audit_log(ts,actor,action,prev_hash,hash) VALUES('x','a','b','p','h')")))));63 rec("nobody (even system) can UPDATE/DELETE audit rows via the app role", !!(await fails(() => as({ mode: "system" }, c => c.query("UPDATE audit_log SET actor='x'")))) && !!(await fails(() => as({ mode: "system" }, c => c.query("DELETE FROM audit_log")))));64 rec("tenant cannot change platform settings", !!(await fails(() => as({ org: A, mode: "tenant" }, c => c.query("INSERT INTO settings(key,value) VALUES('security.trusted_tls','1')")))));65 rec("tenant cannot read platform inventory or contact requests", (await cnt({ org: A, mode: "tenant" }, "managed_inventory")) === 0 && (await cnt({ org: A, mode: "tenant" }, "contact_requests")) === 0);66 // ---- platform admin: metadata yes, content no ----67 rec("platform mode sees every tenant's instances (metadata)", (await as({ org: "org_owner", mode: "platform" }, c => c.query("SELECT 1 FROM instances WHERE org_id IN ($1,$2)", [A, B]))).rowCount === 2);68 rec("platform mode cannot read tenant projects / sessions / credentials / messages", (await as({ org: "org_owner", mode: "platform" }, c => c.query("SELECT 1 FROM projects WHERE org_id IN ($1,$2) UNION ALL SELECT 1 FROM ai_sessions WHERE org_id IN ($1,$2) UNION ALL SELECT 1 FROM credentials WHERE org_id IN ($1,$2) UNION ALL SELECT 1 FROM ai_messages WHERE session_id IN ('s_'||$1,'s_'||$2)", [A, B]))).rowCount === 0);69 rec("platform mode cannot read tenant node jobs", (await as({ org: "org_owner", mode: "platform" }, c => c.query("SELECT 1 FROM node_jobs WHERE org_id IN ($1,$2)", [A, B]))).rowCount === 0);70 // ---- demo (anonymous) ----71 rec("demo mode is read-only", !!(await fails(() => as({ org: "org_owner", mode: "demo" }, c => c.query("UPDATE projects SET name=name")))));72 rec("demo mode cannot read other tenants", (await as({ org: "org_owner", mode: "demo" }, c => c.query("SELECT 1 FROM projects WHERE org_id IN ($1,$2)", [A, B]))).rowCount === 0);73 rec("demo mode cannot read credentials", (await as({ org: "org_owner", mode: "demo" }, c => c.query("SELECT 1 FROM credentials"))).rowCount >= 0 && (await as({ org: "org_owner", mode: "demo" }, c => c.query("SELECT 1 FROM sessions"))).rowCount === 0);74 // ---- system (explicitly authorized) ----75 rec("system mode can read across tenants (queue/admin operation)", (await as({ mode: "system" }, c => c.query("SELECT 1 FROM projects WHERE org_id IN ($1,$2)", [A, B]))).rowCount === 2);76 // ---- connection pool reuse ----77 await as({ org: A, mode: "tenant" }, c => c.query("SELECT 1"));78 rec("pool reuse: after a tenant transaction the SAME connection carries no identity", (await app.query("SELECT current_setting('app.org_id', true) o, current_setting('app.mode', true) m")).rows[0].o === "" && (await app.query("SELECT count(*)::int n FROM projects")).rows[0].n === 0);79 const par = await Promise.all(Array.from({ length: 24 }, (_, i) => as({ org: i % 2 ? A : B, mode: "tenant" }, c => c.query("SELECT org_id FROM projects")).then(r => r.rows.every(x => x.org_id === (i % 2 ? A : B)) && r.rows.length === 1)));80 rec("pool reuse: 24 interleaved concurrent requests on one connection never cross tenants", par.every(Boolean));81 rec("rollback leaves no residual identity", await (async () => { await fails(() => as({ org: A, mode: "tenant" }, c => c.query("SELECT 1/0"))); return (await app.query("SELECT count(*)::int n FROM projects")).rows[0].n === 0; })());82 // ---- known limit (documented, not a pass) ----83 const esc = (await as({ org: A, mode: "tenant" }, c => c.query("SELECT set_config('app.mode','system',true)").then(() => c.query("SELECT count(*)::int n FROM projects")))).rows[0].n;84 console.log(`NOTE: GUC-based RLS protects against missing/incorrect WHERE clauses and cross-tenant logic bugs; a SQL-injection that can run set_config() could escalate (observed visible rows after set_config: ${esc}). Queries are parameterized; this limit is documented.`);85 // ---- owner data preserved ----86 const after = { audit: (await owner.query("SELECT count(*)::int n, max(seq) m FROM audit_log")).rows[0], proj: (await owner.query("SELECT count(*)::int n FROM projects WHERE org_id='org_owner'")).rows[0].n };87 rec("existing owner-tenant data unchanged", after.proj === before.proj && after.audit.n === before.audit.n);88} finally {89 for (const o of [A, B]) { await owner.query("DELETE FROM organizations WHERE id=$1", [o]); await owner.query("DELETE FROM users WHERE id=$1", ["u_" + o]); }90 await owner.query("DELETE FROM ai_sessions WHERE org_id = ANY($1)", [[A, B]]); await owner.query("DELETE FROM credentials WHERE org_id = ANY($1)", [[A, B]]); await owner.query("DELETE FROM projects WHERE org_id = ANY($1)", [[A, B]]); await owner.end(); await app.end();91}92const fail = results.filter(r => !r.ok); console.log(`\n${results.length - fail.length}/${results.length} RLS checks passed`);93fs.mkdirSync("../design/verification", { recursive: true }); fs.writeFileSync("../design/verification/rls.json", JSON.stringify({ at: new Date().toISOString(), total: results.length, passed: results.length - fail.length, results }, null, 1));94process.exit(fail.length ? 1 : 0);95
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 a177d6e on master.
Approval requests
None pending.