FR
apps/winzik / tests / SecurityTest.php · commit 6576d6f
<?phpnamespace Tests;use App\Core\AutoUpdate;use App\Media\FileDownload;use App\Media\Process;use App\Media\Tools;use App\Media\Transcriber;use App\Media\YouTube;use JumPHP\Http\Http;use PHPUnit\Framework\TestCase;/** What comes from outside (update.json, servers, addresses, Claude's answers) cannot make WinZik do what it should not. */final class SecurityTest extends TestCase{    /** @return array{0: AutoUpdate, 1: \OpenSSLAsymmetricKey} */    private function updater(string $current = '1.0.0'): array    {        $key = openssl_pkey_new(['private_key_type' => OPENSSL_KEYTYPE_EC, 'curve_name' => 'prime256v1']);        self::assertNotFalse($key);        $http = (new \ReflectionClass(Http::class))->newInstanceWithoutConstructor();     // parse() never uses it        $updater = new AutoUpdate($http, 'https://example.org/update.json', $current, 'winzik', (string)openssl_pkey_get_details($key)['key'], '/opt/winzik/WinZik');        return [$updater, $key];    }    /** @param array<string, mixed> $signed */    private static function signedJson(array $signed, \OpenSSLAsymmetricKey $key): string    {        $text = (string)json_encode($signed);        openssl_sign($text, $signature, $key, OPENSSL_ALGO_SHA256);        return (string)json_encode(['signed' => $text, 'signature' => base64_encode((string)$signature)]);    }    private const SHA = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';    public function testAnUpdateIsOnlyTakenSignedNewerAndWithItsSha256(): void    {        [$updater, $key] = $this->updater();        $file = ['url' => 'https://example.org/WinZik', 'sha256' => self::SHA, 'size' => 1234];        $good = ['id' => 'winzik', 'version' => '1.0.1', 'platforms' => ['linux-x86_64' => $file]];        self::assertSame($file, $updater->parse(self::signedJson($good, $key), 'linux-x86_64'));        self::assertSame('/opt/winzik/WinZik.download', $updater->downloadPath(), 'next to the program, not a guessable name of /tmp');        // the same with another key: refused before anything is downloaded        [, $other] = $this->updater();        try {            $updater->parse(self::signedJson($good, $other), 'linux-x86_64');            self::fail('another key accepted');        } catch (\RuntimeException $e) {            self::assertStringContainsString('signature', $e->getMessage());        }        // signed, then changed        $tampered = json_decode(self::signedJson($good, $key), true);        $tampered['signed'] = str_replace('example.org', 'evil.example', $tampered['signed']);        $this->expectRefused($updater, (string)json_encode($tampered));        // an older (or the same) version, even signed: nothing (no downgrade by an old update.json served again)        self::assertNull($updater->parse(self::signedJson(['version' => '0.9.99'] + $good, $key), 'linux-x86_64'));        self::assertNull($updater->parse(self::signedJson(['version' => '1.0.0'] + $good, $key), 'linux-x86_64'));        // another program's file        $this->expectRefused($updater, self::signedJson(['id' => 'other'] + $good, $key));        // no real SHA-256: never installed        $this->expectRefused($updater, self::signedJson(['platforms' => ['linux-x86_64' => ['sha256' => ''] + $file]] + $good, $key));    }    private function expectRefused(AutoUpdate $updater, string $json): void    {        try {            $updater->parse($json, 'linux-x86_64');            self::fail('accepted: ' . $json);        } catch (\RuntimeException) {            self::assertTrue(true);        }    }    public function testADownloadAddressWithLineEndsIsRefusedAtOnce(): void    {        $target = sys_get_temp_dir() . '/wz-sec-' . getmypid() . '.bin';        $d = new FileDownload("http://127.0.0.1:9/a HTTP/1.0\r\nX-Other: 1\r\n\r\nGET /b", $target);        self::assertTrue($d->poll());        self::assertFalse($d->ok());        self::assertStringContainsString('adresse invalide', $d->error);        self::assertFileDoesNotExist($target . '.part');    }    public function testADownloadBiggerThanAllowedStopsWithoutFillingTheDisk(): void    {        $port = 19000 + random_int(0, 999);        $server = proc_open([PHP_BINARY, '-S', "127.0.0.1:$port", __DIR__ . '/fixtures/download-server.php'], [1 => ['file', '/dev/null', 'w'], 2 => ['file', '/dev/null', 'w']], $pipes);        self::assertIsResource($server);        try {            usleep(400000);            $target = sys_get_temp_dir() . '/wz-sec-big-' . getmypid() . '.bin';            // 1 000 000 bytes said, 300 000 at most: refused on its length            $d = new FileDownload("http://127.0.0.1:$port/file.bin", $target, 0, 300000);            $until = microtime(true) + 10;            while (!$d->poll() && microtime(true) < $until) {                usleep(5000);            }            self::assertFalse($d->ok());            self::assertStringContainsString('trop gros', $d->error);            self::assertFileDoesNotExist($target);            self::assertFileDoesNotExist($target . '.part');            // its size known beforehand (update.json says 200 000): no byte more            $d = new FileDownload("http://127.0.0.1:$port/file.bin", $target, 200000);            $until = microtime(true) + 10;            while (!$d->poll() && microtime(true) < $until) {                usleep(5000);            }            self::assertFalse($d->ok());            self::assertFileDoesNotExist($target);        } finally {            proc_terminate($server);            proc_close($server);        }    }    public function testAnAddressStartingWithADashIsNeverAnOptionOfYtDlp(): void    {        $dir = sys_get_temp_dir() . '/wz-sec-yt-' . getmypid();        $tools = new Tools("$dir/bin", "$dir/tmp");        $tools->state = ['yt-dlp' => 'ready', 'ffmpeg' => 'ready'];        $tools->path = ['yt-dlp' => '/fake/yt-dlp', 'ffmpeg' => '/fake/ffmpeg'];        $commands = [];        $yt = new YouTube($tools, "$dir/logs", function (array $cmd) use (&$commands): Process {            $commands[] = $cmd;            return Process::finished($cmd, [], 1);        }, "$dir/music", "$dir/videos");        $yt->download(['id' => 'x', 'title' => 'x', 'url' => '--exec=touch /tmp/pwned'], 'mp3');        $cmd = $commands[0] ?? [];        self::assertSame('--exec=touch /tmp/pwned', end($cmd));        self::assertSame('--', $cmd[count($cmd) - 2], 'after "--": an address, whatever it starts with');        Tools::remove($dir);    }    public function testClaudesSourcesAreOnlyHttpsAddressesOfTheInternet(): void    {        self::assertSame(['url:https://example.org/a.lrc'], Transcriber::sources("URL:https://example.org/a.lrc"));        foreach (['http://example.org/a.lrc', 'https://localhost/a.lrc', 'https://127.0.0.1/a', 'https://192.168.1.1/a', 'https://[::1]/a',            'https://10.0.0.2:8080/a', 'https://router/a', 'https://0x7f.1/a', 'https://user:[email protected]/a', 'https://nas.local/a'] as $url) {            self::assertSame([], Transcriber::sources("URL:$url"), $url);            self::assertFalse(Transcriber::publicUrl($url), $url);        }        self::assertTrue(Transcriber::publicUrl('https://raw.githubusercontent.com/a/b/song.lrc'));    }}