}> */ private array $asked = []; /** @var \Closure(string, string, ?string): (array{0: int, 1: mixed}|\Throwable) */ private \Closure $answer; /** @var list */ private array $opened = []; /** @var list */ private array $kept = []; private bool $browserOpens = true; protected function setUp(): void { $this->answer = fn (string $method, string $url, ?string $body): array => [500, ['error' => ['message' => 'unexpected']]]; } private function account(string $refresh = '', string $clientId = 'client123'): SpotifyAccount { $request = function (string $method, string $url, ?string $body, array $headers): Task { $this->asked[] = ['method' => $method, 'url' => $url, 'body' => $body, 'headers' => $headers]; $answer = ($this->answer)($method, $url, $body); $task = new Task(); if ($answer instanceof \Throwable) { $task->settle(null, $answer); } else { $task->settle(new HttpResponse($answer[0], is_string($answer[1]) ? $answer[1] : (string)json_encode($answer[1]))); } return $task; }; $browser = function (string $url): bool { $this->opened[] = $url; return $this->browserOpens; }; return new SpotifyAccount($clientId, $request, $browser, $refresh, function (string $refresh): void { $this->kept[] = $refresh; }); } /** @return mixed what the task settled with (it settles at once: the fake answers at once) */ private static function value(Task $task): mixed { self::assertTrue($task->isDone(), 'settled'); return $task->result(); } /** @return list the addresses asked, "METHOD url" */ private function urls(): array { return array_map(fn (array $a) => $a['method'] . ' ' . $a['url'], $this->asked); } private static function tokens(int $expires = 3600, string $refresh = 'ref'): array { return [200, ['access_token' => 'tok', 'expires_in' => $expires, 'refresh_token' => $refresh]]; } /** Logs in when the port 8888 is free, else skips the test. */ private function loginOrSkip(SpotifyAccount $account): void { $probe = @stream_socket_server('tcp://127.0.0.1:' . SpotifyAccount::PORT); if ($probe === false) { self::markTestSkipped('the port 8888 is taken on this computer'); } fclose($probe); self::assertTrue($account->login()); } /** The browser (or any page) sent to the redirect: what it shows. */ private function browserBack(SpotifyAccount $account, string $path): string { $browser = stream_socket_client('tcp://127.0.0.1:' . SpotifyAccount::PORT, $no, $why, 2); self::assertIsResource($browser, $why); fwrite($browser, "GET $path HTTP/1.1\r\nHost: 127.0.0.1:8888\r\n\r\n"); for ($i = 0; $i < 100; $i++) { $account->poll(); $read = [$browser]; $none = null; if (stream_select($read, $none, $none, 0, 20_000) > 0) { break; } } stream_set_timeout($browser, 2); $page = (string)stream_get_contents($browser); fclose($browser); return $page; } private function state(SpotifyAccount $account): string { return (string)(new \ReflectionProperty($account, 'expected'))->getValue($account); } public function testWithoutAClientIdTheLoginSaysWhatToDo(): void { $account = $this->account('', ''); self::assertFalse($account->login()); self::assertSame('error', $account->state); self::assertStringContainsString('Client ID', $account->error); self::assertSame([], $this->opened); } public function testTheLoginOpensSpotifysPageWithPkceThenTheCodeBecomesATokenKept(): void { $this->answer = fn (string $method, string $url, ?string $body): array => self::tokens(); $account = $this->account(); $this->loginOrSkip($account); try { self::assertSame('waiting', $account->state); self::assertCount(1, $this->opened); parse_str((string)parse_url($this->opened[0], PHP_URL_QUERY), $q); self::assertStringStartsWith('https://accounts.spotify.com/authorize?', $this->opened[0]); self::assertSame(['client123', 'code', SpotifyAccount::REDIRECT, 'S256'], [$q['client_id'], $q['response_type'], $q['redirect_uri'], $q['code_challenge_method']]); self::assertSame($this->state($account), $q['state']); self::assertStringNotContainsString('=', (string)$q['code_challenge'], 'base64url without padding'); // a favicon first: answered, still listening $this->browserBack($account, '/favicon.ico'); self::assertSame('waiting', $account->state); $page = $this->browserBack($account, '/callback?code=CODE&state=' . $q['state']); self::assertStringContainsString('vous pouvez fermer cet onglet', $page); self::assertTrue($account->connected()); self::assertSame(['ref'], $this->kept, 'the refresh token kept in the settings'); self::assertCount(1, $this->asked); parse_str((string)$this->asked[0]['body'], $form); self::assertSame('authorization_code', $form['grant_type']); self::assertSame('CODE', $form['code']); self::assertSame('client123', $form['client_id']); self::assertArrayNotHasKey('client_secret', $form); $challenge = rtrim(strtr(base64_encode(hash('sha256', (string)$form['code_verifier'], true)), '+/', '-_'), '='); self::assertSame($q['code_challenge'], $challenge, 'the verifier proves the challenge'); self::assertFalse(@stream_socket_client('tcp://127.0.0.1:' . SpotifyAccount::PORT, $no, $why, 0.5), 'no longer listening'); } finally { $account->logout(); } self::assertSame('', $account->state); self::assertSame('', end($this->kept), 'logged out: forgotten'); } public function testACallbackWithAnotherStateIsIgnoredAndTheLoginGoesOn(): void { // any web page open meanwhile can call the redirect: it must neither connect nor stop the login $this->answer = fn (string $method, string $url, ?string $body): array => self::tokens(); $account = $this->account(); $this->loginOrSkip($account); try { $state = $this->state($account); foreach (['/callback?code=CODE&state=forged', '/callback?error=access_denied', '/callback?error=x&state=' . substr($state, 0, -1), '/callback?code[]=a&state[]=b', '/callback?code=CODE'] as $path) { $page = $this->browserBack($account, $path); self::assertStringContainsString('connexion refusée', $page, $path); self::assertSame('waiting', $account->state, "$path: still waiting"); self::assertSame([], $this->asked, "$path: no token asked for a code of someone else"); } $this->browserBack($account, '/callback?code=GOOD&state=' . $state); self::assertTrue($account->connected()); parse_str((string)$this->asked[0]['body'], $form); self::assertSame('GOOD', $form['code']); } finally { $account->logout(); } } public function testTheUserRefusingOnSpotifysPageEndsTheLogin(): void { $account = $this->account(); $this->loginOrSkip($account); try { $page = $this->browserBack($account, '/callback?error=access_denied&state=' . $this->state($account)); self::assertStringContainsString('access_denied', $page); self::assertSame('error', $account->state); self::assertStringContainsString('access_denied', $account->error); self::assertSame([], $this->asked); } finally { $account->logout(); } } public function testABrowserThatDoesNotOpenGivesTheAddressToOpen(): void { $this->browserOpens = false; $account = $this->account(); $this->loginOrSkip($account); $account->logout(); self::assertStringContainsString('https://accounts.spotify.com/authorize?', $this->opened[0]); } public function testNoAnswerInFiveMinutesStopsWaiting(): void { $account = $this->account(); $this->loginOrSkip($account); (new \ReflectionProperty($account, 'waitingSince'))->setValue($account, microtime(true) - 301); $account->poll(); self::assertSame('error', $account->state); self::assertStringContainsString('5 minutes', $account->error); $again = @stream_socket_server('tcp://127.0.0.1:' . SpotifyAccount::PORT); self::assertNotFalse($again, 'the port given back'); fclose($again); } public function testTheRefreshTokenGivesATokenUsedUntilItIsOld(): void { $this->answer = fn (string $method, string $url, ?string $body): array => match (true) { str_contains($url, '/api/token') => self::tokens(3600, 'newref'), default => [200, ['items' => [], 'next' => null]], }; $account = $this->account('oldref'); self::assertTrue($account->connected(), 'a refresh token kept: connected'); self::assertSame([['id' => 'liked', 'name' => 'Titres likés', 'count' => 0]], self::value($account->playlists())); self::assertSame(['POST https://accounts.spotify.com/api/token', 'GET https://api.spotify.com/v1/me/playlists?limit=50'], $this->urls()); parse_str((string)$this->asked[0]['body'], $form); self::assertSame(['refresh_token', 'oldref', 'client123'], [$form['grant_type'], $form['refresh_token'], $form['client_id']]); self::assertSame('Bearer tok', $this->asked[1]['headers']['Authorization']); self::assertSame(['newref'], $this->kept, 'Spotify may give a new refresh token: kept'); self::assertSame('newref', $account->refresh); self::value($account->playlists()); self::assertCount(3, $this->asked, 'the token still young: no new one'); (new \ReflectionProperty($account, 'until'))->setValue($account, microtime(true) - 1); self::value($account->playlists()); self::assertSame('POST https://accounts.spotify.com/api/token', $this->urls()[3], 'old: renewed first'); } public function testEveryPageOfAListIsReadFollowingNext(): void { $this->answer = fn (string $method, string $url, ?string $body): array => match (true) { str_contains($url, '/api/token') => self::tokens(), str_contains($url, 'offset=50') => [200, ['items' => [['id' => 'p3', 'name' => 'Trois', 'items' => ['total' => 7]]], 'next' => null]], str_contains($url, '/me/playlists') => [200, ['items' => [['id' => 'p1', 'name' => 'Un', 'tracks' => ['total' => 2]], 'pas une playlist', ['id' => 'p2', 'name' => 'Deux']], 'next' => 'https://api.spotify.com/v1/me/playlists?offset=50&limit=50']], default => [500, []], }; $lists = self::value($this->account('ref')->playlists()); self::assertSame([['liked', 'Titres likés', 0], ['p1', 'Un', 2], ['p2', 'Deux', 0], ['p3', 'Trois', 7]], array_map(fn (array $l) => [$l['id'], $l['name'], $l['count']], $lists)); } public function testThePlaylistsOldAddressRefusedTheNewOneIsUsedAndThePodcastsLeftOut(): void { foreach ([403, 404, 410] as $status) { $this->asked = []; $this->answer = fn (string $method, string $url, ?string $body): array => match (true) { str_contains($url, '/api/token') => self::tokens(), str_contains($url, '/playlists/p%201/tracks') => [$status, ['error' => ['status' => $status, 'message' => 'gone']]], str_contains($url, '/playlists/p%201/items') && !str_contains($url, 'offset') => [200, ['items' => [ ['track' => ['type' => 'track', 'name' => 'Mistral gagnant', 'artists' => [['name' => 'Renaud']]]], ['track' => ['type' => 'episode', 'name' => 'Un podcast']], ['track' => null], ['item' => ['type' => 'track', 'name' => 'Ella, elle l\'a', 'artists' => [['name' => 'France Gall'], ['name' => 'X, Y']]]], ], 'next' => 'https://api.spotify.com/v1/playlists/p%201/items?offset=50']], str_contains($url, 'offset=50') => [200, ['items' => [['track' => ['name' => 'Sans artiste']]], 'next' => null]], default => [500, []], }; $songs = self::value($this->account('ref')->songs('p 1')); self::assertSame([ ['title' => 'Renaud - Mistral gagnant', 'url' => 'ytsearch1:Renaud Mistral gagnant'], ['title' => 'France Gall, X, Y - Ella, elle l\'a', 'url' => 'ytsearch1:France Gall X Y Ella, elle l\'a'], ['title' => 'Sans artiste', 'url' => 'ytsearch1: Sans artiste'], ], $songs, "HTTP $status"); } } public function testTheLikedSongsHaveNoOtherAddress(): void { $this->answer = fn (string $method, string $url, ?string $body): array => match (true) { str_contains($url, '/api/token') => self::tokens(), default => [404, ['error' => ['status' => 404, 'message' => 'Not found']]], }; $account = $this->account('ref'); self::assertSame([], self::value($account->songs('liked'))); self::assertSame(['POST https://accounts.spotify.com/api/token', 'GET https://api.spotify.com/v1/me/tracks?limit=50'], $this->urls()); self::assertSame('Spotify : HTTP 404 (Not found)', $account->error); self::assertTrue($account->connected(), 'one error does not disconnect'); } public function testAnAnswerThatIsNotJsonOrNoAnswerAtAllIsAnErrorNotACrash(): void { foreach (['token' => true, 'list' => false] as $where => $tokenBroken) { $this->answer = fn (string $method, string $url, ?string $body): array => match (true) { str_contains($url, '/api/token') => $tokenBroken ? [502, 'Bad gateway'] : self::tokens(), default => [200, 'maintenance'], }; $account = $this->account('ref'); self::assertSame([], self::value($account->songs('p1')), $where); self::assertStringContainsString($tokenBroken ? 'HTTP 502' : 'Spotify', $account->error, $where); } $this->answer = fn (string $method, string $url, ?string $body): \Throwable => new \RuntimeException('no network'); $account = $this->account('ref'); self::assertSame([], self::value($account->playlists())); self::assertSame('Spotify injoignable : no network', $account->error); $this->answer = fn (string $method, string $url, ?string $body): array|\Throwable => str_contains($url, '/api/token') ? self::tokens() : new \RuntimeException('timeout'); $account = $this->account('ref'); self::assertSame([], self::value($account->playlists())); self::assertSame('Spotify injoignable : timeout', $account->error); } public function testARefreshTokenRevokedByTheUserAsksToLogInAgain(): void { $this->answer = fn (string $method, string $url, ?string $body): array => [400, ['error' => 'invalid_grant', 'error_description' => 'Refresh token revoked']]; $account = $this->account('revoked'); self::assertSame([], self::value($account->playlists())); self::assertStringContainsString('Refresh token revoked', $account->error); self::assertFalse($account->connected(), 'no longer shown as connected'); self::assertSame('', $account->refresh); self::assertSame([''], $this->kept, 'forgotten in the settings'); self::assertSame([], self::value($account->playlists())); self::assertCount(1, $this->asked, 'not asked again and again'); } public function testWithoutAnyTokenNothingIsAsked(): void { $account = $this->account(); self::assertSame([], self::value($account->playlists())); self::assertSame([], $this->asked); self::assertSame('connectez-vous à Spotify', $account->error); } }