From a6a919c32c17f376b9a7bbfdf0d9dcc950e910bc Mon Sep 17 00:00:00 2001 From: Jhon Farias Date: Fri, 27 Nov 2026 07:48:19 +0100 Subject: [PATCH] fix(tia): keep the graph writable when a path is not valid UTF-8 (#2079) * fix(tia): keep the graph writable when a path is not valid UTF-8 * test: update the suite totals for the byte-safe JSON tests --------- Co-authored-by: Punyapal Shah --- src/Plugins/Tia.php | 74 ++++++++++------- src/Plugins/Tia/ByteSafeJson.php | 104 ++++++++++++++++++++++++ src/Plugins/Tia/Graph.php | 46 +++++++++-- tests/.snapshots/success.txt | 15 +++- tests/Features/Tia.php | 6 +- tests/Features/Tia/HostileState.php | 2 +- tests/Features/Tia/NonUtf8Paths.php | 27 ++++++ tests/Fixtures/Tia/Project.php | 13 +-- tests/Unit/Plugins/Tia/ByteSafeJson.php | 51 ++++++++++++ tests/Unit/Plugins/Tia/Graph.php | 51 ++++++++++++ tests/Visual/Parallel.php | 2 +- 11 files changed, 337 insertions(+), 54 deletions(-) create mode 100644 src/Plugins/Tia/ByteSafeJson.php create mode 100644 tests/Features/Tia/NonUtf8Paths.php create mode 100644 tests/Unit/Plugins/Tia/ByteSafeJson.php diff --git a/src/Plugins/Tia.php b/src/Plugins/Tia.php index ed6519a0..b7a2e6b8 100644 --- a/src/Plugins/Tia.php +++ b/src/Plugins/Tia.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Pest\Plugins; +use JsonException; use NunoMaduro\Collision\Adapters\Phpunit\Printers\DefaultPrinter; use Pest\Contracts\Plugins\AddsOutput; use Pest\Contracts\Plugins\HandlesArguments; @@ -20,6 +21,7 @@ use Pest\Exceptions\TiaRequiresRemote; use Pest\Panic; use Pest\Plugins\Concerns\HandleArguments; use Pest\Plugins\Tia\BaselineSync; +use Pest\Plugins\Tia\ByteSafeJson; use Pest\Plugins\Tia\ChangedFiles; use Pest\Plugins\Tia\CiBranch; use Pest\Plugins\Tia\ConfigurationFile; @@ -222,6 +224,8 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument private ?string $freshGraphReason = null; + private ?string $graphEncodeError = null; + public function __construct( private readonly OutputInterface $output, private readonly Recorder $recorder, @@ -310,15 +314,26 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument private function saveGraph(Graph $graph): bool { - $json = $graph->encode(); + try { + $json = $graph->encode(); + } catch (JsonException $exception) { + $this->graphEncodeError = $exception->getMessage(); - if ($json === null) { return false; } + $this->graphEncodeError = null; + return $this->state->write(self::KEY_GRAPH, $json); } + private function renderGraphWriteFailure(): void + { + $this->renderBadge('ERROR', $this->graphEncodeError === null + ? 'Could not write the dependency graph.' + : sprintf('Could not write the dependency graph: %s.', $this->graphEncodeError)); + } + /** * @param array $arguments */ @@ -671,7 +686,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument $this->seedResultsInto($graph); if (! $this->saveGraph($graph)) { - $this->renderBadge('ERROR', 'Could not write the dependency graph.'); + $this->renderGraphWriteFailure(); $recorder->reset(); return; @@ -783,7 +798,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument $graph->replaceJsFileToComponents(JsModuleGraph::build($projectRoot)); if (! $this->saveGraph($graph)) { - $this->renderBadge('ERROR', 'Could not write the dependency graph.'); + $this->renderGraphWriteFailure(); return $exitCode; } @@ -1032,7 +1047,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument return; } - $decoded = json_decode($raw, true); + $decoded = ByteSafeJson::decode($raw); if (! is_array($decoded)) { return; @@ -1408,9 +1423,9 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument */ private function persistAffectedSet(array $affected): bool { - $json = json_encode(array_values($affected), JSON_UNESCAPED_SLASHES); - - if ($json === false) { + try { + $json = ByteSafeJson::encode(array_values($affected)); + } catch (JsonException) { return false; } @@ -1534,13 +1549,13 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument */ private function flushWorkerPartial(array $perTestFiles, array $perTestTables, array $perTestInertiaComponents): void { - $json = json_encode([ - 'files' => $perTestFiles, - 'tables' => $perTestTables, - 'inertia' => $perTestInertiaComponents, - ], JSON_UNESCAPED_SLASHES); - - if ($json === false) { + try { + $json = ByteSafeJson::encode([ + 'files' => $perTestFiles, + 'tables' => $perTestTables, + 'inertia' => $perTestInertiaComponents, + ]); + } catch (JsonException) { return; } @@ -1614,15 +1629,15 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument $results[$testId] = $this->replayedAsRecorded($testId, $result); } - $json = json_encode([ - 'results' => $results, - 'replayed' => $this->replayedCount, - 'affected' => $this->affectedCount, - 'executed' => $this->executedCount, - 'truncated' => $this->stoppedEarly() || $collector->hasUnfinishedTest(), - ], JSON_UNESCAPED_SLASHES); - - if ($json === false) { + try { + $json = ByteSafeJson::encode([ + 'results' => $results, + 'replayed' => $this->replayedCount, + 'affected' => $this->affectedCount, + 'executed' => $this->executedCount, + 'truncated' => $this->stoppedEarly() || $collector->hasUnfinishedTest(), + ]); + } catch (JsonException) { return; } @@ -1650,7 +1665,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument continue; } - $decoded = json_decode($raw, true); + $decoded = ByteSafeJson::decode($raw); if (! is_array($decoded)) { continue; @@ -1765,7 +1780,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument return null; } - $data = json_decode($raw, true); + $data = ByteSafeJson::decode($raw); if (! is_array($data)) { return null; @@ -2159,7 +2174,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument $this->fallbackBranchResolved = $resolved !== null; $this->fallbackBranch = $resolved ?? self::DEFAULT_BRANCH; - Parallel::setGlobal(self::FALLBACK_BRANCH_GLOBAL, $this->fallbackBranch); + Parallel::setGlobal(self::FALLBACK_BRANCH_GLOBAL, ByteSafeJson::encode($this->fallbackBranch)); $this->branch = $changedFiles->currentBranch() ?? CiBranch::detectCurrent() @@ -2177,9 +2192,10 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument private function resolveFallbackBranch(ChangedFiles $changedFiles): ?string { $inherited = Parallel::getGlobal(self::FALLBACK_BRANCH_GLOBAL); + $inheritedBranch = is_string($inherited) ? ByteSafeJson::decode($inherited) : null; - if (is_string($inherited) && $inherited !== '') { - return $inherited; + if (is_string($inheritedBranch) && $inheritedBranch !== '') { + return $inheritedBranch; } return $this->watchPatterns->defaultBranch() diff --git a/src/Plugins/Tia/ByteSafeJson.php b/src/Plugins/Tia/ByteSafeJson.php new file mode 100644 index 00000000..a963445c --- /dev/null +++ b/src/Plugins/Tia/ByteSafeJson.php @@ -0,0 +1,104 @@ + $item) { + $escaped[is_string($key) ? self::escapeString($key) : $key] = self::escape($item); + } + + return $escaped; + } + + private static function unescape(mixed $value): mixed + { + if (is_string($value)) { + return self::unescapeString($value); + } + + if (! is_array($value)) { + return $value; + } + + $unescaped = []; + + foreach ($value as $key => $item) { + $unescaped[is_string($key) ? self::unescapeString($key) : $key] = self::unescape($item); + } + + return $unescaped; + } + + private static function escapeString(string $value): string + { + if (preg_match('//u', $value) === 1 && ! str_starts_with($value, self::ESCAPE_PREFIX)) { + return $value; + } + + return self::ESCAPE_PREFIX.base64_encode($value); + } + + private static function unescapeString(string $value): string + { + if (! str_starts_with($value, self::ESCAPE_PREFIX)) { + return $value; + } + + $raw = base64_decode(substr($value, strlen(self::ESCAPE_PREFIX)), true); + + return $raw === false ? $value : $raw; + } +} diff --git a/src/Plugins/Tia/Graph.php b/src/Plugins/Tia/Graph.php index 53107c07..401b7803 100644 --- a/src/Plugins/Tia/Graph.php +++ b/src/Plugins/Tia/Graph.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Pest\Plugins\Tia; +use JsonException; use Pest\Factories\TestCaseFactory; use Pest\Factories\TestCaseMethodFactory; use Pest\Support\Container; @@ -20,6 +21,10 @@ final class Graph { public const string WORKSPACE_BRANCH_PREFIX = '@workspace:'; + private const int LEGACY_SCHEMA = 1; + + private const int SCHEMA = 2; + /** * @var array */ @@ -1698,7 +1703,7 @@ final class Graph */ public static function branchesIn(string $json): array { - $data = json_decode($json, true); + $data = ByteSafeJson::decode($json); if (! is_array($data) || ! is_array($data['baselines'] ?? null)) { return []; @@ -1715,11 +1720,35 @@ final class Graph return $branches; } - public static function decode(string $json, string $projectRoot): ?self + /** + * @return array|null + */ + private static function payload(string $json): ?array { $data = json_decode($json, true); - if (! is_array($data) || ($data['schema'] ?? null) !== 1) { + if (! is_array($data)) { + return null; + } + + if (($data['schema'] ?? null) === self::LEGACY_SCHEMA) { + return $data; + } + + if (($data['schema'] ?? null) !== self::SCHEMA) { + return null; + } + + $restored = ByteSafeJson::restore($data, $json); + + return is_array($restored) ? $restored : null; + } + + public static function decode(string $json, string $projectRoot): ?self + { + $data = self::payload($json); + + if ($data === null) { return null; } @@ -1922,10 +1951,13 @@ final class Graph return $out; } - public function encode(): ?string + /** + * @throws JsonException + */ + public function encode(): string { $payload = [ - 'schema' => 1, + 'schema' => self::SCHEMA, 'fingerprint' => $this->fingerprint, 'files' => $this->files, 'edges' => $this->edges, @@ -1935,9 +1967,7 @@ final class Graph 'js_file_to_components' => $this->jsFileToComponents, ]; - $json = json_encode($payload, JSON_UNESCAPED_SLASHES); - - return $json === false ? null : $json; + return ByteSafeJson::encode($payload); } private function relative(string $path): ?string diff --git a/tests/.snapshots/success.txt b/tests/.snapshots/success.txt index e1faa3af..a70675ac 100644 --- a/tests/.snapshots/success.txt +++ b/tests/.snapshots/success.txt @@ -1975,6 +1975,15 @@ ✓ units → it collects every test class the given units bundle ✓ units → it writes bundled units, and reads back both shapes + PASS Tests\Unit\Plugins\Tia\ByteSafeJson + ✓ it round-trips keys and values that are not valid UTF-8 + ✓ it keeps valid UTF-8 as plain JSON + ✓ it does not confuse a real string with an escaped one + ✓ it leaves a malformed escape untouched + ✓ it returns null for invalid JSON + ✓ it throws with the reason when a value cannot be encoded + ✓ it carries a string that is not valid UTF-8 through a parallel global + PASS Tests\Unit\Plugins\Tia\ChangedFiles ✓ it resolves the project prefix inside the repository ✓ it keeps a space that begins the name of the project directory @@ -2102,6 +2111,10 @@ ✓ Laravel boot files → it watches the config and bootstrap files in the Laravel defaults ✓ clearResults() → it drops the results of the fallback branch too ✓ branch baseline over the fallback → it reads results written after an earlier read + ✓ encode() and decode() → it round-trips paths that are not valid UTF-8 + ✓ encode() and decode() → it lists a branch whose name is not valid UTF-8 + ✓ legacy schema → it reads a graph of the previous schema without unescaping its strings + ✓ legacy schema → it rebuilds a graph of an unknown schema but still lists its branches PASS Tests\Unit\Plugins\Tia\IsEnabledForRun ✓ does not throw when an integer --random-order-seed is passed as a separate argv element @@ -2704,4 +2717,4 @@ ✓ pass with dataset with ('my-datas-set-value') ✓ within describe → pass with dataset with ('my-datas-set-value') - Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 39 skipped, 1989 passed (4487 assertions) \ No newline at end of file + Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 39 skipped, 2000 passed (4505 assertions) \ No newline at end of file diff --git a/tests/Features/Tia.php b/tests/Features/Tia.php index 9ccf1c13..16d5b854 100644 --- a/tests/Features/Tia.php +++ b/tests/Features/Tia.php @@ -34,10 +34,6 @@ it('does not run user hooks when replaying cached skipped and incomplete results $graph->setResult($branch, $id('replayed skip'), 1, 'cached skip', 0.01, 0, $fixture); $graph->setResult($branch, $id('replayed incomplete'), 2, 'cached incomplete', 0.01, 0, $fixture); - $json = $graph->encode(); - - expect($json)->not->toBeNull(); - $originalHome = getenv('HOME'); putenv('HOME='.$home); @@ -47,7 +43,7 @@ it('does not run user hooks when replaying cached skipped and incomplete results putenv($originalHome === false ? 'HOME' : 'HOME='.$originalHome); } - expect($storage->write(Tia::KEY_GRAPH, (string) $json))->toBeTrue(); + expect($storage->write(Tia::KEY_GRAPH, $graph->encode()))->toBeTrue(); $process = new Process( ['php', 'bin/pest', '--configuration', $configuration, '--tia'], diff --git a/tests/Features/Tia/HostileState.php b/tests/Features/Tia/HostileState.php index f6b85a2f..1491f9eb 100644 --- a/tests/Features/Tia/HostileState.php +++ b/tests/Features/Tia/HostileState.php @@ -179,7 +179,7 @@ test('a graph from a schema this build does not know is rebuilt, not read', func $project->seed('master'); $project->mutateGraph(function (array $graph): array { - $graph['schema'] = 2; + $graph['schema'] = 99; return $graph; }); diff --git a/tests/Features/Tia/NonUtf8Paths.php b/tests/Features/Tia/NonUtf8Paths.php new file mode 100644 index 00000000..ef15681d --- /dev/null +++ b/tests/Features/Tia/NonUtf8Paths.php @@ -0,0 +1,27 @@ +seed('master'); + + $project->write("caf\xe9.txt", "one\n"); + + $first = $project->pest('--tia', ...$arguments); + + expect($first->exitCode)->toBe(0, $first->describe()) + ->and($first->output)->not->toContain('Could not write the dependency graph') + ->and($project->graph()['baselines']['master']['tree'] ?? [])->toHaveKey("caf\xe9.txt"); + + $second = $project->pest('--tia', ...$arguments); + + expect($second->exitCode)->toBe(0, $second->describe()) + ->and($second->replayed())->toBe(Project::TOTAL_TESTS, $second->describe()); +})->with(Project::SEQUENTIAL_AND_PARALLEL)->onlyOnLinux(); diff --git a/tests/Fixtures/Tia/Project.php b/tests/Fixtures/Tia/Project.php index f17a3203..bd559300 100644 --- a/tests/Fixtures/Tia/Project.php +++ b/tests/Fixtures/Tia/Project.php @@ -6,6 +6,7 @@ namespace Tests\Fixtures\Tia; use FilesystemIterator; use Pest\Plugins\Tia; +use Pest\Plugins\Tia\ByteSafeJson; use Pest\Plugins\Tia\ChangedFiles; use Pest\Plugins\Tia\ConfigurationFile; use Pest\Plugins\Tia\FileState; @@ -248,13 +249,7 @@ final class Project } } - $json = $graph->encode(); - - if ($json === null) { - throw new RuntimeException('Unable to encode the seeded graph.'); - } - - if (! $this->state()->write(Tia::KEY_GRAPH, $json)) { + if (! $this->state()->write(Tia::KEY_GRAPH, $graph->encode())) { throw new RuntimeException('Unable to persist the seeded graph.'); } @@ -365,7 +360,7 @@ final class Project throw new RuntimeException('There is no graph to mutate.'); } - $this->state()->write(Tia::KEY_GRAPH, (string) json_encode($callback($graph), JSON_UNESCAPED_SLASHES)); + $this->state()->write(Tia::KEY_GRAPH, ByteSafeJson::encode($callback($graph))); $this->snapshot(); } @@ -381,7 +376,7 @@ final class Project return null; } - $graph = json_decode($json, true); + $graph = ByteSafeJson::decode($json); return is_array($graph) ? $graph : null; } diff --git a/tests/Unit/Plugins/Tia/ByteSafeJson.php b/tests/Unit/Plugins/Tia/ByteSafeJson.php new file mode 100644 index 00000000..735a38cd --- /dev/null +++ b/tests/Unit/Plugins/Tia/ByteSafeJson.php @@ -0,0 +1,51 @@ + ["tests/caf\xe9Test.php", 'tests/PlainTest.php'], + 'plain' => "message \xff\xfe", + 'count' => 3, + 'list' => [1, 2.5, true, null], + ]; + + expect(ByteSafeJson::decode(ByteSafeJson::encode($value)))->toBe($value); +}); + +it('keeps valid UTF-8 as plain JSON', function (): void { + expect(ByteSafeJson::encode(['app/café.php' => ['tests/a/b.php']])) + ->toBe('{"app/caf\\u00e9.php":["tests/a/b.php"]}'); +}); + +it('does not confuse a real string with an escaped one', function (): void { + $lookalike = "\0base64:".base64_encode("caf\xe9"); + $value = [$lookalike => $lookalike, "caf\xe9" => "caf\xe9"]; + + expect(ByteSafeJson::decode(ByteSafeJson::encode($value)))->toBe($value); +}); + +it('leaves a malformed escape untouched', function (): void { + expect(ByteSafeJson::decode('["\u0000base64:!!"]'))->toBe(["\0base64:!!"]); +}); + +it('returns null for invalid JSON', function (): void { + expect(ByteSafeJson::decode('{'))->toBeNull(); +}); + +it('throws with the reason when a value cannot be encoded', function (): void { + ByteSafeJson::encode(['time' => INF]); +})->throws(JsonException::class, 'Inf and NaN cannot be JSON encoded'); + +it('carries a string that is not valid UTF-8 through a parallel global', function (): void { + Parallel::setGlobal('BYTE_SAFE_JSON_TEST', ByteSafeJson::encode("feature/caf\xe9")); + + try { + expect(ByteSafeJson::decode((string) Parallel::getGlobal('BYTE_SAFE_JSON_TEST')))->toBe("feature/caf\xe9"); + } finally { + unset($_ENV['PEST_PARALLEL_GLOBAL_BYTE_SAFE_JSON_TEST']); + } +}); diff --git a/tests/Unit/Plugins/Tia/Graph.php b/tests/Unit/Plugins/Tia/Graph.php index ed56d830..4ea941f9 100644 --- a/tests/Unit/Plugins/Tia/Graph.php +++ b/tests/Unit/Plugins/Tia/Graph.php @@ -409,3 +409,54 @@ describe('branch baseline over the fallback', function (): void { ->and($graph->getTime('feature', 'Tests\BarTest::it passes', 'main'))->toBe(0.5); }); }); + +describe('encode() and decode()', function (): void { + it('round-trips paths that are not valid UTF-8', function (): void { + $root = sys_get_temp_dir(); + $graph = new Graph($root); + $graph->link("tests/caf\xe9Test.php", "app/caf\xe9.php"); + $graph->setLastRunTree('master', ["caf\xe9.txt" => 'hash']); + $graph->setResult('master', "P\\Tests\\caf\xe9Test::__pest_evaluable_it_works", 0, "caf\xe9", 0.1, 1, "tests/caf\xe9Test.php"); + + $decoded = Graph::decode($graph->encode(), $root); + + expect($decoded)->toBeInstanceOf(Graph::class) + ->and($decoded->affected(["app/caf\xe9.php"]))->toBe(["tests/caf\xe9Test.php"]) + ->and($decoded->lastRunTree('master'))->toBe(["caf\xe9.txt" => 'hash']) + ->and($decoded->getAssertions('master', "P\\Tests\\caf\xe9Test::__pest_evaluable_it_works"))->toBe(1) + ->and($decoded->testFilesToRerun('master'))->toBeEmpty(); + }); + + it('lists a branch whose name is not valid UTF-8', function (): void { + $graph = new Graph(sys_get_temp_dir()); + $graph->setRecordedAtSha("feature/caf\xe9", 'abc'); + + expect(Graph::branchesIn($graph->encode()))->toBe(["feature/caf\xe9"]); + }); +}); + +describe('legacy schema', function (): void { + it('reads a graph of the previous schema without unescaping its strings', function (): void { + $root = sys_get_temp_dir(); + $id = 'P\\Tests\\FooTest::__pest_evaluable_it_skips'; + $legacy = json_encode([ + 'schema' => 1, + 'baselines' => ['master' => [ + 'sha' => null, + 'tree' => [], + 'results' => [$id => ['status' => 1, 'message' => "\0base64:b2xk", 'time' => 0.1]], + ]], + ], JSON_UNESCAPED_SLASHES); + + $graph = Graph::decode((string) $legacy, $root); + + expect($graph)->toBeInstanceOf(Graph::class) + ->and($graph->getResult('master', $id)?->message())->toBe("\0base64:b2xk") + ->and(Graph::decode($graph->encode(), $root)?->getResult('master', $id)?->message())->toBe("\0base64:b2xk"); + }); + + it('rebuilds a graph of an unknown schema but still lists its branches', function (): void { + expect(Graph::decode('{"schema":99}', sys_get_temp_dir()))->toBeNull() + ->and(Graph::branchesIn('{"schema":99,"baselines":{"master":{}}}'))->toBe(['master']); + }); +}); diff --git a/tests/Visual/Parallel.php b/tests/Visual/Parallel.php index 1be1b367..5976e3ad 100644 --- a/tests/Visual/Parallel.php +++ b/tests/Visual/Parallel.php @@ -21,7 +21,7 @@ test('parallel', function () use ($run): void { $output = implode("\n", array_slice(explode("\n", (string) $output), -10)); $profileOutput = $run('tests/Fixtures/Suites/SuccessOnly.php', '--profile'); - $expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 31 skipped, 1861 passed (3960 assertions)'; + $expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 31 skipped, 1872 passed (3978 assertions)'; expect($output) ->toContain("Tests: {$expected}")