/** Owned fresh PostgreSQL acceptance using the fixed REST host and its actual * authority factory. No source, signer, SQL, session or authority overrides. */ import assert from "node:assert/strict" import { randomUUID } from "node:crypto" import { createServer } from "node:http" import { basename, dirname, resolve } from "node:path" import type { AuthUser } from "../lib/permissions.js" import type { ServerPollRestContext } from "./server-poll-rest.js" export async function acceptServerPollRestAuthoritySql(options: { httpRoute?: true } = {}) { // These assertions precede all imports capable of creating a configured pool. assert.equal(process.env.MMAPP_OWN_SERVER_POLL_STORAGE_FRESH, "true") const endpoint = new URL(process.env.DATABASE_URL ?? "") assert.equal(endpoint.hostname, "127.0.0.1"); assert.equal(endpoint.pathname, "/postgres") assert(process.env.MCP_STATE_DIR && basename(dirname(resolve(process.env.MCP_STATE_DIR))).startsWith("mm-mcp-test-")) const { pool } = await import("../db/index.js") const { ensurePartitionFor } = await import("../db/partitions.js") const { executeDurableServerPollRest } = await import("./server-poll-rest.js") const ownerId = "owned-rest-authority-" + randomUUID(), name = "owned-rest-authority" let serverId: number | undefined, requests = 0, checkedAdmissions = 0, dispatchFailure = false let app: Awaited> | undefined let httpOrigin = "" const paths: string[] = [] const listener = createServer(async (request, response) => { requests++; paths.push(request.url ?? "") try { assert.equal(request.method, "GET") const rows = (await pool.query(`SELECT a.receipt_id,a.claim_token,a.claim_attempted_at,a.used_rows, u.admissions,u.reserved_rows,u.reserved_bytes::text FROM server_poll_storage_admissions a JOIN server_poll_storage_usage u ON u.scope='owner:'||a.owner_id JOIN server_poll_executions e USING(receipt_id) WHERE a.owner_id=$1 AND a.identity_kind='rest' AND e.context_proof=a.context_proof`, [ownerId])).rows assert.equal(rows.length, 1); assert.equal(rows[0].claim_token, null) assert(rows[0].claim_attempted_at); assert(Number(rows[0].used_rows) >= 1) assert.equal(Number(rows[0].admissions), 1); assert.equal(Number(rows[0].reserved_rows), 4019) assert.equal(rows[0].reserved_bytes, "8421376"); checkedAdmissions++ const result = request.url === "/rest/system/identity" ? { name } : request.url === "/rest/system/resource" ? { version: "7.synthetic", "board-name": "owned", uptime: "1h", "cpu-load": "2", "free-memory": "1024", "total-memory": "2048" } : request.url === "/rest/interface" ? [{ type: "ether", name: "owned-interface" }] : request.url === "/rest/ip/address" ? [{ interface: "owned-interface", address: "192.0.2.1/24" }] : null assert.notEqual(result, null) response.setHeader("content-type", "application/json"); response.statusCode = 200; response.end(JSON.stringify(result)) } catch { dispatchFailure = true; response.statusCode = 500; response.end("Owned dispatch refused") } }) const actor: AuthUser = { id: ownerId, email: "owned@example.invalid", name: "Owned REST authority", apps: ["mm"], permissions: ["mm:servers:write"], issuedAt: Date.now() - 1000, expiresAt: Date.now() + 600000 } const context = (patch: Partial = {}): ServerPollRestContext => ({ actor, authRequired: true, acceptedAt: Date.now(), requestId: randomUUID(), deadlineAt: Date.now() + 180000, ...patch }) const call = async (id: string, accepted: ServerPollRestContext) => { if (!options.httpRoute) return executeDurableServerPollRest(id, accepted) assert(app && httpOrigin) const { env } = await import("../config.js") const token = accepted.actor ? app.jwt.sign({ iss: env.authIssuer, sub: accepted.actor.id, email: accepted.actor.email, name: accepted.actor.name, apps: accepted.actor.apps, permissions: accepted.actor.permissions, iat: Math.floor(accepted.actor.issuedAt! / 1000), exp: Math.floor(accepted.actor.expiresAt! / 1000) }) : undefined const response = await fetch(httpOrigin + "/api/servers/" + encodeURIComponent(id) + "/poll", { method: "POST", headers: { "content-type": "application/json", "x-request-id": "untrusted-header", ...(token ? { authorization: "Bearer " + token } : {}) }, body: JSON.stringify({ actor: { id: "untrusted-owner" }, authRequired: false, requestId: "untrusted-body", deadlineAt: Date.now() + 86400000 }), signal: AbortSignal.timeout(185000) }) return { statusCode: response.status, body: await response.json() as Record } } try { await new Promise((yes, no) => { listener.once("error", no); listener.listen(0, "127.0.0.1", () => { listener.off("error", no); yes() }) }) const port = (listener.address() as { port: number }).port serverId = Number((await pool.query("INSERT INTO servers(name,host,port,enabled,username,password,use_ssl,verify_ssl) VALUES($1,'127.0.0.1',$2,true,'SYNTHETIC-USER','SYNTHETIC-PRIVATE-PASSWORD',false,true) RETURNING id", [name, port])).rows[0].id) await ensurePartitionFor(pool, "server_snapshots", "week", new Date()) if (options.httpRoute) { const { buildApp } = await import("../index.js") app = await buildApp({ logger: false, startScheduler: false }) await app.listen({ host: "127.0.0.1", port: 0 }) const address = app.server.address(); assert(address && typeof address !== "string") httpOrigin = `http://127.0.0.1:${address.port}` } const before = (await pool.query("SELECT count(*)::int AS n FROM server_poll_storage_admissions")).rows[0].n const negative = [ await call("invalid-id", context()), await call(String(serverId), context({ actor: undefined })), await call(String(serverId), context({ actor: { ...actor, permissions: ["mm:servers:read"] } })), await call("2147483647", context()), ] assert.deepEqual(negative.map(reply => reply.statusCode), [400, options.httpRoute ? 401 : 403, 403, 404]) assert.equal(requests, 0) assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_poll_storage_admissions")).rows[0].n, before) const started = Date.now() // Exactly one invocation. A failed/unknown attempt is never replayed here. const reply = await call(String(serverId), context()) const elapsedMs = Date.now() - started if (reply.statusCode !== 200) { const phase = (await pool.query(`SELECT a.used_rows,a.claim_attempted_at IS NOT NULL AS consumed, EXISTS(SELECT 1 FROM server_poll_receipts r WHERE r.receipt_id=a.receipt_id) AS receipt, EXISTS(SELECT 1 FROM server_poll_quarantines q WHERE q.receipt_id=a.receipt_id) AS quarantine, (SELECT stage FROM server_poll_intents i WHERE i.receipt_id=a.receipt_id ORDER BY created_at DESC,stage DESC LIMIT 1) AS last_stage FROM server_poll_storage_admissions a WHERE owner_id=$1`, [ownerId])).rows console.log("Owned actual REST authority failure:", JSON.stringify({ elapsedMs, statusCode: reply.statusCode, nativeGets: requests, phase, publicError: reply.body.error, automaticReplay: false })) } assert.equal(reply.statusCode, 200, "Actual REST authority full poll failed; no automatic replay") assert.equal(dispatchFailure, false); assert.equal(requests, 4); assert.equal(checkedAdmissions, 4) assert.deepEqual(paths.sort(), ["/rest/interface", "/rest/ip/address", "/rest/system/identity", "/rest/system/resource"]) assert.deepEqual(Object.keys(reply.body).sort(), ["id", "serverId", "polledAt", "status", "latencyMs", "rosVersion", "boardName", "uptime", "cpuLoad", "freeMemory", "totalMemory", "identityName"].sort()) assert.equal(reply.body.serverId, serverId); assert.equal(reply.body.status, "online"); assert.equal(reply.body.identityName, name) assert.equal(reply.body.rosVersion, "7.synthetic"); assert.equal(reply.body.boardName, "owned"); assert.equal(reply.body.uptime, "1h") assert.equal(reply.body.cpuLoad, 2); assert.equal(reply.body.freeMemory, 1024); assert.equal(reply.body.totalMemory, 2048) assert(Number.isSafeInteger(reply.body.id) && Number(reply.body.id) > 0) assert.equal(typeof reply.body.polledAt, "string"); assert(Number.isFinite(Date.parse(String(reply.body.polledAt)))) assert.equal(typeof reply.body.latencyMs, "number"); assert(Number(reply.body.latencyMs) >= 0) const serialized = JSON.stringify(reply.body) for (const secret of ["SYNTHETIC-USER", "SYNTHETIC-PRIVATE-PASSWORD", "rawInterfaces", "rawIpAddresses", "192.0.2.1", "owned-interface"]) assert.equal(serialized.includes(secret), false) const result = { statusCode: reply.statusCode, elapsedMs, nativeGets: requests, dispatchesAfterConsumedAdmission: checkedAdmissions, actualRestAuthorityFactory: true, actualProductionSession: true, actualRegisteredHttpRoute: options.httpRoute === true, actualSignedJwt: options.httpRoute === true, httpAppSchedulerStarted: false, negativeStatuses: negative.map(value => value.statusCode), exactLegacySnapshotShape: true, privateFieldsAbsent: true, automaticReplay: false } console.log("Owned actual REST authority:", JSON.stringify(result)); return result } finally { await app?.close() listener.closeAllConnections(); if (listener.listening) await new Promise(yes => listener.close(() => yes())) if (serverId !== undefined) await pool.query("UPDATE servers SET enabled=false WHERE id=$1", [serverId]) } }