dsh-brain/verify-api-contract-round2.mjs

261 lines
13 KiB
JavaScript

// Regression tests for the round-2 fixes (#6 login target pinning,
// #11 runtime API response-shape validation). Runs against the built lib/
// output only: temp DSH_HOME, loopback stub servers, fake cmt_ tokens.
import http from 'node:http'
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const home = mkdtempSync(join(tmpdir(), 'brain-api-contract-'))
process.env.DSH_HOME = home
for (const key of ['DSH_BRAIN_ACTIVITY_TOKEN', 'DSH_CLOUD_MEMORY_MEMORY_TOKEN', 'DSH_BRAIN_TOKEN_ORIGIN', 'DSH_CLOUD_MEMORY_TOKEN_ORIGIN']) {
delete process.env[key]
}
const results = []
function check(name, ok, detail) {
results.push({ name, ok })
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`)
}
const { CloudClient } = await import('./lib/api.js')
function sendJson(res, status, payload, headers = {}) {
res.writeHead(status, { 'content-type': 'application/json', ...headers })
res.end(JSON.stringify(payload))
}
async function startServer(handler) {
const server = http.createServer(handler)
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
const baseUrl = `http://127.0.0.1:${server.address().port}/api/longmemory`
return { server, baseUrl }
}
async function stopServer(server) {
server.closeAllConnections?.()
await new Promise((resolve) => server.close(resolve))
}
function makeClient(baseUrl) {
return new CloudClient({ baseUrl: () => baseUrl, token: () => 'cmt_test', timeoutMs: () => 3000 })
}
async function withJson(payload, call, status = 200) {
const { server, baseUrl } = await startServer((req, res) => sendJson(res, status, payload))
try {
return await call(makeClient(baseUrl))
} finally {
await stopServer(server)
}
}
async function withRaw(text, call, status = 200, headers = {}) {
const { server, baseUrl } = await startServer((req, res) => {
res.writeHead(status, { 'content-type': 'application/json', ...headers })
res.end(text)
})
try {
return await call(makeClient(baseUrl))
} finally {
await stopServer(server)
}
}
function expectInvalidResponse(name, result) {
check(name, result.ok === false && result.error?.code === 'invalid_response', JSON.stringify(result).slice(0, 240))
}
const turnPayload = {
client_id: 'client', conversation_id: 'conv', turn_id: 'turn',
status: 'completed', started_at: 1, completed_at: 2,
}
const summaryPayload = { conversation_id: 'conv', turn_id: 'turn', messages: [] }
// ═══ A. response-shape validation: null / array / string / missing / type ══
{
const cases = [
['list null', (c) => c.list(), null],
['list array', (c) => c.list(), []],
['list string', (c) => c.list(), 'not-an-object'],
['list missing items', (c) => c.list(), {}],
['list items wrong type', (c) => c.list(), { items: {} }],
['search missing matches', (c) => c.search('q', 3), { total: 1 }],
['search matches wrong type', (c) => c.search('q', 3), { matches: 'no' }],
['projects missing projects', (c) => c.projects(), {}],
['projects wrong type', (c) => c.projects(), { projects: 'no' }],
['skills missing items', (c) => c.listSkills(), {}],
['skills items wrong type', (c) => c.listSkills(), { items: 'no' }],
['skills item missing name', (c) => c.listSkills(), { items: [{ revision: 1 }] }],
['bundle missing revision', (c) => c.skillBundle('demo'), { name: 'demo', manifest_sha256: 'm', files: [] }],
['bundle file wrong type', (c) => c.skillBundle('demo'), { name: 'demo', revision: 1, manifest_sha256: 'm', files: [{ path: 'a', sha256: 's', data: 1 }] }],
['read null', (c) => c.read('m1'), null],
['read missing id', (c) => c.read('m1'), {}],
['add null', (c) => c.add({ content: 'x', operationId: 'op' }), null],
['report turn string', (c) => c.reportTurn(turnPayload, 'cmt_test'), 'ok'],
['submit summary array', (c) => c.submitSummary(summaryPayload, 'cmt_test'), []],
['storage status null', (c) => c.storageStatus(), null],
]
for (const [name, call, payload] of cases) {
const result = await withJson(payload, call)
expectInvalidResponse(name, result)
}
}
// ═══ B. empty bodies: add accepts {}, list requires items ═════════════════
{
const add = await withRaw('', (c) => c.add({ content: 'x', operationId: 'op' }))
check('add accepts an empty 200 body as {}', add.ok === true && JSON.stringify(add.data) === '{}', JSON.stringify(add).slice(0, 200))
const turn = await withRaw('', (c) => c.reportTurn(turnPayload, 'cmt_test'))
check('reportTurn accepts an empty 200 body as {}', turn.ok === true && JSON.stringify(turn.data) === '{}', JSON.stringify(turn).slice(0, 200))
const summary = await withRaw('', (c) => c.submitSummary(summaryPayload, 'cmt_test'))
check('submitSummary accepts an empty 200 body as {}', summary.ok === true && JSON.stringify(summary.data) === '{}', JSON.stringify(summary).slice(0, 200))
const list = await withRaw('', (c) => c.list())
expectInvalidResponse('list rejects an empty 200 body', list)
const skills = await withRaw('', (c) => c.listSkills())
expectInvalidResponse('listSkills rejects an empty 200 body', skills)
}
// ═══ C. invalid JSON and body-read failures ═══════════════════════════════
{
const invalidJson = await withRaw('{"items":', (c) => c.list())
check('invalid JSON is an invalid_json error, not a fake success',
invalidJson.ok === false && invalidJson.error?.code === 'invalid_json', JSON.stringify(invalidJson).slice(0, 240))
const invalidAuthJson = await withRaw('not-json', (c) => c.login('u', 'p'), 200,
{ 'set-cookie': 'session=abc; Path=/' })
check('invalid JSON from the auth surface is an invalid_json error',
invalidAuthJson.ok === false && invalidAuthJson.error?.code === 'invalid_json', JSON.stringify(invalidAuthJson).slice(0, 240))
const { server, baseUrl } = await startServer((req, res) => {
// Declared length larger than the actual body: response headers arrive,
// the payload read fails.
res.writeHead(200, { 'content-type': 'application/json', 'content-length': '100' })
res.end('{"items":[]}')
})
try {
const result = await makeClient(baseUrl).list()
check('a 200 whose body cannot be read stays body_read_error',
result.ok === false && result.error?.code === 'body_read_error', JSON.stringify(result).slice(0, 240))
} finally {
await stopServer(server)
}
}
// ═══ D. probe endpoints keep 400 = authenticated semantics ════════════════
{
const { server, baseUrl } = await startServer((req, res) => {
const path = new URL(req.url, 'http://stub').pathname
if (path.endsWith('/activity/turn') || path.endsWith('/activity/summary')) {
return sendJson(res, 400, { error: 'invalid_input', message: 'body rejected' })
}
return sendJson(res, 404, { error: 'unknown_route' })
})
try {
const client = makeClient(baseUrl)
const activity = await client.probeActivity('cmt_test')
const summary = await client.probeSummary('cmt_test')
check('probeActivity treats 400 as authenticated', activity.ok === true && activity.data?.authenticated === true, JSON.stringify(activity).slice(0, 200))
check('probeSummary treats 400 as authenticated', summary.ok === true && summary.data?.authenticated === true, JSON.stringify(summary).slice(0, 200))
} finally {
await stopServer(server)
}
}
// ═══ E. CloudClient auth calls can be pinned to an explicit baseUrl ═══════
{
const requestsA = []
const requestsB = []
const handleA = await startServer((req, res) => {
requestsA.push(req.url)
if (req.url === '/api/auth/login') {
res.writeHead(200, { 'content-type': 'application/json', 'set-cookie': 'session=abc; Path=/' })
res.end(JSON.stringify({ user: { username: 'u', role: 'admin' } }))
return
}
if (req.url === '/api/auth/tokens') {
return sendJson(res, 200, { token: { token: 'cmt_from_a', scope: 'memory:write' } })
}
sendJson(res, 404, { error: 'unknown_route' })
})
const handleB = await startServer((req, res) => {
requestsB.push(req.url)
sendJson(res, 500, { error: 'wrong_target' })
})
try {
// Live settings point at B; the explicit target must keep both auth calls on A.
let liveBase = handleB.baseUrl
const client = new CloudClient({ baseUrl: () => liveBase, token: () => 'cmt_test', timeoutMs: () => 3000 })
const login = await client.login('u', 'p', { baseUrl: handleA.baseUrl, timeoutMs: 2000 })
liveBase = handleB.baseUrl
const mint = await client.mintToken(login.data?.sessionCookie ?? '', 'memory:write', 'label', { baseUrl: handleA.baseUrl, timeoutMs: 2000 })
check('login honours the explicit baseUrl override', login.ok === true && login.data?.sessionCookie === 'session=abc', JSON.stringify(login).slice(0, 240))
check('mintToken honours the explicit baseUrl override', mint.ok === true && mint.data?.token === 'cmt_from_a', JSON.stringify(mint).slice(0, 240))
check('both auth requests hit the pinned target', requestsA.length === 2 && requestsA[0] === '/api/auth/login' && requestsA[1] === '/api/auth/tokens', requestsA.join(','))
check('the live settings target is never contacted', requestsB.length === 0, requestsB.join(','))
} finally {
await stopServer(handleA.server)
await stopServer(handleB.server)
}
}
// ═══ F. serveLogin: target snapshot + final baseUrl recheck (#6) ══════════
{
const { SettingsStore } = await import('./lib/store.js')
const { createCloudSyncRoutes } = await import('./lib/cloudsync-routes.js')
const store = new SettingsStore({}, join(home, 'routes.json'))
const oldUrl = 'https://old.example.test/api/longmemory'
const newUrl = 'https://new.example.test/api/longmemory'
store.patch({ baseUrl: oldUrl })
const calls = []
const clientStub = {
login: async (username, password, target) => {
calls.push({ op: 'login', target })
// Simulate a settings edit racing the login flow: the login response is
// still for oldUrl, while the configured address is now newUrl.
store.patch({ baseUrl: newUrl })
return { ok: true, status: 200, data: { sessionCookie: 'sc', user: { username: 'u', role: 'admin' } } }
},
mintToken: async (cookie, scope, label, target) => {
calls.push({ op: `mint:${scope}`, target })
return { ok: true, status: 200, data: { token: `cmt_${scope.split(':')[0]}_new` } }
},
reportTurn: async () => ({ ok: true, status: 201, data: {} }),
probeActivity: async () => ({ ok: true, status: 200, data: {} }),
probeSummary: async () => ({ ok: true, status: 200, data: {} }),
}
const routes = createCloudSyncRoutes({
store,
client: () => clientStub,
reporter: { flush: async () => ({ sent: 0, remaining: 0 }), snapshot: () => ({}) },
statusView: () => ({}),
})
const server = http.createServer((req, res) => {
const url = new URL(req.url, 'http://stub')
const route = routes.find((entry) => (entry.kind === 'exact' ? url.pathname === entry.path : url.pathname.startsWith(entry.path)))
if (route === undefined) { res.writeHead(404); res.end('{}'); return }
route.handler(req, res)
})
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
const base = `http://127.0.0.1:${server.address().port}`
try {
const response = await fetch(`${base}/dsh-brain/login`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ username: 'u', password: 'p' }),
})
const body = await response.json().catch(() => ({}))
check('login refuses to patch after the configured baseUrl changed', response.status === 409, `status=${response.status} body=${JSON.stringify(body).slice(0, 160)}`)
check('no token from the old target is saved', store.activityToken() === '' && store.memoryToken() === '' && store.summaryToken() === '', `activity=${store.activityToken()} memory=${store.memoryToken()} summary=${store.summaryToken()}`)
check('login and all three mintToken calls share one frozen target', calls.length === 4 && calls.every((entry) => entry.target?.baseUrl === oldUrl), JSON.stringify(calls.map((entry) => ({ op: entry.op, baseUrl: entry.target?.baseUrl }))).slice(0, 400))
check('the frozen target carries a fixed timeout', calls.every((entry) => typeof entry.target?.timeoutMs === 'number' && entry.target.timeoutMs > 0), JSON.stringify(calls.map((entry) => entry.target?.timeoutMs)))
} finally {
await stopServer(server)
}
}
rmSync(home, { recursive: true, force: true })
const failed = results.filter((entry) => !entry.ok).length
console.log(`${results.length - failed}/${results.length} API-contract checks passed`)
process.exit(failed === 0 ? 0 : 1)