Files
marqdo-app-harness/packages/marqdo/harness/tests/core.test.ts
T
cflmy 25fc24eea4 feat: add Marqdo Harness product services and workbench
Implement the downstream product in `packages/marqdo`:

- `@marqdo/mdh-harness`: application home layout, atomic writes, locks,
  bounded fixed-argv processes, safe tar extraction, Observation 1 and
  ValueWire validation;
- trusted Gitea release discovery, SHA-256/platform/Bundle verification,
  transactional environment install, rollback and cleanup, CLI Tool changes;
- private knowledge collections with strict import policy, the official
  `marqdo-knowledge` compile/query adapter and a disclosed locator fallback;
- Analysis 3 parsing, approved run/call execution, evidence and staleness;
- the six model operations (find/read/check/program/ecosystem/knowledge_search);
- the `/mdh` workbench over the existing web server with a same-origin fence;
- `mdh` launcher, CI/package/upstream scripts and a Woodpecker pipeline.

Tests: 28 node:test cases (27 PASS, one network-gated install test also PASS
with MDH_TEST_INSTALL=1). Product install/workbench evidence is recorded in
docs/mdh/evidence.

Part of marqdo#25 (MDH-03..MDH-08).
2026-11-28 10:41:39 +08:00

196 lines
9.1 KiB
TypeScript

/**
* Core behavior tests: home layout, path ownership, safe extraction, process
* bounds, Observation validation and ValueWire precision.
*/
import assert from 'node:assert/strict'
import { mkdtemp, mkdir, readFile, symlink, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { test } from 'node:test'
import { gzipSync } from 'node:zlib'
import { ensureMdhHome, resolveMdhHome } from '../src/core/home.ts'
import { assertWithin, isWithin, listRegularFiles, writeFileAtomic } from '../src/core/fsx.ts'
import { readTar, extractTarGz } from '../src/core/tar.ts'
import { validateObservation } from '../src/core/observation.ts'
import { scanUnsafeNumbers, safeJsonParse, wireInteger } from '../src/core/valuewire.ts'
import { runProcess } from '../src/core/process.ts'
import { acquireLock } from '../src/core/lock.ts'
/** Create a private temporary directory. */
async function temp(prefix: string): Promise<string> {
return await mkdtemp(join(tmpdir(), `mdh-${prefix}-`))
}
test('home layout is private and rejects a symlinked home', async () => {
const root = await temp('home')
const home = join(root, 'data')
const layout = await ensureMdhHome(home)
assert.equal(layout.home, home)
assert.equal(resolveMdhHome(home), home)
const directory = (await import('node:fs/promises')).stat
const mode = (await directory(layout.knowledgeSources)).mode & 0o777
assert.equal(mode, 0o700)
const link = join(root, 'link')
await symlink(home, link, 'dir')
await assert.rejects(ensureMdhHome(link), /symbolic link|not a directory/)
})
test('path ownership rejects lexical escapes and accepts children', () => {
assert.equal(isWithin('/a/b', '/a/b/c'), true)
assert.equal(isWithin('/a/b', '/a/bc'), false)
assert.throws(() => assertWithin('/a/b', '/a/b/../c'), /escapes/)
assert.doesNotThrow(() => assertWithin('/a/b', '/a/b/c/d'))
})
test('atomic writes are private and complete', async () => {
const root = await temp('atomic')
const target = join(root, 'nested', 'record.json')
await writeFileAtomic(target, '{"a":1}\n')
assert.equal(await readFile(target, 'utf8'), '{"a":1}\n')
const mode = (await (await import('node:fs/promises')).stat(target)).mode & 0o777
assert.equal(mode, 0o600)
})
test('file listing refuses symbolic links', async () => {
const root = await temp('list')
await mkdir(join(root, 'sub'))
await writeFile(join(root, 'sub', 'a.md'), 'hello')
assert.deepEqual((await listRegularFiles(root, { maxFiles: 10 })).map(file => file.relative), ['sub/a.md'])
await symlink(join(root, 'sub', 'a.md'), join(root, 'link.md'))
await assert.rejects(listRegularFiles(root, { maxFiles: 10 }), /symbolic link/)
})
/** Build one minimal ustar entry. */
function tarEntry(name: string, body: string, type = '0', linkname = ''): Buffer {
const header = Buffer.alloc(512, 0)
header.write(name.slice(0, 100), 0, 'utf8')
header.write('0000644\0', 100, 'ascii')
header.write('0000000\0', 108, 'ascii')
header.write('0000000\0', 116, 'ascii')
header.write(`${body.length.toString(8).padStart(11, '0')}\0`, 124, 'ascii')
header.write('00000000000\0', 136, 'ascii')
header.write(' ', 148, 'ascii')
header.write(type, 156, 'ascii')
header.write(linkname.slice(0, 100), 157, 'utf8')
header.write('ustar\0', 257, 'ascii')
header.write('00', 263, 'ascii')
let sum = 0
for (const byte of header) sum += byte
header.write(`${sum.toString(8).padStart(6, '0')}\0 `, 148, 'ascii')
const padded = Buffer.alloc(Math.ceil(body.length / 512) * 512, 0)
padded.write(body)
return Buffer.concat([header, padded])
}
test('safe tar extraction writes files and rejects unsafe entries', async () => {
const root = await temp('tar')
const ok = Buffer.concat([tarEntry('pkg/README.md', 'hello\n'), Buffer.alloc(1024, 0)])
const files = await extractTarGz(gzipSync(ok), join(root, 'ok'))
assert.deepEqual(files.map(file => file.path), ['pkg/README.md'])
assert.equal(await readFile(join(root, 'ok', 'pkg', 'README.md'), 'utf8'), 'hello\n')
const traversal = Buffer.concat([tarEntry('../escape.md', 'x'), Buffer.alloc(1024, 0)])
await assert.rejects(extractTarGz(gzipSync(traversal), join(root, 'bad1')), /unsafe path/)
const absolute = Buffer.concat([tarEntry('/etc/passwd', 'x'), Buffer.alloc(1024, 0)])
await assert.rejects(extractTarGz(gzipSync(absolute), join(root, 'bad2')), /absolute path/)
const link = Buffer.concat([tarEntry('pkg/link', '', '2', 'target'), Buffer.alloc(1024, 0)])
await assert.rejects(extractTarGz(gzipSync(link), join(root, 'bad3')), /link entries are not accepted/)
const duplicate = Buffer.concat([tarEntry('a.md', '1'), tarEntry('A.md', '2'), Buffer.alloc(1024, 0)])
await assert.rejects(extractTarGz(gzipSync(duplicate), join(root, 'bad4')), /duplicate path/)
})
test('readTar enforces the per-file limit', () => {
const archive = Buffer.concat([tarEntry('big.md', 'hello'), Buffer.alloc(1024, 0)])
assert.throws(() => readTar(archive, {
maxEntries: 10, maxTotalBytes: 1024, maxFileBytes: 2, maxPathBytes: 100, maxTarBytes: 1024,
}), /file too large/)
})
test('Observation requires one run id, contiguous seq and one terminal', () => {
const line = (seq: number, kind: string, payload: unknown, run = 'r1') => JSON.stringify({
schema: 'marqdo.observation', schema_version: 1, run_id: run, seq, kind, payload,
})
const digest = 'sha256:abc'
const good = [
line(0, 'stream.opened', { limits: { max_observation_events: 100 } }),
line(1, 'run.started', { source: { analysis_digest: digest } }),
line(2, 'run.completed', { status: 'ok', value: { type: 'int', decimal: '120' } }),
].join('\n')
const summary = validateObservation(good, digest)
assert.equal(summary.status, 'completed')
assert.equal(summary.eventCount, 3)
assert.deepEqual(summary.value, { type: 'int', decimal: '120' })
assert.deepEqual(summary.violations, [])
const missing = validateObservation([line(0, 'stream.opened', {}), line(1, 'run.started', { source: { analysis_digest: digest } })].join('\n'), digest)
assert.equal(missing.status, 'incomplete')
assert.match(missing.violations.join(' '), /missing terminal/)
const duplicate = validateObservation([
line(0, 'stream.opened', {}), line(1, 'run.started', { source: { analysis_digest: digest } }),
line(2, 'run.completed', { value: { type: 'int', decimal: '1' } }), line(3, 'run.completed', { value: { type: 'int', decimal: '1' } }),
].join('\n'), digest)
assert.equal(duplicate.status, 'incomplete')
assert.match(duplicate.violations.join(' '), /duplicate terminal/)
const gap = validateObservation([
line(0, 'stream.opened', {}), line(2, 'run.started', { source: { analysis_digest: digest } }),
line(3, 'run.completed', { value: { type: 'int', decimal: '1' } }),
].join('\n'), digest)
assert.match(gap.violations.join(' '), /seq 2/)
const mismatch = validateObservation(good, 'sha256:other')
assert.equal(mismatch.status, 'incomplete')
assert.match(mismatch.violations.join(' '), /Analysis digest mismatch/)
})
test('ValueWire rejects integers a JS number cannot represent', () => {
assert.deepEqual(scanUnsafeNumbers('{"value":{"type":"int","decimal":"9007199254740993"}}'), [])
const unsafe = scanUnsafeNumbers('{"value":9007199254740993}')
assert.equal(unsafe.length, 1)
assert.throws(() => safeJsonParse('{"value":9007199254740993}'), /precision loss/)
assert.deepEqual(safeJsonParse('{"value":42}'), { value: 42 })
assert.equal(wireInteger({ type: 'int', decimal: '12345678901234567890' }), '12345678901234567890')
assert.equal(wireInteger({ type: 'int', decimal: 'abc' }), undefined)
})
test('subprocess capture is bounded and cancellation kills the group', async () => {
const root = await temp('process')
const echo = await runProcess('/bin/echo', ['hello'], { cwd: root, limits: { maxOutputBytes: 10 } })
assert.equal(echo.exitCode, 0)
assert.equal(echo.stdout, 'hello\n')
const env = await runProcess(process.execPath, ['-e', 'console.log(process.env.MDH_TEST_SECRET ?? "none")'], {
cwd: root, env: { MDH_TEST_SECRET: 'leak' }, limits: {},
})
// Explicit additions are allowed, inherited secrets are not.
assert.equal(env.stdout.trim(), 'leak')
const timeout = await runProcess('/bin/sleep', ['5'], { cwd: root, limits: { timeoutMs: 150 } })
assert.equal(timeout.timedOut, true)
const controller = new AbortController()
setTimeout(() => controller.abort(), 100)
const aborted = await runProcess('/bin/sleep', ['5'], { cwd: root, limits: { signal: controller.signal } })
assert.equal(aborted.aborted, true)
})
test('a second lock waits and a stale lock is reclaimed', async () => {
const root = await temp('lock')
const path = join(root, 'install.lock')
const release = await acquireLock(path, { waitMs: 100, pollMs: 10 })
await assert.rejects(acquireLock(path, { waitMs: 80, pollMs: 10 }), /timed out waiting/)
await release()
// A forged stale owner with a dead pid is reclaimed.
await writeFile(path, JSON.stringify({ pid: 999999, created: 0 }))
const old = new Date(Date.now() - 3_600_000)
await (await import('node:fs/promises')).utimes(path, old, old)
const release2 = await acquireLock(path, { waitMs: 500, pollMs: 10, staleMs: 1000 })
await release2()
})