<?phpnamespace Tests;use App\Core\AutoUpdate;use JumPHP\Http\Http;use PHPUnit\Framework\TestCase;/** The phone app finds its new APK in the signed update.json, downloads it, checks it and gives it to Android. */final class AndroidUpdateTest extends TestCase{ private const SHA = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'; private string $dir = ''; protected function setUp(): void { $this->dir = sys_get_temp_dir() . '/wz-apk-' . getmypid() . '-' . bin2hex(random_bytes(4)); mkdir($this->dir, 0700, true); } protected function tearDown(): void { exec('rm -rf ' . escapeshellarg($this->dir)); putenv('JUMPHP_ANDROID_VERSION_NAME'); putenv('JUMPHP_ANDROID_VERSION_CODE'); } private static function key(): \OpenSSLAsymmetricKey { $key = openssl_pkey_new(['private_key_type' => OPENSSL_KEYTYPE_EC, 'curve_name' => 'prime256v1']); self::assertNotFalse($key); return $key; } private static function http(): Http { return (new \ReflectionClass(Http::class))->newInstanceWithoutConstructor(); // never used by offer() / parse() } private function phone(\OpenSSLAsymmetricKey $key, string $version = '1.0.0', int $code = 9): AutoUpdate { return new AutoUpdate(self::http(), 'https://example.org/update.json', $version, 'winzik', (string)openssl_pkey_get_details($key)['key'], null, $this->dir . '/update', $code); } /** @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)]); } /** @return array<string, mixed> an update.json of 1.0.1: the computers' executables and the phone's APK */ private static function release(string $apkUrl = 'https://example.org/WinZik-android-1.0.1.apk', string $sha = self::SHA, int $size = 1234, int $code = 10): array { return ['id' => 'winzik', 'version' => '1.0.1', 'notes' => 'Les nouveautés', 'platforms' => [ 'linux-x86_64' => ['url' => 'https://example.org/winzik-linux-x86_64', 'sha256' => self::SHA, 'size' => 99], 'windows-x86_64' => ['url' => 'https://example.org/winzik-windows-x86_64.exe', 'sha256' => self::SHA, 'size' => 98], 'android' => ['url' => $apkUrl, 'sha256' => $sha, 'size' => $size, 'versionCode' => $code], ]]; } public function testThePhoneSeesTheNewerApkAndTheUiGetsItsVersionNotesAndSize(): void { $key = self::key(); $u = $this->phone($key); self::assertTrue($u->isPhone()); self::assertFalse($u->enabled(), 'not the desktop self-replacement: the splash and the song do not wait for it'); self::assertNull($u->androidUpdate()); $u->offer(self::signedJson(self::release(), $key)); self::assertSame('available', $u->state); self::assertSame(['version' => '1.0.1', 'notes' => 'Les nouveautés', 'size' => 1234, 'state' => 'available', 'progress' => 0.0, 'error' => '', 'phase' => 'available'], $u->androidUpdate()); self::assertStringEndsWith('/update/WinZik-android-1.0.1-10.apk', $u->apkPath()); } public function testAnOlderOrTheSameVersionIsIgnored(): void { $key = self::key(); // the same versionCode (the app installed is that one), then an older one foreach ([9, 8] as $code) { $u = $this->phone($key); $u->offer(self::signedJson(self::release(code: $code), $key)); self::assertSame('latest', $u->state, "versionCode $code"); self::assertNull($u->androidUpdate()); } // versionCode unknown (an engine that does not say it): the names, as on a computer $u = $this->phone($key, '1.0.1', 0); $u->offer(self::signedJson(self::release(), $key)); self::assertSame('latest', $u->state, 'the same name'); $u = $this->phone($key, '1.0.0', 0); $u->offer(self::signedJson(self::release(), $key)); self::assertSame('available', $u->state, 'a newer name'); // a release without an APK: nothing for the phone $release = self::release(); unset($release['platforms']['android']); $u = $this->phone($key); $u->offer(self::signedJson($release, $key)); self::assertSame('latest', $u->state); } public function testAnUpdateJsonSignedByAnotherKeyIsRefusedInFrench(): void { $u = $this->phone(self::key()); $u->offer(self::signedJson(self::release(), self::key())); self::assertSame('error', $u->state); self::assertStringContainsString('mauvaise signature', $u->error); self::assertNull($u->androidUpdate()); } public function testTheComputersStillReadTheirOwnFileAndIgnoreTheApk(): void { $key = self::key(); $desktop = new AutoUpdate(self::http(), 'https://example.org/update.json', '1.0.0', 'winzik', (string)openssl_pkey_get_details($key)['key'], '/opt/winzik/WinZik'); self::assertTrue($desktop->enabled()); self::assertFalse($desktop->isPhone()); $json = self::signedJson(self::release(), $key); self::assertSame(['url' => 'https://example.org/winzik-linux-x86_64', 'sha256' => self::SHA, 'size' => 99], $desktop->parse($json, 'linux-x86_64')); self::assertSame(['url' => 'https://example.org/winzik-windows-x86_64.exe', 'sha256' => self::SHA, 'size' => 98], $desktop->parse($json, 'windows-x86_64')); self::assertNull($desktop->androidUpdate(), 'a computer has no APK to offer'); self::assertFalse($desktop->installAndroidUpdate()); } public function testTheVersionOfTheApkComesFromTheEngine(): void { putenv('JUMPHP_ANDROID_VERSION_NAME=1.0.1'); putenv('JUMPHP_ANDROID_VERSION_CODE=10'); $key = self::key(); $u = AutoUpdate::phone(self::http(), 'https://example.org/update.json', '0.0.1', 'winzik', (string)openssl_pkey_get_details($key)['key'], $this->dir); $u->offer(self::signedJson(self::release(), $key)); self::assertSame('latest', $u->state, 'the APK installed is already versionCode 10'); $u = AutoUpdate::phone(self::http(), '', '0.0.1', 'winzik', (string)openssl_pkey_get_details($key)['key'], $this->dir); self::assertFalse($u->isPhone(), 'no address: off'); } /** the APK the test server sends (tests/fixtures/download-server.php /file.bin) */ private static function served(): string { $bytes = ''; for ($i = 0; $i < 20; $i++) { $bytes .= str_repeat(chr(65 + $i), 50000); } return $bytes; } /** @param \Closure(int): void $test the test, given the server's port */ private function withServer(\Closure $test): 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); $test($port); } finally { proc_terminate($server); proc_close($server); } } private static function poll(AutoUpdate $u): void { $until = microtime(true) + 15; while ($u->state === 'downloading' && microtime(true) < $until) { $u->poll(); usleep(5000); } } public function testTheApkIsDownloadedCheckedThenGivenToAndroid(): void { $this->withServer(function (int $port): void { $key = self::key(); $u = $this->phone($key); $given = []; $u->installer = function (string $path) use (&$given): bool { $given[] = $path; return true; }; $apk = self::served(); $u->offer(self::signedJson(self::release("http://127.0.0.1:$port/file.bin", hash('sha256', $apk), strlen($apk)), $key)); self::assertTrue($u->installAndroidUpdate()); self::assertSame('downloading', $u->state); self::assertFalse($u->installAndroidUpdate(), 'once'); self::poll($u); self::assertSame('opened', $u->state, $u->error); self::assertSame([$u->apkPath()], $given, "Android's installer gets the file checked"); self::assertSame(1.0, $u->androidUpdate()['progress'] ?? null); // the installer closed without installing: asked again, the same file at once (no download) self::assertTrue($u->installAndroidUpdate()); self::assertSame('opened', $u->state); self::assertCount(2, $given); }); } public function testAnApkWhoseSha256IsNotTheSignedOneIsNeverInstalled(): void { $this->withServer(function (int $port): void { $key = self::key(); $u = $this->phone($key); $given = 0; $u->installer = function () use (&$given): bool { $given++; return true; }; $apk = self::served(); $u->offer(self::signedJson(self::release("http://127.0.0.1:$port/file.bin", self::SHA, strlen($apk)), $key)); $u->installAndroidUpdate(); self::poll($u); self::assertSame('error', $u->state); self::assertStringContainsString("n'est pas la bonne", $u->error); self::assertSame(0, $given, 'never given to Android'); self::assertFileDoesNotExist($u->apkPath(), 'removed'); self::assertSame($u->error, $u->androidUpdate()['error'] ?? null, 'the UI shows why'); }); } public function testAppReleaseSignsTheApkEntryOfARelease(): void { $script = dirname(__DIR__, 3) . '/tools/app-release.php'; if (!is_file($script)) { self::markTestSkipped('JumPHP\'s tools/ are not here'); } $app = $this->dir . '/app'; mkdir("$app/config", 0700, true); mkdir("$app/dist/standalone", 0700, true); file_put_contents("$app/config/project.yaml", "project:\n id: winzik\n version: 1.0.1\n"); file_put_contents("$app/dist/standalone/winzik-linux-x86_64", 'linux'); file_put_contents("$this->dir/WinZik-android-1.0.1.apk", 'the apk'); exec(implode(' ', array_map('escapeshellarg', [PHP_BINARY, $script, $app, "$this->dir/key.pem", 'https://example.org/v1.0.1', 'notes', 'linux-x86_64,windows-x86_64', "android=$this->dir/WinZik-android-1.0.1.apk;versionCode=10"])) . ' 2>/dev/null', $out, $status); self::assertSame(0, $status, implode("\n", $out)); $json = (string)file_get_contents("$app/dist/standalone/update.json"); $u = new AutoUpdate(self::http(), 'https://example.org/update.json', '1.0.0', 'winzik', (string)file_get_contents("$app/config/update.pub"), null, "$this->dir/update", 9); $u->offer($json); self::assertSame('available', $u->state, $u->error); self::assertSame(7, $u->androidUpdate()['size'] ?? null); self::assertSame(['url' => 'https://example.org/v1.0.1/WinZik-android-1.0.1.apk', 'sha256' => hash('sha256', 'the apk'), 'size' => 7, 'versionCode' => 10], $u->parse($json, AutoUpdate::ANDROID)); $desktop = new AutoUpdate(self::http(), 'https://example.org/update.json', '1.0.0', 'winzik', (string)file_get_contents("$app/config/update.pub"), '/opt/WinZik'); self::assertSame('https://example.org/v1.0.1/winzik-linux-x86_64', $desktop->parse($json, 'linux-x86_64')['url'] ?? null); } // the phone updates itself (option autoUpdate), as a computer -------------------------------------------------- /** * A phone updater with fake Android parts: the network, the moment, the session and what it became. * @param array<string, mixed> $android network, moment, session (what installSilently answers), state (installState) * @param list<string> $log what happened, in order */ private function autoPhone(\OpenSSLAsymmetricKey $key, array &$android, array &$log): AutoUpdate { $u = $this->phone($key); $u->network = function () use (&$android): ?string { return $android['network']; }; $u->goodMoment = function () use (&$android): bool { return $android['moment']; }; $u->beforeInstall = function () use (&$log): void { $log[] = 'saved'; }; $u->sessionInstaller = function (string $path) use (&$android, &$log): string { $log[] = 'session ' . basename($path); return $android['session']; }; $u->installState = function () use (&$android): array { return $android['state']; }; $u->installer = function (string $path) use (&$log): bool { $log[] = 'screen ' . basename($path); return true; }; return $u; } private static function tickUntil(AutoUpdate $u, string $state, bool $auto = true): void { $until = microtime(true) + 15; while ($u->state !== $state && microtime(true) < $until) { $u->tick(0.016, $auto); $u->poll(); usleep(5000); } } public function testWithTheOptionOnTheApkComesOnWifiAndGoesInBetweenTwoSongsWithoutTheUser(): void { $this->withServer(function (int $port): void { $key = self::key(); $android = ['network' => 'unmetered', 'moment' => false, 'session' => 'started', 'state' => ['state' => 'installing', 'message' => '', 'status' => 0]]; $log = []; $u = $this->autoPhone($key, $android, $log); $apk = self::served(); $u->offer(self::signedJson(self::release("http://127.0.0.1:$port/file.bin", hash('sha256', $apk), strlen($apk)), $key)); self::assertSame('available', $u->state); $u->tick(0.016, true); self::assertSame('downloading', $u->state, 'on Wi-Fi the download starts by itself'); self::tickUntil($u, 'ready'); self::assertSame('ready', $u->state, $u->error); self::assertSame(hash('sha256', $apk), hash_file('sha256', $u->apkPath()), 'the file checked against the signed update.json'); // a song plays: it waits for ($i = 0; $i < 30; $i++) { $u->tick(0.016, true); } self::assertSame('ready', $u->state, 'never in the middle of a song'); self::assertSame([], $log); self::assertSame('opened', $u->androidUpdate()['state'] ?? null, 'the UI: downloaded, its button installs now'); self::assertSame('ready', $u->androidUpdate()['phase'] ?? null); // the next song starts (or the user pauses): saved, then the session $android['moment'] = true; $u->tick(0.016, true); self::assertSame('installing', $u->state); self::assertSame(['saved', 'session ' . basename($u->apkPath())], $log, 'the song and its position saved before Android stops the app'); $u->tick(0.016, true); self::assertSame('installing', $u->state, 'Android stops the app and installs: nothing else'); }); } public function testOnMobileDataOrWithoutTheOptionNothingIsDownloadedByItself(): void { $key = self::key(); foreach ([['metered', true], ['none', true], ['unmetered', false]] as [$network, $auto]) { $android = ['network' => $network, 'moment' => true, 'session' => 'started', 'state' => ['state' => '', 'message' => '', 'status' => 0]]; $log = []; $u = $this->autoPhone($key, $android, $log); $u->offer(self::signedJson(self::release(), $key)); for ($i = 0; $i < 10; $i++) { $u->tick(0.016, $auto); } self::assertSame('available', $u->state, "$network, option " . ($auto ? 'on' : 'off')); self::assertSame([], $log); } } public function testTheFirstTimeAndroidAsksOnceAndARefusalStopsTheAutomaticInstallButNotTheButton(): void { $this->withServer(function (int $port): void { $key = self::key(); $android = ['network' => 'unmetered', 'moment' => true, 'session' => 'started', 'state' => ['state' => 'installing', 'message' => '', 'status' => 0]]; $log = []; $u = $this->autoPhone($key, $android, $log); $apk = self::served(); $u->offer(self::signedJson(self::release("http://127.0.0.1:$port/file.bin", hash('sha256', $apk), strlen($apk)), $key)); self::tickUntil($u, 'installing'); self::assertSame('installing', $u->state, $u->error); // WinZik is not yet its own installer of record: Android shows its confirmation $android['state'] = ['state' => 'confirm', 'message' => '', 'status' => -1]; $u->tick(0.016, true); self::assertSame('confirm', $u->state); // the user says no $android['state'] = ['state' => 'failed', 'message' => 'INSTALL_FAILED_ABORTED: User rejected permissions', 'status' => 3]; $u->tick(0.016, true); self::assertSame('error', $u->state); self::assertStringContainsString('annulée', $u->error); $u->offer(self::signedJson(self::release("http://127.0.0.1:$port/file.bin", hash('sha256', $apk), strlen($apk)), $key)); $log = []; for ($i = 0; $i < 20; $i++) { $u->tick(0.016, true); } self::assertSame('available', $u->state, 'the next check offers it again, but nothing installs by itself'); self::assertSame([], $log); // the button: at once (the file is already there and right), whatever the moment $android['moment'] = false; $android['state'] = ['state' => 'installing', 'message' => '', 'status' => 0]; self::assertTrue($u->installAndroidUpdate()); self::assertSame('installing', $u->state); self::assertSame(['saved', 'session ' . basename($u->apkPath())], $log); self::assertFalse($u->installAndroidUpdate(), 'not twice'); }); } public function testAFailedInstallIsSaidInFrenchAndAnEngineWithoutSessionsOpensTheInstallerScreen(): void { $key = self::key(); $android = ['network' => 'unmetered', 'moment' => true, 'session' => 'started', 'state' => ['state' => 'failed', 'message' => 'INSTALL_FAILED_UPDATE_INCOMPATIBLE', 'status' => 1]]; $log = []; $u = $this->autoPhone($key, $android, $log); $bytes = 'an apk'; $u->offer(self::signedJson(self::release(sha: hash('sha256', $bytes), size: strlen($bytes)), $key)); mkdir(dirname($u->apkPath()), 0700, true); file_put_contents($u->apkPath(), $bytes); $u->tick(0.016, true); self::assertSame('ready', $u->state, 'already downloaded and right: no download'); $u->tick(0.016, true); self::assertSame('installing', $u->state); $u->tick(0.016, true); self::assertSame('error', $u->state); self::assertStringContainsString("Android n'a pas installé la mise à jour (INSTALL_FAILED_UPDATE_INCOMPATIBLE)", $u->error); // an engine without sessions (an older app): the installer's screen, as before $android['session'] = 'unsupported'; $log = []; self::assertTrue($u->installAndroidUpdate()); self::assertSame('opened', $u->state); self::assertSame(['saved', 'session ' . basename($u->apkPath()), 'screen ' . basename($u->apkPath())], $log); } public function testOnceUpToDateTheApkOfTheUpdateIsRemoved(): void { $key = self::key(); $u = $this->phone($key, '1.0.1', 10); mkdir($this->dir . '/update', 0700, true); file_put_contents($this->dir . '/update/WinZik-android-1.0.1-10.apk', 'installed now'); $u->offer(self::signedJson(self::release(), $key)); self::assertSame('latest', $u->state); self::assertFileDoesNotExist($this->dir . '/update/WinZik-android-1.0.1-10.apk'); }}