IT
apps/winzik / tests / Cloud / FakeCloudServer.php · commit 6576d6f
<?phpnamespace Tests\Cloud;use JumPHP\Async\Task;use JumPHP\Http\HttpError;use JumPHP\Http\HttpResponse;/** * The accounts API of jumphp.net (branch app-accounts of the playground) in memory, for the tests: the same routes, * answers and errors (/account/signup, login, me, hello, devices, cloud/playlist with If-Match, cloud/lyrics, cloud/link). * request() is what CloudAccount takes; every answer settles at once. $offline = true: no answer (network down). */final class FakeCloudServer{    public const BASE = 'https://cloud.test/api/apps/winzik';    public bool $offline = false;    /** @var array<string, array{password: string, recovery: string, version: int, entries: list<array<string, mixed>>, lyrics: array<string, string>}> */    public array $accounts = [];    /** @var array<string, array{login: string, id: string, name: string, kind: string, seen: float, revoked: bool}> token => device */    public array $tokens = [];    /** @var list<string> "METHOD path" asked */    public array $log = [];    /** @var list<array<string, string>> the headers of each request (to check no token leaks where it should not) */    public array $headers = [];    /** a PUT of the playlist answered 412 this many times more (another device wrote) */    public int $conflicts = 0;    public string $roomKey;    public string $room;    public function __construct()    {        $b64 = static fn (string $bytes): string => rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');        $this->roomKey = $b64(random_bytes(32));        $this->room = $b64(random_bytes(32));    }    public function request(string $method, string $url, string|array|null $body, array $headers): Task    {        $task = new Task();        $path = substr($url, strlen(self::BASE . '/account'));        $this->log[] = "$method $path";        $this->headers[] = $headers;        if ($this->offline) {            $task->settle(null, new HttpError('network down', $url));            return $task;        }        $data = is_array($body) ? $body : (is_string($body) ? json_decode($body, true) : null);        try {            [$status, $answer, $more] = $this->route($method, $path, is_array($data) ? $data : [], is_string($body) ? $body : '', $headers) + [2 => []];        } catch (\Throwable $e) {            [$status, $answer, $more] = [500, ['error' => $e->getMessage()], []];        }        $task->settle(new HttpResponse($status, is_string($answer) ? $answer : (string)json_encode($answer), $more, $url));        return $task;    }    /** @return array{0: int, 1: mixed, 2?: array<string, string>} */    private function route(string $method, string $path, array $data, string $raw, array $headers): array    {        if ($method === 'POST' && ($path === '/signup' || $path === '/login')) {            $login = strtolower((string)($data['login'] ?? ''));            if ($path === '/signup') {                if (isset($this->accounts[$login])) {                    return [409, ['error' => 'taken', 'code' => 'login_taken']];                }                if (str_contains($login, '@')) {                    return [400, ['error' => 'bad', 'code' => 'bad_login']];                }                $this->accounts[$login] = ['password' => (string)$data['password'], 'recovery' => 'ABCD-EFGH-IJKL-MNOP-QRST', 'version' => 0, 'entries' => [], 'lyrics' => []];            } elseif (($this->accounts[$login]['password'] ?? null) !== ($data['password'] ?? '')) {                return [401, ['error' => 'bad', 'code' => 'bad_credentials']];            }            $token = 'wzd_' . bin2hex(random_bytes(16));            $device = ['login' => $login, 'id' => substr(bin2hex(random_bytes(6)), 0, 12), 'name' => (string)($data['device']['name'] ?? ''),                'kind' => (string)($data['device']['kind'] ?? 'desktop'), 'seen' => microtime(true), 'revoked' => false];            $this->tokens[$token] = $device;            $out = ['login' => $login, 'device' => $this->view($device, $device), 'token' => $token];            if ($path === '/signup') {                $out['recovery'] = $this->accounts[$login]['recovery'];            }            return [$path === '/signup' ? 201 : 200, $out];        }        $auth = (string)($headers['Authorization'] ?? '');        $device = $this->tokens[substr($auth, 7)] ?? null;        if ($device === null || $device['revoked']) {            return [401, ['error' => 'no', 'code' => $device === null ? 'unauthorized' : 'revoked']];        }        $this->tokens[substr($auth, 7)]['seen'] = microtime(true);        $login = $device['login'];        $account = &$this->accounts[$login];        $mine = array_values(array_filter($this->tokens, fn (array $d) => $d['login'] === $login && !$d['revoked']));        switch (true) {            case $method === 'GET' && $path === '/me':                return [200, ['login' => $login, 'device' => $this->view($device, $device), 'devices' => array_map(fn ($d) => $this->view($d, $device), $mine)]];            case $method === 'POST' && $path === '/hello':                return [200, ['device' => $device['id'], 'online' => array_map(fn ($d) => $this->view($d, $device), $mine),                    'playlist' => ['version' => $account['version'], 'entries' => count($account['entries'])], 'next' => 60]];            case $method === 'POST' && $path === '/logout':                $this->tokens[substr($auth, 7)]['revoked'] = true;                return [200, ['signedOut' => true]];            case $method === 'DELETE' && str_starts_with($path, '/devices/'):                foreach ($this->tokens as $t => $d) {                    if ($d['id'] === substr($path, 9) && $d['login'] === $login) {                        $this->tokens[$t]['revoked'] = true;                        return [200, ['revoked' => $d['id']]];                    }                }                return [404, ['error' => 'unknown']];            case $method === 'GET' && $path === '/cloud/playlist':                return [200, ['version' => $account['version'], 'entries' => $account['entries']], ['etag' => '"' . $account['version'] . '"']];            case $method === 'PUT' && $path === '/cloud/playlist':                $match = trim((string)($headers['If-Match'] ?? ''), '"');                if ($match === '') {                    return [428, ['code' => 'precondition_required', 'version' => $account['version']]];                }                if ($this->conflicts > 0) {                    // another device wrote just now: an entry of its own appears                    $this->conflicts--;                    $account['version']++;                    $account['entries'][] = ['id' => 'other-' . $account['version'] . '-xxxxxxxx', 'title' => 'De l\'autre appareil', 'artist' => '', 'duration' => 0,                        'size' => 10, 'sha256' => '', 'addedBy' => 'aaaaaaaaaaaa', 'source' => ['type' => 'pc', 'device' => 'aaaaaaaaaaaa'], 'lyrics' => false, 'at' => '2026-11-20T10:00:00Z'];                }                if ((int)$match !== $account['version']) {                    return [412, ['code' => 'version_conflict', 'version' => $account['version'], 'entries' => $account['entries']]];                }                $account['entries'] = array_values(array_map(fn (array $e) => $e + ['addedBy' => $device['id']], (array)($data['entries'] ?? [])));                $account['version']++;                return [200, ['version' => $account['version'], 'entries' => $account['entries']]];            case str_starts_with($path, '/cloud/lyrics/'):                $id = substr($path, 14);                if ($method === 'PUT') {                    if (strlen($raw) > 65536 || !mb_check_encoding($raw, 'UTF-8')) {                        return [415, ['error' => 'text']];                    }                    $account['lyrics'][$id] = $raw;                    return [200, ['entry' => $id, 'bytes' => strlen($raw)]];                }                if ($method === 'DELETE') {                    unset($account['lyrics'][$id]);                    return [200, []];                }                if (!isset($account['lyrics'][$id])) {                    return [404, ['error' => 'none']];                }                $etag = '"' . substr(hash('sha256', $account['lyrics'][$id]), 0, 32) . '"';                return ($headers['If-None-Match'] ?? '') === $etag ? [304, '', ['etag' => $etag]] : [200, $account['lyrics'][$id], ['etag' => $etag]];            case $method === 'GET' && $path === '/cloud/link':                return [200, ['relay' => 'ws://relay.test/ws', 'room' => $this->room, 'key' => $this->roomKey, 'alg' => 'AES-256-GCM', 'week' => '2026-W47',                    'exp' => '2026-11-23T00:00:00+00:00', 'expiresIn' => 270000]];        }        return [404, ['error' => 'not found']];    }    /** @param array<string, mixed> $d */    private function view(array $d, array $current): array    {        return ['id' => $d['id'], 'name' => $d['name'], 'kind' => $d['kind'], 'online' => microtime(true) - $d['seen'] < 150,            'lastSeen' => gmdate(DATE_ATOM), 'current' => $d['id'] === $current['id']];    }}