76 lines
6.0 KiB
TypeScript
76 lines
6.0 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import http from "node:http"
|
|
import https from "node:https"
|
|
import { execFileSync } from "node:child_process"
|
|
import { mkdtemp, readFile, rm } from "node:fs/promises"
|
|
import { tmpdir } from "node:os"
|
|
import { basename, isAbsolute, join, relative, resolve } from "node:path"
|
|
import type { TLSSocket } from "node:tls"
|
|
import { randomUUID } from "node:crypto"
|
|
import { routeContextClients } from "./routing-community-context-native.js"
|
|
import { resolveRoutingNetworkDestinationPins } from "./routing-network-native-destination.js"
|
|
import type { RoutingEndpoint } from "./routing-observation-source.js"
|
|
|
|
// Actual local TLS; trust only this freshly generated test certificate for the
|
|
// exact bound fixture. No configured SQL pool, public endpoint or user key.
|
|
const openssl = process.env.MMAPP_TEST_OPENSSL
|
|
assert(openssl, "Set MMAPP_TEST_OPENSSL to an installed OpenSSL executable")
|
|
const directory = await mkdtemp(join(tmpdir(), "mm-mcp-tls-"))
|
|
let server: https.Server | undefined, trustedAgent: https.Agent | undefined, untrustedAgent: https.Agent | undefined
|
|
const originalRequest = https.request
|
|
try {
|
|
const keyFile = join(directory, "fixture.key"), certFile = join(directory, "fixture.crt")
|
|
execFileSync(openssl, ["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-subj", "/CN=localhost", "-addext", "subjectAltName=DNS:localhost", "-days", "2", "-keyout", keyFile, "-out", certFile], { stdio: "ignore", timeout: 20000 })
|
|
const cert = await readFile(certFile), key = await readFile(keyFile)
|
|
const seen: { host: string; sni: string | false | undefined }[] = []
|
|
const payload = JSON.stringify([{ version: "7.26" }])
|
|
server = https.createServer({ key, cert }, (request, response) => {
|
|
assert.equal(request.method, "GET"); assert.equal(request.url, "/rest/system/resource")
|
|
assert.equal(request.headers.authorization, "Basic " + Buffer.from("fixture:inert-only").toString("base64"))
|
|
seen.push({ host: request.headers.host!, sni: (request.socket as TLSSocket).servername })
|
|
response.setHeader("Content-Type", "application/json"); response.end(payload)
|
|
})
|
|
server.on("tlsClientError", () => {})
|
|
await new Promise<void>(done => server!.listen(0, "127.0.0.1", done))
|
|
const address = server.address(); assert(address && typeof address === "object" && address.address === "127.0.0.1")
|
|
trustedAgent = new https.Agent({ keepAlive: true, maxSockets: 2, maxTotalSockets: 2, ca: cert })
|
|
untrustedAgent = new https.Agent({ keepAlive: false, ca: [] })
|
|
let trust = true
|
|
https.request = ((...args: unknown[]) => {
|
|
const options = args[0] as https.RequestOptions
|
|
assert(options && options.hostname === "127.0.0.1" && Number(options.port) === address.port, "TLS fixture must never connect outside its owned loopback endpoint")
|
|
args[0] = { ...options, agent: trust ? trustedAgent : untrustedAgent }
|
|
return Reflect.apply(originalRequest, https, args) as http.ClientRequest
|
|
}) as typeof https.request
|
|
const endpoint: RoutingEndpoint = { id: 1, host: "localhost", port: address.port, useSsl: true, verifySsl: true, username: "fixture", password: "inert-only", enabled: true, routingEndpointEpoch: randomUUID() }
|
|
const deadline = Date.now() + 90000, abort = new AbortController()
|
|
let fences = 0
|
|
const resolved = await resolveRoutingNetworkDestinationPins([endpoint], { deadline, signal: abort.signal, authorize: async () => { fences++ } })
|
|
assert.equal(resolved.length, 1); assert.equal(resolved[0].address, "127.0.0.1"); assert.equal(resolved[0].host, "localhost")
|
|
const pins = resolved.map(pin => ({ ...pin }))
|
|
const clients = routeContextClients([endpoint], abort.signal, { deadline, maxCalls: 2, maxBytes: 1024, pins })
|
|
pins[0].host = "outer-mutated.invalid"; pins[0].address = "127.0.0.2"; endpoint.host = "outer-mutated.invalid"; endpoint.password = "changed"
|
|
assert.deepEqual(await clients.get(1)!.get("/system/resource"), [{ version: "7.26" }])
|
|
assert.deepEqual(await clients.get(1)!.get("/system/resource"), [{ version: "7.26" }])
|
|
assert.deepEqual(seen, [{ host: `localhost:${address.port}`, sni: "localhost" }, { host: `localhost:${address.port}`, sni: "localhost" }])
|
|
assert.equal(clients.readBudget().bytes, 2 * Buffer.byteLength(payload)); assert.equal(clients.readBudget().deadline, deadline)
|
|
await assert.rejects(clients.get(1)!.get("/system/resource")); assert.equal(seen.length, 2)
|
|
assert(fences >= 2)
|
|
const originalEndpoint = { ...endpoint, host: "localhost", password: "inert-only" }
|
|
const wrongName = { ...originalEndpoint, host: "127.0.0.1" }
|
|
const wrongClient = routeContextClients([wrongName], undefined, { deadline, maxCalls: 1, maxBytes: 1024, pins: [{ serverId: 1, host: "127.0.0.1", address: "127.0.0.1", family: 4 }] })
|
|
await assert.rejects(wrongClient.get(1)!.get("/system/resource"), (error: unknown) => !!error && typeof error === "object" && Reflect.get(error, "code") === "ERR_TLS_CERT_ALTNAME_INVALID")
|
|
assert.equal(seen.length, 2, "A valid trusted certificate for another hostname must fail before HTTP/authentication")
|
|
trust = false
|
|
const untrusted = routeContextClients([originalEndpoint], undefined, { deadline, maxCalls: 1, maxBytes: 1024, pins: resolved })
|
|
await assert.rejects(untrusted.get(1)!.get("/system/resource"), (error: unknown) => !!error && typeof error === "object" && ["DEPTH_ZERO_SELF_SIGNED_CERT", "SELF_SIGNED_CERT_IN_CHAIN"].includes(String(Reflect.get(error, "code"))))
|
|
assert.equal(seen.length, 2)
|
|
console.log("Actual native TLS fixture: localhost DNS pin, authenticated HTTPS, preserved Host/SNI, CA and hostname verification, captured immutable pin, actual wire budget and pre-HTTP request cap; no SQL/CHR/public network")
|
|
} finally {
|
|
https.request = originalRequest; trustedAgent?.destroy(); untrustedAgent?.destroy()
|
|
if (server) { server.closeAllConnections(); await new Promise<void>(done => server!.close(() => done())) }
|
|
const within = relative(resolve(tmpdir()), resolve(directory))
|
|
assert(within && !within.startsWith("..") && !isAbsolute(within) && basename(directory).startsWith("mm-mcp-tls-"), "Unsafe TLS fixture cleanup path")
|
|
await rm(directory, { recursive: true, force: true })
|
|
}
|