Files
wp-asciiplayer/tests/php/security-fixtures.php
T

200 lines
9.2 KiB
PHP

<?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();
}