- signUp / signIn / recover / signOut / me / devices / revokeDevice / hello / changePassword / deleteAccount ; jeton dans var/ (jumphp-account.json), oublié sur un 401 (onSignedOut). - Clé-valeur : get / value / set (If-Match) / setText / delete / search (préfixe, motif, curseur, valeurs) / getMany ; un conflit 412 échoue avec AppAccountError::isConflict() et data['current']. - Objets : put / getObject (?version, SHA-256 vérifié) / versions / objects / deleteObject ; store() sérialise un objet PHP, load() le relit avec allowed_classes obligatoire (une classe hors liste, même au fond, est refusée), AppAccount::unserialize(). - Jamais bloquant (Tasks par $engine->http()), bureau, navigateur et Android ; AppAccount::for($engine) (platform_url, JUMPHP_PLATFORM_URL). - Tests engine/tests/Platform/AppAccountTest.php (faux serveur), docs/platform-account.md, AGENTS.md §1 et §9. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JkYTqrBXzYFUXiSrqYBdP3
284 lines
15 KiB
PHP
284 lines
15 KiB
PHP
<?php
|
|
|
|
namespace JumPHP\Tests\Platform;
|
|
|
|
use JumPHP\Async\Task;
|
|
use JumPHP\Http\HttpError;
|
|
use JumPHP\Http\HttpResponse;
|
|
use JumPHP\Platform\AppAccount;
|
|
use JumPHP\Platform\AppAccountError;
|
|
use JumPHP\Save\Storage;
|
|
use PHPUnit\Framework\TestCase;
|
|
|
|
final class SavedGame
|
|
{
|
|
public function __construct(public int $level = 1, private array $items = [], protected ?SavedPlayer $player = null)
|
|
{
|
|
}
|
|
|
|
public function items(): array
|
|
{
|
|
return $this->items;
|
|
}
|
|
|
|
public function player(): ?SavedPlayer
|
|
{
|
|
return $this->player;
|
|
}
|
|
}
|
|
|
|
final class SavedPlayer
|
|
{
|
|
public function __construct(public string $name = '')
|
|
{
|
|
}
|
|
}
|
|
|
|
/** The client of jumphp.net's account API (docs/platform-account.md) against a fake server: requests, token kept in var/, errors, safe load(). */
|
|
final class AppAccountTest extends TestCase
|
|
{
|
|
private const URL = 'https://jumphp.test/api/apps/my-app/account';
|
|
|
|
/** @var list<array{method: string, url: string, body: ?string, headers: array<string, string>}> */
|
|
private array $sent = [];
|
|
/** @var list<HttpResponse|\Throwable> */
|
|
private array $answers = [];
|
|
private string $dir;
|
|
|
|
protected function setUp(): void
|
|
{
|
|
$this->dir = sys_get_temp_dir() . '/jumphp-account-test-' . getmypid() . '-' . random_int(0, 99999);
|
|
}
|
|
|
|
protected function tearDown(): void
|
|
{
|
|
@unlink("$this->dir/jumphp-account.json");
|
|
@rmdir($this->dir);
|
|
}
|
|
|
|
private function account(): AppAccount
|
|
{
|
|
return new AppAccount(function (string $method, string $url, ?string $body, array $headers, float $timeout): Task {
|
|
$this->sent[] = ['method' => $method, 'url' => $url, 'body' => $body, 'headers' => $headers];
|
|
$task = new Task();
|
|
$answer = array_shift($this->answers) ?? new HttpResponse(500, '{"error":"no answer queued","code":"test"}');
|
|
$answer instanceof \Throwable ? $task->settle(null, $answer) : $task->settle($answer);
|
|
return $task;
|
|
}, self::URL, new Storage($this->dir), 'jumphp-account.json', 'desktop');
|
|
}
|
|
|
|
private function answer(int $status, mixed $json = null, array $headers = [], ?string $raw = null): void
|
|
{
|
|
$this->answers[] = new HttpResponse($status, $raw ?? (string)json_encode($json), $headers);
|
|
}
|
|
|
|
private static function value(Task $task): mixed
|
|
{
|
|
self::assertTrue($task->isDone(), 'the fake server answers at once');
|
|
return $task->result();
|
|
}
|
|
|
|
private static function error(Task $task): AppAccountError
|
|
{
|
|
self::assertTrue($task->isDone());
|
|
$e = $task->error();
|
|
self::assertInstanceOf(AppAccountError::class, $e);
|
|
return $e;
|
|
}
|
|
|
|
private function signedIn(): AppAccount
|
|
{
|
|
$account = $this->account();
|
|
$this->answer(200, ['login' => 'ada', 'device' => ['id' => 'a1b2c3d4e5f6'], 'token' => 'wzd_secret']);
|
|
self::value($account->signIn('ada', 'correct horse'));
|
|
$this->sent = [];
|
|
return $account;
|
|
}
|
|
|
|
public function testSignUpKeepsTheTokenInVarAndSendsIt(): void
|
|
{
|
|
$account = $this->account();
|
|
self::assertFalse($account->signedIn());
|
|
self::assertSame('signed_out', self::error($account->me())->errorCode);
|
|
self::assertSame([], $this->sent, 'nothing sent without a token');
|
|
|
|
$this->answer(201, ['login' => 'ada', 'device' => ['id' => 'a1b2c3d4e5f6'], 'token' => 'wzd_secret', 'recovery' => 'AAAA-BBBB-CCCC-DDDD-EEEE']);
|
|
self::assertSame(['login' => 'ada', 'recovery' => 'AAAA-BBBB-CCCC-DDDD-EEEE'], self::value($account->signUp(' ada ', 'correct horse', 'PC salon')));
|
|
self::assertSame('POST', $this->sent[0]['method']);
|
|
self::assertSame(self::URL . '/signup', $this->sent[0]['url']);
|
|
self::assertSame(['login' => 'ada', 'password' => 'correct horse', 'device' => ['name' => 'PC salon', 'kind' => 'desktop']], json_decode((string)$this->sent[0]['body'], true));
|
|
self::assertArrayNotHasKey('Authorization', $this->sent[0]['headers']);
|
|
self::assertTrue($account->signedIn());
|
|
self::assertSame('a1b2c3d4e5f6', $account->deviceId);
|
|
|
|
// kept in var/: another start of the application is still signed in; the recovery code is never kept
|
|
$saved = (string)file_get_contents("$this->dir/jumphp-account.json");
|
|
self::assertStringContainsString('wzd_secret', $saved);
|
|
self::assertStringNotContainsString('AAAA', $saved);
|
|
self::assertStringNotContainsString('correct horse', $saved);
|
|
$again = $this->account();
|
|
self::assertTrue($again->signedIn());
|
|
$this->answer(200, ['login' => 'ada', 'devices' => [['id' => 'a1b2c3d4e5f6', 'current' => true]]]);
|
|
self::assertSame([['id' => 'a1b2c3d4e5f6', 'current' => true]], self::value($again->devices()));
|
|
self::assertSame('Bearer wzd_secret', $this->sent[1]['headers']['Authorization']);
|
|
self::assertSame(self::URL . '/me', $this->sent[1]['url']);
|
|
|
|
// signing out forgets the token here even without the server
|
|
$this->answers[] = new HttpError('down');
|
|
$again->signOut();
|
|
self::assertFalse($again->signedIn());
|
|
self::assertFalse($this->account()->signedIn());
|
|
self::assertSame('ada', $this->account()->login);
|
|
}
|
|
|
|
public function testErrorsCarryTheServersCodeAndARevokedTokenIsForgotten(): void
|
|
{
|
|
$account = $this->account();
|
|
$this->answer(401, ['error' => 'wrong pseudo or password', 'code' => 'bad_credentials']);
|
|
$e = self::error($account->signIn('ada', 'nope'));
|
|
self::assertSame('bad_credentials', $e->errorCode);
|
|
self::assertSame(401, $e->status);
|
|
self::assertSame('wrong pseudo or password', $e->getMessage());
|
|
|
|
$account = $this->signedIn();
|
|
$gone = 0;
|
|
$account->onSignedOut = function () use (&$gone): void {
|
|
$gone++;
|
|
};
|
|
$this->answer(429, ['error' => 'too many requests', 'code' => 'rate_limited', 'retryAfter' => 12]);
|
|
self::assertSame(12, self::error($account->hello())->data['retryAfter']);
|
|
self::assertTrue($account->signedIn());
|
|
$this->answer(401, ['error' => 'this device was signed out', 'code' => 'revoked']);
|
|
self::assertSame('revoked', self::error($account->hello())->errorCode);
|
|
self::assertFalse($account->signedIn());
|
|
self::assertSame(1, $gone);
|
|
|
|
$account = $this->signedIn();
|
|
$this->answers[] = new HttpError('network down');
|
|
self::assertSame('network', self::error($account->me())->errorCode);
|
|
self::assertTrue($account->signedIn(), 'no answer is not a sign-out');
|
|
|
|
$none = new AppAccount(fn () => new Task(), '');
|
|
self::assertSame('disabled', self::error($none->signIn('a', 'b'))->errorCode);
|
|
}
|
|
|
|
public function testKeysAreWrittenReadSearchedAndConflictsCarryTheCurrentValue(): void
|
|
{
|
|
$account = $this->signedIn();
|
|
$this->answer(201, ['key' => 'settings', 'type' => 'json', 'version' => 1, 'size' => 14]);
|
|
self::assertSame(1, self::value($account->set('settings', ['volume' => 1.0]))['version']);
|
|
self::assertSame('PUT', $this->sent[0]['method']);
|
|
self::assertSame(self::URL . '/kv/settings', $this->sent[0]['url']);
|
|
self::assertSame('{"volume":1.0}', $this->sent[0]['body']);
|
|
self::assertSame('application/json', $this->sent[0]['headers']['Content-Type']);
|
|
self::assertArrayNotHasKey('If-Match', $this->sent[0]['headers']);
|
|
|
|
$this->answer(200, ['key' => 'n', 'version' => 1]);
|
|
$account->set('n', 42, 0);
|
|
self::assertSame('42', $this->sent[1]['body']);
|
|
self::assertSame('"0"', $this->sent[1]['headers']['If-Match']);
|
|
$this->answer(200, ['key' => 'notes/a', 'version' => 1]);
|
|
$account->setText('notes/a', 'été');
|
|
self::assertSame('text/plain; charset=utf-8', $this->sent[2]['headers']['Content-Type']);
|
|
self::assertSame(self::URL . '/kv/notes/a', $this->sent[2]['url']);
|
|
|
|
$this->answer(412, ['error' => 'this key changed meanwhile', 'code' => 'version_conflict', 'current' => ['key' => 'settings', 'version' => 2, 'value' => ['volume' => 0.5]]]);
|
|
$e = self::error($account->set('settings', ['volume' => 0.1], 1));
|
|
self::assertTrue($e->isConflict());
|
|
self::assertSame(['volume' => 0.5], $e->data['current']['value']);
|
|
|
|
$this->answer(200, ['key' => 'settings', 'type' => 'json', 'value' => ['volume' => 0.5], 'version' => 2]);
|
|
self::assertSame(['volume' => 0.5], self::value($account->value('settings')));
|
|
$this->answer(404, ['error' => 'no such key', 'code' => 'not_found']);
|
|
self::assertSame('none', self::value($account->value('missing', 'none')));
|
|
$this->answer(404, ['error' => 'no such key', 'code' => 'not_found']);
|
|
self::assertNull(self::value($account->get('missing')));
|
|
$this->answer(404, ['error' => 'no such key', 'code' => 'not_found']);
|
|
self::assertFalse(self::value($account->delete('missing')));
|
|
$this->answer(200, ['deleted' => 'settings']);
|
|
self::assertTrue(self::value($account->delete('settings', 2)));
|
|
self::assertSame('DELETE', end($this->sent)['method']);
|
|
|
|
$this->answer(200, ['items' => [['key' => 'score:2026-12']], 'next' => null]);
|
|
self::assertSame([['key' => 'score:2026-12']], self::value($account->search('score:', '*-12', 50, null, true))['items']);
|
|
self::assertSame(self::URL . '/kv?prefix=score%3A&match=%2A-12&limit=50&values=1', end($this->sent)['url']);
|
|
$this->answer(200, ['items' => [], 'missing' => ['a', 'b']]);
|
|
self::assertSame(['a', 'b'], self::value($account->getMany(['a', 'b']))['missing']);
|
|
self::assertSame(self::URL . '/kv?keys=a%2Cb', end($this->sent)['url']);
|
|
|
|
$this->expectException(\InvalidArgumentException::class);
|
|
$account->get('../etc');
|
|
}
|
|
|
|
public function testStoreAndLoadAPhpObjectWithOnlyTheClassesAllowed(): void
|
|
{
|
|
$account = $this->signedIn();
|
|
$game = new SavedGame(3, ['sword', 'key'], new SavedPlayer("Ada\0x"));
|
|
$this->answer(201, ['name' => 'save', 'version' => 1, 'format' => 'php-serialize']);
|
|
self::assertSame(1, self::value($account->store('save', $game, 5))['version']);
|
|
$sent = $this->sent[0];
|
|
self::assertSame(serialize($game), $sent['body']);
|
|
self::assertStringContainsString("\0", (string)$sent['body']);
|
|
self::assertSame(self::URL . '/objects/save?format=php-serialize&keep=5&sha256=' . hash('sha256', serialize($game)), $sent['url']);
|
|
|
|
$bytes = serialize($game);
|
|
$headers = ['x-object-version' => '1', 'x-object-latest' => '1', 'x-object-format' => 'php-serialize', 'x-object-sha256' => hash('sha256', $bytes), 'etag' => '"1"'];
|
|
$this->answer(200, null, $headers, $bytes);
|
|
$loaded = self::value($account->load('save', [SavedGame::class, SavedPlayer::class]));
|
|
self::assertInstanceOf(SavedGame::class, $loaded);
|
|
self::assertSame(3, $loaded->level);
|
|
self::assertSame(['sword', 'key'], $loaded->items());
|
|
self::assertSame("Ada\0x", $loaded->player()?->name);
|
|
|
|
// a class left out of the list, even deep inside: refused, never half made
|
|
$this->answer(200, null, $headers, $bytes);
|
|
$e = self::error($account->load('save', [SavedGame::class]));
|
|
self::assertSame('unserialize', $e->errorCode);
|
|
self::assertSame(SavedPlayer::class, $e->data['class']);
|
|
$this->answer(200, null, $headers, $bytes);
|
|
self::assertSame('unserialize', self::error($account->load('save', []))->errorCode);
|
|
// damaged on the way, not a serialize() string, another format
|
|
$this->answer(200, null, ['x-object-sha256' => str_repeat('0', 64)] + $headers, $bytes);
|
|
self::assertSame('damaged', self::error($account->load('save', [SavedGame::class]))->errorCode);
|
|
$this->answer(200, null, ['x-object-sha256' => hash('sha256', 'nope')] + $headers, 'nope');
|
|
self::assertSame('unserialize', self::error($account->load('save', [SavedGame::class]))->errorCode);
|
|
$this->answer(200, null, ['x-object-format' => 'json', 'x-object-sha256' => hash('sha256', '{}')] + $headers, '{}');
|
|
self::assertSame('unserialize', self::error($account->load('save', []))->errorCode);
|
|
// arrays and scalars need no class at all; false is a value
|
|
self::assertSame(['a' => [1, 2.5, null]], AppAccount::unserialize(serialize(['a' => [1, 2.5, null]]), []));
|
|
self::assertFalse(AppAccount::unserialize(serialize(false), []));
|
|
// nothing stored yet: null; an older version
|
|
$this->answer(404, ['error' => 'no such object', 'code' => 'not_found']);
|
|
self::assertNull(self::value($account->load('save', [SavedGame::class])));
|
|
$this->answer(404, ['error' => 'this version is no longer kept', 'code' => 'version_not_found', 'latest' => 9]);
|
|
self::assertSame('version_not_found', self::error($account->load('save', [SavedGame::class], 2))->errorCode);
|
|
self::assertSame(self::URL . '/objects/save?version=2', end($this->sent)['url']);
|
|
// a closure cannot be stored
|
|
self::assertSame('bad_request', self::error($account->store('bad', fn () => 1))->errorCode);
|
|
}
|
|
|
|
public function testRawObjectsTheirVersionsAndTheList(): void
|
|
{
|
|
$account = $this->signedIn();
|
|
$this->answer(200, ['name' => 'blob', 'version' => 4]);
|
|
$account->put('blob', "\x00\xff", 'raw', null, 3);
|
|
self::assertSame('"3"', $this->sent[0]['headers']['If-Match']);
|
|
self::assertSame("\x00\xff", $this->sent[0]['body']);
|
|
$this->answer(200, null, ['x-object-version' => '2', 'x-object-latest' => '4', 'x-object-format' => 'raw'], "\x00");
|
|
$got = self::value($account->getObject('blob', 2));
|
|
self::assertSame(["\x00", 2, 4], [$got['bytes'], $got['version'], $got['latest']]);
|
|
$this->answer(200, ['name' => 'blob', 'latest' => 4, 'keep' => 10, 'versions' => [['version' => 4], ['version' => 3]]]);
|
|
self::assertSame([4, 3], array_column(self::value($account->versions('blob'))['versions'], 'version'));
|
|
self::assertSame(self::URL . '/objects/blob/versions', end($this->sent)['url']);
|
|
$this->answer(200, ['items' => [['name' => 'blob']], 'next' => 'YmxvYg']);
|
|
self::assertSame('YmxvYg', self::value($account->objects('b', 1))['next']);
|
|
self::assertSame(self::URL . '/objects?prefix=b&limit=1', end($this->sent)['url']);
|
|
$this->answer(200, ['deleted' => 'blob']);
|
|
self::assertTrue(self::value($account->deleteObject('blob')));
|
|
$this->answer(200, ['usage' => ['keys' => 1], 'limits' => ['keys' => 2000]]);
|
|
self::assertSame(1, self::value($account->usage())['usage']['keys']);
|
|
|
|
$this->expectException(\InvalidArgumentException::class);
|
|
$account->put('a/b', 'x');
|
|
}
|
|
}
|