diff --git a/composer.json b/composer.json index 7bdf9a5..0851154 100644 --- a/composer.json +++ b/composer.json @@ -25,6 +25,7 @@ "php": "^8.2", "ext-json": "*", "ext-phar": "*", + "ext-openssl": "*", "humbug/box": "^4.0", "symfony/console": "^6.4|^7.0", "symfony/filesystem": "^6.4|^7.0", diff --git a/composer.lock b/composer.lock index 20948b3..c95b469 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "e0c43f9d3781fc47c1eb1e9f16b2f9c8", + "content-hash": "8d7a5147f44ab9843f2caa627bed1695", "packages": [ { "name": "amphp/amp", @@ -6597,8 +6597,9 @@ "platform": { "php": "^8.2", "ext-json": "*", - "ext-phar": "*" + "ext-phar": "*", + "ext-openssl": "*" }, "platform-dev": {}, - "plugin-api-version": "2.6.0" + "plugin-api-version": "2.9.0" } diff --git a/src/Application.php b/src/Application.php index 9996bb7..8be42ab 100644 --- a/src/Application.php +++ b/src/Application.php @@ -8,6 +8,7 @@ use Parcel\Command\PatchComposerCommand; use Parcel\Command\PrepareCommand; use Parcel\Command\PushStubsCommand; +use Parcel\Command\SignCommand; use Symfony\Component\Console\Application as SymfonyApplication; class Application extends SymfonyApplication @@ -20,5 +21,6 @@ public function __construct() $this->add(new PatchComposerCommand); $this->add(new PrepareCommand); $this->add(new CompileCommand); + $this->add(new SignCommand); } } diff --git a/src/Command/PrepareCommand.php b/src/Command/PrepareCommand.php index 8937bd5..817ad17 100644 --- a/src/Command/PrepareCommand.php +++ b/src/Command/PrepareCommand.php @@ -22,7 +22,8 @@ protected function configure(): void { $this ->addArgument('target', InputArgument::OPTIONAL, 'Target Laravel project directory', '.') - ->addOption('force', 'f', InputOption::VALUE_NONE, 'Overwrite existing files'); + ->addOption('force', 'f', InputOption::VALUE_NONE, 'Overwrite existing files') + ->addOption('mobile', null, InputOption::VALUE_NONE, 'Use the NativePHP Mobile configuration (for an app staged by native:build)'); } protected function execute(InputInterface $input, OutputInterface $output): int @@ -35,6 +36,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $pushStubsInput = new ArrayInput([ 'target' => $target, '--force' => $force, + '--mobile' => $input->getOption('mobile'), ]); $result = $pushStubsCommand->run($pushStubsInput, $output); diff --git a/src/Command/PushStubsCommand.php b/src/Command/PushStubsCommand.php index 04a973b..7670b7d 100644 --- a/src/Command/PushStubsCommand.php +++ b/src/Command/PushStubsCommand.php @@ -33,6 +33,7 @@ protected function configure(): void $this ->addArgument('target', InputArgument::OPTIONAL, 'Target Laravel project directory', '.') ->addOption('force', 'f', InputOption::VALUE_NONE, 'Overwrite existing files') + ->addOption('mobile', null, InputOption::VALUE_NONE, 'Use the NativePHP Mobile configuration (for an app staged by native:build)') ->setHelp('This command copies NativePHP stubs and creates box.json configuration for a Laravel project.'); } @@ -51,26 +52,38 @@ protected function execute(InputInterface $input, OutputInterface $output): int return Command::FAILURE; } - if (! $this->filesystem->exists(Path::join($targetDir, 'artisan'))) { - $io->error("Target directory doesn't appear to be a Laravel project (missing artisan file)"); + $mobile = (bool) $input->getOption('mobile'); + + // A mobile build stages the app without artisan, so look for the + // file every Laravel app boots from instead. + $marker = $mobile ? 'bootstrap/app.php' : 'artisan'; + + if (! $this->filesystem->exists(Path::join($targetDir, $marker))) { + $io->error("Target directory doesn't appear to be a Laravel project (missing {$marker} file)"); return Command::FAILURE; } $stubsDir = $this->getStubsDirectory(); - // Copy individual stub files - $stubFiles = [ - 'box.json', - 'box-helper.php', - 'phar-router.php', - 'custom-stub.php', - // 'serverless.php', - ]; - - foreach ($stubFiles as $stubFile) { + // Copy individual stub files (stub => file in the project) + $stubFiles = $mobile + ? [ + 'mobile/box.json' => 'box.json', + 'box-helper.php' => 'box-helper.php', + 'mobile/mobile-stub.php' => 'mobile-stub.php', + ] + : [ + 'box.json' => 'box.json', + 'box-helper.php' => 'box-helper.php', + 'phar-router.php' => 'phar-router.php', + 'custom-stub.php' => 'custom-stub.php', + // 'serverless.php' => 'serverless.php', + ]; + + foreach ($stubFiles as $stubFile => $targetFile) { $source = Path::join($stubsDir, $stubFile); - $target = Path::join($targetDir, $stubFile); + $target = Path::join($targetDir, $targetFile); if (! $this->filesystem->exists($source)) { continue; diff --git a/src/Command/SignCommand.php b/src/Command/SignCommand.php new file mode 100644 index 0000000..0aa9b33 --- /dev/null +++ b/src/Command/SignCommand.php @@ -0,0 +1,198 @@ +addArgument('bundle', InputArgument::REQUIRED, 'Path to the compiled bundle') + ->addOption('project', null, InputOption::VALUE_REQUIRED, 'The Bifrost project the bundle belongs to') + ->addOption('output', 'o', InputOption::VALUE_REQUIRED, 'Where to write the signature (default: .sig)') + ->addOption('public-key-output', null, InputOption::VALUE_REQUIRED, 'Also write {"": ""} to this file') + ->setHelp( + "Signs the bundle with ECDSA P-256, the scheme Bifrost uses for OTA releases.\n\n". + "The signed message is the format, the project, the bundle's SHA-256 and its size, one per line.\n". + "The signature is written as JSON: {\"key_id\": ..., \"signature\": }.\n\n". + "With PARCEL_SIGNING_URL and PARCEL_SIGNING_TOKEN set, Bifrost signs it: only the hash is sent,\n". + "and the private key never leaves Bifrost. Otherwise PARCEL_SIGNING_KEY holds a PEM private key\n". + '(or base64 of one) and PARCEL_SIGNING_KEY_ID names it (default "local").' + ); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $io = new SymfonyStyle($input, $output); + $bundle = (string) $input->getArgument('bundle'); + $project = (string) $input->getOption('project'); + + if (! is_file($bundle)) { + $io->error("Bundle not found: {$bundle}"); + + return Command::FAILURE; + } + + if ($project === '') { + $io->error('Pass --project: the signature binds the bundle to one project.'); + + return Command::FAILURE; + } + + $sha256 = (string) hash_file('sha256', $bundle); + $size = (int) filesize($bundle); + + try { + $signed = getenv('PARCEL_SIGNING_URL') + ? $this->signRemotely($project, $sha256, $size) + : $this->signLocally(self::message($project, $sha256, $size)); + } catch (RuntimeException $e) { + $io->error($e->getMessage()); + + return Command::FAILURE; + } + + // Whoever signed it, the signature has to check out against the key + // it came with before anything ships with it. + if (! self::verify(self::message($project, $sha256, $size), $signed['signature'], $signed['public_key'])) { + $io->error('The signature does not match the bundle.'); + + return Command::FAILURE; + } + + $signaturePath = $input->getOption('output') ?: $bundle.'.sig'; + file_put_contents($signaturePath, json_encode([ + 'key_id' => $signed['key_id'], + 'signature' => $signed['signature'], + ], JSON_UNESCAPED_SLASHES)); + + if ($publicKeyPath = $input->getOption('public-key-output')) { + file_put_contents($publicKeyPath, json_encode([$signed['key_id'] => $signed['public_key']], JSON_UNESCAPED_SLASHES)); + } + + $io->definitionList( + ['Signature' => $signaturePath], + ['Key' => $signed['key_id']], + ); + + return Command::SUCCESS; + } + + /** + * The exact text that gets signed, one field per line. + */ + public static function message(string $project, string $sha256, int $size): string + { + return implode("\n", [self::FORMAT, $project, $sha256, (string) $size]); + } + + /** + * @param string $signature base64 DER ECDSA signature + * @param string $publicKey base64 DER SubjectPublicKeyInfo + */ + public static function verify(string $message, string $signature, string $publicKey): bool + { + $der = base64_decode($signature, true); + $key = openssl_pkey_get_public(self::pem(base64_decode($publicKey, true) ?: '', 'PUBLIC KEY')); + + return $der !== false && $key !== false && openssl_verify($message, $der, $key, OPENSSL_ALGO_SHA256) === 1; + } + + /** + * @return array{key_id: string, signature: string, public_key: string} + */ + private function signLocally(string $message): array + { + $encoded = trim((string) getenv('PARCEL_SIGNING_KEY')); + + if ($encoded === '') { + throw new RuntimeException('Set PARCEL_SIGNING_URL and PARCEL_SIGNING_TOKEN to sign with Bifrost, or PARCEL_SIGNING_KEY to sign with a local key.'); + } + + $pem = str_contains($encoded, '-----BEGIN') ? $encoded : (string) base64_decode($encoded, true); + $key = openssl_pkey_get_private($pem); + $details = $key === false ? false : openssl_pkey_get_details($key); + + if ($key === false || $details === false || ($details['ec']['curve_name'] ?? null) !== 'prime256v1') { + throw new RuntimeException('PARCEL_SIGNING_KEY must be an ECDSA P-256 private key in PEM.'); + } + + if (! openssl_sign($message, $signature, $key, OPENSSL_ALGO_SHA256)) { + throw new RuntimeException('Signing with PARCEL_SIGNING_KEY failed.'); + } + + return [ + 'key_id' => getenv('PARCEL_SIGNING_KEY_ID') ?: 'local', + 'signature' => base64_encode($signature), + 'public_key' => self::der($details['key']), + ]; + } + + /** + * Ask Bifrost to sign. Only the project, hash and size are sent; Bifrost + * builds the message itself from its own record of the build. + * + * @return array{key_id: string, signature: string, public_key: string} + */ + private function signRemotely(string $project, string $sha256, int $size): array + { + $context = stream_context_create(['http' => [ + 'method' => 'POST', + 'header' => implode("\r\n", [ + 'Content-Type: application/json', + 'Accept: application/json', + 'Authorization: Bearer '.getenv('PARCEL_SIGNING_TOKEN'), + ]), + 'content' => json_encode(['format' => self::FORMAT, 'project' => $project, 'sha256' => $sha256, 'size' => $size]), + 'timeout' => 60, + 'ignore_errors' => true, + ]]); + + $body = @file_get_contents((string) getenv('PARCEL_SIGNING_URL'), false, $context); + $status = (int) (explode(' ', $http_response_header[0] ?? '')[1] ?? 0); + $response = is_string($body) ? json_decode($body, true) : null; + + if ($status !== 200 || ! is_array($response)) { + throw new RuntimeException("The signing service refused the bundle (HTTP {$status})."); + } + + foreach (['key_id', 'signature', 'public_key'] as $field) { + if (! is_string($response[$field] ?? null) || $response[$field] === '') { + throw new RuntimeException("The signing service's answer has no {$field}."); + } + } + + return ['key_id' => $response['key_id'], 'signature' => $response['signature'], 'public_key' => $response['public_key']]; + } + + private static function der(string $pem): string + { + return (string) preg_replace('/-----[^-]+-----|\s+/', '', $pem); + } + + private static function pem(string $der, string $label): string + { + return "-----BEGIN {$label}-----\n".chunk_split(base64_encode($der), 64, "\n")."-----END {$label}-----\n"; + } +} diff --git a/src/Compactor/RealPathMod.php b/src/Compactor/RealPathMod.php index ed39b9d..bb2d392 100644 --- a/src/Compactor/RealPathMod.php +++ b/src/Compactor/RealPathMod.php @@ -18,27 +18,81 @@ public function compact(string $file, string $contents): string { $normalizedFile = str_replace('\\', '/', $file); - // Handle SplFileInfo modifications + if (! str_ends_with($normalizedFile, '.php')) { + return $contents; + } + + // A few files need more than the general rewrites below, never + // instead of them: LoadConfiguration also calls realpath() on the + // config path, and left alone it finds no config files at all. if (preg_match(self::FILE_PATTERNS['SplFileInfo'], $normalizedFile)) { - return $this->modifySplFileInfo($contents); + $contents = $this->modifySplFileInfo($contents); + } elseif (preg_match(self::FILE_PATTERNS['LoadConfiguration'], $normalizedFile)) { + $contents = $this->modifyLoadConfiguration($contents); + } elseif (preg_match(self::FILE_PATTERNS['BladeIconsServiceProvider'], $normalizedFile)) { + $contents = $this->modifyBladeIconsServiceProvider($contents); + } + + return $this->replaceGlobCalls($this->replaceRealpathCalls($contents)); + } + + /** + * Point calls to the global glob() at nativephp_glob(), which can see + * inside the phar. Works on tokens so that methods called glob, like + * Filesystem::glob(), keep their declarations and call sites. + */ + private function replaceGlobCalls(string $contents): string + { + if (stripos($contents, 'glob') === false) { + return $contents; + } + + $tokens = \PhpToken::tokenize($contents); + $count = count($tokens); + $previous = null; + $output = ''; + + foreach ($tokens as $index => $token) { + if ($this->isGlobFunctionCall($token, $previous, $tokens, $index, $count)) { + $output .= '\\nativephp_glob'; + $previous = $token; + + continue; + } + + $output .= $token->text; + + if (! $token->isIgnorable()) { + $previous = $token; + } } - // Handle LoadConfiguration modifications - if (preg_match(self::FILE_PATTERNS['LoadConfiguration'], $normalizedFile)) { - return $this->modifyLoadConfiguration($contents); + return $output; + } + + /** + * @param list<\PhpToken> $tokens + */ + private function isGlobFunctionCall(\PhpToken $token, ?\PhpToken $previous, array $tokens, int $index, int $count): bool + { + $name = strtolower($token->text); + + if (! ($token->is(T_STRING) && $name === 'glob') && ! ($token->is(T_NAME_FULLY_QUALIFIED) && $name === '\\glob')) { + return false; } - // Handle Blade Icons service provider - if (preg_match(self::FILE_PATTERNS['BladeIconsServiceProvider'], $normalizedFile)) { - return $this->modifyBladeIconsServiceProvider($contents); + // A declaration, a method or static call, or a constant: not ours. + if ($previous?->is([T_FUNCTION, T_OBJECT_OPERATOR, T_NULLSAFE_OBJECT_OPERATOR, T_DOUBLE_COLON, T_NEW, T_CONST])) { + return false; } - // Handle general PHP files for realpath replacement - if (str_ends_with($normalizedFile, '.php')) { - return $this->replaceRealpathCalls($contents); + for ($next = $index + 1; $next < $count; $next++) { + if (! $tokens[$next]->isIgnorable()) { + return $tokens[$next]->text === '('; + } } - return $contents; + return false; } private function modifySplFileInfo(string $contents): string diff --git a/stubs/box-helper.php b/stubs/box-helper.php index 31b74d5..decb15d 100644 --- a/stubs/box-helper.php +++ b/stubs/box-helper.php @@ -55,3 +55,320 @@ function nativephp_rp($value = null, $pharPath = null): mixed return str_replace('/', DIRECTORY_SEPARATOR, $fullPath); } + +/** + * glob() that can see inside a phar. + * + * PHP's glob() only reads the real filesystem, so under a phar:// path it + * quietly returns nothing. Laravel finds migrations and discovers event + * listeners with it, so in a bundled app those just go missing. Outside a + * phar this is plain glob(). + */ +function nativephp_glob(string $pattern, int $flags = 0): array|false +{ + if (! str_starts_with($pattern, 'phar://')) { + return glob($pattern, $flags); + } + + $brace = defined('GLOB_BRACE') ? GLOB_BRACE : 0; + $noSort = defined('GLOB_NOSORT') ? GLOB_NOSORT : 0; + $noCheck = defined('GLOB_NOCHECK') ? GLOB_NOCHECK : 0; + + $patterns = ($flags & $brace) ? nativephp_glob_expand_braces($pattern) : [$pattern]; + + // Like glob(), each brace alternative is sorted on its own and the + // alternatives keep their order. + $matches = []; + + foreach ($patterns as $expanded) { + $found = nativephp_glob_phar($expanded, $flags); + + if (! ($flags & $noSort)) { + sort($found, SORT_STRING); + } + + array_push($matches, ...$found); + } + + $matches = array_values(array_unique($matches)); + + if ($matches === [] && ($flags & $noCheck)) { + return [$pattern]; + } + + return $matches; +} + +/** + * @internal + */ +function nativephp_glob_phar(string $pattern, int $flags): array +{ + $escape = ! ($flags & (defined('GLOB_NOESCAPE') ? GLOB_NOESCAPE : 0)); + $onlyDir = (bool) ($flags & (defined('GLOB_ONLYDIR') ? GLOB_ONLYDIR : 0)); + $mark = (bool) ($flags & (defined('GLOB_MARK') ? GLOB_MARK : 0)); + + // A trailing slash asks for directories only, as it does for glob(). + if (str_ends_with($pattern, '/') && strlen($pattern) > strlen('phar:///')) { + $pattern = rtrim($pattern, '/'); + $onlyDir = true; + $mark = true; + } + + $segments = explode('/', substr($pattern, strlen('phar://'))); + + // Everything up to the first segment with a wildcard is a literal path. + $base = []; + + while ($segments !== [] && ! nativephp_glob_has_magic($segments[0], $escape)) { + $segment = array_shift($segments); + $base[] = $escape ? preg_replace('/\\\\(.)/s', '$1', $segment) : $segment; + } + + $candidates = ['phar://'.implode('/', $base)]; + + $last = count($segments) - 1; + + foreach ($segments as $index => $segment) { + $next = []; + + foreach ($candidates as $directory) { + $entries = is_dir($directory) ? scandir($directory) : false; + + if ($entries === false) { + continue; + } + + foreach ($entries as $entry) { + if ($entry === '.' || $entry === '..') { + continue; + } + + if (! nativephp_glob_match($segment, $entry, $escape)) { + continue; + } + + $path = $directory.'/'.$entry; + + if ($index < $last && ! is_dir($path)) { + continue; + } + + $next[] = $path; + } + } + + $candidates = $next; + } + + $matches = []; + + foreach ($candidates as $path) { + if (! file_exists($path)) { + continue; + } + + $isDir = is_dir($path); + + if ($onlyDir && ! $isDir) { + continue; + } + + $matches[] = $mark && $isDir ? $path.'/' : $path; + } + + return $matches; +} + +/** + * @internal + */ +function nativephp_glob_has_magic(string $segment, bool $escape): bool +{ + $length = strlen($segment); + + for ($i = 0; $i < $length; $i++) { + if ($escape && $segment[$i] === '\\') { + $i++; + + continue; + } + + if ($segment[$i] === '*' || $segment[$i] === '?' || $segment[$i] === '[') { + return true; + } + } + + return false; +} + +/** + * Match one path segment against one glob segment, the way glob() does: + * a leading dot has to be matched by a leading dot in the pattern. + * + * Not fnmatch(): PHP built for iOS doesn't have it. + * + * @internal + */ +function nativephp_glob_match(string $segment, string $name, bool $escape): bool +{ + if (str_starts_with($name, '.') && ! str_starts_with($segment, '.') && ! str_starts_with($segment, '\\.')) { + return false; + } + + $regex = ''; + $length = strlen($segment); + + for ($i = 0; $i < $length; $i++) { + $char = $segment[$i]; + + if ($escape && $char === '\\' && $i + 1 < $length) { + $regex .= preg_quote($segment[++$i], '#'); + + continue; + } + + if ($char === '*') { + $regex .= '.*'; + + continue; + } + + if ($char === '?') { + $regex .= '.'; + + continue; + } + + if ($char === '[') { + // A ']' straight after the '[' (or '[!') is part of the class. + $close = $i + 1; + + if ($close < $length && ($segment[$close] === '!' || $segment[$close] === '^')) { + $close++; + } + + if ($close < $length && $segment[$close] === ']') { + $close++; + } + + $close = strpos($segment, ']', $close); + + if ($close === false) { + $regex .= '\\['; + + continue; + } + + $class = substr($segment, $i + 1, $close - $i - 1); + $negate = $class !== '' && ($class[0] === '!' || $class[0] === '^'); + $class = $negate ? substr($class, 1) : $class; + + $body = ''; + + for ($j = 0, $classLength = strlen($class); $j < $classLength; $j++) { + if ($escape && $class[$j] === '\\' && $j + 1 < $classLength) { + $body .= '\\'.$class[++$j]; + } elseif (in_array($class[$j], ['\\', '[', ']', '^', '#'], true)) { + $body .= '\\'.$class[$j]; + } else { + $body .= $class[$j]; + } + } + + $regex .= '['.($negate ? '^' : '').$body.']'; + $i = $close; + + continue; + } + + $regex .= preg_quote($char, '#'); + } + + return (bool) preg_match('#^'.$regex.'$#s', $name); +} + +/** + * Expand the first {a,b} group (and, recursively, any that follow). + * + * @internal + */ +function nativephp_glob_expand_braces(string $pattern): array +{ + $length = strlen($pattern); + $depth = 0; + $start = null; + + for ($i = 0; $i < $length; $i++) { + $char = $pattern[$i]; + + if ($char === '\\') { + $i++; + + continue; + } + + if ($char === '{') { + if ($depth === 0) { + $start = $i; + } + + $depth++; + + continue; + } + + if ($char !== '}' || $depth === 0) { + continue; + } + + $depth--; + + if ($depth > 0) { + continue; + } + + $inner = substr($pattern, $start + 1, $i - $start - 1); + $prefix = substr($pattern, 0, $start); + $suffix = substr($pattern, $i + 1); + + $options = []; + $current = ''; + $level = 0; + + for ($j = 0, $innerLength = strlen($inner); $j < $innerLength; $j++) { + $c = $inner[$j]; + + if ($c === '\\' && $j + 1 < $innerLength) { + $current .= $c.$inner[++$j]; + + continue; + } + + if ($c === '{') { + $level++; + } elseif ($c === '}') { + $level--; + } elseif ($c === ',' && $level === 0) { + $options[] = $current; + $current = ''; + + continue; + } + + $current .= $c; + } + + $options[] = $current; + + $expanded = []; + + foreach ($options as $option) { + array_push($expanded, ...nativephp_glob_expand_braces($prefix.$option.$suffix)); + } + + return $expanded; + } + + return [$pattern]; +} diff --git a/stubs/mobile/box.json b/stubs/mobile/box.json new file mode 100644 index 0000000..956ce53 --- /dev/null +++ b/stubs/mobile/box.json @@ -0,0 +1,55 @@ +{ + "stub": "mobile-stub.php", + "main": false, + "check-requirements": false, + "dump-autoload": false, + "exclude-composer-files": false, + "files-bin": ["box-helper.php"], + "finder": [ + { + "in": ".", + "notPath": ["#^(vendor|public|storage|build|tests|nativephp)/#"], + "exclude": ["node_modules"], + "notName": ["box.json", "box-helper.php", "mobile-stub.php", ".env", "*.phar", "*.sqlite", "*.sqlite-journal"] + }, + { + "in": "vendor", + "notName": [ + "LICENSE", + "*.md", + "*.dist", + "Makefile", + "phpunit*.xml", + "phpstan*", + ".php-cs-fixer.*", + "CHANGELOG*", + "UPGRADE*", + "CONTRIBUTING*" + ], + "exclude": [ + "doc", + "docs", + "test", + "test_old", + "tests", + "Tests", + "examples", + "example", + "fixtures", + "benchmarks", + "benchmark", + "nativephp/mobile/resources", + "nativephp/mobile/vendor", + "endroid" + ] + } + ], + "output": "build/__nativephp_app_bundle.phar", + "compression": "GZ", + "algorithm": "SHA256", + "compactors": [ + "KevinGH\\Box\\Compactor\\Php", + "KevinGH\\Box\\Compactor\\Json", + "Parcel\\Compactor\\RealPathMod" + ] +} diff --git a/stubs/mobile/mobile-stub.php b/stubs/mobile/mobile-stub.php new file mode 100644 index 0000000..1bb160b --- /dev/null +++ b/stubs/mobile/mobile-stub.php @@ -0,0 +1,11 @@ + 'bifrost-test', + 'signature' => base64_encode($signature), + 'public_key' => preg_replace('/-----[^-]+-----|\s+/', '', openssl_pkey_get_details($key)['key']), +]); diff --git a/tests/Unit/NativePhpGlobTest.php b/tests/Unit/NativePhpGlobTest.php new file mode 100644 index 0000000..46e47c1 --- /dev/null +++ b/tests/Unit/NativePhpGlobTest.php @@ -0,0 +1,135 @@ +dir = sys_get_temp_dir().'/parcel-glob-'.uniqid(); + mkdir($this->dir.'/src/database/migrations', 0777, true); + mkdir($this->dir.'/src/app/Listeners/Nested', 0777, true); + mkdir($this->dir.'/src/fonts', 0777, true); + + foreach ([ + 'database/migrations/2024_01_02_000000_b.php', + 'database/migrations/2024_01_01_000000_a.php', + 'database/migrations/README', + 'database/migrations/.hidden_x.php', + 'app/Listeners/SendEmail.php', + 'app/Listeners/Nested/Other.php', + 'fonts/b.otf', + 'fonts/a.ttf', + 'fonts/c.woff', + 'weird[1].txt', + ] as $file) { + file_put_contents($this->dir.'/src/'.$file, 'pharFile = $this->dir.'/app.phar'; + $build = sprintf( + '$p = new Phar(%s); $p->buildFromDirectory(%s); $p->setStub("pharFile, true), + var_export($this->dir.'/src', true), + ); + exec(escapeshellarg(PHP_BINARY).' -d phar.readonly=0 -r '.escapeshellarg($build), $output, $status); + expect($status)->toBe(0); + + $this->root = 'phar://'.$this->pharFile; +}); + +afterEach(function () { + if (isset($this->dir)) { + exec('rm -rf '.escapeshellarg($this->dir)); + } +}); + +it('finds files inside a phar that glob() cannot see', function () { + expect(glob($this->root.'/database/migrations/*_*.php'))->toBe([]); + + expect(nativephp_glob($this->root.'/database/migrations/*_*.php'))->toBe([ + $this->root.'/database/migrations/2024_01_01_000000_a.php', + $this->root.'/database/migrations/2024_01_02_000000_b.php', + ]); +}); + +it('matches wildcards in directory segments', function () { + expect(nativephp_glob($this->root.'/*/Listeners/*.php'))->toBe([ + $this->root.'/app/Listeners/SendEmail.php', + ]); +}); + +it('honours GLOB_ONLYDIR and GLOB_MARK', function () { + expect(nativephp_glob($this->root.'/app/Listeners/*', GLOB_ONLYDIR))->toBe([ + $this->root.'/app/Listeners/Nested', + ]); + + expect(nativephp_glob($this->root.'/app/*', GLOB_MARK))->toBe([ + $this->root.'/app/Listeners/', + ]); + + expect(nativephp_glob($this->root.'/app/Listeners/*/'))->toBe([ + $this->root.'/app/Listeners/Nested/', + ]); +}); + +it('expands braces in order, like glob()', function () { + expect(nativephp_glob($this->root.'/fonts/*.{ttf,otf}', GLOB_BRACE))->toBe([ + $this->root.'/fonts/a.ttf', + $this->root.'/fonts/b.otf', + ]); +}); + +it('returns a literal path only when it exists', function () { + expect(nativephp_glob($this->root.'/fonts/a.ttf'))->toBe([$this->root.'/fonts/a.ttf']) + ->and(nativephp_glob($this->root.'/fonts/missing.ttf'))->toBe([]); +}); + +it('returns the pattern for GLOB_NOCHECK when nothing matches', function () { + expect(nativephp_glob($this->root.'/nope/*', GLOB_NOCHECK))->toBe([$this->root.'/nope/*']); +}); + +it('treats escaped brackets as literals', function () { + expect(nativephp_glob($this->root.'/weird\[1\].txt'))->toBe([$this->root.'/weird[1].txt']); +}); + +it('leaves paths outside a phar to glob()', function () { + expect(nativephp_glob($this->dir.'/src/fonts/*.ttf'))->toBe(glob($this->dir.'/src/fonts/*.ttf')); +}); + +it('matches names the way fnmatch() does', function (string $pattern, string $name) { + expect(nativephp_glob_match($pattern, $name, true)) + ->toBe(fnmatch($pattern, $name, FNM_PERIOD)); +})->with([ + ['*_*.php', '2024_01_01_a.php'], + ['*_*.php', 'README'], + ['*.php', '.hidden.php'], + ['.*', '.hidden.php'], + ['?.txt', 'a.txt'], + ['?.txt', 'ab.txt'], + ['[abc].ttf', 'b.ttf'], + ['[!abc].ttf', 'b.ttf'], + ['[!abc].ttf', 'd.ttf'], + ['[a-c]*', 'cat'], + ['[a-c]*', 'dog'], + ['[]x].txt', '].txt'], + ['weird\[1\].txt', 'weird[1].txt'], + ['weird\[1\].txt', 'weird1.txt'], + ['a#b.php', 'a#b.php'], + ['file.(1)+', 'file.(1)+'], +]); + +it('works without fnmatch(), which PHP built for iOS lacks', function () { + $script = sprintf( + 'require %s; echo json_encode(nativephp_glob(%s));', + var_export(realpath(__DIR__.'/../../stubs/box-helper.php'), true), + var_export($this->root.'/database/migrations/*_*.php', true), + ); + + exec(escapeshellarg(PHP_BINARY).' -d disable_functions=fnmatch -r '.escapeshellarg($script).' 2>&1', $output, $status); + + expect($status)->toBe(0) + ->and(json_decode(implode('', $output), true))->toBe([ + $this->root.'/database/migrations/2024_01_01_000000_a.php', + $this->root.'/database/migrations/2024_01_02_000000_b.php', + ]); +}); diff --git a/tests/Unit/PushStubsMobileTest.php b/tests/Unit/PushStubsMobileTest.php new file mode 100644 index 0000000..48787ba --- /dev/null +++ b/tests/Unit/PushStubsMobileTest.php @@ -0,0 +1,44 @@ +dir = sys_get_temp_dir().'/parcel-mobile-'.uniqid(); + mkdir($this->dir.'/bootstrap', 0777, true); + file_put_contents($this->dir.'/bootstrap/app.php', 'dir)); +}); + +function pushStubs(array $input): CommandTester +{ + $tester = new CommandTester((new Application)->find('push-stubs')); + $tester->execute($input); + + return $tester; +} + +it('pushes the mobile configuration to an app staged without artisan', function () { + $tester = pushStubs(['target' => $this->dir, '--mobile' => true]); + + expect($tester->getStatusCode())->toBe(0) + ->and($this->dir.'/box.json')->toBeFile() + ->and($this->dir.'/box-helper.php')->toBeFile() + ->and($this->dir.'/mobile-stub.php')->toBeFile() + ->and($this->dir.'/phar-router.php')->not->toBeFile(); + + $config = json_decode(file_get_contents($this->dir.'/box.json'), true); + + // The runtime opens files inside the bundle by phar:// path, which only + // works when the archive's file name has an extension. + expect($config['output'])->toEndWith('.phar') + ->and($config['stub'])->toBe('mobile-stub.php') + ->and($config['dump-autoload'])->toBeFalse(); +}); + +it('still wants artisan for a desktop app', function () { + expect(pushStubs(['target' => $this->dir])->getStatusCode())->toBe(1); +}); diff --git a/tests/Unit/RealPathModGlobTest.php b/tests/Unit/RealPathModGlobTest.php new file mode 100644 index 0000000..83fe852 --- /dev/null +++ b/tests/Unit/RealPathModGlobTest.php @@ -0,0 +1,30 @@ +compact('/app/vendor/foo/src/Thing.php', $code); +} + +it('points global glob() calls at nativephp_glob()', function (string $code, string $expected) { + expect(compactGlob($code))->toBe($expected); +})->with([ + 'plain call' => [' [' [' ["toBe($code); +})->with([ + 'method declaration' => [' ['files->glob($p);'], + 'nullsafe method call' => ['glob($p);'], + 'static call' => [' [' [' [' ['configPath()); + return $configPath; + } + protected function getNestedDirectory($file, $configPath) { + $directory = $file->getPath(); + return $directory; + } + } + PHP; + + $compacted = (new RealPathMod)->compact('/app/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php', $code); + + expect($compacted) + ->toContain('$configPath = \nativephp_rp($app->configPath());') + ->toContain('$directory = \nativephp_rp($file->getPath());') + ->not->toContain(' realpath('); +}); + +it('adds getRealPath() to SplFileInfo without breaking it', function () { + $code = "getPathname()); }\n}\n"; + + $compacted = (new RealPathMod)->compact('/app/vendor/symfony/finder/SplFileInfo.php', $code); + + expect($compacted) + ->toContain('public function getRealPath(): string|false') + ->toContain('return \nativephp_rp($this->getPathname());'); + + exec('echo '.escapeshellarg($compacted).' | '.escapeshellarg(PHP_BINARY).' -l', $output, $status); + expect($status)->toBe(0); +}); + +it('leaves files that are not PHP alone', function () { + expect((new RealPathMod)->compact('/app/composer.json', '{"x": "realpath(y)"}'))->toBe('{"x": "realpath(y)"}'); +}); diff --git a/tests/Unit/SignCommandTest.php b/tests/Unit/SignCommandTest.php new file mode 100644 index 0000000..8cd3429 --- /dev/null +++ b/tests/Unit/SignCommandTest.php @@ -0,0 +1,149 @@ +dir = sys_get_temp_dir().'/parcel-sign-'.uniqid(); + mkdir($this->dir); + $this->bundle = $this->dir.'/__nativephp_app_bundle.phar'; + file_put_contents($this->bundle, random_bytes(4096)); + + $key = openssl_pkey_new(['private_key_type' => OPENSSL_KEYTYPE_EC, 'curve_name' => 'prime256v1']); + openssl_pkey_export($key, $this->privateKey); + + $this->previousEnv = array_map(fn ($name) => getenv($name), array_combine(SIGNING_ENV, SIGNING_ENV)); + + foreach (SIGNING_ENV as $name) { + putenv($name); + } +}); + +afterEach(function () { + foreach ($this->previousEnv as $name => $value) { + $value === false ? putenv($name) : putenv("{$name}={$value}"); + } + + if (isset($this->server)) { + $this->server->stop(); + } + + exec('rm -rf '.escapeshellarg($this->dir)); +}); + +function sign(string $bundle, array $options = []): CommandTester +{ + $tester = new CommandTester((new Application)->find('sign')); + $tester->execute(['bundle' => $bundle, '--project' => 'project-uuid', ...$options]); + + return $tester; +} + +function signatureVerifies(string $bundle, string $project = 'project-uuid'): bool +{ + $signed = json_decode(file_get_contents($bundle.'.sig'), true); + $keys = json_decode(file_get_contents(dirname($bundle).'/keys.json'), true); + $message = SignCommand::message($project, hash_file('sha256', $bundle), filesize($bundle)); + + return SignCommand::verify($message, $signed['signature'], $keys[$signed['key_id']]); +} + +function startSigningServer(object $test, array $env): string +{ + $port = random_int(20000, 40000); + $test->server = new Process( + [PHP_BINARY, '-S', "127.0.0.1:{$port}", __DIR__.'/../Fixtures/signing-server.php'], + null, + $env, + ); + $test->server->start(); + $test->server->waitUntil(fn ($type, $output) => str_contains($output, 'started')); + + return "http://127.0.0.1:{$port}/sign"; +} + +it('signs with a local P-256 key, bound to the project', function () { + putenv('PARCEL_SIGNING_KEY='.$this->privateKey); + putenv('PARCEL_SIGNING_KEY_ID=dev-1'); + + $tester = sign($this->bundle, ['--public-key-output' => $this->dir.'/keys.json']); + + expect($tester->getStatusCode())->toBe(0) + ->and(json_decode(file_get_contents($this->bundle.'.sig'), true)['key_id'])->toBe('dev-1') + ->and(signatureVerifies($this->bundle))->toBeTrue() + ->and(signatureVerifies($this->bundle, 'another-project'))->toBeFalse(); +}); + +it('accepts the key base64 encoded', function () { + putenv('PARCEL_SIGNING_KEY='.base64_encode($this->privateKey)); + + expect(sign($this->bundle, ['--public-key-output' => $this->dir.'/keys.json'])->getStatusCode())->toBe(0) + ->and(signatureVerifies($this->bundle))->toBeTrue(); +}); + +it('no longer verifies once the bundle changes', function () { + putenv('PARCEL_SIGNING_KEY='.$this->privateKey); + sign($this->bundle, ['--public-key-output' => $this->dir.'/keys.json']); + + $bytes = file_get_contents($this->bundle); + $bytes[100] = chr(ord($bytes[100]) ^ 1); + file_put_contents($this->bundle, $bytes); + + expect(signatureVerifies($this->bundle))->toBeFalse(); +}); + +it('has Bifrost sign it when given a signing URL, sending only the hash', function () { + putenv('PARCEL_SIGNING_URL='.startSigningServer($this, ['FIXTURE_TOKEN' => 'build-token', 'FIXTURE_KEY' => $this->privateKey])); + putenv('PARCEL_SIGNING_TOKEN=build-token'); + + $tester = sign($this->bundle, ['--public-key-output' => $this->dir.'/keys.json']); + + expect($tester->getStatusCode())->toBe(0, $tester->getDisplay()) + ->and(json_decode(file_get_contents($this->bundle.'.sig'), true)['key_id'])->toBe('bifrost-test') + ->and(signatureVerifies($this->bundle))->toBeTrue(); +}); + +it('refuses what a signing service returns when it does not match the bundle', function () { + putenv('PARCEL_SIGNING_URL='.startSigningServer($this, ['FIXTURE_TOKEN' => 'build-token', 'FIXTURE_KEY' => $this->privateKey, 'FIXTURE_LIE' => '1'])); + putenv('PARCEL_SIGNING_TOKEN=build-token'); + + expect(sign($this->bundle)->getStatusCode())->toBe(1) + ->and($this->bundle.'.sig')->not->toBeFile(); +}); + +it('fails when the signing service turns the token away', function () { + putenv('PARCEL_SIGNING_URL='.startSigningServer($this, ['FIXTURE_TOKEN' => 'build-token', 'FIXTURE_KEY' => $this->privateKey])); + putenv('PARCEL_SIGNING_TOKEN=wrong'); + + $tester = sign($this->bundle); + + expect($tester->getStatusCode())->toBe(1) + ->and($tester->getDisplay())->toContain('HTTP 401') + ->and($this->bundle.'.sig')->not->toBeFile(); +}); + +it('refuses to sign without a key', function () { + expect(sign($this->bundle)->getStatusCode())->toBe(1) + ->and($this->bundle.'.sig')->not->toBeFile(); +}); + +it('refuses a key that is not P-256', function () { + $rsa = openssl_pkey_new(['private_key_type' => OPENSSL_KEYTYPE_RSA, 'private_key_bits' => 2048]); + openssl_pkey_export($rsa, $pem); + putenv('PARCEL_SIGNING_KEY='.$pem); + + expect(sign($this->bundle)->getStatusCode())->toBe(1); +}); + +it('refuses to sign without a project', function () { + putenv('PARCEL_SIGNING_KEY='.$this->privateKey); + + $tester = new CommandTester((new Application)->find('sign')); + $tester->execute(['bundle' => $this->bundle]); + + expect($tester->getStatusCode())->toBe(1); +});