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
-11
View File
@@ -4,7 +4,6 @@ import { DEFAULT_LIMITS } from '../../src/recording-loader.js';
const blockName = 'lamgc/asciiplayer';
const fixtureRoot = '/wp-content/uploads/asciiplayer-fixtures';
const messages = {
bytes: 'This recording exceeds the file size limit.',
markers: 'This recording contains too many markers.',
dimensions: 'This recording requests terminal dimensions that exceed the supported limits.',
cells: 'This recording requests too many terminal cells.',
@@ -152,16 +151,6 @@ for (const version of [1, 2, 3]) {
const firstUnsafeRows = Math.floor(DEFAULT_LIMITS.cells / DEFAULT_LIMITS.dimension) + 1;
const rejectedRecordings = [
{
name: 'actual received byte limit', code: 'bytes',
body: () => {
const header = `${JSON.stringify({ version: 2, width: 64, height: 12 })}\n`;
// Keep every comment line well below the line limit and use no
// events, isolating the total-byte cap without huge terminal output.
const comment = `#${'x'.repeat(1022)}\n`;
return header + comment.repeat(Math.ceil((DEFAULT_LIMITS.bytes + 1 - header.length) / comment.length));
},
},
{
name: 'marker count limit', code: 'markers',
body: () => recording(2, { events: Array.from({ length: DEFAULT_LIMITS.markers + 1 }, (_, index) => [index / 1000, 'm', 'marker']) }),
+318
View File
@@ -0,0 +1,318 @@
import { test, expect } from '@playwright/test';
import { getSecurityCase, securityFixtureBuffer } from '../fixtures/security/generate.mjs';
const blockName = 'lamgc/asciiplayer';
const fixtureRoot = '/wp-content/uploads/asciiplayer-fixtures/security';
const messages = {
markers: 'This recording contains too many markers.',
dimensions: 'This recording requests terminal dimensions that exceed the supported limits.',
cells: 'This recording requests too many terminal cells.',
};
async function openEditor(page) {
await page.goto('/wp-login.php');
await page.locator('#user_login').fill(process.env.WP_USERNAME || 'admin');
await page.locator('#user_pass').fill(process.env.WP_PASSWORD || 'password');
await page.locator('#wp-submit').click();
await expect(page).toHaveURL(/\/wp-admin\//);
await page.goto('/wp-admin/post-new.php');
await page.waitForFunction((name) => Boolean(
window.wp?.apiFetch && window.wp?.blocks?.getBlockType(name) &&
window.wp?.data?.select('core/editor')?.getCurrentPostId()
), blockName);
await page.evaluate(() => {
for (const scope of ['core/edit-post', 'core/editor']) {
window.wp.data.dispatch('core/preferences').set(scope, 'welcomeGuide', false);
}
});
await expect(page.locator('iframe[name="editor-canvas"]')).toBeVisible();
}
const canvas = (page) => page.frameLocator('iframe[name="editor-canvas"]');
async function insertPlayer(page, source) {
const id = await page.evaluate(({ name, source }) => {
const block = window.wp.blocks.createBlock(name, { source, controls: 'always' });
window.wp.data.dispatch('core/block-editor').insertBlocks(block);
window.wp.data.dispatch('core/block-editor').selectBlock(block.clientId);
return block.clientId;
}, { name: blockName, source });
return { id, block: canvas(page).locator(`[data-block="${id}"]`) };
}
async function routeFixture(context, page, id) {
const fixture = getSecurityCase(id);
// Full 32 MiB and 100,000-event boundaries belong in Node/PHP, not a browser.
expect(fixture.bytes).toBeLessThan(128 * 1024);
const source = new URL(`${fixtureRoot}/${id}.cast`, page.url()).href;
const body = securityFixtureBuffer(id);
let requests = 0;
await context.route(source, async (route) => {
requests += 1;
await route.fulfill({ contentType: 'text/plain; charset=utf-8', body });
});
return { source, fixture, requests: () => requests };
}
/** Observe real fetch signals and allocation-facing DOM; do not mock the player. */
function observeSecurityState() {
if (window.__securityFixtureState) return;
const state = window.__securityFixtureState = {
fetches: [], maxTerms: 0, maxCols: 0, maxRows: 0, maxCells: 0,
maxLines: 0, maxSymbolLines: 0, maxMarkers: 0,
};
const fetch = window.fetch;
window.fetch = function (source, options) {
if (String(source).includes('/asciiplayer-fixtures/security/')) {
const entry = { source: String(source), aborted: Boolean(options?.signal?.aborted) };
state.fetches.push(entry);
options?.signal?.addEventListener('abort', () => { entry.aborted = true; }, { once: true });
}
return fetch.call(this, source, options);
};
const sample = () => {
const terminals = document.querySelectorAll('.ap-term');
state.maxTerms = Math.max(state.maxTerms, terminals.length);
state.maxMarkers = Math.max(state.maxMarkers, document.querySelectorAll('.ap-marker').length);
for (const terminal of terminals) {
const cols = Number(terminal.style.getPropertyValue('--term-cols'));
const rows = Number(terminal.style.getPropertyValue('--term-rows'));
state.maxCols = Math.max(state.maxCols, cols);
state.maxRows = Math.max(state.maxRows, rows);
state.maxCells = Math.max(state.maxCells, cols * rows);
state.maxLines = Math.max(state.maxLines, terminal.querySelectorAll('.ap-line').length);
state.maxSymbolLines = Math.max(state.maxSymbolLines, terminal.querySelectorAll('.ap-symbol-line').length);
}
};
state.sample = sample;
new MutationObserver(sample).observe(document, {
childList: true, subtree: true, attributes: true, attributeFilter: ['style'],
});
sample();
}
async function observedState(scope) {
return scope.locator('body').evaluate((body) => {
const state = body.ownerDocument.defaultView.__securityFixtureState;
state.sample();
return { ...state, sample: undefined };
});
}
async function expectFetch(scope, source, aborted) {
await expect.poll(async () => (await observedState(scope)).fetches.filter((entry) => entry.source === source))
.toEqual([{ source, aborted }]);
}
async function expectNativeSize(page, cols, rows) {
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
const columns = page.getByRole('spinbutton', { name: 'Columns', exact: true });
const height = page.getByRole('spinbutton', { name: 'Rows', exact: true });
if (!await columns.isVisible()) {
await page.locator('.components-panel__body-toggle').filter({ hasText: /^Terminal size$/ }).click();
}
await expect(columns).toHaveAttribute('placeholder', cols === undefined ? 'From recording' : String(cols));
await expect(height).toHaveAttribute('placeholder', rows === undefined ? 'From recording' : String(rows));
await expect(columns).toHaveValue('');
await expect(height).toHaveValue('');
}
async function expectPlayable(container, fixture) {
const playback = fixture.playback;
expect(fixture.safePlayback).toBe(true);
expect(playback.seekPercent).toBe(80);
await expect(container.locator('.ap-wrapper')).toHaveCount(1);
await expect(container.locator('.ap-term')).toBeVisible();
await expect.poll(() => container.locator('.ap-term').evaluate((terminal) => ({
cols: Number(terminal.style.getPropertyValue('--term-cols')),
rows: Number(terminal.style.getPropertyValue('--term-rows')),
}))).toEqual({ cols: playback.cols, rows: playback.rows });
await expect(container.locator('.ap-line')).toHaveCount(playback.rows);
await expect(container.locator('.ap-marker')).toHaveCount(0);
await container.locator('.ap-overlay-start .ap-play-button').click();
const terminal = container.locator('.ap-term-text');
await expect(terminal).toContainText(playback.startText);
const button = container.locator('.ap-playback-button');
await expect(button).toHaveAttribute('aria-label', 'Pause');
await button.click();
await expect(button).toHaveAttribute('aria-label', 'Play');
await expect(terminal).not.toContainText(playback.seekText);
// The real UI seeks to 80% (9.6s), beyond the seeded frame at 8s, then back.
await terminal.press(String(playback.seekPercent / 10));
await expect(terminal).toContainText(playback.seekText);
await terminal.press('0');
await expect(terminal).toContainText(playback.startText);
await expect(terminal).not.toContainText(playback.seekText);
await expect(container.locator('.ap-wrapper')).toHaveCount(1);
await expect(container.locator('.ap-line')).toHaveCount(playback.rows);
}
async function expectNoUnsafeAllocation(scope, container) {
await expect(container.locator('.ap-marker')).toHaveCount(0);
// api.create legitimately creates an 80x24 shell before fetching. The
// untrusted header/resizes must never expand it or create marker elements.
expect(await container.locator('.ap-wrapper').count()).toBeLessThanOrEqual(1);
await expect(container.locator('.ap-term-text')).toHaveText(/^\s*$/);
const state = await observedState(scope);
expect(state.maxTerms).toBeLessThanOrEqual(1);
expect(state.maxCols).toBeLessThanOrEqual(80);
expect(state.maxRows).toBeLessThanOrEqual(24);
expect(state.maxCells).toBeLessThanOrEqual(80 * 24);
expect(state.maxLines).toBeLessThanOrEqual(24);
expect(state.maxSymbolLines).toBeLessThanOrEqual(24);
expect(state.maxMarkers).toBe(0);
}
/** Real PHP-rendered public post; retain the editor page for guaranteed cleanup. */
async function withPublicPlayer(control, context, source, run) {
const post = await control.evaluate(async ({ name, source }) => {
const content = window.wp.blocks.serialize([
window.wp.blocks.createBlock(name, { source, controls: 'always' }),
]);
return window.wp.apiFetch({
path: '/wp/v2/posts', method: 'POST',
data: { title: `Security corpus regression ${Date.now()}`, status: 'publish', content },
});
}, { name: blockName, source });
const frontend = await context.newPage();
try {
await frontend.goto(post.link);
const container = frontend.locator('.asciiplayer-container');
await expect(container).toHaveCount(1);
await run(frontend, container);
} finally {
await frontend.close();
// REST's normal delete moves this isolated test post to recoverable
// Trash. It does not force-delete data or touch pre-existing posts.
await control.evaluate((id) => window.wp.apiFetch({
path: `/wp/v2/posts/${id}`, method: 'DELETE',
}), post.id);
}
}
test.beforeEach(async ({ page, context }) => {
await context.addInitScript(observeSecurityState);
await openEditor(page);
// Also cover WordPress versions that replace the iframe document in place.
await canvas(page).locator('body').evaluate(observeSecurityState);
});
for (const version of [1, 2, 3]) {
test(`seeded v${version} corpus plays and seeks in the actual editor and public player`, async ({ page, context }) => {
const routed = await routeFixture(context, page, `seeded-v${version}-valid`);
const { id, block } = await insertPlayer(page, routed.source);
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready');
await expectNativeSize(page, routed.fixture.playback.cols, routed.fixture.playback.rows);
await expectPlayable(block, routed.fixture);
await expectFetch(canvas(page), routed.source, false);
expect(routed.requests()).toBe(1);
const attributes = await page.evaluate((id) => window.wp.data.select('core/block-editor').getBlockAttributes(id), id);
expect(attributes.cols).toBeUndefined();
expect(attributes.rows).toBeUndefined();
await withPublicPlayer(page, context, routed.source, async (frontend, container) => {
await expect(container).toHaveAttribute('data-ap-status', 'ready');
await expectPlayable(container, routed.fixture);
await expectFetch(frontend, routed.source, false);
expect(routed.requests()).toBe(2);
});
});
}
const rejectionIds = [
'dimensions-v1-over', 'dimensions-v2-over', 'dimensions-v3-over',
'markers-v2-over', 'markers-v3-over',
'late-resize-v2-over', 'late-resize-v3-over',
];
for (const id of rejectionIds) {
test(`shared ${id} is rejected before unsafe DOM allocation on both playback paths`, async ({ page, context }) => {
const rejected = await routeFixture(context, page, id);
const recovery = await routeFixture(context, page, `seeded-v${rejected.fixture.format}-valid`);
const { block } = await insertPlayer(page, rejected.source);
const message = messages[rejected.fixture.expected.jsError];
expect(message).toBeTruthy();
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'error');
await expect(block.locator('.components-notice')).toContainText(message);
await expectNativeSize(page);
await expectFetch(canvas(page), rejected.source, true);
await expectNoUnsafeAllocation(canvas(page), block);
expect(rejected.requests()).toBe(1);
await withPublicPlayer(page, context, rejected.source, async (frontend, container) => {
await expect(container).toHaveAttribute('data-ap-status', 'error');
await expect(container.locator('.asciiplayer-error')).toHaveText(message);
await expectFetch(frontend, rejected.source, true);
await expectNoUnsafeAllocation(frontend, container);
expect(rejected.requests()).toBe(2);
});
// A rejected corpus member must not poison the next valid recording.
await block.getByRole('textbox', { name: 'Recording URL', exact: true }).fill(recovery.source);
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready');
await expect(block.locator('.components-notice')).toHaveCount(0);
await expectNativeSize(page, recovery.fixture.playback.cols, recovery.fixture.playback.rows);
await expectPlayable(block, recovery.fixture);
await expectFetch(canvas(page), recovery.source, false);
expect(recovery.requests()).toBe(1);
});
}
async function openMedia(page, block) {
await block.getByRole('button', { name: 'Choose recording', exact: true }).click();
const dialog = page.getByRole('dialog', { name: 'Choose an Asciicast recording', exact: true });
await expect(dialog).toBeVisible();
return dialog;
}
async function uploadCorpusFixture(page, dialog, id, unique) {
const fixture = getSecurityCase(id);
expect(fixture.bytes).toBeLessThan(32 * 1024);
await dialog.getByRole('tab', { name: 'Upload files', exact: true }).click();
// The real WordPress Plupload input can live outside the media modal.
// Observe the actual upload endpoint rather than substituting its response.
const input = page.locator('.moxie-shim input[type="file"]').last();
await expect(input).toBeAttached();
const response = page.waitForResponse((result) =>
/\/wp-admin\/async-upload\.php(?:\?|$)/.test(result.url()) && result.request().method() === 'POST'
);
await input.setInputFiles({
name: `security-${id}-${unique}.cast`, mimeType: 'application/x-asciicast',
buffer: securityFixtureBuffer(id),
});
return (await response).json();
}
test('real WordPress uploads reject shared marker/cell fixtures and accept a seeded recording', async ({ page }, testInfo) => {
const { id, block } = await insertPlayer(page, '');
const unique = `${Date.now()}-${testInfo.retry}`;
const validationMessage = 'Upload a valid Asciicast v2/v3 JSONL or v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, 1,000 markers, 1,000 columns or rows, 40,000 terminal cells, and bounded JSON structure).';
for (const fixtureId of ['markers-v2-over', 'cells-v1-over']) {
const dialog = await openMedia(page, block);
const result = await uploadCorpusFixture(page, dialog, fixtureId, unique);
expect(result.success, JSON.stringify(result)).toBe(false);
// Exact plugin copy distinguishes registered resource validation from
// MIME, filesystem, transport, or unrelated WordPress upload failures.
expect(result.data.message).toBe(validationMessage);
await expect(dialog).toContainText(validationMessage);
await expect(dialog.locator('.media-button-select')).toBeDisabled();
await dialog.locator('.media-modal-close').click();
await expect(block.getByRole('textbox', { name: 'Recording URL', exact: true })).toHaveValue('');
expect(await page.evaluate((id) => window.wp.data.select('core/block-editor').getBlockAttributes(id).source, id)).toBe('');
await expect(block.locator('.asciiplayer-editor__preview')).toHaveCount(0);
}
const fixture = getSecurityCase('seeded-v3-valid');
const dialog = await openMedia(page, block);
const accepted = await uploadCorpusFixture(page, dialog, fixture.id, unique);
expect(accepted.success, JSON.stringify(accepted)).toBe(true);
expect(accepted.data.mime).toBe('application/x-asciicast');
await dialog.getByRole('tab', { name: 'Media Library', exact: true }).click();
const attachment = dialog.locator(`.attachment[data-id="${accepted.data.id}"]`);
await expect(attachment).toBeVisible();
if (!await attachment.evaluate((element) => element.classList.contains('selected'))) await attachment.click();
await expect(dialog.locator('.media-button-select')).toBeEnabled();
await dialog.locator('.media-button-select').click();
await expect(dialog).toBeHidden();
await expect(block.getByRole('textbox', { name: 'Recording URL', exact: true })).toHaveValue(accepted.data.url);
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready');
await expectNativeSize(page, fixture.playback.cols, fixture.playback.rows);
// This fetches the file WordPress actually saved, without a route mock.
await expectPlayable(block, fixture);
});
+69
View File
@@ -0,0 +1,69 @@
# Official asciinema fixture provenance
These three small baselines were recorded by the official, unmodified asciinema CLI. They are genuine recordings, not hand-written files labeled as recorder output. They contain only a controlled synthetic program and are safe for public source control. None includes input capture, credentials, a user name, a host name, or an absolute workspace path.
## Recorder support and sources
- asciicast v1: official PyPI `asciinema` **1.4.0** source distribution, executed unchanged using Python **3.12.14** and its `python3 -m asciinema` entrypoint. [Published package and hash](https://pypi.org/project/asciinema/1.4.0/#files).
- asciicast v2 and v3: official Linux x86_64 GNU release binary of asciinema **3.0.1**. [Official release](https://github.com/asciinema/asciinema/releases/tag/v3.0.1), [release asset metadata](https://api.github.com/repos/asciinema/asciinema/releases/tags/v3.0.1).
- CLI 3.x defaults to v3 and provides `--output-format asciicast-v2`. It does not offer v1 recording output. Using the historical CLI for v1 avoids a custom conversion here. [Official 3.0 release notes](https://github.com/asciinema/asciinema/releases/tag/v3.0.0).
The source downloads were verified against the publisher-provided SHA-256 values before execution:
| Download | SHA-256 |
| --- | --- |
| `asciinema-x86_64-unknown-linux-gnu`, v3.0.1 | `eb3a55e8778f6b86575ad58b47f1ee21d934e4baa8f01abaa5151cad490021f8` |
| `asciinema-1.4.0.tar.gz` | `fb31457e7a4689340b872f625658dbaea33bcf6863fb5d696cf3857010432ecb` |
The binaries and legacy package are not vendored in the test corpus. The official [installation guide](https://docs.asciinema.org/manual/cli/installation/) documents release binaries and the historical PyPI package.
## Safe, reproducible payload
`synthetic-output.py` writes a fixed introductory line, four harmless hexadecimal samples, and an ANSI green completion line. It reads no files or user input and uses no network. The seed is `0x41c0ffee` (1103167470), with unsigned 32-bit xorshift operations `<< 13`, `>> 17`, `<< 5`. Terminal line discipline converts its newline characters to CRLF in the captures.
All recorders receive an environment cleared with `env -i`, a temporary HOME and configuration directory, fixed locale/TERM/SHELL values, and an 80×24 terminal. CLI 1.4.0 requires a token field even for local recording; its isolated config contains the fixed noncredential value `fixture-no-upload`. No real credential is created, loaded or sent. Every `rec` command has an explicit local filename, and no upload, streaming or authentication command is used.
The recorded command is exactly `python3 synthetic-output.py`. `record-official-baselines.sh` contains the complete shell invocations and refuses to overwrite a previous capture. With the two verified tools available:
```sh
ASCIINEMA3=/path/to/asciinema-3.0.1 \
ASCIINEMA1_SRC=/path/to/asciinema-1.4.0 \
./record-official-baselines.sh /path/to/new-captures
```
The essential recorder commands are:
```sh
python3 -m asciinema rec --title 'PR41 synthetic baseline' \
--command 'python3 synthetic-output.py' official-v1.cast
asciinema-3.0.1 rec --headless --window-size 80x24 \
--output-format asciicast-v2 --title 'PR41 synthetic baseline' \
--command 'python3 synthetic-output.py' official-v2.cast
asciinema-3.0.1 rec --headless --window-size 80x24 \
--output-format asciicast-v3 --title 'PR41 synthetic baseline' \
--command 'python3 synthetic-output.py' official-v3.cast
```
Use the wrapper to supply the isolation, Python module path and legacy terminal dimensions; the commands alone omit that setup.
## Baseline identity and validation
| Raw capture | SHA-256 |
| --- | --- |
| `official-v1.cast` | `5570c9cdec60a779585db195ecd8dee4756d84706d6b27d3ccd87cf3ba311c97` |
| `official-v2.cast` | `6be6f5cd70d4a428692fc7807549b9c1437c1c8b60902220ad5e7e01a201f3ee` |
| `official-v3.cast` | `8c07c04edf86605558a9795152fcba32337d72aeaa073bc89adb1c285f06763e` |
All three captures were successfully read using the official CLI 3.0.1 `convert --output-format raw` command. The resulting 187-byte exports are identical by `cmp` and SHA-256: `c759f03280f9a48ecfafbe7b11d7f2b75a2b418d368bc5fd5d13f1d957ee7d4d`. The official converter prepends the terminal-size escape sequence `ESC[8;24;80t`. Independently concatenating the recorded output events produces the same 177 bytes for all three formats, SHA-256 `390dbc2f2102cc0540c71c6db823622e1869596bd0b71c1d0721125083ca6550`.
Each has six output events. The v2 and v3 captures also contain the official recorder's trailing `x` exit event. Preserve those raw files exactly; do not silently delete metadata or events and continue calling the result an unmodified capture.
`provenance.json` records tool/source versions, source hashes, exact command arguments, baseline hashes, header fields, event counts and shared output hash. The repository tests exercise the raw baselines and deterministic derived fixtures against its pinned asciinema-player **3.17.0** parser/core; see the test results separately for what was executed.
## What is deterministic
The payload, seed and corpus mutation recipes are deterministic. A fresh terminal recording is **not byte-for-byte deterministic**: wall-clock timestamps, scheduling delays, total duration and PTY read boundaries can differ. The checked-in raw captures are therefore immutable, hash-pinned provenance anchors. Large and boundary fixtures are explicitly generated derivatives, with fixed timing/metadata and documented mutation recipes; they must not be described as untouched CLI output.
Format semantics are checked against the official specifications: [v1](https://docs.asciinema.org/manual/asciicast/v1/) uses a whole JSON document with per-output delays; [v2](https://docs.asciinema.org/manual/asciicast/v2/) uses JSON lines with elapsed timestamps; [v3](https://docs.asciinema.org/manual/asciicast/v3/) uses JSON lines with relative event intervals and nested terminal dimensions. Format conformance and genuine provenance complement, rather than replace, resource-boundary and real-player regression tests.
+155
View File
@@ -0,0 +1,155 @@
# TEST ONLY: deterministic recording-security corpus
This corpus exercises PR41's resource gates against ordinary, boundary and
intentionally malformed asciicast input. It is **not** a collection to open in an
unprotected terminal player. Do not upload generated boundary files to a real
WordPress site, serve them publicly, or commit expanded large payloads.
Only small, readable `.cast` files are checked in. Large cases are compact
literal/repeat recipes materialized one at a time in temporary storage. The
largest possible file is **32 MiB + 1 byte**. There is no arbitrary size argument,
unbounded fuzz loop, network request, remote command, or production-code import
in the generator. The ordinary plugin package excludes the `tests` directory.
## Provenance and reproducibility
- `official-v1.cast`, `official-v2.cast`, and `official-v3.cast` are unmodified
**native recordings** from pinned official CLI versions. Legacy CLI 1.4.0
produced v1; CLI 3.0.1 produced v2 and v3. Their actual timestamps and PTY delays
remain intact. See [PROVENANCE.md](PROVENANCE.md) and `provenance.json` for
official source URLs, verified package hashes, commands and capture hashes.
- `seeded-v*-valid.cast` are explicitly **normalized derivatives**, not raw CLI
output. They retain the captured output text and the recorded format/dimension
envelope, remove nondeterministic metadata, add seeded harmless UTF-8 output,
and use fixed visible START/SEEK/END frames across a 12-second timeline. v2
stores absolute time; v1/v3 store matching intervals. These are the interactive
playback/seek controls.
- Resource-boundary derivatives mutate one documented resource purpose. JSONL
byte and line fillers are actual output events, not padding comments. Wide
metadata, deep metadata and large valid grids are valid-format resource-unsafe
cases; they must fail the intended policy rather than generic JSON syntax.
- Blank/comment/indented lines, zero header dimensions and duplicate keys are
marked `upstream-compatible`, independently of strict format provenance.
- `malformed-v*` cases deliberately contain broken JSON and are labeled
`intentionally-malformed`.
`recipes.mjs` uses real unsigned xorshift32 (`<<13`, `>>>17`, `<<5`) with the
single allowed seed `0x41c0ffee` (1103167470). Randomized output chunks, text and
bounded timings are deterministic. Equivalent purposes use all three formats
where their semantics permit it. v1 has a whole-document 2 MiB budget and no
marker/resize event types; those JSONL-only purposes apply to v2/v3. A fresh
official PTY recording is not byte-identical; the checked-in raw captures are
immutable, independently hash-pinned anchors, not regenerated during tests.
## Commands
Run from the repository root using the project's supported Node version:
```sh
# List bounded, known case IDs, sizes and expected results.
node tests/fixtures/security/generate.mjs --list
# Compare deterministic recipes to the golden manifest and verify every hash.
node tests/fixtures/security/generate.mjs --verify
# Write exactly one known file to a new OS temporary directory.
node tests/fixtures/security/generate.mjs --case markers-v2-over
# Independent corpus metrics plus actual production loader and player Core.
node --test tests/js/security-fixtures.test.js tests/js/security-loader-fixtures.test.js
# All JavaScript checks, including both corpus suites.
npm test
# Native PHP 7.4+; needs neither Node nor the asciinema CLI.
php tests/php/run.php
# Real isolated WordPress/Chromium integration; see tests/e2e/README.md setup.
npx --no-install playwright test tests/e2e/security-fixtures.spec.js
```
The `--case` command prints the temporary path, byte count, SHA-256 and cleanup
directory. Delete that directory after inspection. Test consumers clean up their
own temporary files in `finally` blocks. Never replace the named case ID with a
user-controlled arbitrary size. Large samples must stay outside source control.
When intentionally changing a recipe, run `--refresh` and review the complete
manifest/hash/small-fixture diff, then rerun the checks above. This writes only
the manifest and tiny derivative files; it never rewrites official captures or
expands large cases into the repository. Provenance checks independently reject
a changed raw baseline even if someone refreshes the golden manifest.
## Shared cross-language contract
`manifest.json` has `schemaVersion: 1`, an independently pinned `policy`, seed,
and a `cases` array. Each case declares:
- `id`, `format`, `description`, `category`, `validity`, and `provenance`
- Exactly one `source.file` relative to this directory, or ordered
`source.segments: [{ "text": "literal UTF-8", "repeat": positiveInteger }]`
- `bytes` and lowercase SHA-256 of the exact generated bytes
- `expected.accepted` and exact `expected.jsError` (null for accepted controls)
- Optional `boundary: {metric, limit, value}` and independent `metrics`
- `safePlayback: true` only for the six tiny official/seeded accepted controls
- Optional `playback` expectations for the normalized interactive controls
Concatenate the UTF-8 bytes of each literal repeated by its count in order. Do
not normalize newlines, strip BOMs, reserialize JSON, execute text, or shell out
to Node from PHP. The JavaScript reader verifies size and SHA-256 before use;
the PHP reader streams at most 64 KiB at a time to one temporary file and checks
the same identity before invoking the actual file/upload/sideload gates.
`expected.noDecodeAtOrAboveBytes` is a witness threshold for rejected JSON trees:
the decoder must not see any tree input that large. Small safe headers or tiny
version-discriminator scalar parses may still occur. Byte-over JSONL differs by
consumer: PHP rejects from file size before any decode, expressed by the stronger
`expected.phpNoDecodeAtOrAboveBytes: 1`; a browser stream must parse safe earlier
records before discovering the final byte, then cancel without handing the
recording to the player. This is not a claim that all streaming prefix parsing
can or should be avoided.
## Coverage map
| Purpose | Case IDs | Boundary |
| --- | --- | --- |
| Official provenance and real playback | `official-v{1,2,3}`, `seeded-v{1,2,3}-valid` | Same native output; normalized equivalent timelines |
| Zero/blank/multiline compatibility | `valid-v*-zero`, `valid-v{2,3}-filtered-lines`, `valid-v1-multiline-late-version` | Small actual files |
| Format discrimination | `valid-v1-escaped-version`, `valid-v1-duplicate-version`, `valid-v1-long-first-line`, `invalid-v2-duplicate-version-wide` | v1 limits cannot leak into v2 |
| Whole body bytes | `bytes-v{2,3}-{at,over}` | 33,554,432 / 33,554,433 bytes |
| Legacy v1 bytes | `v1-bytes-{at,over}` | 2,097,152 / 2,097,153 bytes |
| JSONL bytes including LF | `line-v{2,3}-{at,over}` | 262,144 / 262,145 bytes |
| Events | `events-v{1,2,3}-{at,over}` | 100,000 / 100,001 events |
| Physical JSONL work | `ignored-lines-v{2,3}-{at,over}` | 100,000 / 100,001 lines; exactly one output event |
| Markers | `markers-v{2,3}-{at,over}` | 1,000 / 1,001 markers |
| Header and late-resize axes | `dimensions-v*-{at,over}`, `late-resize-v{2,3}-dimensions-{at,over}` | 1,000 / 1,001 columns, otherwise safe |
| Header and late-resize cells | `cells-v*-{at,over}`, `late-resize-v{2,3}-{at,over}` | 200×200 / 201×200; each axis remains valid |
| v1 scalar/key allocation | `tokens-v1-{at,over}` | 400,000 / 400,001 tokens |
| v1 container allocation | `containers-v1-{at,over}` | 100,016 / 100,017 containers |
| JSONL scalar/key allocation | `line-tokens-v{2,3}-{at,over}` | 20,000 / 20,001 tokens |
| Nesting | `depth-v{1,2,3}-{at,over}` | 15 / 16 container levels |
| Intentional bad syntax | `malformed-v1-json`, `malformed-v{2,3}-event` | Stable invalid-result controls |
The cells-over value is 40,200, not an assertion that every integer cell count
has a valid integer grid. Event-only JSONL reaches the physical-line and event
caps together; the ignored-line pair independently isolates physical-line work.
There is no separate per-line cap on whole-document v1, and no JSONL-wide 400,000
token budget: those distinctions are explicit rather than false all-format
equivalence.
The corpus invariant suite independently parses tightly bounded test data to
measure structure, verify valid/malformed labels, pin exact boundary values,
and prove an unrelated limit is not masking the intended one. Only the six
`safePlayback` controls reach the real pinned player Core. Hostile/boundary
recordings first exercise the production loader guard or PHP upload validator.
Browser tests use the existing isolated WordPress setup and check visible errors
and recovery. Passing Node/PHP checks does not imply that a browser run occurred.
## Relationship to existing tests
Existing `hello.cast`, `replacement.cast`, `resize.cast`, `v1-pretty.cast`, and
`v3-comments.cast` remain the ordinary UI regression fixtures. Existing inline
small-limit unit tests remain useful for cancellation, option overrides, UTF-8
failures and timing edge cases. This corpus adds durable official provenance,
actual full-default at/over resource pairs, deterministic cross-language input,
decoder-order witnesses and a common source for upload and playback integration;
it does not replace those focused tests.
+1
View File
@@ -0,0 +1 @@
{"version":1,"width":200,"height":200,"stdout":[[0,"PR41 bounded control\r\n"]]}
+1
View File
@@ -0,0 +1 @@
{"version":1,"width":201,"height":200,"stdout":[[0,"PR41 bounded control\r\n"]]}
+2
View File
@@ -0,0 +1,2 @@
{"version":2,"width":200,"height":200}
[0,"o","PR41 bounded control\r\n"]
+2
View File
@@ -0,0 +1,2 @@
{"version":2,"width":201,"height":200}
[0,"o","PR41 bounded control\r\n"]
+2
View File
@@ -0,0 +1,2 @@
{"version":3,"term":{"cols":200,"rows":200}}
[0,"o","PR41 bounded control\r\n"]
+2
View File
@@ -0,0 +1,2 @@
{"version":3,"term":{"cols":201,"rows":200}}
[0,"o","PR41 bounded control\r\n"]
+1
View File
@@ -0,0 +1 @@
{"version":1,"width":80,"height":24,"stdout":[],"metadata":[[[[[[[[[[[[[[0]]]]]]]]]]]]]]}
+1
View File
@@ -0,0 +1 @@
{"version":1,"width":80,"height":24,"stdout":[],"metadata":[[[[[[[[[[[[[[[0]]]]]]]]]]]]]]]}
+1
View File
@@ -0,0 +1 @@
{"version":2,"width":80,"height":24,"metadata":[[[[[[[[[[[[[[0]]]]]]]]]]]]]]}
+1
View File
@@ -0,0 +1 @@
{"version":2,"width":80,"height":24,"metadata":[[[[[[[[[[[[[[[0]]]]]]]]]]]]]]]}
+1
View File
@@ -0,0 +1 @@
{"version":3,"term":{"cols":80,"rows":24},"metadata":[[[[[[[[[[[[[[0]]]]]]]]]]]]]]}
+1
View File
@@ -0,0 +1 @@
{"version":3,"term":{"cols":80,"rows":24},"metadata":[[[[[[[[[[[[[[[0]]]]]]]]]]]]]]]}
+1
View File
@@ -0,0 +1 @@
{"version":1,"width":1000,"height":24,"stdout":[[0,"PR41 bounded control\r\n"]]}
+1
View File
@@ -0,0 +1 @@
{"version":1,"width":1001,"height":24,"stdout":[[0,"PR41 bounded control\r\n"]]}
+2
View File
@@ -0,0 +1,2 @@
{"version":2,"width":1000,"height":24}
[0,"o","PR41 bounded control\r\n"]
+2
View File
@@ -0,0 +1,2 @@
{"version":2,"width":1001,"height":24}
[0,"o","PR41 bounded control\r\n"]
+2
View File
@@ -0,0 +1,2 @@
{"version":3,"term":{"cols":1000,"rows":24}}
[0,"o","PR41 bounded control\r\n"]
+2
View File
@@ -0,0 +1,2 @@
{"version":3,"term":{"cols":1001,"rows":24}}
[0,"o","PR41 bounded control\r\n"]
+88
View File
@@ -0,0 +1,88 @@
/** TEST ONLY. Materialize one pinned fixture; never accepts arbitrary sizes. */
import { createHash } from 'node:crypto';
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createManifest, createRecipes, MAX_FIXTURE_BYTES } from './recipes.mjs';
const root = dirname( fileURLToPath( import.meta.url ) );
const manifestPath = join( root, 'manifest.json' );
const invoked = process.argv[ 1 ] && resolve( process.argv[ 1 ] ) === fileURLToPath( import.meta.url );
// Maintenance only: deterministic recipes write the small fixtures plus golden
// manifest. No large expanded payload is ever written into the repository.
if ( invoked && process.argv.slice( 2 ).join( ' ' ) === '--refresh' ) {
const recipes = createRecipes();
for ( const { entry, parts } of recipes ) {
if ( ! entry.source.file ) continue;
if ( entry.provenance === 'official-raw-capture' ) continue;
if ( entry.bytes > 16384 ) throw new RangeError( 'Checked-in fixtures must stay small.' );
writeFileSync( join( root, entry.source.file ), parts.map( ( part ) => part.text.repeat( part.repeat ) ).join( '' ), 'utf8' );
}
writeFileSync( manifestPath, JSON.stringify( createManifest(), null, 2 ) + '\n', 'utf8' );
process.stdout.write( `Refreshed ${ recipes.length } recipes and their small controls.\n` );
}
export const securityManifest = JSON.parse( readFileSync( manifestPath, 'utf8' ) );
export const securityCases = securityManifest.cases;
export function getSecurityCase( id ) {
const fixture = securityCases.find( ( item ) => item.id === id );
if ( ! fixture ) throw new RangeError( `Unknown security fixture: ${ id }` );
return fixture;
}
export function securityFixtureBuffer( id ) {
const fixture = getSecurityCase( id );
if ( ! Number.isSafeInteger( fixture.bytes ) || fixture.bytes < 1 || fixture.bytes > MAX_FIXTURE_BYTES ) throw new RangeError( 'Fixture byte cap exceeded.' );
let buffer;
if ( fixture.source.file ) {
if ( ! /^[a-z0-9-]+\.cast$/.test( fixture.source.file ) ) throw new Error( 'Fixture file must stay in its own directory.' );
buffer = readFileSync( join( root, fixture.source.file ) );
} else {
let length = 0;
for ( const { text, repeat } of fixture.source.segments ) {
if ( typeof text !== 'string' || ! text.length || ! Number.isSafeInteger( repeat ) || repeat < 1 ) throw new Error( 'Invalid literal-repeat segment.' );
length += Buffer.byteLength( text ) * repeat;
if ( ! Number.isSafeInteger( length ) || length > MAX_FIXTURE_BYTES ) throw new RangeError( 'Recipe byte cap exceeded.' );
}
if ( length !== fixture.bytes ) throw new Error( `Recipe length differs for ${ id }` );
buffer = Buffer.allocUnsafe( length );
let offset = 0;
for ( const { text, repeat } of fixture.source.segments ) {
const unit = Buffer.from( text, 'utf8' );
const end = offset + unit.length * repeat;
buffer.fill( unit, offset, end );
offset = end;
}
}
if ( buffer.length !== fixture.bytes || createHash( 'sha256' ).update( buffer ).digest( 'hex' ) !== fixture.sha256 ) throw new Error( `Fixture integrity failure: ${ id }` );
return buffer;
}
export function writeSecurityFixture( id, directory ) {
const buffer = securityFixtureBuffer( id );
const path = join( directory, `${ id }.cast` );
writeFileSync( path, buffer, { flag: 'wx' } );
return path;
}
if ( invoked ) {
const args = process.argv.slice( 2 );
if ( args.length === 1 && args[ 0 ] === '--list' ) {
for ( const item of securityCases ) process.stdout.write( `${ item.id }\t${ item.bytes } bytes\t${ item.expected.accepted ? 'accept' : item.expected.jsError }\n` );
} else if ( args.length === 1 && args[ 0 ] === '--verify' ) {
if ( JSON.stringify( securityManifest ) !== JSON.stringify( createManifest() ) ) throw new Error( 'Golden manifest differs; inspect recipes before --refresh.' );
for ( const item of securityCases ) securityFixtureBuffer( item.id );
process.stdout.write( `Verified ${ securityCases.length } deterministic fixtures.\n` );
} else if ( args.length === 2 && args[ 0 ] === '--case' ) {
const fixture = getSecurityCase( args[ 1 ] );
const directory = mkdtempSync( join( tmpdir(), 'asciiplayer-security-' ) );
const path = writeSecurityFixture( fixture.id, directory );
process.stdout.write( JSON.stringify( { path, bytes: fixture.bytes, sha256: fixture.sha256, cleanup: `Remove ${ directory } after testing.` }, null, 2 ) + '\n' );
} else if ( args.length !== 1 || args[ 0 ] !== '--refresh' ) {
process.stderr.write( 'Usage: node tests/fixtures/security/generate.mjs --list | --verify | --case <known-id> | --refresh\n' );
process.exitCode = 1;
}
}
+3
View File
@@ -0,0 +1,3 @@
{"version":2,"width":80,"height":24}
[0,"o","safe prefix\r\n"]
[12,"r","200x200"]
@@ -0,0 +1,3 @@
{"version":2,"width":80,"height":24}
[0,"o","safe prefix\r\n"]
[12,"r","1000x24"]
@@ -0,0 +1,3 @@
{"version":2,"width":80,"height":24}
[0,"o","safe prefix\r\n"]
[12,"r","1001x24"]
+3
View File
@@ -0,0 +1,3 @@
{"version":2,"width":80,"height":24}
[0,"o","safe prefix\r\n"]
[12,"r","201x200"]
+3
View File
@@ -0,0 +1,3 @@
{"version":3,"term":{"cols":80,"rows":24}}
[0,"o","safe prefix\r\n"]
[12,"r","200x200"]
@@ -0,0 +1,3 @@
{"version":3,"term":{"cols":80,"rows":24}}
[0,"o","safe prefix\r\n"]
[12,"r","1000x24"]
@@ -0,0 +1,3 @@
{"version":3,"term":{"cols":80,"rows":24}}
[0,"o","safe prefix\r\n"]
[12,"r","1001x24"]
+3
View File
@@ -0,0 +1,3 @@
{"version":3,"term":{"cols":80,"rows":24}}
[0,"o","safe prefix\r\n"]
[12,"r","201x200"]
+1
View File
@@ -0,0 +1 @@
{"version":1,"width":80,"height":24,"stdout":[}
+2
View File
@@ -0,0 +1,2 @@
{"version":2,"width":80,"height":24}
[0,"o",broken]
+2
View File
@@ -0,0 +1,2 @@
{"version":3,"term":{"cols":80,"rows":24}}
[0,"o",broken]
File diff suppressed because it is too large Load Diff
+38
View File
@@ -0,0 +1,38 @@
{
"version": 1,
"width": 80,
"height": 24,
"duration": 0.146063,
"command": "python3 synthetic-output.py",
"title": "PR41 synthetic baseline",
"env": {
"TERM": "xterm-256color",
"SHELL": "/bin/sh"
},
"stdout": [
[
0.019058,
"PR41 seed 41c0ffee\r\n"
],
[
0.020274,
"fixture 00 sample 999f0ef0\r\n"
],
[
0.020125,
"fixture 01 sample 706768d0\r\n"
],
[
0.020121,
"fixture 02 sample 32d9ebae\r\n"
],
[
0.020144,
"fixture 03 sample fa29a378\r\n"
],
[
0.020086,
"\u001b[32msynthetic terminal output complete\u001b[0m\r\n"
]
]
}
+8
View File
@@ -0,0 +1,8 @@
{"version":2,"width":80,"height":24,"timestamp":1792031567,"command":"python3 synthetic-output.py","title":"PR41 synthetic baseline","env":{"SHELL":"/bin/sh"}}
[0.020203, "o", "PR41 seed 41c0ffee\r\n"]
[0.040345, "o", "fixture 00 sample 999f0ef0\r\n"]
[0.06055, "o", "fixture 01 sample 706768d0\r\n"]
[0.080668, "o", "fixture 02 sample 32d9ebae\r\n"]
[0.100781, "o", "fixture 03 sample fa29a378\r\n"]
[0.12148, "o", "\u001b[32msynthetic terminal output complete\u001b[0m\r\n"]
[0.167553, "x", "0"]
+8
View File
@@ -0,0 +1,8 @@
{"version":3,"term":{"cols":80,"rows":24,"type":"xterm-256color"},"timestamp":1792031567,"command":"python3 synthetic-output.py","title":"PR41 synthetic baseline","env":{"SHELL":"/bin/sh"}}
[0.022, "o", "PR41 seed 41c0ffee\r\n"]
[0.021, "o", "fixture 00 sample 999f0ef0\r\n"]
[0.021, "o", "fixture 01 sample 706768d0\r\n"]
[0.019, "o", "fixture 02 sample 32d9ebae\r\n"]
[0.020, "o", "fixture 03 sample fa29a378\r\n"]
[0.021, "o", "\u001b[32msynthetic terminal output complete\u001b[0m\r\n"]
[0.101, "x", "0"]
+148
View File
@@ -0,0 +1,148 @@
{
"schema_version": 1,
"purpose": "PR41 format-valid official recorder baselines for deterministic security-test derivatives",
"seed_hex": "0x41c0ffee",
"seed_decimal": 1103167470,
"prng": "xorshift32 (unsigned 32-bit): x ^= x << 13; x ^= x >>> 17; x ^= x << 5",
"python_version": "3.12.14",
"sources": [
{
"tool": "asciinema",
"version": "3.0.1",
"kind": "official release binary",
"url": "https://github.com/asciinema/asciinema/releases/download/v3.0.1/asciinema-x86_64-unknown-linux-gnu",
"sha256": "eb3a55e8778f6b86575ad58b47f1ee21d934e4baa8f01abaa5151cad490021f8",
"digest_reference": "https://api.github.com/repos/asciinema/asciinema/releases/tags/v3.0.1",
"digest_verified": true
},
{
"tool": "asciinema",
"version": "1.4.0",
"kind": "unmodified official PyPI source distribution",
"url": "https://files.pythonhosted.org/packages/21/7a/265e78c86b4b4f8c74c0d8321f6f28faa19f80c5c9d7a834a989ed64154a/asciinema-1.4.0.tar.gz",
"sha256": "fb31457e7a4689340b872f625658dbaea33bcf6863fb5d696cf3857010432ecb",
"digest_reference": "https://pypi.org/project/asciinema/1.4.0/#files",
"digest_verified": true
}
],
"commands": {
"v1": "python3 -m asciinema rec --title \"PR41 synthetic baseline\" --command \"python3 synthetic-output.py\" official-v1.cast",
"v2": "asciinema-3.0.1 rec --headless --window-size 80x24 --output-format asciicast-v2 --title \"PR41 synthetic baseline\" --command \"python3 synthetic-output.py\" official-v2.cast",
"v3": "asciinema-3.0.1 rec --headless --window-size 80x24 --output-format asciicast-v3 --title \"PR41 synthetic baseline\" --command \"python3 synthetic-output.py\" official-v3.cast",
"verify_output": "asciinema-3.0.1 convert --output-format raw official-vN.cast official-vN.output"
},
"reproduction_script": "record-official-baselines.sh",
"payload_script": "synthetic-output.py",
"payload_script_sha256": "c23fee8e14fcc65ab372ea898c9e0884f53679393810db049e4749c2bfdb416f",
"reproduction_script_sha256": "2c2fe44b33b34c707efad515e97828d8f1dc2a545878e8042b43be1f243ff007",
"environment": {
"cleared_with": "env -i",
"fixed": {
"LANG": "C.UTF-8",
"LC_ALL": "C.UTF-8",
"TERM": "xterm-256color",
"SHELL": "/bin/sh"
},
"scoped": "Temporary isolated HOME and ASCIINEMA_CONFIG_HOME; only pinned tool paths in PATH/PYTHONPATH; legacy COLUMNS=80 and LINES=24. No input capture, upload, streaming or auth command."
},
"artifacts": [
{
"file": "official-v1.cast",
"format": "asciicast-v1",
"sha256": "5570c9cdec60a779585db195ecd8dee4756d84706d6b27d3ccd87cf3ba311c97",
"bytes": 669,
"cli_version": "1.4.0",
"native_recorder_output": true,
"normalized": false,
"header": {
"version": 1,
"width": 80,
"height": 24,
"duration": 0.146063,
"command": "python3 synthetic-output.py",
"title": "PR41 synthetic baseline",
"env": {
"TERM": "xterm-256color",
"SHELL": "/bin/sh"
}
},
"event_count": 6,
"output_event_count": 6,
"event_types": [
"o"
],
"duration_seconds": 0.146063,
"output_sha256": "390dbc2f2102cc0540c71c6db823622e1869596bd0b71c1d0721125083ca6550"
},
{
"file": "official-v2.cast",
"format": "asciicast-v2",
"sha256": "6be6f5cd70d4a428692fc7807549b9c1437c1c8b60902220ad5e7e01a201f3ee",
"bytes": 498,
"cli_version": "3.0.1",
"native_recorder_output": true,
"normalized": false,
"header": {
"version": 2,
"width": 80,
"height": 24,
"timestamp": 1792031567,
"command": "python3 synthetic-output.py",
"title": "PR41 synthetic baseline",
"env": {
"SHELL": "/bin/sh"
}
},
"event_count": 7,
"output_event_count": 6,
"event_types": [
"o",
"x"
],
"duration_seconds": 0.167553,
"output_sha256": "390dbc2f2102cc0540c71c6db823622e1869596bd0b71c1d0721125083ca6550"
},
{
"file": "official-v3.cast",
"format": "asciicast-v3",
"sha256": "8c07c04edf86605558a9795152fcba32337d72aeaa073bc89adb1c285f06763e",
"bytes": 509,
"cli_version": "3.0.1",
"native_recorder_output": true,
"normalized": false,
"header": {
"version": 3,
"term": {
"cols": 80,
"rows": 24,
"type": "xterm-256color"
},
"timestamp": 1792031567,
"command": "python3 synthetic-output.py",
"title": "PR41 synthetic baseline",
"env": {
"SHELL": "/bin/sh"
}
},
"event_count": 7,
"output_event_count": 6,
"event_types": [
"o",
"x"
],
"duration_seconds": 0.225,
"output_sha256": "390dbc2f2102cc0540c71c6db823622e1869596bd0b71c1d0721125083ca6550"
}
],
"verified": {
"official_cli_raw_conversion_all_three": true,
"identical_concatenated_stdout": true,
"public_safe_metadata_review": true,
"captured_stdout_bytes": 177,
"captured_stdout_sha256": "390dbc2f2102cc0540c71c6db823622e1869596bd0b71c1d0721125083ca6550",
"official_cli_raw_export_bytes": 187,
"official_cli_raw_export_sha256": "c759f03280f9a48ecfafbe7b11d7f2b75a2b418d368bc5fd5d13f1d957ee7d4d",
"official_cli_raw_export_prefix": "\u001b[8;24;80t"
},
"reproducibility": "Synthetic output is fixed-seed reproducible. Raw recorder wall clock, event timing and output read boundaries can vary on recapture. Raw baseline files are retained byte-for-byte under their hashes. Deterministic corpus derivatives must explicitly declare their mutations and normalization; they are not untouched CLI captures."
}
+181
View File
@@ -0,0 +1,181 @@
/** TEST ONLY. Fixed, bounded recipes; never accepts attacker-selected sizes. */
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
export const FIXTURE_SEED = 0x41c0ffee;
export const MAX_FIXTURE_BYTES = 32 * 1024 * 1024 + 1;
export const POLICY = Object.freeze( {
bytes: 33554432, v1Bytes: 2097152, lineBytes: 262144, events: 100000,
lines: 100000, markers: 1000, dimension: 1000, cells: 40000,
depth: 15, containers: 100016, tokens: 400000, lineTokens: 20000,
} );
// This PRNG is part of the reproducibility contract, not a security primitive.
export function seededRandom( seed = FIXTURE_SEED ) {
if ( seed !== FIXTURE_SEED ) throw new RangeError( 'Only the documented fixture seed is supported.' );
let state = seed;
return () => {
state ^= state << 13;
state ^= state >>> 17;
state ^= state << 5;
return state >>> 0;
};
}
const segment = ( text, repeat = 1 ) => ( { text, repeat } );
const json = JSON.stringify;
const byteLength = ( text ) => Buffer.byteLength( text, 'utf8' );
const partsBytes = ( parts ) => parts.reduce( ( sum, part ) => sum + byteLength( part.text ) * part.repeat, 0 );
const officialText = Object.fromEntries( [ 1, 2, 3 ].map( ( version ) => [ version, readFileSync( new URL( `official-v${ version }.cast`, import.meta.url ), 'utf8' ) ] ) );
const officialData = Object.fromEntries( [ 1, 2, 3 ].map( ( version ) => [ version, version === 1 ? JSON.parse( officialText[ version ] ) : officialText[ version ].trimEnd().split( '\n' ).map( JSON.parse ) ] ) );
const officialHeader = ( version ) => version === 1 ? officialData[ version ] : officialData[ version ][ 0 ];
const officialOutput = ( version ) => version === 1 ? officialData[ version ].stdout.map( ( frame ) => frame[ 1 ] ).join( '' ) : officialData[ version ].slice( 1 ).filter( ( frame ) => frame[ 1 ] === 'o' ).map( ( frame ) => frame[ 2 ] ).join( '' );
// Normalize only the envelope: discard wall clock, PTY timing and optional
// capture metadata; retain the officially recorded format and dimensions.
const header = ( version, cols, rows ) => {
const recorded = officialHeader( version );
if ( recorded.version !== version ) throw new Error( 'Official capture format mismatch.' );
return version === 3
? { version: recorded.version, term: { cols: cols ?? recorded.term.cols, rows: rows ?? recorded.term.rows } }
: { version: recorded.version, width: cols ?? recorded.width, height: rows ?? recorded.height };
};
const headerText = ( version, cols = 80, rows = 24 ) => json( header( version, cols, rows ) );
const simpleCast = ( version, cols = 80, rows = 24 ) => version === 1
? json( { ...header( version, cols, rows ), stdout: [ [ 0, 'PR41 bounded control\r\n' ] ] } ) + '\n'
: headerText( version, cols, rows ) + '\n[0,"o","PR41 bounded control\\r\\n"]\n';
/** Identical output and absolute instants; v1/v3 serialize interval timestamps. */
export function seededPlayback( seed = FIXTURE_SEED ) {
const next = seededRandom( seed );
const alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789';
const word = ( length ) => Array.from( { length }, () => alphabet[ next() % alphabet.length ] ).join( '' );
const startText = 'PR41 START seed 41c0ffee';
const seekText = 'PR41 SEEK seed 41c0ffee';
const at = [ 0, 1 + ( next() % 8 ) / 4, 8, 12 ];
const recordedOutput = officialOutput( 1 );
if ( recordedOutput !== officialOutput( 2 ) || recordedOutput !== officialOutput( 3 ) ) throw new Error( 'Official captured output differs across formats.' );
const output = [ startText + '\r\n', recordedOutput + 'seeded ' + word( 24 ) + ' café 你好 🌱\r\n', seekText + '\r\n', 'PR41 END\r\n' ];
return { at, output, title: 'Seeded control ' + word( 8 ), playback: { startText, seekText, seekPercent: 80, cols: 80, rows: 24, duration: 12 } };
}
export function createRecipes( seed = FIXTURE_SEED ) {
const next = seededRandom( seed );
const controls = seededPlayback( seed );
const alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789';
const bytePayload = Array.from( { length: 1013 }, () => alphabet[ next() % alphabet.length ] ).join( '' );
const cases = [];
function add( id, format, description, parts, { error = null, boundary, small = false, category = 'resource-boundary', predecode, playback, metrics, safePlayback = false, provenance = 'normalized-mutation' } = {} ) {
const bytes = partsBytes( parts );
if ( bytes > MAX_FIXTURE_BYTES ) throw new RangeError( `Unbounded recipe: ${ id }` );
const hash = createHash( 'sha256' );
// Hash each recipe without constructing a potentially 32 MiB string.
for ( const part of parts ) {
const chunkRepeats = Math.max( 1, Math.floor( 65536 / byteLength( part.text ) ) );
let remaining = part.repeat;
while ( remaining ) {
const count = Math.min( remaining, chunkRepeats );
hash.update( part.text.repeat( count ), 'utf8' );
remaining -= count;
}
}
const entry = {
id, format, description, category, provenance, safePlayback,
validity: category === 'malformed' ? 'intentionally-malformed' : category === 'upstream-compatibility' ? 'upstream-compatible' : 'format-valid',
source: small ? { file: `${ id }.cast` } : { segments: parts },
expected: { accepted: error === null, jsError: error }, bytes, sha256: hash.digest( 'hex' ),
};
if ( boundary ) entry.boundary = boundary;
if ( predecode !== undefined ) entry.expected.noDecodeAtOrAboveBytes = predecode === 'document' ? bytes - 1 : predecode;
if ( playback ) entry.playback = playback;
if ( metrics ) entry.metrics = metrics;
cases.push( { entry, parts } );
}
const pair = ( metric, limit, value ) => ( { metric, limit, value } );
for ( const version of [ 1, 2, 3 ] ) {
add( `official-v${ version }`, version, 'Unmodified native capture from the pinned official asciinema recorder; original PTY timings are intentionally retained.', [ segment( officialText[ version ] ) ], { small: true, category: 'valid-control', safePlayback: true, provenance: 'official-raw-capture' } );
const frames = controls.output.map( ( output, index ) => [ version === 2 ? controls.at[ index ] : controls.at[ index ] - ( controls.at[ index - 1 ] || 0 ), ...( version === 1 ? [] : [ 'o' ] ), output ] );
const meta = { ...header( version ), title: controls.title, duration: 12 };
const content = version === 1 ? json( { ...meta, stdout: frames }, null, 2 ) + '\n' : [ meta, ...frames ].map( json ).join( '\n' ) + '\n';
add( `seeded-v${ version }-valid`, version, 'Official captured output plus fixed-seed text; normalized equivalent absolute times across all formats.', [ segment( content ) ], { small: true, category: 'valid-control', playback: controls.playback, safePlayback: true } );
add( `valid-v${ version }-zero`, version, 'Zero header dimensions retain upstream 80 by 24 defaults.', [ segment( simpleCast( version, 0, 0 ) ) ], { small: true, category: 'upstream-compatibility' } );
add( `dimensions-v${ version }-at`, version, 'The inclusive per-axis cap still fits within the independent cell budget.', [ segment( simpleCast( version, 1000, 24 ) ) ], { small: true, boundary: pair( 'dimension', POLICY.dimension, 1000 ) } );
add( `dimensions-v${ version }-over`, version, 'Syntactically valid header requests an axis one beyond the dimension cap.', [ segment( simpleCast( version, 1001, 24 ) ) ], { small: true, error: 'dimensions', boundary: pair( 'dimension', POLICY.dimension, 1001 ) } );
for ( const over of [ false, true ] ) {
const suffix = over ? 'over' : 'at';
const cols = over ? 201 : 200;
add( `cells-v${ version }-${ suffix }`, version, 'Each axis is valid; their product alone selects the cell boundary.', [ segment( simpleCast( version, cols, 200 ) ) ], { small: true, error: over ? 'cells' : null, boundary: pair( 'cells', POLICY.cells, cols * 200 ) } );
const depth = POLICY.depth + Number( over );
const prefix = version === 1 ? '{"version":1,"width":80,"height":24,"stdout":[],"metadata":' : headerText( version ).slice( 0, -1 ) + ',"metadata":';
add( `depth-v${ version }-${ suffix }`, version, 'Unknown metadata reaches the lexical container-depth boundary before JSON allocation.', [ segment( prefix + '['.repeat( depth - 1 ) + '0' + ']'.repeat( depth - 1 ) + '}\n' ) ], { small: true, error: over ? 'complexity' : null, boundary: pair( 'depth', POLICY.depth, depth ), predecode: over ? 'document' : undefined } );
const count = POLICY.events + Number( over );
const parts = version === 1
? [ segment( '{"version":1,"width":80,"height":24,"stdout":[' ), segment( '[0,""],', count - 1 ), segment( '[0,""]]}\n' ) ]
: [ segment( headerText( version ) + '\n' ), segment( '[0,"o",""]\n', count ) ];
add( `events-v${ version }-${ suffix }`, version, version === 1 ? 'Full default v1 event boundary without first exhausting scalar/container budgets.' : 'Event and physical-line caps coincide for output-only JSONL.', parts, { error: over ? 'events' : null, boundary: pair( 'events', POLICY.events, count ), metrics: { events: count, ...( version === 1 ? { containers: count + 2 } : {} ) } } );
}
}
add( 'valid-v1-multiline-late-version', 1, 'Pretty v1 document places its version after stdout and nested metadata.', [ segment( '{\n "stdout": [[0,"multiline v1\\r\\n"]],\n "metadata": {"version": 3},\n "width": 80,\n "height": 24,\n "version": 1\n}\n' ) ], { small: true, category: 'valid-control' } );
add( 'valid-v1-escaped-version', 1, 'Escaped top-level version key is still v1.', [ segment( '{"ver\\u0073ion":1,"width":80,"height":24,"stdout":[]}\n' ) ], { small: true, category: 'valid-control' } );
add( 'valid-v1-duplicate-version', 1, 'Last duplicate version wins under the bundled JSON parsers.', [ segment( '{"version":2,"version":1,"width":80,"height":24,"stdout":[]}\n' ) ], { small: true, category: 'upstream-compatibility' } );
add( 'malformed-v1-json', 1, 'Deliberately missing the stdout array closer.', [ segment( '{"version":1,"width":80,"height":24,"stdout":[}\n' ) ], { small: true, category: 'malformed', error: 'invalid' } );
for ( const version of [ 2, 3 ] ) {
const head = headerText( version ) + '\n';
add( `valid-v${ version }-filtered-lines`, version, 'Blank/comment/indented non-event lines follow upstream filtering, not strict canonical JSONL.', [ segment( head + '\n# compatibility comment\nignored text\n [999,"o","ignored"]\n[0,"o","accepted output\\r\\n"]\n' ) ], { small: true, category: 'upstream-compatibility' } );
add( `late-resize-v${ version }-at`, version, 'Ordinary output precedes an inclusive 40,000-cell late resize.', [ segment( head + '[0,"o","safe prefix\\r\\n"]\n[12,"r","200x200"]\n' ) ], { small: true, boundary: pair( 'cells', POLICY.cells, 40000 ) } );
add( `late-resize-v${ version }-over`, version, 'Ordinary output precedes a late resize with valid axes but excessive cells.', [ segment( head + '[0,"o","safe prefix\\r\\n"]\n[12,"r","201x200"]\n' ) ], { small: true, error: 'cells', boundary: pair( 'cells', POLICY.cells, 40200 ) } );
add( `late-resize-v${ version }-dimensions-at`, version, 'Ordinary output precedes an inclusive 1,000-column late resize.', [ segment( head + '[0,"o","safe prefix\\r\\n"]\n[12,"r","1000x24"]\n' ) ], { small: true, boundary: pair( 'dimension', POLICY.dimension, 1000 ) } );
add( `late-resize-v${ version }-dimensions-over`, version, 'Ordinary output precedes a late resize exceeding the per-axis dimension cap.', [ segment( head + '[0,"o","safe prefix\\r\\n"]\n[12,"r","1001x24"]\n' ) ], { small: true, error: 'dimensions', boundary: pair( 'dimension', POLICY.dimension, 1001 ) } );
add( `malformed-v${ version }-event`, version, 'Deliberately invalid JSON event after a valid header.', [ segment( head + '[0,"o",broken]\n' ) ], { small: true, category: 'malformed', error: 'invalid' } );
for ( const over of [ false, true ] ) {
const suffix = over ? 'over' : 'at';
const markerCount = POLICY.markers + Number( over );
add( `markers-v${ version }-${ suffix }`, version, 'Marker count boundary; bytes, line count and dimensions remain small.', [ segment( head ), segment( '[0,"m","mark"]\n', markerCount ) ], { error: over ? 'markers' : null, boundary: pair( 'markers', POLICY.markers, markerCount ) } );
const lineBytes = POLICY.lineBytes + Number( over );
const eventPrefix = '[0,"o","';
const eventSuffix = '"]\n';
add( `line-v${ version }-${ suffix }`, version, 'One syntactically valid output event at the UTF-8 line-byte boundary, including LF.', [ segment( head + eventPrefix ), segment( 'x', lineBytes - byteLength( eventPrefix + eventSuffix ) ), segment( eventSuffix ) ], { error: over ? 'line' : null, boundary: pair( 'lineBytes', POLICY.lineBytes, lineBytes ), predecode: over ? lineBytes - 1 : undefined } );
const totalBytes = POLICY.bytes + Number( over );
const block = eventPrefix + bytePayload + eventSuffix;
let blocks = Math.floor( ( totalBytes - byteLength( head ) ) / 1024 );
let tailBytes = totalBytes - byteLength( head ) - blocks * 1024;
if ( tailBytes < byteLength( eventPrefix + eventSuffix ) ) { blocks--; tailBytes += 1024; }
add( `bytes-v${ version }-${ suffix }`, version, 'Full 32 MiB body boundary using valid output events; no padding comments or oversized line.', [ segment( head ), segment( block, blocks ), segment( eventPrefix ), segment( 'x', tailBytes - byteLength( eventPrefix + eventSuffix ) ), segment( eventSuffix ) ], { error: over ? 'bytes' : null, boundary: pair( 'bytes', POLICY.bytes, totalBytes ), predecode: over ? 'document' : undefined, metrics: { events: blocks + 1, maximumLineBytes: 1024 } } );
if ( over ) cases.at( -1 ).entry.expected.phpNoDecodeAtOrAboveBytes = 1;
const tokenCount = POLICY.lineTokens + Number( over );
const scalarCount = tokenCount - ( version === 2 ? 7 : 8 );
const parts = [ segment( headerText( version ).slice( 0, -1 ) + ',"metadata":[' ), segment( '0,', scalarCount - 1 ), segment( '0]}\n' ) ];
add( `line-tokens-v${ version }-${ suffix }`, version, 'Wide metadata uses the strict per-line scalar/key token cap, never the legacy v1 cap.', parts, { error: over ? 'complexity' : null, boundary: pair( 'lineTokens', POLICY.lineTokens, tokenCount ), predecode: over ? 'document' : undefined } );
const lines = POLICY.lines + Number( over );
add( `ignored-lines-v${ version }-${ suffix }`, version, 'One valid output event plus ignored blank lines isolates the physical JSONL processing budget.', [ segment( head + '[0,"o","line budget control\\r\\n"]\n' ), segment( '\n', lines - 1 ) ], { category: 'upstream-compatibility', error: over ? 'events' : null, boundary: pair( 'lines', POLICY.lines, lines ), metrics: { events: 1 } } );
}
}
for ( const over of [ false, true ] ) {
const suffix = over ? 'over' : 'at';
const bytes = POLICY.v1Bytes + Number( over );
const prefix = '{\n"version":1,"width":80,"height":24,"stdout":[[0,"';
const end = '"]]}\n';
add( `v1-bytes-${ suffix }`, 1, 'Legacy multiline document has its own 2 MiB budget, distinct from JSONL limits.', [ segment( prefix ), segment( 'x', bytes - byteLength( prefix + end ) ), segment( end ) ], { error: over ? 'bytes' : null, boundary: pair( 'v1Bytes', POLICY.v1Bytes, bytes ), predecode: over ? 'document' : undefined } );
const prefixMetadata = '{\n"version":1,"width":80,"height":24,"stdout":[],"metadata":[';
const tokenCount = POLICY.tokens + Number( over );
const scalarCount = tokenCount - 8;
add( `tokens-v1-${ suffix }`, 1, 'Unknown scalar metadata reaches the complete v1 scalar/key allocation budget.', [ segment( prefixMetadata ), segment( '0,', scalarCount - 1 ), segment( '0]}\n' ) ], { error: over ? 'complexity' : null, boundary: pair( 'tokens', POLICY.tokens, tokenCount ), predecode: over ? 'document' : undefined } );
const containers = POLICY.containers + Number( over );
add( `containers-v1-${ suffix }`, 1, 'Empty metadata objects isolate the container budget from scalar and event budgets.', [ segment( prefixMetadata ), segment( '{},', containers - 4 ), segment( '{}]}\n' ) ], { error: over ? 'complexity' : null, boundary: pair( 'containers', POLICY.containers, containers ), predecode: over ? 'document' : undefined } );
}
add( 'valid-v1-long-first-line', 1, 'Version appears after a first line larger than the JSONL cap; v1 discrimination must preserve it.', [ segment( '{"title":"' ), segment( 'x', POLICY.lineBytes ), segment( '",\n"version":1,"width":80,"height":24,"stdout":[[0,"late version\\r\\n"]]}\n' ) ], { category: 'valid-control' } );
add( 'invalid-v2-duplicate-version-wide', 2, 'Last duplicate version is v2; wide metadata must not obtain a v1 allocation budget.', [ segment( '{"version":1,"version":2,"width":80,"height":24,"metadata":[' ), segment( '0,', POLICY.lineTokens ), segment( '0]}\n' ) ], { category: 'upstream-compatibility', error: 'complexity', predecode: 'document' } );
return cases;
}
export function createManifest( seed = FIXTURE_SEED ) {
return {
schemaVersion: 1,
seed: '0x41c0ffee',
generator: 'xorshift32-v1; fixed case IDs and fixed resource policies',
policy: POLICY,
cases: createRecipes( seed ).map( ( item ) => item.entry ),
};
}
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env bash
# Regenerate genuine CLI captures. Real PTY timing and wall clock are nondeterministic.
set -euo pipefail
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
: "${ASCIINEMA3:?Set ASCIINEMA3 to the verified official asciinema 3.0.1 executable}"
: "${ASCIINEMA1_SRC:?Set ASCIINEMA1_SRC to the extracted, unmodified PyPI asciinema-1.4.0 directory}"
ASCIINEMA3=$(realpath "$ASCIINEMA3")
ASCIINEMA1_SRC=$(realpath "$ASCIINEMA1_SRC")
PYTHON=$(command -v python3)
SAFE_PATH="$(dirname "$PYTHON"):/usr/bin:/bin"
OUT=$(realpath -m "${1:-$PWD/raw}")
mkdir -p "$OUT"
for v in 1 2 3; do
if [ -e "$OUT/official-v$v.cast" ]; then
printf 'Refusing to overwrite %s\n' "$OUT/official-v$v.cast" >&2
exit 1
fi
done
WORKDIR=$(mktemp -d)
trap 'rm -rf "$WORKDIR"' EXIT
mkdir -p "$WORKDIR/home" "$WORKDIR/config-legacy" "$WORKDIR/config-modern"
# CLI 1.4.0 requires a token field even for a local-only rec command. This is a
# fixed, noncredential dummy; no credential is created and no upload is invoked.
printf '[api]\ntoken = fixture-no-upload\n' > "$WORKDIR/config-legacy/config"
: > "$WORKDIR/config-modern/config.toml"
cp "$SCRIPT_DIR/synthetic-output.py" "$WORKDIR/synthetic-output.py"
cd "$WORKDIR"
COMMON=(env -i "PATH=$SAFE_PATH" LANG=C.UTF-8 LC_ALL=C.UTF-8 TERM=xterm-256color SHELL=/bin/sh "HOME=$WORKDIR/home")
"${COMMON[@]}" "ASCIINEMA_CONFIG_HOME=$WORKDIR/config-modern" "$ASCIINEMA3" --version
"${COMMON[@]}" "ASCIINEMA_CONFIG_HOME=$WORKDIR/config-legacy" "PYTHONPATH=$ASCIINEMA1_SRC" "$PYTHON" -m asciinema --version
for v in 2 3; do
"${COMMON[@]}" "ASCIINEMA_CONFIG_HOME=$WORKDIR/config-modern" "$ASCIINEMA3" rec \
--headless --window-size 80x24 --output-format "asciicast-v$v" \
--title 'PR41 synthetic baseline' --command 'python3 synthetic-output.py' \
"$OUT/official-v$v.cast"
done
"${COMMON[@]}" "ASCIINEMA_CONFIG_HOME=$WORKDIR/config-legacy" "PYTHONPATH=$ASCIINEMA1_SRC" \
COLUMNS=80 LINES=24 "$PYTHON" -m asciinema rec \
--title 'PR41 synthetic baseline' --command 'python3 synthetic-output.py' \
"$OUT/official-v1.cast"
for v in 1 2 3; do
"${COMMON[@]}" "ASCIINEMA_CONFIG_HOME=$WORKDIR/config-modern" "$ASCIINEMA3" convert \
--output-format raw "$OUT/official-v$v.cast" "$OUT/official-v$v.output"
done
cmp "$OUT/official-v1.output" "$OUT/official-v2.output"
cmp "$OUT/official-v2.output" "$OUT/official-v3.output"
sha256sum "$OUT"/official-v{1,2,3}.cast "$OUT"/official-v1.output
+25
View File
@@ -0,0 +1,25 @@
{
"version": 1,
"width": 80,
"height": 24,
"title": "Seeded control 9oz66x01",
"duration": 12,
"stdout": [
[
0,
"PR41 START seed 41c0ffee\r\n"
],
[
1,
"PR41 seed 41c0ffee\r\nfixture 00 sample 999f0ef0\r\nfixture 01 sample 706768d0\r\nfixture 02 sample 32d9ebae\r\nfixture 03 sample fa29a378\r\n\u001b[32msynthetic terminal output complete\u001b[0m\r\nseeded ikeld355ettzbav0edcciasg café 你好 🌱\r\n"
],
[
7,
"PR41 SEEK seed 41c0ffee\r\n"
],
[
4,
"PR41 END\r\n"
]
]
}
+5
View File
@@ -0,0 +1,5 @@
{"version":2,"width":80,"height":24,"title":"Seeded control 9oz66x01","duration":12}
[0,"o","PR41 START seed 41c0ffee\r\n"]
[1,"o","PR41 seed 41c0ffee\r\nfixture 00 sample 999f0ef0\r\nfixture 01 sample 706768d0\r\nfixture 02 sample 32d9ebae\r\nfixture 03 sample fa29a378\r\n\u001b[32msynthetic terminal output complete\u001b[0m\r\nseeded ikeld355ettzbav0edcciasg café 你好 🌱\r\n"]
[8,"o","PR41 SEEK seed 41c0ffee\r\n"]
[12,"o","PR41 END\r\n"]
+5
View File
@@ -0,0 +1,5 @@
{"version":3,"term":{"cols":80,"rows":24},"title":"Seeded control 9oz66x01","duration":12}
[0,"o","PR41 START seed 41c0ffee\r\n"]
[1,"o","PR41 seed 41c0ffee\r\nfixture 00 sample 999f0ef0\r\nfixture 01 sample 706768d0\r\nfixture 02 sample 32d9ebae\r\nfixture 03 sample fa29a378\r\n\u001b[32msynthetic terminal output complete\u001b[0m\r\nseeded ikeld355ettzbav0edcciasg café 你好 🌱\r\n"]
[7,"o","PR41 SEEK seed 41c0ffee\r\n"]
[4,"o","PR41 END\r\n"]
+20
View File
@@ -0,0 +1,20 @@
"""Harmless deterministic terminal output. No input, files, secrets or network."""
import os
import time
state = 0x41C0FFEE
def next_u32():
global state
state ^= (state << 13) & 0xFFFFFFFF
state ^= state >> 17
state ^= (state << 5) & 0xFFFFFFFF
state &= 0xFFFFFFFF
return state
lines = ['PR41 seed 41c0ffee\n']
for index in range(4):
lines.append(f'fixture {index:02d} sample {next_u32():08x}\n')
lines.append('\x1b[32msynthetic terminal output complete\x1b[0m\n')
for line in lines:
os.write(1, line.encode('utf-8'))
time.sleep(0.02)
@@ -0,0 +1 @@
{"version":2,"version":1,"width":80,"height":24,"stdout":[]}
+1
View File
@@ -0,0 +1 @@
{"ver\u0073ion":1,"width":80,"height":24,"stdout":[]}
@@ -0,0 +1,7 @@
{
"stdout": [[0,"multiline v1\r\n"]],
"metadata": {"version": 3},
"width": 80,
"height": 24,
"version": 1
}
+1
View File
@@ -0,0 +1 @@
{"version":1,"width":0,"height":0,"stdout":[[0,"PR41 bounded control\r\n"]]}
+6
View File
@@ -0,0 +1,6 @@
{"version":2,"width":80,"height":24}
# compatibility comment
ignored text
[999,"o","ignored"]
[0,"o","accepted output\r\n"]
+2
View File
@@ -0,0 +1,2 @@
{"version":2,"width":0,"height":0}
[0,"o","PR41 bounded control\r\n"]
+6
View File
@@ -0,0 +1,6 @@
{"version":3,"term":{"cols":80,"rows":24}}
# compatibility comment
ignored text
[999,"o","ignored"]
[0,"o","accepted output\r\n"]
+2
View File
@@ -0,0 +1,2 @@
{"version":3,"term":{"cols":0,"rows":0}}
[0,"o","PR41 bounded control\r\n"]
+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');
});
+1
View File
@@ -181,6 +181,7 @@ try {
require __DIR__ . '/uploads.php';
require __DIR__ . '/cast-budget.php';
require __DIR__ . '/security-fixtures.php';
echo "OK: {$assertions} assertions passed.\n";
} catch ( Throwable $error ) {
+199
View File
@@ -0,0 +1,199 @@
<?php
/**
* Run the shared, deterministic security corpus through the real upload gates.
*
* The PHP-only CI job needs no Node installation or pre-generated large files.
* Expand one manifest recipe to one temporary file, in at most 64 KiB chunks,
* verify its bytes/hash, exercise each gate, and delete it before the next case.
*/
use function LamGC\Asciiplayer\is_valid_cast_file;
use const LamGC\Asciiplayer\CAST_MAX_BYTES;
/** Write a bounded chunk completely, including on a short filesystem write. */
function security_fixture_write_chunk( $handle, $chunk, $hash, &$bytes ) {
$length = strlen( $chunk );
if ( $bytes + $length > CAST_MAX_BYTES + 1 ) {
throw new RuntimeException( 'A security fixture exceeded the 32 MiB + 1 byte generation cap.' );
}
$offset = 0;
while ( $offset < $length ) {
$written = fwrite( $handle, substr( $chunk, $offset ) );
if ( false === $written || 0 === $written ) {
throw new RuntimeException( 'Could not write a security fixture.' );
}
$offset += $written;
}
hash_update( $hash, $chunk );
$bytes += $length;
}
/** Expand only literal/repeat recipes; never interpret executable generators. */
function security_fixture_materialize( $fixture, $root, $path ) {
$handle = fopen( $path, 'wb' );
if ( false === $handle ) {
throw new RuntimeException( 'Could not open the security fixture temporary file.' );
}
$hash = hash_init( 'sha256' );
$bytes = 0;
try {
$source = $fixture['source'];
if ( isset( $source['file'] ) ) {
$file = realpath( $root . '/' . $source['file'] );
if ( false === $file || 0 !== strpos( $file, $root . DIRECTORY_SEPARATOR ) || ! is_file( $file ) ) {
throw new RuntimeException( 'Security fixture files must stay inside their corpus directory.' );
}
$input = fopen( $file, 'rb' );
if ( false === $input ) {
throw new RuntimeException( 'Could not open a checked-in security fixture.' );
}
try {
while ( ! feof( $input ) ) {
$chunk = fread( $input, 65536 );
if ( false === $chunk || ( '' === $chunk && ! feof( $input ) ) ) {
throw new RuntimeException( 'Could not read a checked-in security fixture.' );
}
security_fixture_write_chunk( $handle, $chunk, $hash, $bytes );
}
} finally {
fclose( $input );
}
} else {
foreach ( $source['segments'] as $segment ) {
$text = $segment['text'];
$remaining = $segment['repeat'];
if ( ! is_string( $text ) || '' === $text || ! is_int( $remaining ) || $remaining < 1 ) {
throw new RuntimeException( 'Security recipes require nonempty text and a positive integer repeat.' );
}
$length = strlen( $text );
if ( $length <= 65536 ) {
$batch = min( $remaining, intdiv( 65536, $length ) );
$chunk = str_repeat( $text, $batch );
while ( $remaining >= $batch ) {
security_fixture_write_chunk( $handle, $chunk, $hash, $bytes );
$remaining -= $batch;
}
if ( $remaining > 0 ) {
security_fixture_write_chunk( $handle, str_repeat( $text, $remaining ), $hash, $bytes );
}
} else {
while ( $remaining-- > 0 ) {
for ( $offset = 0; $offset < $length; $offset += 65536 ) {
security_fixture_write_chunk( $handle, substr( $text, $offset, 65536 ), $hash, $bytes );
}
}
}
}
}
} finally {
fclose( $handle );
}
clearstatcache( true, $path );
same( $fixture['bytes'], $bytes, $fixture['id'] . ': generated byte count matches the shared manifest.' );
same( $bytes, filesize( $path ), $fixture['id'] . ': the actual upload file has those bytes.' );
same( $fixture['sha256'], hash_final( $hash ), $fixture['id'] . ': generated bytes match the shared SHA-256.' );
}
/** Verify ordering at the real decoder, not merely a generic false result. */
function security_fixture_assert_decodes( $fixture, $label ) {
$lengths = $GLOBALS['cast_decode_lengths'];
if ( $fixture['expected']['accepted'] ) {
same( true, count( $lengths ) > 0, $label . ': a valid control actually reaches the native JSON decoder.' );
}
$threshold = $fixture['expected']['phpNoDecodeAtOrAboveBytes'] ?? $fixture['expected']['noDecodeAtOrAboveBytes'] ?? null;
if ( null !== $threshold ) {
same( true, is_int( $threshold ) && $threshold > 0 && $threshold <= $fixture['bytes'], $label . ': decoder witness is bounded by the rejected file.' );
$largest = empty( $lengths ) ? 0 : max( $lengths );
same( true, $largest < $threshold, $label . ': rejected payload never reaches the full decoder (largest decode: ' . $largest . ' bytes).' );
}
}
$security_fixture_root = realpath( dirname( __DIR__ ) . '/fixtures/security' );
$security_fixture_manifest = json_decode( file_get_contents( $security_fixture_root . '/manifest.json' ), true );
same( JSON_ERROR_NONE, json_last_error(), 'The shared security manifest is valid JSON.' );
same( 1, $security_fixture_manifest['schemaVersion'], 'PHP consumes the versioned shared security corpus.' );
same( true, count( $security_fixture_manifest['cases'] ) > 0, 'The security corpus cannot silently become empty.' );
// Independent policy pins keep a production constant change from moving the
// goalposts, including cell limits whose next representable grid may skip one.
foreach ( array(
'CAST_MAX_BYTES' => 33554432,
'CAST_MAX_LINE_BYTES' => 262144,
'CAST_MAX_V1_BYTES' => 2097152,
'CAST_MAX_EVENTS' => 100000,
'CAST_MAX_DIMENSION' => 1000,
'CAST_MAX_CELLS' => 40000,
'CAST_MAX_MARKERS' => 1000,
'CAST_MAX_JSON_TOKENS' => 400000,
'CAST_MAX_JSON_LINE_TOKENS' => 20000,
'CAST_MAX_JSON_CONTAINERS' => 100016,
'CAST_JSON_DEPTH' => 16,
) as $constant => $limit ) {
same( $limit, constant( 'LamGC\\Asciiplayer\\' . $constant ), $constant . ': the documented production limit is unchanged.' );
}
$security_fixture_callbacks = array();
foreach ( $GLOBALS['ap_test']['filters'] as $filter ) {
if ( in_array( $filter[0], array( 'wp_handle_upload_prefilter', 'wp_handle_sideload_prefilter' ), true ) ) {
$security_fixture_callbacks[ $filter[0] ] = $filter[1];
}
}
same( 2, count( $security_fixture_callbacks ), 'Both registered upload and sideload paths consume the security corpus.' );
$security_fixture_wp_state = $GLOBALS['ap_test'];
$GLOBALS['ap_test']['capabilities'] = array( 'upload_files' => true, 'unfiltered_upload' => true );
$GLOBALS['ap_test']['multisite'] = false;
unset( $GLOBALS['ap_test']['allowed_mimes'] );
$security_fixture_ids = array();
try {
foreach ( $security_fixture_manifest['cases'] as $fixture ) {
same( false, isset( $security_fixture_ids[ $fixture['id'] ] ), 'Each security fixture has a unique ID.' );
$security_fixture_ids[ $fixture['id'] ] = $fixture['expected'];
same( true, isset( $fixture['source']['file'] ) !== isset( $fixture['source']['segments'] ), $fixture['id'] . ': exactly one fixture source is defined.' );
same( true, is_bool( $fixture['expected']['accepted'] ), $fixture['id'] . ': the expected upload result is explicit.' );
$path = tempnam( sys_get_temp_dir(), 'ap-security-' );
if ( false === $path ) {
throw new RuntimeException( 'Could not create the security fixture temporary file.' );
}
try {
security_fixture_materialize( $fixture, $security_fixture_root, $path );
$GLOBALS['cast_decode_lengths'] = array();
same( $fixture['expected']['accepted'], is_valid_cast_file( $path ), $fixture['id'] . ': actual file validator result.' );
security_fixture_assert_decodes( $fixture, $fixture['id'] . ' / file validator' );
// Browser MIME and size are deliberately wrong: inspect the actual file.
$upload = array( 'name' => $fixture['id'] . '.cast', 'tmp_name' => $path, 'error' => 0, 'type' => 'image/png', 'size' => 1 );
foreach ( $security_fixture_callbacks as $hook => $callback ) {
$GLOBALS['cast_decode_lengths'] = array();
$result = call_user_func( $callback, $upload );
if ( $fixture['expected']['accepted'] ) {
same( $upload, $result, $fixture['id'] . ' / ' . $hook . ': valid content passes unchanged.' );
} else {
same( true, is_string( $result['error'] ) && 0 === strpos( $result['error'], 'Upload a valid Asciicast' ), $fixture['id'] . ' / ' . $hook . ': content rejection occurs even for unfiltered_upload.' );
$result['error'] = 0;
same( $upload, $result, $fixture['id'] . ' / ' . $hook . ': only the upload error changes.' );
}
security_fixture_assert_decodes( $fixture, $fixture['id'] . ' / ' . $hook );
}
} finally {
unlink( $path );
}
}
foreach ( array( 'bytes-v2-over', 'bytes-v3-over' ) as $id ) {
same( 1, $security_fixture_ids[ $id ]['phpNoDecodeAtOrAboveBytes'] ?? null, $id . ': the PHP file-stat gate must reject before any native decode.' );
}
// These cases must keep decoder witnesses: a false validator result alone
// would not prove that allocation was prevented before the native decode.
foreach ( array(
'bytes-v2-over', 'bytes-v3-over', 'v1-bytes-over',
'line-v2-over', 'line-v3-over',
'tokens-v1-over', 'containers-v1-over',
'depth-v1-over', 'depth-v2-over', 'depth-v3-over',
'line-tokens-v2-over', 'line-tokens-v3-over',
) as $id ) {
same( true, isset( $security_fixture_ids[ $id ]['noDecodeAtOrAboveBytes'] ), $id . ': required predecode witness remains in the corpus.' );
same( false, $security_fixture_ids[ $id ]['accepted'], $id . ': the predecode witness remains a rejection case.' );
}
} finally {
$GLOBALS['ap_test'] = $security_fixture_wp_state;
$GLOBALS['cast_decode_lengths'] = array();
}