railyard/apps/console/test/migration.test.ts
caelum0x 90f6ba3b78 feat(ship): custom domains for shipped apps on the customer's own Cloudflare account (QY1.5, I6)
- packages/cli/src/domains.mjs: a dependency-free client of Cloudflare's
  public Workers Custom Domains API (zones lookup, PUT/GET/DELETE
  /accounts/{id}/workers/domains, certificate pack state). Cloudflare
  issues the TLS certificate; a domain reads active once it is. The token
  goes in the Authorization header only and is scrubbed from every error.
  Byte copy at apps/console/lib/ship/cf-domains.mjs (drift test).
- railyard domains [add|remove HOSTNAME] [--app]: the console attaches the
  hostname to the app's production Worker with the org's Cloudflare grant
  (the QY1.1 OAuth step; the access token is opened and used inside the
  console only). Without a grant (409 no_cloudflare_grant) the CLI does the
  same with the local login (CLOUDFLARE_API_TOKEN or the wrangler login
  file after `wrangler whoami`) and the console records the outcome. Adding
  an attached hostname keeps it; one on another Worker is refused; remove
  is idempotent; a hostname outside the account's zones is refused plainly.
- Console: migration 0010 railyard.app_domains (one org per hostname,
  lower case, cascade, RLS, no anon); GET/POST/DELETE /api/v1/domains and
  POST /api/v1/domains/record (CLI bearer); states refreshed from
  Cloudflare when the org has a grant. Cloudflare OAuth default scopes add
  zone:read and ssl_certs:write (orgs linked before need to run
  railyard link once more for console-side domains).
- Scribase bridge: new signed route domains {scribase_org_id, app?} ->
  {available, domains:[{app, hostname, state, checked_at, created_at}],
  next} for the Deploy tab; contract fixture v2 adds it (additive).

Tests: CLI 23/23 (new domains.test.mjs 5: grant path with the real console
handlers and a fake Cloudflare, local-login path, wrangler config file,
refusals, idempotent remove, no token printed or sent to the console);
console 147/147 (new lib/ship/domains.test.ts 4: drift, worker naming
equal to the CLI's, attach/detach and cross-org refusal, record and
refresh, bridge listing; 0010 migration on a scratch PG); contract 6/6;
console tsc clean.

Owner-only: one real-domain proof (railyard domains add on a domain in the
owner's Cloudflare account) is not run here; record it at the deploy gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 13:45:57 +03:00

278 lines
27 KiB
TypeScript

// The console migration applies to a scratch Postgres twice without error
// (idempotent) and leaves RLS on with no grants for anon. Never a hosted DB.
import { test, after } from "node:test";
import assert from "node:assert/strict";
import { execFileSync, spawnSync } from "node:child_process";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const MIGRATION = join(ROOT, "db/migrations/0001_railyard_console.sql");
const BRIDGE = join(ROOT, "db/migrations/0002_scribase_bridge.sql");
const AI = join(ROOT, "db/migrations/0003_ai_gateway.sql");
const ORDER = join(ROOT, "db/migrations/0004_bridge_order.sql");
const FLAGS = join(ROOT, "db/migrations/0005_flags.sql");
const WATCH = join(ROOT, "db/migrations/0006_watch.sql");
const SHIP = join(ROOT, "db/migrations/0007_ship.sql");
const SHIP_REPO = join(ROOT, "db/migrations/0008_ship_repo_id.sql");
const TARGETING = join(ROOT, "db/migrations/0009_flag_targeting.sql");
const DOMAINS = join(ROOT, "db/migrations/0010_app_domains.sql");
const have = spawnSync("pg_ctl", ["--version"]).status === 0 && spawnSync("initdb", ["--version"]).status === 0;
test("0001 applies twice on a scratch cluster; RLS on; anon has no access", { skip: have ? false : "pg_ctl/initdb not installed" }, () => {
const dir = mkdtempSync(join(tmpdir(), "ry-pg-"));
const port = String(55000 + Math.floor(Math.random() * 2000));
after(() => {
spawnSync("pg_ctl", ["-D", join(dir, "data"), "-m", "immediate", "stop"], { stdio: "ignore" });
rmSync(dir, { recursive: true, force: true });
});
execFileSync("initdb", ["-D", join(dir, "data"), "-U", "postgres", "-A", "trust", "--no-sync"], { stdio: "ignore" });
execFileSync("pg_ctl", ["-D", join(dir, "data"), "-o", `-p ${port} -k ${dir} -c listen_addresses=''`, "-w", "start"], { stdio: "ignore" });
const psql = (args: string[]) => execFileSync("psql", ["-h", dir, "-p", port, "-U", "postgres", "-v", "ON_ERROR_STOP=1", "-qAt", ...args], { encoding: "utf8" });
psql(["-c", "create role anon nologin; create role authenticated nologin; create role service_role nologin bypassrls;"]);
psql(["-f", MIGRATION]);
psql(["-f", MIGRATION]);
const tables = psql(["-c", "select string_agg(tablename, ',' order by tablename) from pg_tables where schemaname = 'railyard'"]).trim();
assert.equal(tables, "api_tokens,apps,billing_events,deploys,device_codes,entitlements,org_members,orgs");
const noRls = psql(["-c", "select count(*) from pg_tables where schemaname = 'railyard' and not rowsecurity"]).trim();
assert.equal(noRls, "0");
const anon = psql(["-c", "select count(*) from information_schema.role_table_grants where table_schema = 'railyard' and grantee = 'anon'"]).trim();
assert.equal(anon, "0");
// Replay protection is a database guarantee, not only application code.
psql(["-c", "insert into railyard.billing_events (webhook_id, event_type, outcome) values ('dodo:m1', 'payment.succeeded', 'applied')"]);
assert.throws(() => psql(["-c", "insert into railyard.billing_events (webhook_id, event_type, outcome) values ('dodo:m1', 'payment.succeeded', 'applied')"]), /duplicate key/);
});
test("0002 (Scribase bridge) applies twice after 0001; add-on plan allowed; bindings unique; anon has no access", { skip: have ? false : "pg_ctl/initdb not installed" }, () => {
const dir = mkdtempSync(join(tmpdir(), "ry-pg-"));
const port = String(57000 + Math.floor(Math.random() * 2000));
after(() => {
spawnSync("pg_ctl", ["-D", join(dir, "data"), "-m", "immediate", "stop"], { stdio: "ignore" });
rmSync(dir, { recursive: true, force: true });
});
execFileSync("initdb", ["-D", join(dir, "data"), "-U", "postgres", "-A", "trust", "--no-sync"], { stdio: "ignore" });
execFileSync("pg_ctl", ["-D", join(dir, "data"), "-o", `-p ${port} -k ${dir} -c listen_addresses=''`, "-w", "start"], { stdio: "ignore" });
const psql = (args: string[]) => execFileSync("psql", ["-h", dir, "-p", port, "-U", "postgres", "-v", "ON_ERROR_STOP=1", "-qAt", ...args], { encoding: "utf8" });
psql(["-c", "create role anon nologin; create role authenticated nologin; create role service_role nologin bypassrls;"]);
psql(["-f", MIGRATION]);
psql(["-f", BRIDGE]);
psql(["-f", MIGRATION]);
psql(["-f", BRIDGE]);
const org = psql(["-c", "insert into railyard.orgs (name, owner_user_id) values ('Acme', gen_random_uuid()) returning id"]).trim();
psql(["-c", `insert into railyard.entitlements (org_id, plan, status, addon_slots) values ('${org}', 'addon', 'active', '{deploy,analytics}')`]);
assert.throws(() => psql(["-c", `update railyard.entitlements set plan = 'free' where org_id = '${org}'`]), /entitlements_plan_check/);
psql(["-c", `insert into railyard.scribase_bindings (scribase_org_id, org_id) values ('org_abc', '${org}')`]);
assert.throws(() => psql(["-c", `insert into railyard.scribase_bindings (scribase_org_id, org_id) values ('org_other', '${org}')`]), /duplicate key/);
assert.throws(() => psql(["-c", `insert into railyard.scribase_bindings (scribase_org_id, org_id) values ('bad id;', '${org}')`]), /check constraint/);
psql(["-c", "insert into railyard.bridge_messages (message_id) values ('scribase:m1')"]);
assert.throws(() => psql(["-c", "insert into railyard.bridge_messages (message_id) values ('scribase:m1')"]), /duplicate key/);
const noRls = psql(["-c", "select count(*) from pg_tables where schemaname = 'railyard' and not rowsecurity"]).trim();
assert.equal(noRls, "0");
const anon = psql(["-c", "select count(*) from information_schema.role_table_grants where table_schema = 'railyard' and grantee in ('anon', 'authenticated')"]).trim();
assert.equal(anon, "0");
});
test("0003 (AI gateway) applies twice; usage adds atomically; secrets are not readable by anon", { skip: have ? false : "pg_ctl/initdb not installed" }, () => {
const dir = mkdtempSync(join(tmpdir(), "ry-pg-"));
const port = String(59000 + Math.floor(Math.random() * 900));
after(() => {
spawnSync("pg_ctl", ["-D", join(dir, "data"), "-m", "immediate", "stop"], { stdio: "ignore" });
rmSync(dir, { recursive: true, force: true });
});
execFileSync("initdb", ["-D", join(dir, "data"), "-U", "postgres", "-A", "trust", "--no-sync"], { stdio: "ignore" });
execFileSync("pg_ctl", ["-D", join(dir, "data"), "-o", `-p ${port} -k ${dir} -c listen_addresses=''`, "-w", "start"], { stdio: "ignore" });
const psql = (args: string[]) => execFileSync("psql", ["-h", dir, "-p", port, "-U", "postgres", "-v", "ON_ERROR_STOP=1", "-qAt", ...args], { encoding: "utf8" });
psql(["-c", "create role anon nologin; create role authenticated nologin; create role service_role nologin bypassrls;"]);
for (const f of [MIGRATION, BRIDGE, AI, MIGRATION, BRIDGE, AI]) psql(["-f", f]);
const org = psql(["-c", "insert into railyard.orgs (name, owner_user_id) values ('Acme', gen_random_uuid()) returning id"]).trim();
const key = psql(["-c", `insert into railyard.ai_keys (org_id, label, key_hash, daily_token_cap, monthly_token_cap) values ('${org}', 'shop', 'h1', 10, 100) returning id`]).trim();
psql(["-c", `select railyard.ai_add_usage('${key}', '2026-09-29', 7); select railyard.ai_add_usage('${key}', '2026-09-29', 5);`]);
assert.equal(psql(["-c", `select tokens || ',' || requests from railyard.ai_usage where key_id = '${key}'`]).trim(), "12,2");
assert.throws(() => psql(["-c", `insert into railyard.ai_credentials (org_id, provider, nonce, ciphertext, key_hint) values ('${org}', 'ours', 'n', 'c', 'h')`]), /check constraint/);
const anon = psql(["-c", "select count(*) from information_schema.role_table_grants where table_schema = 'railyard' and grantee in ('anon', 'authenticated')"]).trim();
assert.equal(anon, "0");
const exec = psql(["-c", "select has_function_privilege('anon', 'railyard.ai_add_usage(uuid, date, bigint)', 'execute')"]).trim();
assert.equal(exec, "f");
});
test("0004 (bridge order, P-Y1) applies twice; the guarded update never moves an entitlement back", { skip: have ? false : "pg_ctl/initdb not installed" }, () => {
const dir = mkdtempSync(join(tmpdir(), "ry-pg-"));
const port = String(53000 + Math.floor(Math.random() * 1900));
after(() => {
spawnSync("pg_ctl", ["-D", join(dir, "data"), "-m", "immediate", "stop"], { stdio: "ignore" });
rmSync(dir, { recursive: true, force: true });
});
execFileSync("initdb", ["-D", join(dir, "data"), "-U", "postgres", "-A", "trust", "--no-sync"], { stdio: "ignore" });
execFileSync("pg_ctl", ["-D", join(dir, "data"), "-o", `-p ${port} -k ${dir} -c listen_addresses=''`, "-w", "start"], { stdio: "ignore" });
const psql = (args: string[]) => execFileSync("psql", ["-h", dir, "-p", port, "-U", "postgres", "-v", "ON_ERROR_STOP=1", "-qAt", ...args], { encoding: "utf8" });
psql(["-c", "create role anon nologin; create role authenticated nologin; create role service_role nologin bypassrls;"]);
for (const f of [MIGRATION, BRIDGE, AI, ORDER, MIGRATION, BRIDGE, AI, ORDER]) psql(["-f", f]);
const org = psql(["-c", "insert into railyard.orgs (name, owner_user_id) values ('Acme', gen_random_uuid()) returning id"]).trim();
psql(["-c", `insert into railyard.entitlements (org_id, plan, status, addon_as_of) values ('${org}', 'addon', 'inactive', 2000)`]);
// The statement PostgrestRepo.saveAddonEntitlement sends (PostgREST or=(addon_as_of.is.null,addon_as_of.lte.N)).
const guarded = (status: string, asOf: number) =>
psql(["-c", `update railyard.entitlements set status = '${status}', addon_as_of = ${asOf} where org_id = '${org}' and (addon_as_of is null or addon_as_of <= ${asOf}) returning status`]).trim();
assert.equal(guarded("active", 1500), "", "an older state changes nothing");
assert.equal(psql(["-c", `select status from railyard.entitlements where org_id = '${org}'`]).trim(), "inactive");
assert.equal(guarded("active", 2500), "active");
assert.throws(() => psql(["-c", `update railyard.entitlements set addon_as_of = -1 where org_id = '${org}'`]), /entitlements_addon_as_of_check/);
});
test("0005 (flags, PY2.1) applies twice; one env per org/app/env; keys and flag names checked; anon has no access", { skip: have ? false : "pg_ctl/initdb not installed" }, () => {
const dir = mkdtempSync(join(tmpdir(), "ry-pg-"));
const port = String(51000 + Math.floor(Math.random() * 1900));
after(() => {
spawnSync("pg_ctl", ["-D", join(dir, "data"), "-m", "immediate", "stop"], { stdio: "ignore" });
rmSync(dir, { recursive: true, force: true });
});
execFileSync("initdb", ["-D", join(dir, "data"), "-U", "postgres", "-A", "trust", "--no-sync"], { stdio: "ignore" });
execFileSync("pg_ctl", ["-D", join(dir, "data"), "-o", `-p ${port} -k ${dir} -c listen_addresses=''`, "-w", "start"], { stdio: "ignore" });
const psql = (args: string[]) => execFileSync("psql", ["-h", dir, "-p", port, "-U", "postgres", "-v", "ON_ERROR_STOP=1", "-qAt", ...args], { encoding: "utf8" });
psql(["-c", "create role anon nologin; create role authenticated nologin; create role service_role nologin bypassrls;"]);
for (const f of [MIGRATION, BRIDGE, AI, ORDER, FLAGS, MIGRATION, BRIDGE, AI, ORDER, FLAGS]) psql(["-f", f]);
const org = psql(["-c", "insert into railyard.orgs (name, owner_user_id) values ('Acme', gen_random_uuid()) returning id"]).trim();
const key = `ry_flags_${"a".repeat(32)}`;
const env = psql(["-c", `insert into railyard.flag_envs (org_id, app, env, client_key) values ('${org}', 'shop', 'production', '${key}') returning id`]).trim();
assert.throws(() => psql(["-c", `insert into railyard.flag_envs (org_id, app, env, client_key) values ('${org}', 'shop', 'production', 'ry_flags_${"b".repeat(32)}')`]), /duplicate key/);
assert.throws(() => psql(["-c", `insert into railyard.flag_envs (org_id, app, env, client_key) values ('${org}', 'shop', 'feature-x', 'not-a-key')`]), /check constraint/);
psql(["-c", `insert into railyard.flags (env_id, key, enabled, value) values ('${env}', 'new_checkout', true, 'blue')`]);
assert.throws(() => psql(["-c", `insert into railyard.flags (env_id, key, enabled) values ('${env}', 'Bad Key', true)`]), /check constraint/);
// A first read is recorded once (the guarded update the store sends).
assert.equal(psql(["-c", `update railyard.flag_envs set first_read_at = now() where id = '${env}' and first_read_at is null returning 1`]).trim(), "1");
assert.equal(psql(["-c", `update railyard.flag_envs set first_read_at = now() where id = '${env}' and first_read_at is null returning 1`]).trim(), "");
psql(["-c", `delete from railyard.orgs where id = '${org}'`]);
assert.equal(psql(["-c", "select count(*) from railyard.flags"]).trim(), "0", "flags go with their org");
const anon = psql(["-c", "select count(*) from information_schema.role_table_grants where table_schema = 'railyard' and grantee in ('anon', 'authenticated')"]).trim();
assert.equal(anon, "0");
const noRls = psql(["-c", "select count(*) from pg_tables where schemaname = 'railyard' and not rowsecurity"]).trim();
assert.equal(noRls, "0");
});
test("0006 (watch, PY2.2) applies twice; https only; one status page per slug; history capped; anon has no access", { skip: have ? false : "pg_ctl/initdb not installed" }, () => {
const dir = mkdtempSync(join(tmpdir(), "ry-pg-"));
const port = String(49000 + Math.floor(Math.random() * 1900));
after(() => {
spawnSync("pg_ctl", ["-D", join(dir, "data"), "-m", "immediate", "stop"], { stdio: "ignore" });
rmSync(dir, { recursive: true, force: true });
});
execFileSync("initdb", ["-D", join(dir, "data"), "-U", "postgres", "-A", "trust", "--no-sync"], { stdio: "ignore" });
execFileSync("pg_ctl", ["-D", join(dir, "data"), "-o", `-p ${port} -k ${dir} -c listen_addresses=''`, "-w", "start"], { stdio: "ignore" });
const psql = (args: string[]) => execFileSync("psql", ["-h", dir, "-p", port, "-U", "postgres", "-v", "ON_ERROR_STOP=1", "-qAt", ...args], { encoding: "utf8" });
psql(["-c", "create role anon nologin; create role authenticated nologin; create role service_role nologin bypassrls;"]);
for (const f of [MIGRATION, BRIDGE, AI, ORDER, FLAGS, WATCH, MIGRATION, BRIDGE, AI, ORDER, FLAGS, WATCH]) psql(["-f", f]);
const org = psql(["-c", "insert into railyard.orgs (name, owner_user_id) values ('Acme', gen_random_uuid()) returning id"]).trim();
const id = psql(["-c", `insert into railyard.watch_checks (org_id, app, name, url, slug) values ('${org}', 'shop', 'Shop', 'https://shop.example.com/', 'shop-abc123') returning id`]).trim();
assert.throws(() => psql(["-c", `insert into railyard.watch_checks (org_id, app, name, url, slug) values ('${org}', 'blog', 'Blog', 'http://blog.example.com/', 'blog-abc123')`]), /check constraint/);
assert.throws(() => psql(["-c", `insert into railyard.watch_checks (org_id, app, name, url, slug) values ('${org}', 'blog', 'Blog', 'https://blog.example.com/', 'shop-abc123')`]), /duplicate key/);
psql(["-c", `insert into railyard.watch_status (check_id, state, history) values ('${id}', 'up', '[{"at":"2026-09-29T12:00:00Z","ok":true,"ms":80}]')`]);
assert.throws(() => psql(["-c", `update railyard.watch_status set state = 'red' where check_id = '${id}'`]), /check constraint/);
const big = JSON.stringify(Array.from({ length: 91 }, () => ({ ok: true })));
assert.throws(() => psql(["-c", `update railyard.watch_status set history = '${big}' where check_id = '${id}'`]), /check constraint/);
psql(["-c", `delete from railyard.orgs where id = '${org}'`]);
assert.equal(psql(["-c", "select count(*) from railyard.watch_status"]).trim(), "0");
assert.equal(psql(["-c", "select count(*) from information_schema.role_table_grants where table_schema = 'railyard' and grantee in ('anon', 'authenticated')"]).trim(), "0");
});
test("0007 (ship on push, PY3.1) applies twice; one link per repository; the grant is sealed columns only; anon has no access", { skip: have ? false : "pg_ctl/initdb not installed" }, () => {
const dir = mkdtempSync(join(tmpdir(), "ry-pg-"));
const port = String(47000 + Math.floor(Math.random() * 1900));
after(() => {
spawnSync("pg_ctl", ["-D", join(dir, "data"), "-m", "immediate", "stop"], { stdio: "ignore" });
rmSync(dir, { recursive: true, force: true });
});
execFileSync("initdb", ["-D", join(dir, "data"), "-U", "postgres", "-A", "trust", "--no-sync"], { stdio: "ignore" });
execFileSync("pg_ctl", ["-D", join(dir, "data"), "-o", `-p ${port} -k ${dir} -c listen_addresses=''`, "-w", "start"], { stdio: "ignore" });
const psql = (args: string[]) => execFileSync("psql", ["-h", dir, "-p", port, "-U", "postgres", "-v", "ON_ERROR_STOP=1", "-qAt", ...args], { encoding: "utf8" });
psql(["-c", "create role anon nologin; create role authenticated nologin; create role service_role nologin bypassrls;"]);
for (const f of [MIGRATION, BRIDGE, AI, ORDER, FLAGS, WATCH, SHIP, MIGRATION, BRIDGE, AI, ORDER, FLAGS, WATCH, SHIP]) psql(["-f", f]);
const org = psql(["-c", "insert into railyard.orgs (name, owner_user_id) values ('Acme', gen_random_uuid()) returning id"]).trim();
psql(["-c", `insert into railyard.github_installations (installation_id, org_id, account_login) values (777, '${org}', 'acme')`]);
const link = psql(["-c", `insert into railyard.ship_links (org_id, app, repo_id, repo_full_name, installation_id, production_branch, workflow_pr_url) values ('${org}', 'shop', 4242, 'acme/shop', 777, 'main', 'https://github.com/acme/shop/pull/1') returning id`]).trim();
assert.throws(() => psql(["-c", `insert into railyard.ship_links (org_id, app, repo_id, repo_full_name, installation_id, production_branch) values ('${org}', 'blog', 4242, 'acme/shop', 777, 'main')`]), /duplicate key/);
assert.throws(() => psql(["-c", `insert into railyard.ship_links (org_id, app, repo_id, repo_full_name, installation_id, production_branch, workflow_pr_url) values ('${org}', 'blog', 1, 'acme/blog', 777, 'main', 'https://evil.example/x')`]), /check constraint/);
assert.throws(() => psql(["-c", `insert into railyard.cloudflare_connections (org_id, account_id, refresh_nonce, refresh_ciphertext) values ('${org}', 'not-an-account', 'n', 'c')`]), /check constraint/);
psql(["-c", `insert into railyard.cloudflare_connections (org_id, account_id, refresh_nonce, refresh_ciphertext) values ('${org}', '0123456789abcdef0123456789abcdef', 'n', 'c')`]);
const cols = psql(["-c", "select string_agg(column_name, ',' order by column_name) from information_schema.columns where table_schema = 'railyard' and table_name = 'cloudflare_connections'"]).trim();
assert.equal(cols, "access_ciphertext,access_expires_at,access_nonce,account_id,account_name,org_id,refresh_ciphertext,refresh_nonce,updated_at");
psql(["-c", `insert into railyard.ship_link_sessions (id_hash, org_id, app, repo_full_name, pkce_verifier, expires_at, link_id) values ('${"a".repeat(64)}', '${org}', 'shop', 'acme/shop', '${"v".repeat(64)}', now() + interval '15 minutes', '${link}')`]);
assert.throws(() => psql(["-c", `update railyard.ship_link_sessions set state = 'done' where id_hash = '${"a".repeat(64)}'`]), /check constraint/);
psql(["-c", `delete from railyard.orgs where id = '${org}'`]);
assert.equal(psql(["-c", "select (select count(*) from railyard.ship_links) + (select count(*) from railyard.cloudflare_connections) + (select count(*) from railyard.ship_link_sessions) + (select count(*) from railyard.github_installations)"]).trim(), "0");
assert.equal(psql(["-c", "select count(*) from pg_tables where schemaname = 'railyard' and not rowsecurity"]).trim(), "0");
assert.equal(psql(["-c", "select count(*) from information_schema.role_table_grants where table_schema = 'railyard' and grantee in ('anon', 'authenticated')"]).trim(), "0");
});
test("0008 (ship repo id, P-Y11) applies twice after 0007; a session stores the checked repository id", { skip: have ? false : "pg_ctl/initdb not installed" }, () => {
const dir = mkdtempSync(join(tmpdir(), "ry-pg-"));
const port = String(49000 + Math.floor(Math.random() * 1900));
after(() => {
spawnSync("pg_ctl", ["-D", join(dir, "data"), "-m", "immediate", "stop"], { stdio: "ignore" });
rmSync(dir, { recursive: true, force: true });
});
execFileSync("initdb", ["-D", join(dir, "data"), "-U", "postgres", "-A", "trust", "--no-sync"], { stdio: "ignore" });
execFileSync("pg_ctl", ["-D", join(dir, "data"), "-o", `-p ${port} -k ${dir} -c listen_addresses=''`, "-w", "start"], { stdio: "ignore" });
const psql = (args: string[]) => execFileSync("psql", ["-h", dir, "-p", port, "-U", "postgres", "-v", "ON_ERROR_STOP=1", "-qAt", ...args], { encoding: "utf8" });
psql(["-c", "create role anon nologin; create role authenticated nologin; create role service_role nologin bypassrls;"]);
for (const f of [MIGRATION, BRIDGE, AI, ORDER, FLAGS, WATCH, SHIP, SHIP_REPO, SHIP_REPO]) psql(["-f", f]);
const org = psql(["-c", "insert into railyard.orgs (name, owner_user_id) values ('Acme', gen_random_uuid()) returning id"]).trim();
// A session starts with no checked id (the link was only opened), then stores the id GitHub confirmed.
psql(["-c", `insert into railyard.ship_link_sessions (id_hash, org_id, app, repo_full_name, pkce_verifier, expires_at) values ('${"b".repeat(64)}', '${org}', 'shop', 'acme/shop', '${"v".repeat(64)}', now() + interval '15 minutes')`]);
assert.equal(psql(["-c", `select repo_id is null from railyard.ship_link_sessions where id_hash = '${"b".repeat(64)}'`]).trim(), "t");
psql(["-c", `update railyard.ship_link_sessions set repo_id = 4242 where id_hash = '${"b".repeat(64)}'`]);
assert.equal(psql(["-c", `select repo_id from railyard.ship_link_sessions where id_hash = '${"b".repeat(64)}'`]).trim(), "4242");
assert.throws(() => psql(["-c", `update railyard.ship_link_sessions set repo_id = 0 where id_hash = '${"b".repeat(64)}'`]), /check constraint/);
assert.throws(() => psql(["-c", `update railyard.ship_link_sessions set repo_id = -1 where id_hash = '${"b".repeat(64)}'`]), /check constraint/);
const col = psql(["-c", "select data_type from information_schema.columns where table_schema = 'railyard' and table_name = 'ship_link_sessions' and column_name = 'repo_id'"]).trim();
assert.equal(col, "bigint");
});
test("0009 (flag targeting, QY1.3) applies twice after 0008; rules and segments are bounded, cascade with the environment, RLS on, no anon", { skip: have ? false : "pg_ctl/initdb not installed" }, () => {
const dir = mkdtempSync(join(tmpdir(), "ry-pg-"));
const port = String(51000 + Math.floor(Math.random() * 1900));
after(() => {
spawnSync("pg_ctl", ["-D", join(dir, "data"), "-m", "immediate", "stop"], { stdio: "ignore" });
rmSync(dir, { recursive: true, force: true });
});
execFileSync("initdb", ["-D", join(dir, "data"), "-U", "postgres", "-A", "trust", "--no-sync"], { stdio: "ignore" });
execFileSync("pg_ctl", ["-D", join(dir, "data"), "-o", `-p ${port} -k ${dir} -c listen_addresses=''`, "-w", "start"], { stdio: "ignore" });
const psql = (args: string[]) => execFileSync("psql", ["-h", dir, "-p", port, "-U", "postgres", "-v", "ON_ERROR_STOP=1", "-qAt", ...args], { encoding: "utf8" });
psql(["-c", "create role anon nologin; create role authenticated nologin; create role service_role nologin bypassrls;"]);
for (const f of [MIGRATION, BRIDGE, AI, ORDER, FLAGS, WATCH, SHIP, SHIP_REPO, TARGETING, TARGETING]) psql(["-f", f]);
const org = psql(["-c", "insert into railyard.orgs (name, owner_user_id) values ('Acme', gen_random_uuid()) returning id"]).trim();
const env = psql(["-c", `insert into railyard.flag_envs (org_id, app, env, client_key) values ('${org}', 'shop', 'production', 'ry_flags_${"a".repeat(32)}') returning id`]).trim();
psql(["-c", `insert into railyard.flag_targeting (env_id, key, targeting) values ('${env}', 'new_checkout', '{"rules":[{"conditions":[],"rollout":50}]}')`]);
psql(["-c", `insert into railyard.flag_segments (env_id, key, name, conditions) values ('${env}', 'paying', 'Paying', '[{"type":"property","key":"plan","operator":"exact","value":"pro"}]')`]);
assert.throws(() => psql(["-c", `insert into railyard.flag_targeting (env_id, key, targeting) values ('${env}', 'empty', '{"rules":[]}')`]), /check constraint/);
assert.throws(() => psql(["-c", `insert into railyard.flag_targeting (env_id, key, targeting) values ('${env}', 'Bad Key', '{"rules":[{}]}')`]), /check constraint/);
assert.throws(() => psql(["-c", `insert into railyard.flag_segments (env_id, key, name, conditions) values ('${env}', 'none', 'None', '[]')`]), /check constraint/);
psql(["-c", `delete from railyard.flag_envs where id = '${env}'`]);
assert.equal(psql(["-c", "select (select count(*) from railyard.flag_targeting) + (select count(*) from railyard.flag_segments)"]).trim(), "0");
assert.equal(psql(["-c", "select count(*) from pg_tables where schemaname = 'railyard' and not rowsecurity"]).trim(), "0");
assert.equal(psql(["-c", "select count(*) from information_schema.role_table_grants where table_schema = 'railyard' and grantee in ('anon', 'authenticated')"]).trim(), "0");
});
test("0010 (custom domains, QY1.5) applies twice after 0009; one org per hostname, lower case, cascade, RLS on, no anon", { skip: have ? false : "pg_ctl/initdb not installed" }, () => {
const dir = mkdtempSync(join(tmpdir(), "ry-pg-"));
const port = String(53000 + Math.floor(Math.random() * 1900));
after(() => {
spawnSync("pg_ctl", ["-D", join(dir, "data"), "-m", "immediate", "stop"], { stdio: "ignore" });
rmSync(dir, { recursive: true, force: true });
});
execFileSync("initdb", ["-D", join(dir, "data"), "-U", "postgres", "-A", "trust", "--no-sync"], { stdio: "ignore" });
execFileSync("pg_ctl", ["-D", join(dir, "data"), "-o", `-p ${port} -k ${dir} -c listen_addresses=''`, "-w", "start"], { stdio: "ignore" });
const psql = (args: string[]) => execFileSync("psql", ["-h", dir, "-p", port, "-U", "postgres", "-v", "ON_ERROR_STOP=1", "-qAt", ...args], { encoding: "utf8" });
psql(["-c", "create role anon nologin; create role authenticated nologin; create role service_role nologin bypassrls;"]);
for (const f of [MIGRATION, BRIDGE, AI, ORDER, FLAGS, WATCH, SHIP, SHIP_REPO, TARGETING, DOMAINS, DOMAINS]) psql(["-f", f]);
const org = psql(["-c", "insert into railyard.orgs (name, owner_user_id) values ('Acme', gen_random_uuid()) returning id"]).trim();
psql(["-c", `insert into railyard.app_domains (org_id, app, hostname, worker) values ('${org}', 'shop', 'app.example.com', 'shop')`]);
assert.throws(() => psql(["-c", `insert into railyard.app_domains (org_id, app, hostname, worker) values ('${org}', 'blog', 'app.example.com', 'blog')`]), /duplicate key/);
assert.throws(() => psql(["-c", `insert into railyard.app_domains (org_id, app, hostname, worker) values ('${org}', 'shop', 'App.Example.com', 'shop')`]), /check constraint/);
assert.throws(() => psql(["-c", `insert into railyard.app_domains (org_id, app, hostname, worker, state) values ('${org}', 'shop', 'b.example.com', 'shop', 'weird')`]), /check constraint/);
psql(["-c", `delete from railyard.orgs where id = '${org}'`]);
assert.equal(psql(["-c", "select count(*) from railyard.app_domains"]).trim(), "0");
assert.equal(psql(["-c", "select count(*) from pg_tables where schemaname = 'railyard' and not rowsecurity"]).trim(), "0");
assert.equal(psql(["-c", "select count(*) from information_schema.role_table_grants where table_schema = 'railyard' and grantee in ('anon', 'authenticated')"]).trim(), "0");
});