tools: Node 26 harness base, smoke and ws-header checks (#16)
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
// Shared by the Node harnesses (DESIGN 10.4: Node 26, built-ins only, no npm deps).
|
||||
// The global WebSocket accepts a non-standard {headers} second argument; wsheaders.test.mjs
|
||||
// re-verifies on the wire that Cookie and Origin reach the server (the old "Node 22" note in
|
||||
// the prototype's lib.mjs was stale; here the pin is the devbox node 26).
|
||||
import fs from 'node:fs'
|
||||
import net from 'node:net'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
export const sleep = ms => new Promise(r => setTimeout(r, ms))
|
||||
|
||||
export const projectRoot = path.dirname(path.dirname(fileURLToPath(import.meta.url)))
|
||||
|
||||
export const baseUrl = port => `http://127.0.0.1:${port}`
|
||||
|
||||
// Ports of a live dev session: never let a test stack touch them (prototype withserver.sh rule).
|
||||
export function refuseLivePort(port) {
|
||||
if ([8088, 8080, 9000].includes(port)) throw new Error(`refusing live port ${port}`)
|
||||
}
|
||||
|
||||
export async function freePort() {
|
||||
const srv = net.createServer()
|
||||
await new Promise((res, rej) => { srv.once('error', rej); srv.listen(0, '127.0.0.1', res) })
|
||||
const { port } = srv.address()
|
||||
await new Promise(res => srv.close(res))
|
||||
return port
|
||||
}
|
||||
|
||||
function decodeIPv4(hex) {
|
||||
const b = []
|
||||
for (let i = 0; i < 8; i += 2) b.unshift(parseInt(hex.slice(i, i + 2), 16))
|
||||
return b.join('.')
|
||||
}
|
||||
|
||||
function decodeIPv6(hex) {
|
||||
// /proc/net/tcp6 stores four 32-bit words, each little-endian.
|
||||
const words = []
|
||||
for (let w = 0; w < 4; w++) {
|
||||
const h = hex.slice(w * 8, w * 8 + 8)
|
||||
words.push(h.slice(6, 8) + h.slice(4, 6) + h.slice(2, 4) + h.slice(0, 2))
|
||||
}
|
||||
let groups = []
|
||||
for (const w of words) groups.push(w.slice(0, 4), w.slice(4, 8))
|
||||
const compact = groups.join(':').replace(/(^|:)0(:0)+(:|$)/, '::')
|
||||
return compact
|
||||
}
|
||||
|
||||
// Listening sockets of this host, from /proc (Linux only; the server side is NixOS).
|
||||
export function listeningSockets(port) {
|
||||
const out = []
|
||||
for (const [file, proto] of [['/proc/net/tcp', 'tcp'], ['/proc/net/tcp6', 'tcp6']]) {
|
||||
let text
|
||||
try { text = fs.readFileSync(file, 'utf8') } catch { continue }
|
||||
for (const line of text.trim().split('\n').slice(1)) {
|
||||
const f = line.trim().split(/\s+/)
|
||||
if (f.length < 4 || f[3] !== '0A') continue // 0A = LISTEN
|
||||
const [addrHex, portHex] = f[1].split(':')
|
||||
if (parseInt(portHex, 16) !== port) continue
|
||||
out.push({ proto, hex: addrHex, addr: proto === 'tcp' ? decodeIPv4(addrHex) : decodeIPv6(addrHex) })
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
+2
-1
@@ -14,6 +14,7 @@
|
||||
# Ctrl-C / TERM / EXIT: kills all jobs and removes the temp dir (fffmut.* under $TMPDIR or /tmp).
|
||||
# Log: results/mutation.log
|
||||
cd "$(dirname "$0")/.." || exit 1
|
||||
PKGS=${NIMBLE_DIR:-$PWD/.devbox/nimble}/pkgs2 # mummy/db_connector for the new server modules
|
||||
job() { # runs in its own session: $1 id $2 title $3 file to mutate $4 sed script ("" = control) $5 expected-failure regex
|
||||
local id=$1 title=$2 file=$3 sedscr=$4 expect=$5 w=$T/$1/w res=$T/$1/res tfs tf out=$T/$1/out r=0 rr F verdict=ok rc=0
|
||||
mkdir -p "$w"; cp -r server tests tools nim.cfg "$w"/
|
||||
@@ -30,7 +31,7 @@ job() { # runs in its own session: $1 id $2 title $3 file to mutate $4 sed s
|
||||
else tfs=$(ls tests/t*.nim); fi
|
||||
: > "$out"
|
||||
for tf in $tfs; do
|
||||
(cd "$w" && nim c -r --hints:off --nimcache:"$T/$id/nc-$(basename "$tf" .nim)" "$tf") >> "$out" 2>&1; rr=$?
|
||||
(cd "$w" && nim c -r --hints:off --nimblePath:"$PKGS" --nimcache:"$T/$id/nc-$(basename "$tf" .nim)" "$tf") >> "$out" 2>&1; rr=$?
|
||||
[ $rr -eq 0 ] || r=$rr
|
||||
done
|
||||
grep -E '\[(OK|FAILED)\]|Success|Failure|Error' "$out" | sed 's/^ *\.* */ /' >> "$res"
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
// M3 slice 1 smoke (#16): the bare server starts under withserver, answers /healthz, binds
|
||||
// loopback only, and a fresh DB is created and migrated by the runner (re-open applies nothing).
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { DatabaseSync } from 'node:sqlite'
|
||||
import { listeningSockets } from './lib.mjs'
|
||||
import { buildServer, makeStateDir, startServer, stopServer, withServer } from './withserver.mjs'
|
||||
|
||||
test('withserver brings the server up and /healthz answers 200 JSON', async () => {
|
||||
await withServer(async s => {
|
||||
const r = await fetch(`${s.origin}/healthz`)
|
||||
assert.equal(r.status, 200)
|
||||
assert.equal(r.headers.get('content-type'), 'application/json')
|
||||
assert.deepEqual(await r.json(), { status: 'ok' })
|
||||
assert.equal((await fetch(`${s.origin}/nope`)).status, 404)
|
||||
assert.equal((await fetch(`${s.origin}/healthz`, { method: 'POST' })).status, 405)
|
||||
// flags reached the config and the start line: the harness origin and the fixed loopback bind
|
||||
assert.match(s.log(), new RegExp(`server_start origin=${s.origin} .* bind=127\\.0\\.0\\.1`))
|
||||
})
|
||||
})
|
||||
|
||||
test('the server listens on 127.0.0.1 only', async () => {
|
||||
await withServer(async s => {
|
||||
const sockets = listeningSockets(s.port)
|
||||
assert.ok(sockets.length > 0, `no LISTEN socket found for port ${s.port}`)
|
||||
for (const sock of sockets) {
|
||||
assert.equal(sock.addr, '127.0.0.1', `bound ${sock.proto} ${sock.addr}, not loopback-only`)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
test('negative control: the loopback check sees a 0.0.0.0 listener', async () => {
|
||||
const net = await import('node:net')
|
||||
const srv = net.createServer()
|
||||
await new Promise((res, rej) => { srv.once('error', rej); srv.listen(0, '0.0.0.0', res) })
|
||||
try {
|
||||
const addrs = listeningSockets(srv.address().port).map(s => s.addr)
|
||||
assert.deepEqual(addrs, ['0.0.0.0'])
|
||||
} finally {
|
||||
await new Promise(res => srv.close(res))
|
||||
}
|
||||
})
|
||||
|
||||
test('a fresh DB is created and migrated; re-opening applies nothing', async () => {
|
||||
const stateDir = makeStateDir()
|
||||
try {
|
||||
const first = await startServer({ stateDir })
|
||||
const firstLog = first.log()
|
||||
await stopServer(first)
|
||||
assert.match(firstLog, /db_ready .*schema_version=1 applied=1/, firstLog)
|
||||
assert.ok(fs.existsSync(first.dbPath), 'state.db was not created')
|
||||
|
||||
const db = new DatabaseSync(first.dbPath)
|
||||
try {
|
||||
assert.equal(Number(db.prepare('PRAGMA user_version').get().user_version), 1)
|
||||
const rows = db.prepare('SELECT version, name FROM schema_migration ORDER BY version').all()
|
||||
assert.deepEqual(rows.map(r => [Number(r.version), r.name]), [[1, 'meta']])
|
||||
assert.equal(Number(db.prepare('SELECT count(*) AS n FROM meta').get().n), 0)
|
||||
assert.equal(db.prepare('PRAGMA journal_mode').get().journal_mode, 'wal')
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
|
||||
const second = await startServer({ stateDir })
|
||||
const secondLog = second.log().slice(firstLog.length)
|
||||
await stopServer(second)
|
||||
assert.match(secondLog, /db_ready .*schema_version=1 applied=0/, secondLog)
|
||||
assert.doesNotMatch(secondLog, /applied=[1-9]/)
|
||||
} finally {
|
||||
fs.rmSync(stateDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('a bad flag is a clean exit 2 with a message, not a crash', () => {
|
||||
const r = spawnSync(buildServer(), ['--port=0'], { encoding: 'utf8', timeout: 10000 })
|
||||
assert.equal(r.status, 2)
|
||||
assert.match(r.stderr, /--port/)
|
||||
assert.doesNotMatch(r.stderr, /Traceback|SIGSEGV/)
|
||||
})
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
# devbox run test: Nim in-process tests first, then the Node black-box harnesses (DESIGN 10.4).
|
||||
# Nim gates Node: a red Nim suite stops the run (the Node stage takes seconds, but no point).
|
||||
# Logs land in results/ like the other gates.
|
||||
cd "$(dirname "$0")/.." || exit 1
|
||||
mkdir -p results
|
||||
if ! nimble test -y > results/nimble-test.log 2>&1; then
|
||||
cat results/nimble-test.log
|
||||
exit 1
|
||||
fi
|
||||
cat results/nimble-test.log
|
||||
node --test tools/*.test.mjs > results/node-test.log 2>&1
|
||||
rc=$?
|
||||
cat results/node-test.log
|
||||
exit $rc
|
||||
@@ -0,0 +1,105 @@
|
||||
// Isolated server for the Node harnesses (ported from prototype-server-vision/tools/withserver.sh).
|
||||
// Own state dir, own port, never a live session: the server is the real binary, built from the
|
||||
// working tree, and its stdout/stderr land in <stateDir>/server.log so a check can grep them.
|
||||
import { spawn, spawnSync } from 'node:child_process'
|
||||
import fs from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { baseUrl, freePort, projectRoot, refuseLivePort, sleep } from './lib.mjs'
|
||||
|
||||
const SERVER_BIN = path.join(projectRoot, 'run', 'test', 'server')
|
||||
|
||||
function nimblePkgs() {
|
||||
const nimbleDir = process.env.NIMBLE_DIR ?? path.join(projectRoot, '.devbox', 'nimble')
|
||||
return path.join(nimbleDir, 'pkgs2')
|
||||
}
|
||||
|
||||
let builtAt = null
|
||||
|
||||
export function buildServer() {
|
||||
if (builtAt) return builtAt
|
||||
fs.mkdirSync(path.dirname(SERVER_BIN), { recursive: true })
|
||||
const args = ['c', '--hints:off', '--mm:orc', `--nimblePath:${nimblePkgs()}`,
|
||||
`-o:${SERVER_BIN}`, path.join('server', 'main.nim')]
|
||||
const r = spawnSync('nim', args, { cwd: projectRoot, encoding: 'utf8' })
|
||||
if (r.status !== 0) throw new Error(`nim c server/main.nim failed:\n${r.stdout}\n${r.stderr}`)
|
||||
builtAt = SERVER_BIN
|
||||
return builtAt
|
||||
}
|
||||
|
||||
export function makeStateDir(prefix = 'fffvtt-') {
|
||||
return fs.mkdtempSync(path.join(process.env.TMPDIR ?? os.tmpdir(), prefix))
|
||||
}
|
||||
|
||||
const hasExited = child => child.exitCode !== null || child.signalCode !== null
|
||||
|
||||
// Ready means *this* process answers /healthz, not merely that something listens on the port.
|
||||
async function waitForHealth(handle) {
|
||||
const deadline = Date.now() + 30000
|
||||
let last = 'no response'
|
||||
while (Date.now() < deadline) {
|
||||
if (hasExited(handle.child)) {
|
||||
throw new Error(`server exited (code=${handle.child.exitCode}, signal=${handle.child.signalCode})`)
|
||||
}
|
||||
try {
|
||||
const r = await fetch(`${handle.origin}/healthz`)
|
||||
if (r.status === 200 && (await r.text()) === '{"status":"ok"}') return
|
||||
last = `status ${r.status}`
|
||||
} catch (e) { last = e.message }
|
||||
await sleep(50)
|
||||
}
|
||||
throw new Error(`timed out waiting for /healthz: ${last}`)
|
||||
}
|
||||
|
||||
// Starts the server and waits for /healthz. Resolves to a handle; stopServer() tears it down.
|
||||
export async function startServer(opts = {}) {
|
||||
const ownStateDir = opts.stateDir === undefined
|
||||
const stateDir = opts.stateDir ?? makeStateDir()
|
||||
const args = opts.args ?? []
|
||||
const bin = buildServer()
|
||||
const port = opts.port ?? await freePort()
|
||||
refuseLivePort(port)
|
||||
fs.mkdirSync(stateDir, { recursive: true })
|
||||
const logPath = path.join(stateDir, 'server.log')
|
||||
const logFd = fs.openSync(logPath, 'a')
|
||||
const child = spawn(bin, [`--port=${port}`, `--state-dir=${stateDir}`,
|
||||
`--public-origin=${baseUrl(port)}`, ...args],
|
||||
{ cwd: projectRoot, stdio: ['ignore', logFd, logFd] })
|
||||
const handle = {
|
||||
port, origin: baseUrl(port), stateDir, dbPath: path.join(stateDir, 'state.db'),
|
||||
logPath, child, log: () => fs.readFileSync(logPath, 'utf8'),
|
||||
}
|
||||
try {
|
||||
await waitForHealth(handle)
|
||||
} catch (e) {
|
||||
await stopServer(handle, logFd)
|
||||
const tail = `server did not come up: ${e.message}\n--- ${logPath} ---\n${handle.log()}`
|
||||
if (ownStateDir) fs.rmSync(stateDir, { recursive: true, force: true })
|
||||
throw new Error(tail)
|
||||
}
|
||||
handle.logFd = logFd
|
||||
return handle
|
||||
}
|
||||
|
||||
export async function stopServer(handle, logFd = handle.logFd) {
|
||||
// A process killed by a signal keeps exitCode null and sets signalCode, so test both.
|
||||
if (!hasExited(handle.child)) {
|
||||
handle.child.kill('SIGTERM')
|
||||
const deadline = Date.now() + 5000
|
||||
while (!hasExited(handle.child) && Date.now() < deadline) await sleep(25)
|
||||
if (!hasExited(handle.child)) handle.child.kill('SIGKILL')
|
||||
}
|
||||
if (logFd !== undefined && logFd !== null) { try { fs.closeSync(logFd) } catch {} }
|
||||
}
|
||||
|
||||
export async function withServer(fn, opts = {}) {
|
||||
const handle = await startServer(opts)
|
||||
try {
|
||||
return await fn(handle)
|
||||
} finally {
|
||||
await stopServer(handle)
|
||||
if (opts.keepState !== true && opts.stateDir === undefined) {
|
||||
fs.rmSync(handle.stateDir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
// #16: re-check the Node 26 header behaviour for the global WebSocket {headers} (research #8
|
||||
// verified v24 only; the prototype lib.mjs note said "Node 22" and is stale). Recorded here as a
|
||||
// test so a Node upgrade that drops the option fails loudly instead of silently un-authenticating
|
||||
// every harness. Result: printed as a RECORD line and in results/node-test.log.
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import crypto from 'node:crypto'
|
||||
import net from 'node:net'
|
||||
|
||||
const WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
|
||||
|
||||
// A TCP trap that answers a WebSocket upgrade and hands back the raw request head.
|
||||
async function upgradeTrap() {
|
||||
let resolveSeen
|
||||
const seen = new Promise(res => { resolveSeen = res })
|
||||
const sockets = new Set()
|
||||
const srv = net.createServer(sock => {
|
||||
sockets.add(sock)
|
||||
sock.on('close', () => sockets.delete(sock))
|
||||
sock.on('error', () => {})
|
||||
let buf = ''
|
||||
sock.on('data', d => {
|
||||
buf += d.toString('latin1')
|
||||
if (!buf.includes('\r\n\r\n')) return
|
||||
const key = /sec-websocket-key:\s*(\S+)/i.exec(buf)?.[1] ?? ''
|
||||
const accept = crypto.createHash('sha1').update(key + WS_GUID).digest('base64')
|
||||
sock.write(['HTTP/1.1 101 Switching Protocols', 'Upgrade: websocket',
|
||||
'Connection: Upgrade', `Sec-WebSocket-Accept: ${accept}`, '', ''].join('\r\n'))
|
||||
resolveSeen(buf)
|
||||
})
|
||||
})
|
||||
await new Promise(res => srv.listen(0, '127.0.0.1', res))
|
||||
return {
|
||||
port: srv.address().port,
|
||||
seen,
|
||||
async close() {
|
||||
for (const s of sockets) s.destroy()
|
||||
await new Promise(res => srv.close(res))
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
test('global WebSocket {headers} puts Cookie and Origin on the wire (Node 26 check)', async () => {
|
||||
const trap = await upgradeTrap()
|
||||
try {
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${trap.port}/ws`, {
|
||||
headers: { Cookie: 'fff_session=abc123', Origin: 'https://evil.example' },
|
||||
})
|
||||
ws.onerror = () => {} // the trap speaks no frames; a teardown error is irrelevant
|
||||
const request = await trap.seen
|
||||
assert.match(request, /^GET \/ws HTTP\/1\.1/m)
|
||||
assert.match(request, /^cookie: fff_session=abc123$/im)
|
||||
assert.match(request, /^origin: https:\/\/evil\.example$/im)
|
||||
console.log(`RECORD ws-headers node=${process.version} cookie=ok origin=ok`)
|
||||
ws.close()
|
||||
} finally {
|
||||
await trap.close()
|
||||
}
|
||||
})
|
||||
|
||||
test('without {headers} no Origin is sent: later Origin checks need it explicitly', async () => {
|
||||
const trap = await upgradeTrap()
|
||||
try {
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${trap.port}/ws`)
|
||||
ws.onerror = () => {}
|
||||
const request = await trap.seen
|
||||
assert.doesNotMatch(request, /^origin:/im)
|
||||
ws.close()
|
||||
} finally {
|
||||
await trap.close()
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user