Add official and seeded cast corpus with cross-layer security regressions

This commit is contained in:
2026-10-15 10:43:39 +08:00
parent 92de7f86f4
commit 487eedf0ba
58 changed files with 4050 additions and 11 deletions
+205
View File
@@ -0,0 +1,205 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createManifest, FIXTURE_SEED, MAX_FIXTURE_BYTES, POLICY, seededPlayback, seededRandom } from '../fixtures/security/recipes.mjs';
import { getSecurityCase, securityCases, securityFixtureBuffer, securityManifest, writeSecurityFixture } from '../fixtures/security/generate.mjs';
const root = new URL( '../fixtures/security/', import.meta.url );
const sha256 = ( bytes ) => createHash( 'sha256' ).update( bytes ).digest( 'hex' );
// Independent test-only measurements from a native JSON parse, not from the
// production budget scanner. Even rejected fixtures here are tightly bounded;
// they never reach the real terminal/player. Duplicate-key compatibility cases
// are not used as exact-token witnesses because native parsing collapses keys.
function structure( value, parentDepth = 0 ) {
if ( value === null || typeof value !== 'object' ) return { tokens: 1, containers: 0, depth: parentDepth };
const depth = parentDepth + 1;
const result = { tokens: Array.isArray( value ) ? 0 : Object.keys( value ).length, containers: 1, depth };
for ( const child of Object.values( value ) ) {
const measured = structure( child, depth );
result.tokens += measured.tokens;
result.containers += measured.containers;
result.depth = Math.max( result.depth, measured.depth );
}
return result;
}
function measure( entry, bytes ) {
const text = bytes.toString( 'utf8' );
let header;
let frames;
const metrics = { bytes: bytes.length, v1Bytes: bytes.length, lineBytes: 0, events: 0, lines: 0, markers: 0, dimension: 0, cells: 0, depth: 0, tokens: 0, containers: 0, lineTokens: 0 };
if ( entry.format === 1 ) {
header = JSON.parse( text );
assert.ok( Array.isArray( header.stdout ) );
frames = header.stdout.map( ( frame ) => {
assert.equal( frame.length, 2 );
return [ frame[ 0 ], 'o', frame[ 1 ] ];
} );
Object.assign( metrics, structure( header ) );
} else {
const lines = text.split( '\n' );
if ( text.endsWith( '\n' ) ) lines.pop();
metrics.lines = lines.length - 1;
header = JSON.parse( lines[ 0 ] );
frames = [];
for ( const [ index, line ] of lines.entries() ) {
const lineBytes = Buffer.byteLength( line ) + Number( index < lines.length - 1 || text.endsWith( '\n' ) );
metrics.lineBytes = Math.max( metrics.lineBytes, lineBytes );
if ( index && ! line.startsWith( '[' ) ) {
assert.equal( entry.validity, 'upstream-compatible', 'strict-format cases must contain actual events, not ignored padding' );
continue;
}
const value = index ? JSON.parse( line ) : header;
const parsed = structure( value );
metrics.depth = Math.max( metrics.depth, parsed.depth );
metrics.containers = Math.max( metrics.containers, parsed.containers );
metrics.lineTokens = Math.max( metrics.lineTokens, parsed.tokens );
if ( index ) frames.push( value );
}
}
assert.equal( header.version, entry.format );
const dimensions = entry.format === 3 ? [ header.term.cols, header.term.rows ] : [ header.width, header.height ];
function size( cols, rows ) {
assert.ok( Number.isSafeInteger( cols ) && cols >= 0 );
assert.ok( Number.isSafeInteger( rows ) && rows >= 0 );
metrics.dimension = Math.max( metrics.dimension, cols, rows );
metrics.cells = Math.max( metrics.cells, ( cols || 80 ) * ( rows || 24 ) );
}
size( ...dimensions );
let time = 0;
for ( const frame of frames ) {
assert.ok( Array.isArray( frame ) );
assert.equal( frame.length, 3 );
assert.ok( Number.isFinite( frame[ 0 ] ) && frame[ 0 ] >= 0 );
assert.equal( typeof frame[ 1 ], 'string' );
assert.ok( frame[ 1 ].length );
assert.equal( typeof frame[ 2 ], 'string' );
if ( entry.format === 2 ) assert.ok( frame[ 0 ] >= time );
time = entry.format === 2 ? frame[ 0 ] : time + frame[ 0 ];
assert.ok( Number.isFinite( time ) );
if ( frame[ 1 ] === 'm' ) metrics.markers++;
if ( frame[ 1 ] === 'r' ) {
assert.match( frame[ 2 ], /^[1-9][0-9]*x[1-9][0-9]*$/ );
size( ...frame[ 2 ].split( 'x' ).map( Number ) );
}
}
metrics.events = frames.length;
return metrics;
}
test( 'golden recipes are deterministic, genuinely seeded, and bounded to known cases', () => {
assert.equal( FIXTURE_SEED, 0x41c0ffee );
assert.deepEqual( createManifest(), securityManifest );
assert.deepEqual( createManifest(), createManifest() );
assert.deepEqual( seededPlayback(), seededPlayback() );
const next = seededRandom();
assert.deepEqual( Array.from( { length: 4 }, () => next().toString( 16 ) ), [ '999f0ef0', '706768d0', '32d9ebae', 'fa29a378' ] );
assert.throws( () => seededRandom( 0 ), RangeError );
assert.throws( () => createManifest( 1 ), RangeError );
assert.throws( () => securityFixtureBuffer( '../../arbitrary' ), RangeError );
assert.throws( () => securityFixtureBuffer( 'bytes-v2-999999999' ), RangeError );
assert.equal( new Set( securityCases.map( ( entry ) => entry.id ) ).size, securityCases.length );
} );
test( 'every shared resource purpose retains its exact at/over pair', () => {
for ( const version of [ 1, 2, 3 ] ) {
for ( const purpose of [ 'dimensions', 'cells', 'depth', 'events' ] ) {
for ( const side of [ 'at', 'over' ] ) {
const entry = getSecurityCase( `${ purpose }-v${ version }-${ side }` );
assert.equal( entry.expected.accepted, side === 'at' );
}
}
assert.equal( getSecurityCase( `official-v${ version }` ).safePlayback, true );
assert.equal( getSecurityCase( `seeded-v${ version }-valid` ).safePlayback, true );
}
for ( const purpose of [ 'v1-bytes', 'tokens-v1', 'containers-v1', ...[ 2, 3 ].flatMap( ( version ) => [ 'bytes', 'line', 'line-tokens', 'markers', 'ignored-lines', 'late-resize' ].map( ( kind ) => `${ kind }-v${ version }` ) ) ] ) {
assert.equal( getSecurityCase( `${ purpose }-at` ).expected.accepted, true );
assert.equal( getSecurityCase( `${ purpose }-over` ).expected.accepted, false );
}
for ( const version of [ 2, 3 ] ) {
assert.equal( getSecurityCase( `late-resize-v${ version }-dimensions-at` ).expected.accepted, true );
assert.equal( getSecurityCase( `late-resize-v${ version }-dimensions-over` ).expected.accepted, false );
}
} );
test( 'official native captures retain independently pinned provenance and identical output', () => {
const provenance = JSON.parse( readFileSync( new URL( 'provenance.json', root ), 'utf8' ) );
assert.deepEqual( provenance.artifacts.map( ( artifact ) => artifact.file ).sort(), [ 'official-v1.cast', 'official-v2.cast', 'official-v3.cast' ] );
assert.equal( sha256( readFileSync( new URL( provenance.payload_script, root ) ) ), provenance.payload_script_sha256 );
assert.equal( sha256( readFileSync( new URL( provenance.reproduction_script, root ) ) ), provenance.reproduction_script_sha256 );
for ( const artifact of provenance.artifacts ) {
const bytes = readFileSync( new URL( artifact.file, root ) );
assert.equal( bytes.length, artifact.bytes );
assert.equal( sha256( bytes ), artifact.sha256 );
const text = bytes.toString( 'utf8' );
const output = artifact.format === 'asciicast-v1' ? JSON.parse( text ).stdout.map( ( frame ) => frame[ 1 ] ).join( '' ) : text.trimEnd().split( '\n' ).slice( 1 ).map( JSON.parse ).filter( ( frame ) => frame[ 1 ] === 'o' ).map( ( frame ) => frame[ 2 ] ).join( '' );
assert.equal( Buffer.byteLength( output ), provenance.verified.captured_stdout_bytes );
assert.equal( sha256( output ), provenance.verified.captured_stdout_sha256 );
}
} );
test( 'seeded recordings preserve equivalent visible output and timing in all formats', () => {
const comparable = [];
for ( const version of [ 1, 2, 3 ] ) {
const text = securityFixtureBuffer( `seeded-v${ version }-valid` ).toString( 'utf8' );
const frames = version === 1 ? JSON.parse( text ).stdout.map( ( frame ) => [ frame[ 0 ], 'o', frame[ 1 ] ] ) : text.trimEnd().split( '\n' ).slice( 1 ).map( JSON.parse );
let time = 0;
comparable.push( frames.map( ( frame ) => { time = version === 2 ? frame[ 0 ] : time + frame[ 0 ]; return [ time, frame[ 2 ] ]; } ) );
assert.ok( text.includes( 'café 你好 🌱' ), 'fragmented-stream tests need actual multibyte content' );
}
assert.deepEqual( comparable[ 0 ], comparable[ 1 ] );
assert.deepEqual( comparable[ 1 ], comparable[ 2 ] );
} );
for ( const entry of securityCases ) {
test( `fixture validity and independent boundary measurement: ${ entry.id }`, () => {
assert.ok( entry.bytes > 0 && entry.bytes <= MAX_FIXTURE_BYTES );
assert.equal( Boolean( entry.source.file ), ! Boolean( entry.source.segments ) );
const bytes = securityFixtureBuffer( entry.id );
assert.equal( bytes.length, entry.bytes );
assert.equal( sha256( bytes ), entry.sha256 );
if ( entry.validity === 'intentionally-malformed' ) {
assert.equal( entry.expected.accepted, false );
assert.throws( () => measure( entry, bytes ), SyntaxError );
return;
}
const metrics = measure( entry, bytes );
if ( entry.boundary ) {
assert.equal( entry.boundary.limit, POLICY[ entry.boundary.metric ] );
assert.equal( metrics[ entry.boundary.metric ], entry.boundary.value );
assert.equal( entry.expected.accepted, entry.boundary.value <= entry.boundary.limit );
// Rejections isolate their named budget. In JSONL the event and line
// thresholds necessarily coincide for an event-only recording.
for ( const metric of Object.keys( POLICY ) ) {
if ( metric === entry.boundary.metric || ( entry.format === 1 ? [ 'lineBytes', 'lineTokens', 'lines' ] : [ 'v1Bytes', 'tokens' ] ).includes( metric ) ) continue;
if ( entry.boundary.metric === 'events' && metric === 'lines' ) continue;
assert.ok( metrics[ metric ] <= POLICY[ metric ], `${ metric } must not mask ${ entry.boundary.metric }: ${ metrics[ metric ] }` );
}
}
if ( entry.metrics ) for ( const [ key, value ] of Object.entries( entry.metrics ) ) {
assert.equal( metrics[ key === 'maximumLineBytes' ? 'lineBytes' : key ], value );
}
if ( entry.safePlayback ) {
assert.equal( entry.expected.accepted, true );
assert.ok( entry.bytes < 16384 );
assert.ok( entry.id.startsWith( 'official-' ) || entry.id.startsWith( 'seeded-' ) );
}
} );
}
test( 'checked-in cast files stay tiny and temporary materialization refuses overwrites', () => {
for ( const name of readdirSync( root ).filter( ( file ) => file.endsWith( '.cast' ) ) ) {
assert.ok( readFileSync( new URL( name, root ) ).length < 16384, `${ name } must not be a committed large payload` );
assert.ok( securityCases.some( ( entry ) => entry.source.file === name ), `${ name } must have an explicit manifest expectation` );
}
const directory = mkdtempSync( join( tmpdir(), 'asciiplayer-fixture-test-' ) );
try {
const path = writeSecurityFixture( 'seeded-v2-valid', directory );
assert.deepEqual( readFileSync( path ), securityFixtureBuffer( 'seeded-v2-valid' ) );
assert.throws( () => writeSecurityFixture( 'seeded-v2-valid', directory ), { code: 'EEXIST' } );
} finally { rmSync( directory, { recursive: true, force: true } ); }
} );
+221
View File
@@ -0,0 +1,221 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { loadRecording, RecordingLoadError, DEFAULT_LIMITS } from '../../src/recording-loader.js';
import { securityManifest, securityCases, getSecurityCase, securityFixtureBuffer } from '../fixtures/security/generate.mjs';
test('shared security corpus pins the production policy and all six safe controls', () => {
assert.equal(securityManifest.schemaVersion, 1);
for (const [name, value] of Object.entries(securityManifest.policy)) {
assert.equal(DEFAULT_LIMITS[name], value, `the ${name} fixture boundary must match production`);
}
assert.deepEqual(securityCases.filter((entry) => entry.safePlayback).map((entry) => entry.id).sort(), [
'official-v1', 'official-v2', 'official-v3',
'seeded-v1-valid', 'seeded-v2-valid', 'seeded-v3-valid',
]);
});
/** A bounded stream, with observations rather than a replacement loader/parser. */
function streamedFixture(bytes, chunkSizes = [16 * 1024]) {
let offset = 0;
let reads = 0;
const state = { fetches: 0, cancels: 0, releases: 0, eof: 0, signal: undefined };
const fetchImpl = async (source, options) => {
state.fetches += 1;
assert.equal(source, '/security-fixture.cast');
assert.equal(options.credentials, 'same-origin');
state.signal = options.signal;
return {
ok: true,
// A false advertised length must not replace measuring actual bytes.
headers: new Headers({ 'Content-Length': '1' }),
body: { getReader: () => ({
read: async () => {
if (offset === bytes.length) {
state.eof += 1;
return { done: true };
}
const end = Math.min(offset + chunkSizes[reads++ % chunkSizes.length], bytes.length);
const value = bytes.subarray(offset, end);
offset = end;
return { done: false, value };
},
cancel: async () => { state.cancels += 1; },
releaseLock: () => { state.releases += 1; },
}) },
};
};
return { fetchImpl, state };
}
for (const entry of securityCases) {
test(`shared security corpus: ${entry.id}`, async (t) => {
const bytes = await securityFixtureBuffer(entry.id);
assert.equal(bytes.length, entry.bytes, 'fixture byte length is reproducible');
assert.equal(createHash('sha256').update(bytes).digest('hex'), entry.sha256, 'fixture bytes match the cross-language manifest');
const input = streamedFixture(bytes);
const metadata = [];
let largestParsedTree = 0;
const parse = JSON.parse;
t.after(() => { JSON.parse = parse; });
JSON.parse = (text, ...args) => {
// Version-sniffing parses short scalar keys. Only full JSON trees
// allocate the arrays/objects that the structural guard must bound.
if (/^\s*[\[{]/.test(text)) largestParsedTree = Math.max(largestParsedTree, Buffer.byteLength(text));
return parse(text, ...args);
};
const pending = loadRecording('/security-fixture.cast', {
fetchImpl: input.fetchImpl,
onMetadata: (value) => metadata.push(value),
});
if (entry.expected.accepted) {
const result = await pending;
const header = entry.format === 1 ? result : result[0];
assert.equal(header.version, entry.format);
const cols = entry.format === 3 ? header.term.cols : header.width;
const rows = entry.format === 3 ? header.term.rows : header.height;
assert.deepEqual(metadata, [cols > 0 && rows > 0 ? { cols, rows } : null], 'metadata is emitted exactly once, only after complete validation');
assert.equal(input.state.eof, 1, 'an accepted recording is validated through EOF');
assert.equal(input.state.cancels, 0);
assert.equal(input.state.signal.aborted, false);
} else {
await assert.rejects(pending, (error) => error instanceof RecordingLoadError && error.code === entry.expected.jsError,
`expected the production ${entry.expected.jsError} guard`);
assert.deepEqual(metadata, [], 'rejected content must not leak native-size metadata');
assert.equal(input.state.cancels, 1, 'the rejected body reader is canceled once');
assert.equal(input.state.signal.aborted, true, 'the rejected fetch is aborted');
const threshold = entry.expected.noDecodeAtOrAboveBytes;
if (threshold !== undefined) {
assert.ok(largestParsedTree < threshold,
`unsafe JSON at/above ${threshold} bytes reached JSON.parse: ${largestParsedTree}`);
}
}
assert.equal(input.state.fetches, 1, 'validation and metadata share a single fetch');
assert.equal(input.state.releases, 1, 'the body reader lock is released exactly once');
});
}
for (const version of [1, 2, 3]) {
test(`seeded v${version} corpus survives byte and JSON token stream boundaries`, async () => {
const entry = getSecurityCase(`seeded-v${version}-valid`);
const bytes = await securityFixtureBuffer(entry.id);
const fragmented = streamedFixture(bytes, [1, 2, 3, 5, 13]);
const contiguous = streamedFixture(bytes, [bytes.length]);
const metadata = [];
const actual = await loadRecording('/security-fixture.cast', {
fetchImpl: fragmented.fetchImpl, onMetadata: (value) => metadata.push(value),
});
assert.deepEqual(actual, await loadRecording('/security-fixture.cast', { fetchImpl: contiguous.fetchImpl }));
assert.equal(metadata.length, 1);
assert.equal(fragmented.state.fetches, 1);
assert.equal(fragmented.state.cancels, 0);
assert.equal(fragmented.state.releases, 1);
});
}
/**
* Exercise the actual pinned player parser/recording driver without importing
* its DOM UI. Discover Core through the package's own entrypoint import, rather
* than hard-coding a generated chunk hash or copying upstream parser code.
* A package layout/version change deliberately fails this compatibility check.
*/
async function playerCore() {
const entrypoint = new URL(import.meta.resolve('asciinema-player'));
const manifest = JSON.parse(await readFile(new URL('../package.json', entrypoint), 'utf8'));
assert.equal(manifest.version, '3.17.0');
const source = await readFile(entrypoint, 'utf8');
const imported = /import \{ (\w+) as Core \} from ['"]([^'"]+)['"]/.exec(source);
assert.ok(imported, 'the pinned player entrypoint must expose its Core import for compatibility tests');
const module = await import(new URL(imported[2], entrypoint));
assert.equal(typeof module[imported[1]], 'function');
return module[imported[1]];
}
function expectedPlayback(data) {
const header = Array.isArray(data) ? data[0] : data;
let time = 0;
const frames = header.version === 1 ? data.stdout.map(([delta, text]) => [delta, 'o', text]) : data.slice(1);
const absolute = frames.map(([timestamp, type, text]) => {
time = header.version === 2 ? timestamp : time + timestamp;
return [time, type, text];
});
return {
cols: (header.version === 3 ? header.term.cols : header.width) || 80,
rows: (header.version === 3 ? header.term.rows : header.height) || 24,
duration: time,
events: absolute,
output: absolute.filter((event) => event[1] === 'o').map((event) => event[2]).join(''),
markers: absolute.filter((event) => event[1] === 'm').map((event) => [event[0], event[2]]),
};
}
async function inspectPlayer(data) {
const Core = await playerCore();
const events = { metadata: [], reset: [], output: [], error: [] };
const core = new Core({ data }, {
preload: true, speed: 1,
logger: { debug() {}, info() {}, warn() {}, error() {} },
});
for (const [name, values] of Object.entries(events)) core.addEventListener(name, (value) => values.push(value));
try {
core.terminalReady();
await core.init();
const duration = core.getDuration();
await core.seek('100%');
const output = events.output.flat().join('');
await core.seek('0%');
assert.equal(core.getCurrentTime(), 0, 'the real driver can seek back to the start');
assert.deepEqual(events.error, []);
assert.equal(events.metadata.length, 1);
return { duration, output, metadata: events.metadata[0], reset: events.reset[0] };
} finally {
await core.stop();
}
}
// Only known-small, accepted controls reach the real upstream parser/driver.
// Oversized/hostile corpus members are tested exclusively through our guard.
const playableCases = securityCases.filter((entry) => entry.safePlayback === true);
for (const entry of playableCases) {
test(`pinned player 3.17 parses and seeks validated ${entry.id}`, async () => {
assert.equal(entry.expected.accepted, true);
assert.ok(entry.bytes < 128 * 1024, 'actual-player controls must remain small');
const bytes = await securityFixtureBuffer(entry.id);
const data = await loadRecording('/security-fixture.cast', { fetchImpl: streamedFixture(bytes).fetchImpl });
const text = bytes.toString('utf8');
const original = entry.format === 1 ? JSON.parse(text) : text.split('\n')
.filter((line, index) => index === 0 || line.startsWith('[')).map((line) => JSON.parse(line));
assert.deepEqual(data, original, 'the guard preserves every original header and event');
const expected = expectedPlayback(original);
const actual = await inspectPlayer(data);
assert.ok(Math.abs(actual.duration - expected.duration) < 1e-8);
assert.deepEqual(actual.reset.size, { cols: expected.cols, rows: expected.rows });
assert.equal(actual.output, expected.output, 'the real parser preserves complete terminal output');
assert.deepEqual(actual.metadata.markers, expected.markers);
// Independently prove both official captures and seeded mutations also
// work through upstream's original raw-input path before our adapter.
const raw = await inspectPlayer(new Response(bytes));
assert.deepEqual(raw, actual);
});
}
test('official outputs and seeded playback timelines are equivalent across all three formats', async () => {
const controls = { official: [], seeded: [] };
for (const version of [1, 2, 3]) {
for (const kind of ['official', 'seeded']) {
const id = kind === 'official' ? `official-v${version}` : `seeded-v${version}-valid`;
const bytes = securityFixtureBuffer(id);
const text = bytes.toString('utf8');
const data = version === 1 ? JSON.parse(text) : text.trimEnd().split('\n').map(JSON.parse);
controls[kind].push(expectedPlayback(data));
}
}
assert.equal(controls.official[0].output, controls.official[1].output);
assert.equal(controls.official[0].output, controls.official[2].output);
assert.deepEqual(controls.seeded[0], controls.seeded[1]);
assert.deepEqual(controls.seeded[0], controls.seeded[2]);
assert.deepEqual(controls.seeded[0].events.map((event) => event[0]), [0, 1, 8, 12]);
assert.ok(controls.seeded[0].output.includes(controls.official[0].output), 'seeded mutations retain the official captured output');
});