feat(ix): добавить точки обмена трафиком
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Failing after 4m0s
Docker images / backend-image (push) Skipped
Docker images / frontend-image (push) Successful in 5m0s
Docker images / updater-image (push) Successful in 1m56s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / publish-release (push) Skipped
Docker images / notify-webhook (push) Skipped
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Failing after 4m0s
Docker images / backend-image (push) Skipped
Docker images / frontend-image (push) Successful in 5m0s
Docker images / updater-image (push) Successful in 1m56s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / publish-release (push) Skipped
Docker images / notify-webhook (push) Skipped
This commit is contained in:
1 parent
80cd3a18d7
commit
d422050a4b
65 files changed
+2563
-59
No files matched your search
@@ -0,0 +1,36 @@
|
||||
import { execFileSync } from "node:child_process"
|
||||
import { homedir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
|
||||
export const hosts = ["194.226.121.150", "104.165.244.7"] as const
|
||||
const key = join(homedir(), ".ssh", "chr_claude")
|
||||
const known = process.env.MMAPP_IX_TEST_KNOWN_HOSTS ?? join(homedir(), ".ssh", "known_hosts")
|
||||
|
||||
export const quote = (value: string) => '"' + value.replace(/[\\"$]/g, "\\$&").replace(/\n/g, "\\n") + '"'
|
||||
export const sshOptions = ["-F", process.platform === "win32" ? "NUL" : "/dev/null", "-i", key,
|
||||
"-o", "IdentitiesOnly=yes", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes", "-o", "UserKnownHostsFile=" + known,
|
||||
"-o", "ConnectTimeout=12", "-o", "LogLevel=ERROR"]
|
||||
|
||||
export function cli(side: number, expression: string, stage?: string) {
|
||||
const args = [...sshOptions, "claude@" + hosts[side],
|
||||
`:onerror err in={ ${expression.replace(/\r?\n\s*/g, " ")}; :put "IX_OK" } do={ :put ("IX_ERROR:" . $err) }`]
|
||||
const run = () => execFileSync("ssh", args, { encoding: "utf8", timeout: 35000, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }).trim()
|
||||
let stdout: string
|
||||
try {
|
||||
for (let attempt = 0;; attempt++) {
|
||||
try { stdout = run(); break } catch (error) {
|
||||
// Retry only when the command could not have reached the router.
|
||||
const failure = error as { status?: number; stderr?: string; stdout?: string }
|
||||
if (attempt >= 2 || failure.status !== 255 || failure.stdout || !/^ssh: connect to host .* port 22: Connection timed out\s*$/i.test(failure.stderr ?? "")) throw error
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (stage) throw Error(`CHR ${side + 1}: SSH failed during ${stage}`)
|
||||
throw error
|
||||
}
|
||||
if (!stdout.split(/\r?\n/).includes("IX_OK") || stdout.includes("IX_ERROR") || /syntax error|expected end|expected closing/.test(stdout)) {
|
||||
const diagnostic = stdout.replace(/[a-f0-9]{36,}/gi, "[redacted]").slice(0, 420)
|
||||
throw Error(`CHR ${side + 1} rejected ${stage ?? expression.slice(0, 360)} · ${diagnostic}`)
|
||||
}
|
||||
return stdout.replace(/\r?\n?IX_OK$/, "").trim()
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { randomBytes, randomUUID, X509Certificate } from "node:crypto"
|
||||
import { mkdtemp } from "node:fs/promises"
|
||||
import { createServer, isIPv4 } from "node:net"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { setTimeout as delay } from "node:timers/promises"
|
||||
import { getCACertificates, setDefaultCACertificates } from "node:tls"
|
||||
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"
|
||||
import EmbeddedPostgres from "embedded-postgres"
|
||||
import { SignJWT } from "jose"
|
||||
import { ixNamespace } from "../../src/services/internet-exchange-plan.js"
|
||||
import { cli, hosts, quote } from "./ix-chr-ssh.mjs"
|
||||
|
||||
assert.deepEqual(process.argv.slice(2), ["--owned-test-pair"])
|
||||
for (const name of Object.keys(process.env)) {
|
||||
if (/^(DATABASE_|MCP_|AUTH_|PG|MMAPP_)/.test(name)) delete process.env[name]
|
||||
}
|
||||
process.env.DOTENV_CONFIG_PATH = join(tmpdir(), "mmapp-ix-no-env-" + randomUUID())
|
||||
|
||||
const id = randomUUID(), ns = ixNamespace(id), short = ns.slice(0, 12)
|
||||
const segment = short + "-gre", gre = short + "-gre", pin = (side: number) => "10.245.0." + (1 + side)
|
||||
const psk = randomBytes(32).toString("hex"), password = randomBytes(24).toString("hex")
|
||||
const roots = getCACertificates("default")
|
||||
const certificates: string[] = []
|
||||
const entered = new Map<number, string>()
|
||||
const result: Record<string, unknown> = {}
|
||||
let appliedNamespace: string | undefined
|
||||
const ipsecPaths = ["/ip/ipsec/policy", "/ip/ipsec/identity", "/ip/ipsec/peer", "/ip/ipsec/proposal", "/ip/ipsec/profile"]
|
||||
const ixPaths = ["/ip/route", "/ip/address", "/ip/firewall/filter", "/ipv6/firewall/filter", "/ip/vrf", "/interface/bridge"]
|
||||
const sides = [0, 1]
|
||||
|
||||
function baseline(side: number) {
|
||||
return cli(side, `:put [/system resource get version]; :put [/system resource get board-name];
|
||||
:put [/ip/service/print as-value proplist=disabled,port,certificate,address where name=www-ssl and dynamic=no];
|
||||
:put [:len [/interface/gre/find]]; :put [:len [/ip/vrf/find]];
|
||||
:put [:len [/ip/ipsec/peer/find]]; :put [:len [/ip/ipsec/installed-sa/find]];
|
||||
:put [:len [/ip/firewall/filter/find]]; :put [:len [/ipv6/firewall/filter/find]];
|
||||
:put [:len [/ip/address/find where address~${quote("^" + hosts[side] + "/")}]]`)
|
||||
}
|
||||
|
||||
async function port() {
|
||||
const socket = createServer()
|
||||
await new Promise<void>((ok, fail) => socket.listen(0, "127.0.0.1", ok).on("error", fail))
|
||||
const value = (socket.address() as { port: number }).port
|
||||
await new Promise<void>((ok, fail) => socket.close(error => error ? fail(error) : ok()))
|
||||
return value
|
||||
}
|
||||
|
||||
async function until<T>(label: string, check: () => T | Promise<T>, timeout = 45000) {
|
||||
const end = Date.now() + timeout
|
||||
do {
|
||||
const value = await check()
|
||||
if (value) return value
|
||||
await delay(900)
|
||||
} while (Date.now() < end)
|
||||
throw Error(label + " timed out")
|
||||
}
|
||||
|
||||
function prepareGre(side: number) {
|
||||
const local = hosts[side], remote = hosts[1 - side]
|
||||
const p = quote(short)
|
||||
cli(side, `:put "profile"; /ip/ipsec/profile/add name=${p} enc-algorithm=aes-256 hash-algorithm=sha256 dh-group=modp2048;
|
||||
:put "proposal"; /ip/ipsec/proposal/add name=${p} enc-algorithms=aes-256-cbc auth-algorithms=sha256 pfs-group=modp2048;
|
||||
:put "peer"; /ip/ipsec/peer/add name=${p} address=${remote}/32 local-address=${local} profile=${p} exchange-mode=ike2 passive=${side ? "yes" : "no"};
|
||||
:put "identity"; /ip/ipsec/identity/add peer=${p} auth-method=pre-shared-key secret=${quote(psk)} comment=${p};
|
||||
:put "policy"; /ip/ipsec/policy/add peer=${p} src-address=${local}/32 dst-address=${remote}/32 protocol=gre action=encrypt level=require tunnel=no proposal=${p} comment=${p};
|
||||
:put "GRE"; /interface/gre/add name=${quote(gre)} local-address=${local} remote-address=${remote} allow-fast-path=no comment=${quote("IX:" + segment)};
|
||||
/ip/address/add address=${pin(side)}/30 interface=${quote(gre)} comment=${quote(ns + ":lab:gre")}`, "isolated IKEv2/GRE setup")
|
||||
}
|
||||
|
||||
async function openRest(side: number) {
|
||||
const sessions = cli(side, ':put [/user/active/print as-value proplist=address where name=claude and via=ssh]')
|
||||
const sources = [...new Set([...sessions.matchAll(/address=([\d.]+)/g)].map(match => match[1]))]
|
||||
assert(sources.length === 1 && isIPv4(sources[0]), "Cannot pin HTTPS to a single observed management address")
|
||||
const source = sources[0] + "/32", host = hosts[side], ca = short + "-ca", leaf = short + "-tls"
|
||||
cli(side, `/certificate/add name=${quote(ca)} common-name=${quote(ca)} key-usage=key-cert-sign,crl-sign days-valid=1;
|
||||
/certificate/sign [find where name=${quote(ca)}];
|
||||
/certificate/add name=${quote(leaf)} common-name=${quote(host)} subject-alt-name=IP:${host} key-usage=tls-server days-valid=1;
|
||||
/certificate/sign [find where name=${quote(leaf)}] ca=${quote(ca)};
|
||||
/certificate/export-certificate [find where name=${quote(ca)}] file-name=${quote(ca)}`)
|
||||
const certificate = cli(side, `:put [/file/get [find where name=${quote(ca + ".crt")}] contents]`)
|
||||
assert.equal(new X509Certificate(certificate).ca, true)
|
||||
certificates.push(certificate)
|
||||
setDefaultCACertificates([...roots, ...certificates])
|
||||
cli(side, `/ip/firewall/filter/add chain=input action=drop protocol=tcp dst-port=443 dst-address=${host}/32 src-address=!${source} comment=${quote(ns + ":lab:tls")};
|
||||
/user/group/add name=${quote(short)} policy=read,write,api,rest-api;
|
||||
/user/add name=${quote(short)} address=${source} group=${quote(short)} password=${quote(password)};
|
||||
/ip/service/set [find where name=www-ssl and dynamic=no] address=${source} certificate=${quote(leaf)} disabled=no`, "restricted HTTPS REST setup")
|
||||
let lastError = ""
|
||||
await until("router REST on verified HTTPS", async () => {
|
||||
const response = await fetch(`https://${host}/rest/system/resource`, {
|
||||
headers: { authorization: "Basic " + Buffer.from(short + ":" + password).toString("base64") }, signal: AbortSignal.timeout(5000),
|
||||
}).catch(error => { lastError = String(error.cause ?? error); return undefined })
|
||||
if (!response) return false
|
||||
assert.equal(response.status, 200, "REST test user was refused")
|
||||
assert.equal((await response.json()).version, "7.24.5 (stable)")
|
||||
return true
|
||||
}, 18000).catch(error => { throw Error(`CHR ${side + 1}: ${error.message} · ${lastError}`) })
|
||||
}
|
||||
|
||||
function clean(side: number, before: string) {
|
||||
const own = `where comment~${quote(appliedNamespace ? `^(${ns}|${appliedNamespace}):` : "^" + ns + ":")}`
|
||||
const checks = ixPaths.map(path => `[:len [${path}/find ${own}]]`)
|
||||
cli(side, `/ip/service/set [find where name=www-ssl and dynamic=no] disabled=yes address="" certificate=none;
|
||||
/user/remove [/user/find where name=${quote(short)}]; /user/group/remove [/user/group/find where name=${quote(short)}];
|
||||
/file/remove [/file/find where name=${quote(short + "-ca.crt")}];
|
||||
/certificate/remove [/certificate/find where name=${quote(short + "-tls")}];
|
||||
/certificate/remove [/certificate/find where name=${quote(short + "-ca")}];
|
||||
${ixPaths.map(path => `${path}/remove [${path}/find ${own}]`).join("; ")};
|
||||
/interface/gre/remove [/interface/gre/find where name=${quote(gre)} and comment=${quote("IX:" + segment)}];
|
||||
${ipsecPaths.map((path, i) => `${path}/remove [${path}/find where ${i < 2 ? "comment" : "name"}=${quote(short)}]`).join("; ")}`)
|
||||
checks.push(...ipsecPaths.map((path, i) => `[:len [${path}/find where ${i < 2 ? "comment" : "name"}=${quote(short)}]]`),
|
||||
`[:len [/user/find where name=${quote(short)}]]`, `[:len [/user/group/find where name=${quote(short)}]]`,
|
||||
`[:len [/certificate/find where name~${quote("^" + short + "-(ca|tls)$")}]]`, `[:len [/file/find where name=${quote(short + "-ca.crt")}]]`)
|
||||
assert.equal(cli(side, ":put (" + checks.join("+") + ")"), "0")
|
||||
assert.equal(baseline(side), before)
|
||||
}
|
||||
|
||||
async function useManager() {
|
||||
const root = await mkdtemp(join(tmpdir(), "mmapp-ix-mcp-"))
|
||||
process.chdir(root)
|
||||
const pgPort = await port(), httpPort = await port()
|
||||
const origin = `http://127.0.0.1:${httpPort}`, endpoint = new URL("/mcp", origin)
|
||||
const pgPassword = randomBytes(24).toString("hex"), jwtSecret = randomBytes(32).toString("hex")
|
||||
Object.assign(process.env, { DATABASE_URL: `postgresql://ixlab:${pgPassword}@127.0.0.1:${pgPort}/postgres`,
|
||||
NODE_ENV: "test", AUTH_REQUIRED: "true", AUTH_JWT_SECRET: jwtSecret, AUTH_ISSUER: origin,
|
||||
AUTH_PORTAL_URL: origin, MCP_STATE_DIR: join(root, "state"), MCP_PUBLIC_URL: endpoint.href, MCP_UI_URL: origin, CORS_ORIGIN: origin })
|
||||
const pg = new EmbeddedPostgres({ databaseDir: join(root, "db"), user: "ixlab", password: pgPassword, port: pgPort,
|
||||
persistent: false, createPostgresUser: false, initdbFlags: ["--encoding=UTF8", "--no-locale"], postgresFlags: ["-h", "127.0.0.1"],
|
||||
onLog: () => {}, onError: () => {} })
|
||||
await pg.initialise()
|
||||
await pg.start()
|
||||
const { pool, closePool } = await import("../../src/db/index.js")
|
||||
const { applySqlMigrations } = await import("../../src/db/migrate.js")
|
||||
const { buildApp } = await import("../../src/index.js")
|
||||
const { updateMcpSettings } = await import("../../src/modules/mcp/store.js")
|
||||
let app: Awaited<ReturnType<typeof buildApp>> | undefined
|
||||
const client = new Client({ name: "owned-ix-gre", version: "1.0.0" })
|
||||
try {
|
||||
await applySqlMigrations(pool)
|
||||
const serverIds: number[] = []
|
||||
for (const [side, host] of hosts.entries()) {
|
||||
const { rows } = await pool.query(`INSERT INTO servers(name,host,port,username,password,use_ssl,verify_ssl,enabled,type)
|
||||
VALUES($1,$2,443,$3,$4,true,true,true,'ix-node') RETURNING id`, [`ix-chr-${side + 1}`, host, short, password])
|
||||
serverIds.push(Number(rows[0].id))
|
||||
}
|
||||
const permissions = ["mm:network:read", "mm:network:write", "mm:mcp:admin", "mm:mcp:approve"]
|
||||
const actor = { id: "ix-fixture", email: "[email protected]", name: "IX fixture", apps: ["mm"], permissions,
|
||||
expiresAt: Date.now() + 1800000, issuedAt: Date.now() }
|
||||
await updateMcpSettings({ enabled: true }, actor)
|
||||
app = await buildApp({ startScheduler: false, logger: false })
|
||||
await app.listen({ port: httpPort, host: "127.0.0.1" })
|
||||
const jwt = await new SignJWT({ sub: actor.id, apps: actor.apps, permissions }).setProtectedHeader({ alg: "HS256" })
|
||||
.setIssuer(origin).setIssuedAt().setExpirationTime("15m").sign(new TextEncoder().encode(jwtSecret))
|
||||
async function rest(path: string, data?: object) {
|
||||
const response = await fetch(origin + "/api" + path, { method: data ? "POST" : "GET",
|
||||
headers: { authorization: "Bearer " + jwt, "content-type": "application/json" },
|
||||
...(data ? { body: JSON.stringify(data) } : {}), signal: AbortSignal.timeout(15000) })
|
||||
const body = await response.json()
|
||||
assert(response.ok, `${path}: ${response.status} ${JSON.stringify(body).slice(0, 600)}`)
|
||||
return body
|
||||
}
|
||||
const configuration = { name: segment, sites: serverIds.map((serverId, side) => ({
|
||||
serverId, routerId: pin(side), autonomousSystem: 64512 + side,
|
||||
interfaces: [{ name: gre, kind: "gre-ipsec", localEndpoint: hosts[side], endpoint: hosts[1 - side], peerServerId: serverIds[1 - side] }],
|
||||
})) }
|
||||
const draft = await rest("/ix/segments", { revision: 0, configuration })
|
||||
const segmentId: string = draft.segment.id
|
||||
assert.match(segmentId, /^[0-9a-f-]{36}$/)
|
||||
appliedNamespace = ixNamespace(segmentId)
|
||||
assert.equal(draft.segment.revision, 1)
|
||||
assert.equal(draft.segment.appliedRevision, null)
|
||||
result.managerRestDraft = true
|
||||
const { token } = await rest("/mcp/connections", { name: "Owned IX approval", mode: "approval", permissions: ["mm:network:read", "mm:network:write"],
|
||||
limits: { mutationsPerHour: 40, callsPerMinute: 120 },
|
||||
expiresAt: new Date(Date.now() + 600000).toISOString(), scope: { serverIds, allowGlobal: false,
|
||||
operationIds: ["network.ix.configure", "network.ix.read", "changes.apply", "operations.read"] } })
|
||||
await client.connect(new StreamableHTTPClientTransport(endpoint, {
|
||||
requestInit: { headers: { authorization: "Bearer " + token } },
|
||||
}), { timeout: 10000 })
|
||||
async function call(name: string, args: object, expectedError = false) {
|
||||
const reply = await client.callTool({ name, arguments: args }, undefined, { timeout: 120000 })
|
||||
assert.equal(Boolean(reply.isError), expectedError, name + " " + JSON.stringify(reply.structuredContent ?? reply.content).slice(0, 1200))
|
||||
return (reply.structuredContent as { result: any })?.result
|
||||
}
|
||||
const plan = await call("mm_ix_change_plan", { change: { id: segmentId, revision: 1, configuration } })
|
||||
assert.equal(plan.state, "awaiting-approval")
|
||||
const apply = { planId: plan.planId, idempotencyKey: randomUUID() }
|
||||
await call("mm_change_apply", apply, true)
|
||||
await rest("/mcp/plans/" + plan.planId + "/decision", { approve: true })
|
||||
const op = await call("mm_change_apply", apply)
|
||||
const terminal = await until("MCP terminal operation", async () => {
|
||||
const value = await call("mm_operation_get", { operationId: op.id })
|
||||
return !["pending", "running"].includes(value.state) && value
|
||||
}, 90000)
|
||||
assert.equal(terminal.state, "applied", JSON.stringify({ state: terminal.state, error: terminal.error_code }))
|
||||
assert.equal(terminal.verification, "passed")
|
||||
assert.equal((await call("mm_change_apply", apply)).id, op.id)
|
||||
const verified = await call("mm_ix_segment_get", { id: segmentId })
|
||||
assert.equal(verified.segment.appliedRevision, 2)
|
||||
const status = await rest("/ix/segments/" + segmentId + "/status")
|
||||
assert.deepEqual(status.sites.map(({ serverId, available }: { serverId: number; available: boolean }) => [serverId, available]),
|
||||
serverIds.map(serverId => [serverId, true]))
|
||||
result.mcpAppliedAndVerified = true
|
||||
result.routerRestSites = status.sites.length
|
||||
} finally {
|
||||
await client.close()
|
||||
await app?.close()
|
||||
await closePool()
|
||||
await pg.stop()
|
||||
}
|
||||
}
|
||||
|
||||
function packets(side: number) {
|
||||
assert(appliedNamespace)
|
||||
return Number(cli(side, `:put [/ping address=${pin(1 - side)} src-address=${pin(side)} vrf=${appliedNamespace} count=3 interval=250ms]`).split(/\r?\n/).at(-1))
|
||||
}
|
||||
|
||||
let failure: unknown
|
||||
try {
|
||||
const original = sides.map(baseline)
|
||||
for (const value of original) {
|
||||
const [version, board, ...expected] = value.split(/\r?\n/)
|
||||
assert.equal(version, "7.24.5 (stable)")
|
||||
assert.match(board, /^CHR/)
|
||||
const [https, ...inventory] = expected
|
||||
assert.match(https, /(?:^|;)certificate=none;disabled=true;port=443$/)
|
||||
assert.deepEqual(inventory, ["0", "1", "0", "0", "0", "0", "1"])
|
||||
}
|
||||
for (const side of sides) {
|
||||
entered.set(side, original[side])
|
||||
prepareGre(side)
|
||||
}
|
||||
for (const side of sides) await openRest(side)
|
||||
console.log("Both RouterOS REST endpoints authenticated with temporary trusted HTTPS certificates")
|
||||
await useManager()
|
||||
console.log("MCP applied the reviewed configuration to both routers")
|
||||
await until("encrypted GRE forwarding", () => packets(0) === 3 && packets(1) === 3)
|
||||
const sas = sides.map(side => Number(cli(side, ":put [:len [/ip/ipsec/installed-sa/find where state=mature]]")))
|
||||
assert(sas.every(count => count === 2))
|
||||
result.greReplies = [3, 3]
|
||||
result.matureIpsecSAs = sas
|
||||
// Turn off both matching policies during the plaintext negative test.
|
||||
for (const side of sides) cli(side, `/ip/ipsec/policy/disable [/ip/ipsec/policy/find where comment=${quote(short)}]`)
|
||||
for (const side of sides) assert.equal(packets(side), 0)
|
||||
result.plaintextGreBlocked = true
|
||||
for (const side of sides) cli(side, `/ip/ipsec/policy/enable [/ip/ipsec/policy/find where comment=${quote(short)}]`)
|
||||
await until("GRE recovery with required IPsec", () => packets(0) === 3 && packets(1) === 3)
|
||||
result.greRecovered = true
|
||||
} catch (error) {
|
||||
failure = error
|
||||
}
|
||||
setDefaultCACertificates(roots)
|
||||
let testStandRestored = true
|
||||
for (const [side, original] of entered) {
|
||||
try { clean(side, original) } catch (error) {
|
||||
console.error(`Cleanup unconfirmed on CHR ${side + 1} · ${ns} ${appliedNamespace ?? ""}`)
|
||||
testStandRestored = false
|
||||
failure ??= error
|
||||
}
|
||||
}
|
||||
console.log(JSON.stringify({ ...result, testStandRestored }))
|
||||
if (failure) throw failure
|
||||
@@ -0,0 +1,198 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { randomInt, randomUUID } from "node:crypto"
|
||||
import { setTimeout as delay } from "node:timers/promises"
|
||||
import { ixSegmentConfigurationSchema } from "@mmapp/contracts/internet-exchange"
|
||||
import { compileIxConfiguration, ixDiscardInterface, ixNamespace } from "../../src/services/internet-exchange-plan.js"
|
||||
import { cli, hosts, quote } from "./ix-chr-ssh.mjs"
|
||||
|
||||
assert.equal(process.argv[2], "--owned-test-pair")
|
||||
assert(process.argv.length === 3 || (process.argv.length === 4 && process.argv[3] === "--ipv6"))
|
||||
const ipv6 = process.argv[3] === "--ipv6"
|
||||
const id = randomUUID(), ns = ixNamespace(id), short = ns.slice(0, 10)
|
||||
const discard = ixDiscardInterface(id)
|
||||
const marker = ns + ":lab", primary = short + "-p", backup = short + "-b"
|
||||
const port = randomInt(45000, 55000)
|
||||
const net = "10.247." + randomInt(32, 224)
|
||||
const [aP, bP, aB, bB] = ipv6 ? ["fd00:247:1::1", "fd00:247:1::2", "fd00:247:2::1", "fd00:247:2::2"] : [1, 2, 5, 6].map(n => net + "." + n)
|
||||
const [target, pProbe, bProbe, trafficSource] = ipv6 ? ["2001:db8:3::200", "2001:db8:3::201", "2001:db8:3::202", "2001:db8:3::203"] : ["192.0.2.200", "192.0.2.201", "192.0.2.202", "192.0.2.203"]
|
||||
const afi = ipv6 ? "ipv6" : "ip", length = ipv6 ? "/128" : "/32", gateway = ipv6 ? "fd00:198:18::101" : "198.18.0.101"
|
||||
const addressPath = "/" + afi + "/address", routePath = "/" + afi + "/route", filterPath = "/" + afi + "/firewall/filter", listPath = "/" + afi + "/firewall/address-list"
|
||||
const advertise: Record<string, string> = ipv6 ? { advertise: "no" } : {}
|
||||
const community = "65000:120"
|
||||
const entered = new Set<number>()
|
||||
const results: Record<string, unknown> = {}
|
||||
const pending: string[][] = [[], []]
|
||||
|
||||
const fields = (values: Record<string, string>) => Object.entries(values).map(([name, value]) => name === "blackhole" && value === "yes" ? name : name + "=" + quote(value)).join(" ")
|
||||
function add(side: number, path: string, values: Record<string, string>, beforeMain = false) {
|
||||
pending[side].push(path + " add " + fields(values) + (beforeMain ? " place-before=[/ip/vrf/find where name=main]" : ""))
|
||||
}
|
||||
function flush(side: number) {
|
||||
while (pending[side].length) {
|
||||
const commands = pending[side].splice(0, 10)
|
||||
cli(side, commands.map((command, index) => `:put "IX_STAGE_${index}"; ${command}`).join("; "))
|
||||
}
|
||||
}
|
||||
function owned(side: number, path: string, values: Record<string, string>, tag: string) {
|
||||
add(side, path, { ...values, comment: marker + ":" + tag })
|
||||
}
|
||||
function preflight(side: number) {
|
||||
const data = cli(side, `:put [/system resource get version]; :put [/system resource get board-name];
|
||||
:put ([:len [/ip/vrf/find]]=1 && [:len [/interface/wireguard/find]]=0 && [:len [/routing/bgp/connection/find]]=0 && [:len [/ip/firewall/filter/find]]=0 && [:len [/ipv6/firewall/filter/find]]=0);
|
||||
:put [:len [/ip/address/find where address~${quote("^" + hosts[side] + "/")}]]`)
|
||||
const [version, board, empty, address] = data.split(/\r?\n/)
|
||||
assert.equal(version, "7.24.5 (stable)")
|
||||
assert.match(board, /^CHR/)
|
||||
assert.equal(empty, "true", "Stand changed, refusing a modified baseline")
|
||||
assert.equal(address, "1", "Expected test WAN address missing")
|
||||
}
|
||||
|
||||
const config = ixSegmentConfigurationSchema.parse({
|
||||
name: "ix-acceptance",
|
||||
sites: [
|
||||
{ serverId: 501, autonomousSystem: 64512, routerId: net + ".5",
|
||||
interfaces: [{ name: primary, kind: "wireguard", peerServerId: 502 }, { name: backup, kind: "wireguard", peerServerId: 502 }],
|
||||
groups: [{ id: "far", gateway, primary: { interface: primary, nextHop: bP, probe: pProbe },
|
||||
backup: { interface: backup, nextHop: bB, probe: bProbe } }],
|
||||
neighbors: [{ id: "feed", type: "public-feed", address: bB, localAddress: aB, remoteAs: 64513, binding: backup, rules: [{ community, group: "far" }] }],
|
||||
},
|
||||
{ serverId: 502, autonomousSystem: 64513, routerId: net + ".6",
|
||||
interfaces: [{ name: primary, kind: "wireguard", peerServerId: 501 }, { name: backup, kind: "wireguard", peerServerId: 501 }] },
|
||||
],
|
||||
})
|
||||
const compiled = compileIxConfiguration(id, config)
|
||||
const deferred = new Set([routePath, "/routing/bgp/instance", "/routing/filter/rule", "/routing/bgp/connection"])
|
||||
const cleanupPaths = [...deferred].reverse().concat(listPath,
|
||||
"/interface/wireguard/peers", addressPath, "/ip/firewall/filter", "/ipv6/firewall/filter", "/ip/vrf", "/interface/bridge", "/interface/wireguard")
|
||||
|
||||
function clean(side: number) {
|
||||
const where = `where comment~${quote("^" + ns + ":")}`
|
||||
cli(side, cleanupPaths.map(path => `${path} remove [${path}/find ${where}]`).join("; "))
|
||||
assert.equal(cli(side, `:put (${cleanupPaths.map(path => `[:len [${path}/find ${where}]]`).join("+")})`), "0")
|
||||
preflight(side)
|
||||
}
|
||||
|
||||
function observe() {
|
||||
return cli(0, `:put [/routing/route/print as-value where dst-address=${quote(target + length)} and routing-table=${quote(ns)}]`)
|
||||
}
|
||||
async function until(label: string, check: () => boolean, timeout = 75000) {
|
||||
const start = Date.now()
|
||||
while (!check()) {
|
||||
if (Date.now() - start > timeout) throw new Error(label + " timeout: " + observe())
|
||||
await delay(900)
|
||||
}
|
||||
return Date.now() - start
|
||||
}
|
||||
function hasPath(name: string) {
|
||||
const fields = observe().split(";")
|
||||
return fields.includes("bgp=true") && fields.includes("active=true") && fields.some(field => field.startsWith("immediate-gw=") && field.endsWith("%" + name))
|
||||
}
|
||||
function establishedSession() {
|
||||
const session = cli(0, `:put [/routing/bgp/session/print as-value where name~${quote(ns + "-feed")}]`).split(";")
|
||||
assert.ok(session.includes("established=true"))
|
||||
assert.ok(session.includes("prefix-count=1"))
|
||||
const started = session.find(field => field.startsWith("last-started="))
|
||||
assert.ok(started)
|
||||
return started
|
||||
}
|
||||
function packetProbe(destination: string, source?: string, side = 0, routingTable = ns) {
|
||||
return Number(cli(side, `:put [/ping address=${destination} vrf=${routingTable} count=3 interval=250ms${source ? " src-address=" + source : ""}]`).split(/\r?\n/).at(-1))
|
||||
}
|
||||
|
||||
async function run() {
|
||||
preflight(0); preflight(1)
|
||||
for (let side = 0; side < 2; side++) {
|
||||
entered.add(side)
|
||||
for (const [index, name] of [primary, backup].entries()) owned(side, "/interface/wireguard", { name, "listen-port": String(port + index), vrf: "main" }, "wg" + index)
|
||||
for (const object of compiled.filter(object => object.serverId === 501 + side && !deferred.has(object.path))) {
|
||||
add(side, object.path, object.fields, object.path === "/ip/vrf")
|
||||
if (object.path === "/ip/vrf") {
|
||||
flush(side)
|
||||
await until("VRF interface", () => cli(side, `:put [:len [/interface/find where name=${quote(ns)}]]`) === "1", 9000)
|
||||
}
|
||||
}
|
||||
for (const [index, name] of [primary, backup].entries()) {
|
||||
owned(side, "/ip/firewall/filter", { chain: "input", action: "accept", protocol: "udp", "src-address": hosts[1 - side] + "/32", "dst-port": String(port + index) }, "allow-wg" + index)
|
||||
const inner = (side ? [bP, bB] : [aP, aB])[index]
|
||||
owned(side, addressPath, { address: inner + (ipv6 ? "/64" : "/30"), interface: name, ...advertise }, "address" + index)
|
||||
}
|
||||
flush(side)
|
||||
}
|
||||
for (const [index, name] of [primary, backup].entries()) {
|
||||
const keys = [0, 1].map(side => cli(side, `:put [/interface/wireguard/get [/interface/wireguard/find where name=${quote(name)}] public-key]`))
|
||||
keys.forEach(value => assert.match(value, /^[A-Za-z0-9+/]{43}=$/))
|
||||
for (const side of [0, 1]) owned(side, "/interface/wireguard/peers", { interface: name, "public-key": keys[1 - side], "endpoint-address": hosts[1 - side],
|
||||
"endpoint-port": String(port + index), "allowed-address": (side
|
||||
? [index ? aB : aP, trafficSource]
|
||||
: [index ? bB : bP, target, index ? bProbe : pProbe]).map(address => address + length).join(","),
|
||||
"persistent-keepalive": "5" }, "peer" + index)
|
||||
}
|
||||
for (const [index, address] of [target, pProbe, bProbe].entries()) {
|
||||
owned(1, addressPath, { address: address + length, interface: discard, ...advertise }, "destination" + index)
|
||||
}
|
||||
owned(0, addressPath, { address: trafficSource + length, interface: discard, ...advertise }, "source")
|
||||
// Keep the same source and return path across both forward paths.
|
||||
owned(1, routePath, { "dst-address": trafficSource + length, "routing-table": ns,
|
||||
gateway: aB + "%" + backup + "@" + ns, "target-scope": "10" }, "return")
|
||||
const control = { chain: "input", "in-interface": ns, protocol: "tcp", "src-address": aB + length, action: "accept" }
|
||||
const beforeDeny = " place-before=[" + filterPath + "/find where comment=" + quote(ns + ":deny-input-" + (ipv6 ? "6" : "4")) + "]"
|
||||
cli(1, [fields({ ...control, "dst-port": "179", comment: marker + ":bgp-accept" }),
|
||||
fields({ ...control, "src-port": "179", "connection-state": "established", comment: marker + ":bgp-reply" })]
|
||||
.map(rule => filterPath + " add " + rule + beforeDeny).join("; "))
|
||||
owned(1, listPath, { list: short + "-net", address: target + length }, "network")
|
||||
owned(1, "/routing/bgp/instance", { name: ns, as: "64513", "router-id": net + ".6", vrf: ns, "routing-table": ns }, "instance")
|
||||
owned(1, "/routing/filter/rule", { chain: short + "-out", rule: `if (dst == ${target}${length}) { set bgp-communities ${community}; accept; } reject;` }, "export")
|
||||
owned(1, "/routing/bgp/connection", { name: short + "-export", instance: ns, afi, "local.role": "ebgp", "local.address": bB,
|
||||
"remote.address": aB + length, "remote.as": "64512", vrf: ns, "routing-table": ns, "output.network": short + "-net", "output.filter-chain": short + "-out" }, "connection")
|
||||
for (const object of compiled.filter(object => object.serverId === 501 && deferred.has(object.path))) add(0, object.path, object.fields)
|
||||
flush(1); flush(0)
|
||||
await until("primary WireGuard transport", () => packetProbe(bP, aP) === 3, 40000)
|
||||
await until("backup WireGuard transport", () => packetProbe(bB, aB) === 3, 40000)
|
||||
await until("BGP primary route", () => hasPath(primary))
|
||||
const session = establishedSession()
|
||||
results.bgpEstablished = true
|
||||
results.primaryRoute = observe()
|
||||
results.primaryReplies = packetProbe(target, trafficSource)
|
||||
assert.equal(results.primaryReplies, 3)
|
||||
assert.equal(cli(0, `:put [:len [/routing/route/find where dst-address=${quote(target + length)} and routing-table=main]]`), "0", "BGP prefix must not leak to main")
|
||||
results.mainIsolated = true
|
||||
|
||||
// Drop only A's test UDP flow on the remote end. Interfaces remain enabled,
|
||||
// so this exercises probe-driven failover rather than administrative down.
|
||||
cli(1, "/ip/firewall/filter add " + fields({ chain: "input", action: "drop", protocol: "udp", "src-address": hosts[0] + "/32",
|
||||
"dst-port": String(port), comment: marker + ":cut" }) + " place-before=[/ip/firewall/filter/find where comment=" + quote(marker + ":allow-wg0") + "]")
|
||||
results.failoverMs = await until("primary underlay loss", () => hasPath(backup))
|
||||
results.backupRoute = observe()
|
||||
results.backupReplies = packetProbe(target, trafficSource)
|
||||
assert.equal(results.backupReplies, 3)
|
||||
assert.equal(establishedSession(), session)
|
||||
cli(1, "/ip/firewall/filter remove [/ip/firewall/filter/find where comment=" + quote(marker + ":cut") + "]")
|
||||
results.failbackMs = await until("primary recovery", () => hasPath(primary))
|
||||
results.recoveredReplies = packetProbe(target, trafficSource)
|
||||
assert.equal(results.recoveredReplies, 3)
|
||||
assert.equal(establishedSession(), session)
|
||||
results.bgpSessionKept = true
|
||||
}
|
||||
|
||||
let failure: unknown
|
||||
try { await run() } catch (error) {
|
||||
failure = error
|
||||
for (const side of entered) try {
|
||||
console.error(`Test CHR ${side + 1} · ${cli(side, `:put [/routing/bgp/session/print as-value];
|
||||
:put [/interface/wireguard/peers/print as-value proplist=interface,rx,tx,last-handshake,current-endpoint-address where comment~${quote("^" + ns + ":")}];
|
||||
${filterPath}/print stats where comment~${quote("^" + ns + ":")};
|
||||
:put [${addressPath}/print as-value proplist=address,interface,invalid where comment~${quote("^" + ns + ":")}];
|
||||
:put [/routing/route/print as-value where routing-table=${quote(ns)}]; :put [/routing/nexthop/print as-value where address~${quote(gateway)}]`).slice(0, 8500)}`)
|
||||
} catch { /* Preserve the original failure and continue cleanup. */ }
|
||||
}
|
||||
for (const side of entered) {
|
||||
try { clean(side) } catch (error) {
|
||||
console.error(`Cleanup unconfirmed on test CHR ${side + 1} for ${ns}: ${error}`)
|
||||
failure ??= error
|
||||
}
|
||||
}
|
||||
if (failure) {
|
||||
console.error(JSON.stringify(results))
|
||||
throw failure
|
||||
}
|
||||
console.log(JSON.stringify({ ...results, testStandRestored: true }))
|
||||
@@ -0,0 +1,97 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { mkdtemp, readdir, readFile } from "node:fs/promises"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join, resolve } from "node:path"
|
||||
import { createServer } from "node:net"
|
||||
import { randomBytes } from "node:crypto"
|
||||
import EmbeddedPostgres from "embedded-postgres"
|
||||
import { FIXED59_IX_DELTA } from "../writer-profile/fixed59-ix-delta.js"
|
||||
import { canonical } from "../writer-profile/application-writer-profile-canonical.js"
|
||||
import { ixWriterProfileEnrollmentSql } from "../../src/db/internet-exchange-writer-profile.js"
|
||||
import { FIXED44_CATALOGUE_BUILD_SQL } from "../writer-profile/fixed44-build-sql.js"
|
||||
import { CatalogueValueStream } from "../writer-profile/application-writer-profile-catalogue-values.js"
|
||||
import { projectCatalogueData, GROUPS, sorted, type Inventory, type Row } from "../writer-profile/catalogue-projection.js"
|
||||
|
||||
const root = await mkdtemp(join(tmpdir(), "mmapp-ix-profile-"))
|
||||
assert.equal(resolve(root, ".."), resolve(tmpdir()))
|
||||
const listener = createServer()
|
||||
await new Promise<void>((done, reject) => listener.listen(0, "127.0.0.1", done).on("error", reject))
|
||||
const port = (listener.address() as { port: number }).port
|
||||
await new Promise<void>((done, reject) => listener.close(error => error ? reject(error) : done()))
|
||||
const app = new EmbeddedPostgres({ databaseDir: root, user: "ixlab", password: randomBytes(24).toString("hex"),
|
||||
port, persistent: false, createPostgresUser: false, initdbFlags: ["--encoding=UTF8", "--no-locale"],
|
||||
postgresFlags: ["-h", "127.0.0.1", "-c", "jit=off"], onLog: () => {}, onError: () => {} })
|
||||
const roles = ["ix_operator", "ix_runtime", "ix_capture", "ix_publisher", "ix_control"]
|
||||
const tables = ["ix_segments", "ix_segment_devices", "ix_segment_revisions"]
|
||||
console.log("Initialising disposable PostgreSQL")
|
||||
await app.initialise()
|
||||
console.log("Starting disposable PostgreSQL")
|
||||
await app.start()
|
||||
const db = app.getPgClient("postgres", "127.0.0.1")
|
||||
try {
|
||||
await db.connect()
|
||||
console.log("Applying pinned migrations in the fixture")
|
||||
await db.query("CREATE TABLE schema_migrations(id text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())")
|
||||
const directory = resolve("backend/drizzle")
|
||||
for (const name of (await readdir(directory)).filter(name => name.endsWith(".sql")).sort()) {
|
||||
await db.query(await readFile(join(directory, name), "utf8"))
|
||||
await db.query("INSERT INTO schema_migrations(id) VALUES ($1) ON CONFLICT DO NOTHING", [name.slice(0,-4)])
|
||||
}
|
||||
for (const role of roles) await db.query("CREATE ROLE " + role)
|
||||
await db.query("CREATE SCHEMA IF NOT EXISTS mmapp_control; CREATE FUNCTION mmapp_control.candidate_truncate_preadmitted() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RETURN NULL; END; $$")
|
||||
for (const name of tables) await db.query("ALTER TABLE public." + name + " OWNER TO ix_operator")
|
||||
await db.query("GRANT USAGE ON SCHEMA mmapp_control TO ix_operator; GRANT EXECUTE ON FUNCTION mmapp_control.candidate_truncate_preadmitted() TO ix_operator")
|
||||
await db.query("BEGIN; SET LOCAL ROLE ix_operator")
|
||||
await db.query(ixWriterProfileEnrollmentSql("ix_runtime", "ix_capture"))
|
||||
await db.query("COMMIT")
|
||||
|
||||
const insert = "INSERT INTO ix_segments(id,name,revision,configuration) VALUES ('8dd5d978-83ac-4343-8cff-16655a0a77a7','fixture',1,'{}')"
|
||||
const maintenance = app.getPgClient("postgres", "127.0.0.1")
|
||||
await maintenance.connect()
|
||||
try {
|
||||
await maintenance.query("SELECT pg_advisory_lock(8723110::bigint)")
|
||||
await db.query("BEGIN; SET LOCAL ROLE ix_runtime; SET LOCAL lock_timeout='250ms'")
|
||||
await assert.rejects(db.query(insert), { code: "55P03" })
|
||||
await db.query("ROLLBACK")
|
||||
} finally {
|
||||
await maintenance.end()
|
||||
}
|
||||
await db.query("BEGIN; SET LOCAL ROLE ix_runtime; SELECT pg_advisory_xact_lock_shared(8723110::bigint)")
|
||||
await db.query(insert)
|
||||
await db.query("INSERT INTO ix_segment_revisions(segment_id,revision,configuration,actor_id) VALUES ('8dd5d978-83ac-4343-8cff-16655a0a77a7',1,'{}','fixture')")
|
||||
await assert.rejects(db.query("UPDATE ix_segment_revisions SET actor_id='other'"), { code: "42501" })
|
||||
await db.query("ROLLBACK")
|
||||
|
||||
console.log("Capturing exact IX catalogue rows")
|
||||
await db.query("BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY; SET LOCAL search_path=pg_catalog,public; SET LOCAL TimeZone='UTC'; SET LOCAL DateStyle='ISO, YMD'")
|
||||
const stream = new CatalogueValueStream()
|
||||
const raw = {} as Inventory
|
||||
for (const group of GROUPS) raw[group] = []
|
||||
const statement = FIXED44_CATALOGUE_BUILD_SQL.replace("LIMIT 104", "LIMIT 113")
|
||||
await db.query("DECLARE ix_capture_cursor NO SCROLL CURSOR WITHOUT HOLD FOR " + statement, roles)
|
||||
for (;;) {
|
||||
const page = (await db.query("FETCH FORWARD 128 FROM ix_capture_cursor")).rows
|
||||
if (!page.length) break
|
||||
for (const record of stream.acceptPage(page)) {
|
||||
if (record.kind === "global") raw[record.identity === "base_tables" ? "tables" : record.identity] = record.value.rows as Row[]
|
||||
if (record.kind === "base") for (const group of GROUPS) raw[group].push(...record.value[group] as Row[])
|
||||
}
|
||||
}
|
||||
stream.finish()
|
||||
const projected = projectCatalogueData(raw)
|
||||
const delta: Inventory = {}
|
||||
for (const group of ["tables", ...GROUPS]) delta[group] = sorted(projected[group].filter(row => tables.includes(String(row.relname))))
|
||||
delta.constraints.push(...projected.constraints.filter(row => row.relname === "servers" && row.conname === "servers_type_check"))
|
||||
delta.triggers.push(...projected.triggers.filter(row => row.relname === "servers" && String(row.definition).includes("ix_segment_devices")))
|
||||
assert.equal(delta.tables.length, 3)
|
||||
assert.equal(delta.triggers.filter(row => row.relname === "servers").length, 2)
|
||||
await db.query("ROLLBACK")
|
||||
let text = JSON.stringify(delta, null, 2)
|
||||
for (const [index, role] of roles.entries()) text = text.replaceAll(role, "@mm-role:" + ["operator","runtime","capture","publisher","control"][index] + "@")
|
||||
assert.equal(canonical(JSON.parse(text)), canonical(FIXED59_IX_DELTA), "PostgreSQL catalogue drifted from source59")
|
||||
console.log(JSON.stringify({ postgres: (await db.query("SHOW server_version")).rows[0].server_version, relations: delta.tables.length, constraints: delta.constraints.length,
|
||||
triggers: delta.triggers.length, leastPrivilege: true, sharedWriterLock: true }))
|
||||
} finally {
|
||||
await db.end().catch(() => {})
|
||||
await app.stop()
|
||||
}
|
||||
@@ -20,10 +20,11 @@ test('fixed artifact is reproducible, resolves the compiled backend graph, and r
|
||||
const packageJson=JSON.parse(await readFile(path.join(backend,'package.json'),'utf8'))
|
||||
await mkdir(projectBackend,{recursive:true});await writeFile(path.join(projectBackend,'package.json'),JSON.stringify({type:'module',dependencies:packageJson.dependencies}))
|
||||
const first=await buildDatabaseOperator({backendDirectory:backend,outputDirectory:output}),second=await buildDatabaseOperator({backendDirectory:backend,outputDirectory:output})
|
||||
assert.deepEqual(first,second);assert.equal(first.modules.length,OPERATOR_SOURCES.length);assert.equal(first.modules.length,31);assert.deepEqual(first.runtimeDependencies,['dotenv','pg','zod']);assert.equal(first.backendDistModules.length,30)
|
||||
assert.deepEqual(first,second);assert.equal(first.modules.length,OPERATOR_SOURCES.length);assert.equal(first.modules.length,33);assert.deepEqual(first.runtimeDependencies,['dotenv','pg','zod']);assert.equal(first.backendDistModules.length,32)
|
||||
assert(first.modules.some(item=>item.file==='writer-profile/registry-enrollment.mjs'))
|
||||
assert(first.modules.some(item=>item.file==='writer-profile/marker-fence-enrollment.mjs'))
|
||||
assert(first.modules.some(item=>item.file==='writer-profile/fixed58-build-definition.js'))
|
||||
assert(first.modules.some(item=>item.file==='writer-profile/fixed59-build-definition.js'))
|
||||
assert(first.backendDistImports.includes('db/database-restore-quarantine-profile.js'))
|
||||
assert(first.backendDistImports.includes('db/database-source-activation-record.js'))
|
||||
assert(first.backendDistImports.includes('services/server-probe-legacy-source-inventory.js'))
|
||||
|
||||
@@ -13,5 +13,5 @@ export const OPERATOR_SOURCES=Object.freeze([
|
||||
'writer-profile/catalogue.mts','writer-profile/catalogue-value-bridge.ts','writer-profile/catalogue-projection.ts','writer-profile/catalogue-leaves.ts',
|
||||
'writer-profile/application-writer-profile-catalogue.ts','writer-profile/application-writer-profile-catalogue-values.ts',
|
||||
'writer-profile/application-writer-profile-catalogue-parent-policy.ts','writer-profile/application-writer-profile-canonical.ts',
|
||||
'writer-profile/fixed44-build-sql.ts','writer-profile/fixed44-build-definition.ts','writer-profile/fixed56-build-definition.ts','writer-profile/fixed56-build-delta.ts','writer-profile/fixed57-build-definition.ts','writer-profile/fixed58-build-definition.ts','writer-profile/expanded44-data-policy.ts',
|
||||
'writer-profile/fixed44-build-sql.ts','writer-profile/fixed44-build-definition.ts','writer-profile/fixed56-build-definition.ts','writer-profile/fixed56-build-delta.ts','writer-profile/fixed57-build-definition.ts','writer-profile/fixed58-build-definition.ts','writer-profile/fixed59-build-definition.ts','writer-profile/fixed59-ix-delta.ts','writer-profile/expanded44-data-policy.ts',
|
||||
])
|
||||
@@ -57,11 +57,11 @@ export async function main(args:string[]){
|
||||
// import so a newly loaded NODE_PG_FORCE_NATIVE cannot select another driver.
|
||||
const {createProtectedDatabaseSourceBindingVerifier}=await import('./writer-profile/protected-source-registry.mjs')
|
||||
assertJsDriverEnvironment(process.env)
|
||||
const [{default:pg},{createConnectedPublisher,requireCurrentCatalogueDefinition},{collectSource44Catalogue,collectSource56Catalogue,collectSource57Catalogue,collectSource58Catalogue,approvedDefinition}]=await Promise.all([
|
||||
const [{default:pg},{createConnectedPublisher,requireCurrentCatalogueDefinition},{collectSource44Catalogue,collectSource56Catalogue,collectSource57Catalogue,collectSource58Catalogue,collectSource59Catalogue,approvedDefinition}]=await Promise.all([
|
||||
import('pg'),import('./writer-profile/publisher.mjs'),import('./writer-profile/catalogue.mjs')])
|
||||
assertJsDriverEnvironment(process.env)
|
||||
const reviewedDefinition=legacyInspection?undefined:approvedDefinition(definition)
|
||||
const collectCatalogues={44:collectSource44Catalogue,56:collectSource56Catalogue,57:collectSource57Catalogue,58:collectSource58Catalogue}
|
||||
const collectCatalogues={44:collectSource44Catalogue,56:collectSource56Catalogue,57:collectSource57Catalogue,58:collectSource58Catalogue,59:collectSource59Catalogue}
|
||||
const collectCatalogue=collectCatalogues[reviewedDefinition&&'edition' in reviewedDefinition?reviewedDefinition.edition:44]
|
||||
if(!legacyInspection&&!catalogueInspection){
|
||||
assert.equal(reviewedDefinition!.definitionSha256,pinned!.definitionSha256)
|
||||
|
||||
@@ -7,6 +7,7 @@ import {BUILD44_PROVENANCE,FIXED44_ROLE_TEMPLATE} from './fixed44-build-definiti
|
||||
import {BUILD56_PROVENANCE,FIXED56_ROLE_TEMPLATE} from './fixed56-build-definition.js'
|
||||
import {BUILD57_PROVENANCE,FIXED57_ROLE_TEMPLATE} from './fixed57-build-definition.js'
|
||||
import {BUILD58_PROVENANCE,FIXED58_ROLE_TEMPLATE,normalizeFixed58RestoreRows} from './fixed58-build-definition.js'
|
||||
import {BUILD59_PROVENANCE,FIXED59_ROLE_TEMPLATE} from './fixed59-build-definition.js'
|
||||
import {GLOBALS,GROUPS,object,rows,sorted,text,projectCatalogueData,type CatalogueEdition,type Inventory,type Row,type Json} from './catalogue-projection.js'
|
||||
import {validateCatalogueLeafData} from './catalogue-leaves.js'
|
||||
import {catalogueTopologyPolicy,Expanded44TopologyBudgetData} from './expanded44-data-policy.js'
|
||||
@@ -20,6 +21,7 @@ const definitions = {
|
||||
56: { provenance: BUILD56_PROVENANCE, template: FIXED56_ROLE_TEMPLATE },
|
||||
57: { provenance: BUILD57_PROVENANCE, template: FIXED57_ROLE_TEMPLATE },
|
||||
58: { provenance: BUILD58_PROVENANCE, template: FIXED58_ROLE_TEMPLATE },
|
||||
59: { provenance: BUILD59_PROVENANCE, template: FIXED59_ROLE_TEMPLATE },
|
||||
}
|
||||
const exact=(a:unknown,b:unknown,label:string)=>{if(canonical(a)!==canonical(b))throw Error('Writer catalogue refused: '+label)}
|
||||
function captureBindings(input:InstallationRoleBindingsData):Readonly<Record<LogicalRole,string>> {
|
||||
@@ -68,7 +70,7 @@ export class Fixed44CatalogueDataVerifier {
|
||||
if(this.counts||table.relispartition!==false||this.bases.has(record.identity))throw Error('Duplicate/late base')
|
||||
const header=this.headers!.find(t=>t.relname===record.identity);if(!header)throw Error('Foreign base refused');exact(table,header,'header/table')
|
||||
const actual=projectCatalogueData({...this.globals,...groups,tables:this.headers!})
|
||||
for(const name of GROUPS)exact(this.edition===58?normalizeFixed58RestoreRows(record.identity,name,actual[name]):actual[name],
|
||||
for(const name of GROUPS)exact(this.edition>=58?normalizeFixed58RestoreRows(record.identity,name,actual[name]):actual[name],
|
||||
this.expected[name].filter(r=>r.relname===record.identity),'base '+name+' '+record.identity)
|
||||
this.topology.acceptRelation('base',record.identity,groups);this.bases.add(record.identity);if(fixedCatalogueParentPeriodData(record.identity))this.templates.set(record.identity,{table,groups});return
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ export type Json=null|boolean|number|string|Json[]|{[key:string]:Json}
|
||||
export type Row=Record<string,Json>
|
||||
export type Inventory=Record<string,Row[]>
|
||||
export const GROUPS=['columns','triggers','constraints','indexes','roleGrants','inheritance'] as const
|
||||
export type CatalogueEdition = 44 | 56 | 57 | 58
|
||||
export type CatalogueEdition = 44 | 56 | 57 | 58 | 59
|
||||
export const GLOBALS=['database','effectiveDatabase','effectiveFunctions','effectiveSchemas','effectiveSequences','events','functions','identities','memberships','parameters','roles','schemas','settings','sequences'] as const
|
||||
export const sorted=(rows:Row[])=>rows.slice().sort((a,b)=>canonical(a)<canonical(b)?-1:canonical(a)>canonical(b)?1:0)
|
||||
export const omit=(row:Row,names:readonly string[]):Row=>Object.fromEntries(Object.entries(row).filter(([key])=>!names.includes(key)))
|
||||
|
||||
@@ -5,6 +5,7 @@ import {BUILD44_PROVENANCE,FIXED44_ROLE_TEMPLATE} from './fixed44-build-definiti
|
||||
import {BUILD56_PROVENANCE,FIXED56_ROLE_TEMPLATE} from './fixed56-build-definition.js'
|
||||
import {BUILD57_PROVENANCE,FIXED57_ROLE_TEMPLATE} from './fixed57-build-definition.js'
|
||||
import {BUILD58_PROVENANCE,FIXED58_ROLE_TEMPLATE} from './fixed58-build-definition.js'
|
||||
import {BUILD59_PROVENANCE,FIXED59_ROLE_TEMPLATE} from './fixed59-build-definition.js'
|
||||
import {assertRestoreProfileQuarantine} from '../../src/db/database-restore-quarantine-profile.js'
|
||||
import {canonical,sha} from './application-writer-profile-canonical.js'
|
||||
import type {CatalogueEdition} from './catalogue-projection.js'
|
||||
@@ -23,6 +24,10 @@ export function approvedDefinition(value:unknown){
|
||||
assert.equal(canonical(v.provenance),canonical(BUILD58_PROVENANCE));assert.equal(canonical(v.template),canonical(FIXED58_ROLE_TEMPLATE))
|
||||
return Object.freeze({edition:58 as const,definitionSha256:BUILD58_PROVENANCE.templateSha256,manifestSha256:BUILD58_PROVENANCE.manifestSha256})
|
||||
}
|
||||
if(v.format==='application-writer-source59-definition-approval-v1'){
|
||||
assert.equal(canonical(v.provenance),canonical(BUILD59_PROVENANCE));assert.equal(canonical(v.template),canonical(FIXED59_ROLE_TEMPLATE))
|
||||
return Object.freeze({edition:59 as const,definitionSha256:BUILD59_PROVENANCE.templateSha256,manifestSha256:BUILD59_PROVENANCE.manifestSha256})
|
||||
}
|
||||
assert.equal(v.format,'application-writer-source56-definition-approval-v1')
|
||||
assert.equal(canonical(v.provenance),canonical(BUILD56_PROVENANCE));assert.equal(canonical(v.template),canonical(FIXED56_ROLE_TEMPLATE))
|
||||
return Object.freeze({edition:56 as const,definitionSha256:BUILD56_PROVENANCE.templateSha256,manifestSha256:BUILD56_PROVENANCE.manifestSha256})
|
||||
@@ -31,11 +36,13 @@ type CatalogueSession = {query:(sql:string,values?:unknown[])=>Promise<{rows:Rec
|
||||
type CatalogueInstallation = {roleBindings:ConstructorParameters<typeof Fixed44CatalogueValueBridgeData>[0]}
|
||||
assert.equal(FIXED44_CATALOGUE_BUILD_SQL.split('LIMIT 104').length,2)
|
||||
const fixed56Sql = FIXED44_CATALOGUE_BUILD_SQL.replace('LIMIT 104','LIMIT 110')
|
||||
const fixed59Sql = FIXED44_CATALOGUE_BUILD_SQL.replace('LIMIT 104','LIMIT 113')
|
||||
/** Real incremental DATA verifier on caller's retained transaction. No pool or attestor. */
|
||||
export const collectSource44Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 44)
|
||||
export const collectSource56Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 56)
|
||||
export const collectSource57Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 57)
|
||||
export const collectSource58Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 58)
|
||||
export const collectSource59Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 59)
|
||||
async function collectCatalogue(s:CatalogueSession,installation:CatalogueInstallation,edition:CatalogueEdition){
|
||||
const settings=(await s.query("SELECT pg_catalog.current_setting('search_path') AS path,pg_catalog.current_setting('TimeZone') AS zone,pg_catalog.current_setting('DateStyle') AS dates")).rows
|
||||
assert.equal(settings.length,1);assert(['path','zone','dates'].every(k=>typeof settings[0][k]==='string'))
|
||||
@@ -43,9 +50,9 @@ async function collectCatalogue(s:CatalogueSession,installation:CatalogueInstall
|
||||
try{
|
||||
await s.query("SELECT pg_catalog.set_config('search_path','pg_catalog, public',true),pg_catalog.set_config('TimeZone','UTC',true),pg_catalog.set_config('DateStyle','ISO, YMD',true)")
|
||||
const bindings=installation.roleBindings,values=['operator','runtime','capture','publisher','control'].map(k=>bindings[k as keyof typeof bindings].name)
|
||||
if(edition===58)await assertRestoreProfileQuarantine(s,bindings.runtime.name,bindings.operator.name,bindings.control.name)
|
||||
if(edition>=58)await assertRestoreProfileQuarantine(s,bindings.runtime.name,bindings.operator.name,bindings.control.name)
|
||||
const bridge=new Fixed44CatalogueValueBridgeData(bindings,edition)
|
||||
await s.query('DECLARE mm_publisher44 NO SCROLL CURSOR WITHOUT HOLD FOR '+(edition===44?FIXED44_CATALOGUE_BUILD_SQL:fixed56Sql),values);cursor=true
|
||||
await s.query('DECLARE mm_publisher44 NO SCROLL CURSOR WITHOUT HOLD FOR '+(edition===44?FIXED44_CATALOGUE_BUILD_SQL:edition===59?fixed59Sql:fixed56Sql),values);cursor=true
|
||||
for(;;){const page=(await s.query('FETCH FORWARD 128 FROM mm_publisher44')).rows;bridge.acceptPage(page);if(page.length===0)break}
|
||||
const result=bridge.finish();await s.query('CLOSE mm_publisher44');cursor=false
|
||||
return {catalogSha256:sha(canonical({values:result.values.snapshotSha256,catalogue:result.catalogue})),definitionSha256:result.catalogue.definitionSha256,manifestSha256:result.catalogue.manifestSha256,leafCount:result.catalogue.leafRelations}
|
||||
|
||||
@@ -3,6 +3,7 @@ import {BUILD44_PROVENANCE,FIXED44_ROLE_TEMPLATE} from './fixed44-build-definiti
|
||||
import {BUILD56_PROVENANCE,FIXED56_ROLE_TEMPLATE} from './fixed56-build-definition.js'
|
||||
import {BUILD57_PROVENANCE} from './fixed57-build-definition.js'
|
||||
import {BUILD58_PROVENANCE} from './fixed58-build-definition.js'
|
||||
import {BUILD59_PROVENANCE,FIXED59_ROLE_TEMPLATE} from './fixed59-build-definition.js'
|
||||
import {fixedCatalogueParentPeriodData} from './application-writer-profile-catalogue-parent-policy.js'
|
||||
import {GROUPS,type CatalogueEdition,type Inventory} from './catalogue-projection.js'
|
||||
export const EXPANDED44_POLICY_VERSION='source44-managed-leaves-3000-data-v1' as const
|
||||
@@ -49,8 +50,24 @@ const EXPANDED58_DATA_POLICY = Object.freeze({
|
||||
version: 'source58-managed-leaves-3000-data-v1',
|
||||
definitionSha256: BUILD58_PROVENANCE.templateSha256,
|
||||
})
|
||||
const policies = {44: EXPANDED44_DATA_POLICY, 56: EXPANDED56_DATA_POLICY, 57: EXPANDED57_DATA_POLICY, 58: EXPANDED58_DATA_POLICY}
|
||||
const relationCounts = {44: perRelation, 56: source56PerRelation, 57: source57PerRelation, 58: source57PerRelation}
|
||||
const source59PerRelation = new Map(FIXED59_ROLE_TEMPLATE.tables.map(({relname}) => [String(relname), Object.fromEntries(
|
||||
GROUPS.map(group => [group, FIXED59_ROLE_TEMPLATE[group].filter(row => (group === 'inheritance' ? row.child : row.relname) === relname).length]),
|
||||
) as Record<typeof GROUPS[number],number>]))
|
||||
const source59BaseRows = Object.freeze(Object.fromEntries(GROUPS.map(group => [group,FIXED59_ROLE_TEMPLATE[group].length])) as Record<typeof GROUPS[number],number>)
|
||||
if (source59PerRelation.size !== 113 || parents.some(name => GROUPS.some(group => source59PerRelation.get(name)?.[group] !== source57PerRelation.get(name)?.[group]))) {
|
||||
throw Error('Unexpected source59 IX topology')
|
||||
}
|
||||
const EXPANDED59_DATA_POLICY = Object.freeze({
|
||||
...EXPANDED58_DATA_POLICY,
|
||||
version: 'source59-managed-leaves-3000-data-v1',
|
||||
baseRelations: source59PerRelation.size,
|
||||
maxRelations: source59PerRelation.size + LEAVES,
|
||||
baseRows: source59BaseRows,
|
||||
maxRows: Object.freeze(Object.fromEntries(GROUPS.map(group => [group,source59BaseRows[group] + LEAVES * leafMax[group]])) as Record<typeof GROUPS[number],number>),
|
||||
definitionSha256: BUILD59_PROVENANCE.templateSha256,
|
||||
})
|
||||
const policies = {44: EXPANDED44_DATA_POLICY, 56: EXPANDED56_DATA_POLICY, 57: EXPANDED57_DATA_POLICY, 58: EXPANDED58_DATA_POLICY, 59: EXPANDED59_DATA_POLICY}
|
||||
const relationCounts = {44: perRelation, 56: source56PerRelation, 57: source57PerRelation, 58: source57PerRelation, 59: source59PerRelation}
|
||||
export const catalogueTopologyPolicy = (edition: CatalogueEdition) => policies[edition]
|
||||
export const expanded44ParentRowCountsData=()=>Object.freeze(Object.fromEntries(parents.map(name=>[name,Object.freeze({...perRelation.get(name)!})])))
|
||||
export interface ManagedLeafData {readonly parent:string;readonly name:string}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { test } from "node:test"
|
||||
import { migrationManifestDigest } from "../../src/db/migration-manifest.js"
|
||||
import { ixWriterProfileEnrollmentSql } from "../../src/db/internet-exchange-writer-profile.js"
|
||||
import { approvedDefinition } from "./catalogue.mjs"
|
||||
import { FIXED58_ROLE_TEMPLATE } from "./fixed58-build-definition.js"
|
||||
import { BUILD59_PROVENANCE, FIXED59_ROLE_TEMPLATE } from "./fixed59-build-definition.js"
|
||||
import { catalogueTopologyPolicy } from "./expanded44-data-policy.js"
|
||||
|
||||
test("source59 pins migration 0058 and alters only the IX catalogue and its existing servers references", () => {
|
||||
assert.equal(BUILD59_PROVENANCE.manifestSha256, migrationManifestDigest())
|
||||
assert.equal(catalogueTopologyPolicy(59).baseRelations, catalogueTopologyPolicy(58).baseRelations + 3)
|
||||
const added = new Set(FIXED59_ROLE_TEMPLATE.tables.filter(row => String(row.relname).startsWith("ix_segment")).map(row => row.relname))
|
||||
assert.deepEqual([...added].sort(), ["ix_segment_devices", "ix_segment_revisions", "ix_segments"])
|
||||
for (const group of ["tables", "columns", "roleGrants", "inheritance", "indexes"]) {
|
||||
assert.deepEqual(FIXED59_ROLE_TEMPLATE[group].filter(row => !added.has(row.relname)), FIXED58_ROLE_TEMPLATE[group])
|
||||
}
|
||||
assert.equal(FIXED59_ROLE_TEMPLATE.triggers.length - FIXED58_ROLE_TEMPLATE.triggers.length, 21)
|
||||
assert.equal(FIXED59_ROLE_TEMPLATE.constraints.length - FIXED58_ROLE_TEMPLATE.constraints.length, 24)
|
||||
})
|
||||
|
||||
test("source59 accepts the exact independently reviewed definition and restricts IX runtime grants", () => {
|
||||
const approval = { format: "application-writer-source59-definition-approval-v1", provenance: BUILD59_PROVENANCE, template: FIXED59_ROLE_TEMPLATE }
|
||||
assert.equal(approvedDefinition(approval).definitionSha256, BUILD59_PROVENANCE.templateSha256)
|
||||
assert.throws(() => approvedDefinition({ ...approval, template: FIXED58_ROLE_TEMPLATE }))
|
||||
const granted = FIXED59_ROLE_TEMPLATE.roleGrants.filter(row => row.rolname === "@mm-role:runtime@" && String(row.relname).startsWith("ix_"))
|
||||
assert(granted.every(row => row.read === true && row.insert === true && row.truncate === false))
|
||||
assert.deepEqual(granted.filter(row => row.update === true).map(row => row.relname), ["ix_segments"])
|
||||
assert.deepEqual(granted.filter(row => row.delete === true).map(row => row.relname), ["ix_segment_devices"])
|
||||
assert.match(ixWriterProfileEnrollmentSql("ix_runtime", "ix_capture"), /GRANT SELECT, INSERT ON TABLE public.ix_segment_revisions TO "ix_runtime"/)
|
||||
assert.throws(() => ixWriterProfileEnrollmentSql('bad"role', "ix_capture"))
|
||||
})
|
||||
@@ -0,0 +1,25 @@
|
||||
import { canonical, sha } from "./application-writer-profile-canonical.js"
|
||||
import { GROUPS, sorted, type Inventory } from "./catalogue-projection.js"
|
||||
import { FIXED58_ROLE_TEMPLATE } from "./fixed58-build-definition.js"
|
||||
import { FIXED59_IX_DELTA } from "./fixed59-ix-delta.js"
|
||||
import { IX_WRITER_PROFILE_DEFINITION_SHA256, IX_WRITER_PROFILE_MANIFEST_SHA256 } from "../../src/db/internet-exchange-writer-profile.js"
|
||||
|
||||
const prior: Inventory = {
|
||||
...FIXED58_ROLE_TEMPLATE,
|
||||
constraints: FIXED58_ROLE_TEMPLATE.constraints.filter(row => !(row.relname === "servers" && row.conname === "servers_type_check")),
|
||||
}
|
||||
|
||||
export const FIXED59_ROLE_TEMPLATE: Readonly<Inventory> = Object.freeze({
|
||||
...prior,
|
||||
...Object.fromEntries(["tables", ...GROUPS].map(group => [group, sorted([...prior[group], ...FIXED59_IX_DELTA[group]])])),
|
||||
})
|
||||
|
||||
export const BUILD59_PROVENANCE = Object.freeze({
|
||||
format: "source59-ix-profile-v1",
|
||||
manifestSha256: IX_WRITER_PROFILE_MANIFEST_SHA256,
|
||||
templateSha256: IX_WRITER_PROFILE_DEFINITION_SHA256,
|
||||
})
|
||||
|
||||
if (sha(canonical(FIXED59_ROLE_TEMPLATE)) !== BUILD59_PROVENANCE.templateSha256) {
|
||||
throw new Error("Fixed59 writer catalogue changed")
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// PostgreSQL 18.4 catalogue rows captured after migration 0058 and IX least-privilege enrollment.
|
||||
import type { Inventory } from "./catalogue-projection.js"
|
||||
|
||||
export const FIXED59_IX_DELTA: Inventory = {
|
||||
tables: [
|
||||
{"acl":["@mm-role:capture@=r/@mm-role:operator@","@mm-role:operator@=arwdDxtm/@mm-role:operator@","@mm-role:runtime@=ar/@mm-role:operator@"],"owner":"@mm-role:operator@","relkind":"r","relname":"ix_segment_revisions","namespace":"public","reloptions":null,"partition_key":null,"relispartition":false,"relrowsecurity":false,"partition_bound":null,"relforcerowsecurity":false},
|
||||
{"acl":["@mm-role:capture@=r/@mm-role:operator@","@mm-role:operator@=arwdDxtm/@mm-role:operator@","@mm-role:runtime@=ard/@mm-role:operator@"],"owner":"@mm-role:operator@","relkind":"r","relname":"ix_segment_devices","namespace":"public","reloptions":null,"partition_key":null,"relispartition":false,"relrowsecurity":false,"partition_bound":null,"relforcerowsecurity":false},
|
||||
{"acl":["@mm-role:capture@=r/@mm-role:operator@","@mm-role:operator@=arwdDxtm/@mm-role:operator@","@mm-role:runtime@=arw/@mm-role:operator@"],"owner":"@mm-role:operator@","relkind":"r","relname":"ix_segments","namespace":"public","reloptions":null,"partition_key":null,"relispartition":false,"relrowsecurity":false,"partition_bound":null,"relforcerowsecurity":false},
|
||||
],
|
||||
columns: [
|
||||
{"acl":null,"type":"text","attnum":4,"attname":"actor_id","relname":"ix_segment_revisions","attnotnull":true,"attstorage":"x","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
|
||||
{"acl":null,"type":"integer","attnum":5,"attname":"applied_revision","relname":"ix_segments","attnotnull":false,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
|
||||
{"acl":null,"type":"jsonb","attnum":3,"attname":"configuration","relname":"ix_segment_revisions","attnotnull":true,"attstorage":"x","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
|
||||
{"acl":null,"type":"jsonb","attnum":4,"attname":"configuration","relname":"ix_segments","attnotnull":true,"attstorage":"x","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
|
||||
{"acl":null,"type":"timestamp with time zone","attnum":5,"attname":"created_at","relname":"ix_segment_revisions","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":"now()"},
|
||||
{"acl":null,"type":"uuid","attnum":1,"attname":"id","relname":"ix_segments","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
|
||||
{"acl":null,"type":"text","attnum":2,"attname":"name","relname":"ix_segments","attnotnull":true,"attstorage":"x","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
|
||||
{"acl":null,"type":"integer","attnum":2,"attname":"revision","relname":"ix_segment_revisions","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
|
||||
{"acl":null,"type":"integer","attnum":3,"attname":"revision","relname":"ix_segments","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
|
||||
{"acl":null,"type":"uuid","attnum":1,"attname":"segment_id","relname":"ix_segment_devices","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
|
||||
{"acl":null,"type":"uuid","attnum":1,"attname":"segment_id","relname":"ix_segment_revisions","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
|
||||
{"acl":null,"type":"bigint","attnum":2,"attname":"server_id","relname":"ix_segment_devices","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
|
||||
{"acl":null,"type":"timestamp with time zone","attnum":6,"attname":"updated_at","relname":"ix_segments","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":"now()"},
|
||||
],
|
||||
triggers: [
|
||||
{"tgname":"candidate_application_statement_guard","tgtype":30,"relname":"ix_segment_devices","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER candidate_application_statement_guard BEFORE INSERT OR DELETE OR UPDATE ON public.ix_segment_devices FOR EACH STATEMENT EXECUTE FUNCTION server_partition_writer_guard()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"public.server_partition_writer_guard()","parent":false,"constraint":false},
|
||||
{"tgname":"candidate_application_statement_guard","tgtype":30,"relname":"ix_segment_revisions","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER candidate_application_statement_guard BEFORE INSERT OR DELETE OR UPDATE ON public.ix_segment_revisions FOR EACH STATEMENT EXECUTE FUNCTION server_partition_writer_guard()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"public.server_partition_writer_guard()","parent":false,"constraint":false},
|
||||
{"tgname":"candidate_application_statement_guard","tgtype":30,"relname":"ix_segments","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER candidate_application_statement_guard BEFORE INSERT OR DELETE OR UPDATE ON public.ix_segments FOR EACH STATEMENT EXECUTE FUNCTION server_partition_writer_guard()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"public.server_partition_writer_guard()","parent":false,"constraint":false},
|
||||
{"tgname":"candidate_truncate_preadmitted","tgtype":34,"relname":"ix_segment_devices","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER candidate_truncate_preadmitted BEFORE TRUNCATE ON public.ix_segment_devices FOR EACH STATEMENT EXECUTE FUNCTION mmapp_control.candidate_truncate_preadmitted()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"mmapp_control.candidate_truncate_preadmitted()","parent":false,"constraint":false},
|
||||
{"tgname":"candidate_truncate_preadmitted","tgtype":34,"relname":"ix_segment_revisions","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER candidate_truncate_preadmitted BEFORE TRUNCATE ON public.ix_segment_revisions FOR EACH STATEMENT EXECUTE FUNCTION mmapp_control.candidate_truncate_preadmitted()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"mmapp_control.candidate_truncate_preadmitted()","parent":false,"constraint":false},
|
||||
{"tgname":"candidate_truncate_preadmitted","tgtype":34,"relname":"ix_segments","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER candidate_truncate_preadmitted BEFORE TRUNCATE ON public.ix_segments FOR EACH STATEMENT EXECUTE FUNCTION mmapp_control.candidate_truncate_preadmitted()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"mmapp_control.candidate_truncate_preadmitted()","parent":false,"constraint":false},
|
||||
{"tgname":"server_partition_writer_guard","tgtype":31,"relname":"ix_segment_devices","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER server_partition_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.ix_segment_devices FOR EACH ROW EXECUTE FUNCTION server_partition_writer_guard()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"public.server_partition_writer_guard()","parent":false,"constraint":false},
|
||||
{"tgname":"server_partition_writer_guard","tgtype":31,"relname":"ix_segment_revisions","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER server_partition_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.ix_segment_revisions FOR EACH ROW EXECUTE FUNCTION server_partition_writer_guard()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"public.server_partition_writer_guard()","parent":false,"constraint":false},
|
||||
{"tgname":"server_partition_writer_guard","tgtype":31,"relname":"ix_segments","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER server_partition_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.ix_segments FOR EACH ROW EXECUTE FUNCTION server_partition_writer_guard()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"public.server_partition_writer_guard()","parent":false,"constraint":false},
|
||||
{"tgname":"RI_ConstraintTrigger_a_{oid}","tgtype":9,"relname":"ix_segments","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_a_{oid}\" AFTER DELETE ON public.ix_segments FROM ix_segment_devices NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_cascade_del\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1646","parent":false,"constraint":true},
|
||||
{"tgname":"RI_ConstraintTrigger_a_{oid}","tgtype":9,"relname":"ix_segments","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_a_{oid}\" AFTER DELETE ON public.ix_segments FROM ix_segment_revisions NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_cascade_del\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1646","parent":false,"constraint":true},
|
||||
{"tgname":"RI_ConstraintTrigger_a_{oid}","tgtype":17,"relname":"ix_segments","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_a_{oid}\" AFTER UPDATE ON public.ix_segments FROM ix_segment_devices NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_noaction_upd\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1655","parent":false,"constraint":true},
|
||||
{"tgname":"RI_ConstraintTrigger_a_{oid}","tgtype":17,"relname":"ix_segments","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_a_{oid}\" AFTER UPDATE ON public.ix_segments FROM ix_segment_revisions NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_noaction_upd\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1655","parent":false,"constraint":true},
|
||||
{"tgname":"RI_ConstraintTrigger_c_{oid}","tgtype":5,"relname":"ix_segment_devices","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_c_{oid}\" AFTER INSERT ON public.ix_segment_devices FROM ix_segments NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_check_ins\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1644","parent":false,"constraint":true},
|
||||
{"tgname":"RI_ConstraintTrigger_c_{oid}","tgtype":5,"relname":"ix_segment_devices","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_c_{oid}\" AFTER INSERT ON public.ix_segment_devices FROM servers NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_check_ins\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1644","parent":false,"constraint":true},
|
||||
{"tgname":"RI_ConstraintTrigger_c_{oid}","tgtype":5,"relname":"ix_segment_revisions","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_c_{oid}\" AFTER INSERT ON public.ix_segment_revisions FROM ix_segments NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_check_ins\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1644","parent":false,"constraint":true},
|
||||
{"tgname":"RI_ConstraintTrigger_c_{oid}","tgtype":17,"relname":"ix_segment_devices","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_c_{oid}\" AFTER UPDATE ON public.ix_segment_devices FROM ix_segments NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_check_upd\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1645","parent":false,"constraint":true},
|
||||
{"tgname":"RI_ConstraintTrigger_c_{oid}","tgtype":17,"relname":"ix_segment_devices","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_c_{oid}\" AFTER UPDATE ON public.ix_segment_devices FROM servers NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_check_upd\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1645","parent":false,"constraint":true},
|
||||
{"tgname":"RI_ConstraintTrigger_c_{oid}","tgtype":17,"relname":"ix_segment_revisions","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_c_{oid}\" AFTER UPDATE ON public.ix_segment_revisions FROM ix_segments NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_check_upd\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1645","parent":false,"constraint":true},
|
||||
{"tgname":"RI_ConstraintTrigger_a_{oid}","tgtype":9,"relname":"servers","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_a_{oid}\" AFTER DELETE ON public.servers FROM ix_segment_devices NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_restrict_del\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1648","parent":false,"constraint":true},
|
||||
{"tgname":"RI_ConstraintTrigger_a_{oid}","tgtype":17,"relname":"servers","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_a_{oid}\" AFTER UPDATE ON public.servers FROM ix_segment_devices NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_noaction_upd\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1655","parent":false,"constraint":true},
|
||||
],
|
||||
constraints: [
|
||||
{"conname":"ix_segment_devices_pkey","contype":"p","relname":"ix_segment_devices","definition":"PRIMARY KEY (segment_id, server_id)","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_devices_segment_id_fkey","contype":"f","relname":"ix_segment_devices","definition":"FOREIGN KEY (segment_id) REFERENCES ix_segments(id) ON DELETE CASCADE","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_devices_segment_id_not_null","contype":"n","relname":"ix_segment_devices","definition":"NOT NULL segment_id","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_devices_server_id_fkey","contype":"f","relname":"ix_segment_devices","definition":"FOREIGN KEY (server_id) REFERENCES servers(id) ON DELETE RESTRICT","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_devices_server_id_not_null","contype":"n","relname":"ix_segment_devices","definition":"NOT NULL server_id","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_revisions_actor_id_not_null","contype":"n","relname":"ix_segment_revisions","definition":"NOT NULL actor_id","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_revisions_configuration_check","contype":"c","relname":"ix_segment_revisions","definition":"CHECK ((jsonb_typeof(configuration) = 'object'::text))","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_revisions_configuration_not_null","contype":"n","relname":"ix_segment_revisions","definition":"NOT NULL configuration","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_revisions_created_at_not_null","contype":"n","relname":"ix_segment_revisions","definition":"NOT NULL created_at","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_revisions_pkey","contype":"p","relname":"ix_segment_revisions","definition":"PRIMARY KEY (segment_id, revision)","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_revisions_revision_check","contype":"c","relname":"ix_segment_revisions","definition":"CHECK ((revision > 0))","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_revisions_revision_not_null","contype":"n","relname":"ix_segment_revisions","definition":"NOT NULL revision","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_revisions_segment_id_fkey","contype":"f","relname":"ix_segment_revisions","definition":"FOREIGN KEY (segment_id) REFERENCES ix_segments(id) ON DELETE CASCADE","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_revisions_segment_id_not_null","contype":"n","relname":"ix_segment_revisions","definition":"NOT NULL segment_id","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segments_check","contype":"c","relname":"ix_segments","definition":"CHECK (((applied_revision > 0) AND (applied_revision <= revision)))","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segments_configuration_check","contype":"c","relname":"ix_segments","definition":"CHECK ((jsonb_typeof(configuration) = 'object'::text))","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segments_configuration_not_null","contype":"n","relname":"ix_segments","definition":"NOT NULL configuration","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segments_id_not_null","contype":"n","relname":"ix_segments","definition":"NOT NULL id","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segments_name_key","contype":"u","relname":"ix_segments","definition":"UNIQUE (name)","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segments_name_not_null","contype":"n","relname":"ix_segments","definition":"NOT NULL name","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segments_pkey","contype":"p","relname":"ix_segments","definition":"PRIMARY KEY (id)","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segments_revision_check","contype":"c","relname":"ix_segments","definition":"CHECK ((revision > 0))","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segments_revision_not_null","contype":"n","relname":"ix_segments","definition":"NOT NULL revision","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segments_updated_at_not_null","contype":"n","relname":"ix_segments","definition":"NOT NULL updated_at","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"servers_type_check","contype":"c","relname":"servers","definition":"CHECK ((type = ANY (ARRAY['jump-host'::text, 'exit-node'::text, 'home-router'::text, 'ix-node'::text])))","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
],
|
||||
indexes: [
|
||||
{"relname":"ix_segment_devices","definition":"CREATE INDEX ix_segment_devices_server_idx ON public.ix_segment_devices USING btree (server_id)","index_name":"ix_segment_devices_server_idx","indisready":true,"indisvalid":true,"indisunique":false,"indisprimary":false},
|
||||
{"relname":"ix_segment_devices","definition":"CREATE UNIQUE INDEX ix_segment_devices_pkey ON public.ix_segment_devices USING btree (segment_id, server_id)","index_name":"ix_segment_devices_pkey","indisready":true,"indisvalid":true,"indisunique":true,"indisprimary":true},
|
||||
{"relname":"ix_segment_revisions","definition":"CREATE UNIQUE INDEX ix_segment_revisions_pkey ON public.ix_segment_revisions USING btree (segment_id, revision)","index_name":"ix_segment_revisions_pkey","indisready":true,"indisvalid":true,"indisunique":true,"indisprimary":true},
|
||||
{"relname":"ix_segments","definition":"CREATE UNIQUE INDEX ix_segments_name_key ON public.ix_segments USING btree (name)","index_name":"ix_segments_name_key","indisready":true,"indisvalid":true,"indisunique":true,"indisprimary":false},
|
||||
{"relname":"ix_segments","definition":"CREATE UNIQUE INDEX ix_segments_pkey ON public.ix_segments USING btree (id)","index_name":"ix_segments_pkey","indisready":true,"indisvalid":true,"indisunique":true,"indisprimary":true},
|
||||
],
|
||||
roleGrants: [
|
||||
{"read":false,"delete":false,"insert":false,"update":false,"relname":"ix_segment_devices","rolname":"@mm-role:publisher@","trigger":false,"truncate":false},
|
||||
{"read":false,"delete":false,"insert":false,"update":false,"relname":"ix_segment_revisions","rolname":"@mm-role:publisher@","trigger":false,"truncate":false},
|
||||
{"read":false,"delete":false,"insert":false,"update":false,"relname":"ix_segments","rolname":"@mm-role:publisher@","trigger":false,"truncate":false},
|
||||
{"read":true,"delete":false,"insert":false,"update":false,"relname":"ix_segment_devices","rolname":"@mm-role:capture@","trigger":false,"truncate":false},
|
||||
{"read":true,"delete":false,"insert":false,"update":false,"relname":"ix_segment_revisions","rolname":"@mm-role:capture@","trigger":false,"truncate":false},
|
||||
{"read":true,"delete":false,"insert":false,"update":false,"relname":"ix_segments","rolname":"@mm-role:capture@","trigger":false,"truncate":false},
|
||||
{"read":true,"delete":false,"insert":true,"update":false,"relname":"ix_segment_revisions","rolname":"@mm-role:runtime@","trigger":false,"truncate":false},
|
||||
{"read":true,"delete":false,"insert":true,"update":true,"relname":"ix_segments","rolname":"@mm-role:runtime@","trigger":false,"truncate":false},
|
||||
{"read":true,"delete":true,"insert":true,"update":true,"relname":"ix_segment_devices","rolname":"@mm-role:operator@","trigger":true,"truncate":true},
|
||||
{"read":true,"delete":true,"insert":true,"update":false,"relname":"ix_segment_devices","rolname":"@mm-role:runtime@","trigger":false,"truncate":false},
|
||||
{"read":true,"delete":true,"insert":true,"update":true,"relname":"ix_segment_revisions","rolname":"@mm-role:operator@","trigger":true,"truncate":true},
|
||||
{"read":true,"delete":true,"insert":true,"update":true,"relname":"ix_segments","rolname":"@mm-role:operator@","trigger":true,"truncate":true},
|
||||
],
|
||||
inheritance: [
|
||||
|
||||
],
|
||||
}
|
||||
@@ -12,8 +12,9 @@ const publicationFormat='application-writer-publication-approval-v1'
|
||||
export const UPGRADE_APPROVAL_FORMAT='application-writer-upgrade44-to56-approval-v1'
|
||||
export const UPGRADE57_APPROVAL_FORMAT='application-writer-upgrade56-to57-approval-v1'
|
||||
export const UPGRADE58_APPROVAL_FORMAT='application-writer-upgrade57-to58-approval-v1'
|
||||
export const UPGRADE59_APPROVAL_FORMAT='application-writer-upgrade58-to59-approval-v1'
|
||||
export const REBIND58_APPROVAL_FORMAT='application-writer-rebind58-after-restore-approval-v1'
|
||||
export const isUpgradeApprovalFormat=format=>[UPGRADE_APPROVAL_FORMAT,UPGRADE57_APPROVAL_FORMAT,UPGRADE58_APPROVAL_FORMAT,REBIND58_APPROVAL_FORMAT].includes(format)
|
||||
export const isUpgradeApprovalFormat=format=>[UPGRADE_APPROVAL_FORMAT,UPGRADE57_APPROVAL_FORMAT,UPGRADE58_APPROVAL_FORMAT,UPGRADE59_APPROVAL_FORMAT,REBIND58_APPROVAL_FORMAT].includes(format)
|
||||
function parsedApproval(value,format=publicationFormat){
|
||||
const upgrade=isUpgradeApprovalFormat(format)
|
||||
const keys=['format','manifestSha256','definitionSha256','catalogSha256','expectedHeadSha256','validityMs','expiresAt']
|
||||
|
||||
@@ -3,11 +3,12 @@ import pg from 'pg'
|
||||
import {createPrivateKey,createPublicKey,sign,X509Certificate} from 'node:crypto'
|
||||
import {open,lstat,realpath,unlink} from 'node:fs/promises'
|
||||
import {readProtected,writeFile,withJournalLease} from './operator-files.mjs'
|
||||
import {retainPublisherTlsPeer,upgradeApproval,isUpgradeApprovalFormat,UPGRADE_APPROVAL_FORMAT,UPGRADE57_APPROVAL_FORMAT,UPGRADE58_APPROVAL_FORMAT,REBIND58_APPROVAL_FORMAT} from './operator-contract.mjs'
|
||||
import {retainPublisherTlsPeer,upgradeApproval,isUpgradeApprovalFormat,UPGRADE_APPROVAL_FORMAT,UPGRADE57_APPROVAL_FORMAT,UPGRADE58_APPROVAL_FORMAT,UPGRADE59_APPROVAL_FORMAT,REBIND58_APPROVAL_FORMAT} from './operator-contract.mjs'
|
||||
import {BUILD44_PROVENANCE} from './fixed44-build-definition.js'
|
||||
import {BUILD56_PROVENANCE} from './fixed56-build-definition.js'
|
||||
import {BUILD57_PROVENANCE} from './fixed57-build-definition.js'
|
||||
import {BUILD58_PROVENANCE} from './fixed58-build-definition.js'
|
||||
import {BUILD59_PROVENANCE} from './fixed59-build-definition.js'
|
||||
import path from 'node:path'
|
||||
import {captureDatabaseSourceObservation,assertDatabaseSourceObservationCurrent} from '../../src/db/database-source-observation.js'
|
||||
import {MIGRATION_MANIFEST,migrationManifestDigest} from '../../src/db/migration-manifest.js'
|
||||
@@ -19,6 +20,7 @@ const upgradeTransitions = {
|
||||
[UPGRADE_APPROVAL_FORMAT]: { predecessor: BUILD44_PROVENANCE, successor: BUILD56_PROVENANCE, oldEdition: 44, newEdition: 56 },
|
||||
[UPGRADE57_APPROVAL_FORMAT]: { predecessor: BUILD56_PROVENANCE, successor: BUILD57_PROVENANCE, oldEdition: 56, newEdition: 57 },
|
||||
[UPGRADE58_APPROVAL_FORMAT]: { predecessor: BUILD57_PROVENANCE, successor: BUILD58_PROVENANCE, oldEdition: 57, newEdition: 58 },
|
||||
[UPGRADE59_APPROVAL_FORMAT]: { predecessor: BUILD58_PROVENANCE, successor: BUILD59_PROVENANCE, oldEdition: 58, newEdition: 59 },
|
||||
[REBIND58_APPROVAL_FORMAT]: { predecessor: BUILD58_PROVENANCE, successor: BUILD58_PROVENANCE, oldEdition: 58, newEdition: 58 },
|
||||
}
|
||||
export function requireCurrentCatalogueDefinition(approval,definition){
|
||||
@@ -133,7 +135,7 @@ async function session(pool,deadlineAt,work){
|
||||
return value
|
||||
}
|
||||
async function observeCurrentCatalogue(s,manifestSha256){
|
||||
const security=await protectedStructure(s,installation,definition?.edition===58),catalogue=await collectFixedCatalogue(s)
|
||||
const security=await protectedStructure(s,installation,(definition?.edition??44)>=58),catalogue=await collectFixedCatalogue(s)
|
||||
if(catalogue.manifestSha256!==manifestSha256||catalogue.definitionSha256!==definition.definitionSha256)throw Error('Catalogue evidence differs from the approved migration manifest/definition')
|
||||
// Inspect one extra row so an unexpected marker cannot hide after the expected prefix.
|
||||
const expected=MIGRATION_MANIFEST.map(pin=>pin.file.slice(0,-4))
|
||||
@@ -209,7 +211,7 @@ async function inspectPublication(pool,proposal,{deadlineAt=Date.now()+120000}={
|
||||
if(!proposal||proposal.installationId!==installation.installationId||!(/^[a-f0-9]{64}$/).test(proposal.headSha256)||proposal.previousHeadSha256!==null&&!(/^[a-f0-9]{64}$/).test(proposal.previousHeadSha256))throw Error('Bounded public proposal required')
|
||||
return session(pool,deadlineAt,async s=>{
|
||||
s.phase('publication-inspection');await s.query('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');s.begun(true)
|
||||
const first=await ownedContext(s,installation,PUBLISHER,'publisher-read');await protectedStructure(s,installation,definition?.edition===58)
|
||||
const first=await ownedContext(s,installation,PUBLISHER,'publisher-read');await protectedStructure(s,installation,(definition?.edition??44)>=58)
|
||||
if(canonical(sourceCoordinates(first))!==canonical(installation.expectedSource))throw Error('Pinned inspection source mismatch')
|
||||
const facade=Object.freeze({query:(sql,values)=>s.query(sql,values)}),options={deadlineAt}
|
||||
const observation=await captureDatabaseSourceObservation(facade,options);await sourceVerifier.verify(facade,observation,options)
|
||||
@@ -251,7 +253,8 @@ async function preflightCurrentProfile(pool,{deadlineAt=Date.now()+120000}={}){
|
||||
}
|
||||
async function inspectCurrentCatalogue(pool,{deadlineAt=Date.now()+120000}={}){
|
||||
const manifestSha256=migrationManifestDigest()
|
||||
if(definition?.edition!==58||definition.manifestSha256!==manifestSha256||definition.definitionSha256!==BUILD58_PROVENANCE.templateSha256)throw Error('Approved source58 definition required')
|
||||
const expected=definition?.edition===59?BUILD59_PROVENANCE:definition?.edition===58?BUILD58_PROVENANCE:undefined
|
||||
if(!expected||definition.manifestSha256!==manifestSha256||definition.definitionSha256!==expected.templateSha256)throw Error('Approved current writer definition required')
|
||||
return session(pool,deadlineAt,async s=>{
|
||||
s.phase('source-catalogue-inspection');await s.query('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');s.begun(true)
|
||||
const first=await ownedContext(s,installation,PUBLISHER,'publisher-read')
|
||||
@@ -261,9 +264,10 @@ async function inspectCurrentCatalogue(pool,{deadlineAt=Date.now()+120000}={}){
|
||||
const initial=await sourceVerifier.verify(facade,observation,options)
|
||||
const {security,catalogSha256}=await observeCurrentCatalogue(s,manifestSha256)
|
||||
const current=await readCurrent(s,installation,{validNow:false})
|
||||
if(!current||current.policy.definitionSha256!==definition.definitionSha256||current.policy.manifestSha256!==manifestSha256||
|
||||
const allowedHeads=definition.edition===59?[BUILD58_PROVENANCE,BUILD59_PROVENANCE]:[BUILD58_PROVENANCE]
|
||||
if(!current||!allowedHeads.some(head=>head.templateSha256===current.policy.definitionSha256&&head.manifestSha256===current.policy.manifestSha256)||
|
||||
canonical(current.policy.source)!==canonical(sourceCoordinates(first))||canonical(current.policy.roles)!==canonical(security.roles)){
|
||||
throw Error('Approved source58 predecessor required')
|
||||
throw Error('Approved same-installation writer predecessor required')
|
||||
}
|
||||
const terminal=await sourceVerifier.verify(facade,observation,options)
|
||||
if(initial.platformProtectionVerified!==true||terminal.platformProtectionVerified!==true)throw Error('Protected source evidence required')
|
||||
|
||||
Reference in new issue
Block a user