Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428<?php
declare(strict_types=1);
namespace Wotnak\Atproto\Tests\EndToEnd;
use GuzzleHttp\Client;use GuzzleHttp\Psr7\HttpFactory;use PHPUnit\Framework\TestCase;use Psr\Http\Message\RequestInterface;use Wotnak\Atproto\AtprotoClient;use Wotnak\Atproto\AtprotoClientFactory;use Wotnak\Atproto\Auth\AtprotoAuthenticatedSession;use Wotnak\Atproto\Auth\AtprotoSession;use Wotnak\Atproto\Client\RefreshableAuthenticatedSessionInterface;use Wotnak\Atproto\Client\XrpcOptions;use Wotnak\Atproto\Exception\XrpcHttpException;use Wotnak\Atproto\Security\OutboundUrlPolicy;
/** * Exercises the public client API against a disposable real PDS. */final class PdsEndToEndTest extends TestCase {
private const string PASSWORD = 'correct horse battery staple';
private AtprotoClientFactory $clientFactory;
private OutboundUrlPolicy $urlPolicy;
private AtprotoClient $anonymous;
protected function setUp(): void { $serviceUrl = self::serviceUrl(); $host = \parse_url($serviceUrl, PHP_URL_HOST); static::assertIsString($host);
$httpFactory = new HttpFactory(); $transportOptions = ['http_errors' => FALSE, 'timeout' => 10]; $caFile = \getenv('ATPROTO_E2E_CA_FILE'); if (\is_string($caFile) && $caFile !== '') { $transportOptions['verify'] = $caFile; } $this->clientFactory = new AtprotoClientFactory( new Client($transportOptions), $httpFactory, $httpFactory, ); $this->urlPolicy = new OutboundUrlPolicy(allowedDevelopmentHosts: [$host]); $this->anonymous = $this->clientFactory->create($serviceUrl, urlPolicy: $this->urlPolicy); }
public function testRepositoryAndSyncLifecycle(): void { $description = $this->anonymous->get('com.atproto.server.describeServer'); static::assertContains('.test', $description['availableUserDomains']);
$session = $this->createAccount('alice'); $authenticated = $this->authenticated($session); $collection = 'com.example.e2e';
$described = $this->anonymous->get('com.atproto.repo.describeRepo', ['repo' => $session->did]); static::assertSame($session->did, $described['did']); static::assertSame($session->handle, $described['handle']);
$created = $authenticated->post('com.atproto.repo.createRecord', [ 'repo' => $session->did, 'collection' => $collection, 'record' => self::record('First version'), 'rkey' => 'first', 'validate' => FALSE, ]); static::assertSame("at://{$session->did}/{$collection}/first", $created['uri']); static::assertIsString($created['cid']);
$updated = $authenticated->post('com.atproto.repo.putRecord', [ 'repo' => $session->did, 'collection' => $collection, 'rkey' => 'first', 'record' => self::record('Updated version'), 'validate' => FALSE, 'swapRecord' => $created['cid'], ]); static::assertNotSame($created['cid'], $updated['cid']);
self::assertXrpcError( fn () => $authenticated->post('com.atproto.repo.putRecord', [ 'repo' => $session->did, 'collection' => $collection, 'rkey' => 'first', 'record' => self::record('Stale update'), 'validate' => FALSE, 'swapRecord' => $created['cid'], ]), 'InvalidSwap', 400, );
$batch = $authenticated->post('com.atproto.repo.applyWrites', [ 'repo' => $session->did, 'writes' => [ [ '$type' => 'com.atproto.repo.applyWrites#create', 'collection' => $collection, 'rkey' => 'second', 'value' => self::record('Second record'), ], [ '$type' => 'com.atproto.repo.applyWrites#create', 'collection' => $collection, 'value' => self::record('PDS-keyed record'), ], ], 'validate' => FALSE, ]); static::assertIsString($batch['results'][1]['uri']); $generatedRkey = \substr($batch['results'][1]['uri'], \strrpos($batch['results'][1]['uri'], '/') + 1);
$record = $this->anonymous->get('com.atproto.repo.getRecord', [ 'repo' => $session->did, 'collection' => $collection, 'rkey' => 'first', ]); static::assertSame('Updated version', $record['value']['message']);
$validatedPost = $authenticated->post('com.atproto.repo.createRecord', [ 'repo' => $session->did, 'collection' => 'app.bsky.feed.post', 'record' => [ '$type' => 'app.bsky.feed.post', 'text' => 'Validated by the PDS lexicon', 'createdAt' => '2026-01-02T03:04:05.000Z', ], 'validate' => TRUE, ]); $validatedRkey = \substr($validatedPost['uri'], \strrpos($validatedPost['uri'], '/') + 1); $loadedPost = $this->anonymous->get('com.atproto.repo.getRecord', [ 'repo' => $session->did, 'collection' => 'app.bsky.feed.post', 'rkey' => $validatedRkey, ]); static::assertSame('Validated by the PDS lexicon', $loadedPost['value']['text']); $authenticated->post('com.atproto.repo.deleteRecord', [ 'repo' => $session->did, 'collection' => 'app.bsky.feed.post', 'rkey' => $validatedRkey, ]);
$firstPage = $this->anonymous->get('com.atproto.repo.listRecords', [ 'repo' => $session->did, 'collection' => $collection, 'limit' => 1, ]); static::assertCount(1, $firstPage['records']); static::assertIsString($firstPage['cursor']); $secondPage = $this->anonymous->get('com.atproto.repo.listRecords', [ 'repo' => $session->did, 'collection' => $collection, 'limit' => 1, 'cursor' => $firstPage['cursor'], ]); static::assertCount(1, $secondPage['records']); $listed = $this->anonymous->get('com.atproto.repo.listRecords', [ 'repo' => $session->did, 'collection' => $collection, 'limit' => 100, ]); $records = $listed['records']; static::assertCount(3, $records); $recordKeys = \array_map( static fn (array $item): string => \substr($item['uri'], \strrpos($item['uri'], '/') + 1), $records, ); \sort($recordKeys); $expectedRecordKeys = ['first', 'second', $generatedRkey]; \sort($expectedRecordKeys); static::assertSame($expectedRecordKeys, $recordKeys);
$blobBytes = 'atproto-php-e2e-blob'; $blob = $authenticated->postRaw('com.atproto.repo.uploadBlob', $blobBytes, 'text/plain'); static::assertSame('text/plain', $blob['blob']['mimeType']); static::assertIsString($blob['blob']['ref']['$link']); $authenticated->post('com.atproto.repo.createRecord', [ 'repo' => $session->did, 'collection' => $collection, 'record' => self::record('Blob record') + ['attachment' => $blob['blob']], 'rkey' => 'blob', 'validate' => FALSE, ]); $downloadedBlob = $this->anonymous->requestRaw('GET', 'com.atproto.sync.getBlob', [ 'did' => $session->did, 'cid' => $blob['blob']['ref']['$link'], ]); static::assertSame(200, $downloadedBlob->statusCode); static::assertSame($blobBytes, $downloadedBlob->body);
$latestCommit = $this->anonymous->get('com.atproto.sync.getLatestCommit', ['did' => $session->did]); static::assertIsString($latestCommit['cid']); static::assertIsString($latestCommit['rev']); $repoStatus = $this->anonymous->get('com.atproto.sync.getRepoStatus', ['did' => $session->did]); static::assertSame($session->did, $repoStatus['did']); static::assertTrue($repoStatus['active']);
$carOptions = new XrpcOptions(headers: ['Accept' => 'application/vnd.ipld.car']); $repository = $this->anonymous->requestRaw( 'GET', 'com.atproto.sync.getRepo', ['did' => $session->did], $carOptions, ); static::assertSame(200, $repository->statusCode); static::assertStringContainsString( 'application/vnd.ipld.car', \implode(', ', $repository->headers['Content-Type'] ?? []), ); static::assertNotSame('', $repository->body);
$authenticated->post('com.atproto.repo.createRecord', [ 'repo' => $session->did, 'collection' => $collection, 'record' => self::record('Incremental record'), 'rkey' => 'fourth', 'validate' => FALSE, ]); $incremental = $this->anonymous->requestRaw( 'GET', 'com.atproto.sync.getRepo', ['did' => $session->did, 'since' => $latestCommit['rev']], $carOptions, ); static::assertSame(200, $incremental->statusCode); static::assertNotSame('', $incremental->body);
$authenticated->post('com.atproto.repo.applyWrites', [ 'repo' => $session->did, 'writes' => \array_map( static fn (string $rkey): array => [ '$type' => 'com.atproto.repo.applyWrites#delete', 'collection' => $collection, 'rkey' => $rkey, ], ['blob', 'first', 'second', $generatedRkey, 'fourth'], ), ]); $remaining = $this->anonymous->get('com.atproto.repo.listRecords', [ 'repo' => $session->did, 'collection' => $collection, ]); static::assertSame([], $remaining['records']);
self::assertXrpcError( fn () => $this->anonymous->get('com.atproto.repo.getRecord', [ 'repo' => $session->did, 'collection' => $collection, 'rkey' => 'missing', ]), 'RecordNotFound', 400, ); }
public function testIdentityEndpointsUseTheLocalPlcDirectory(): void { $session = $this->createAccount('carol'); $resolved = $this->anonymous->get('com.atproto.identity.resolveHandle', ['handle' => $session->handle]); static::assertSame($session->did, $resolved['did']);
$newHandle = 'carol-renamed.test'; $this->authenticated($session)->post('com.atproto.identity.updateHandle', ['handle' => $newHandle]);
$resolved = $this->anonymous->get('com.atproto.identity.resolveHandle', ['handle' => $newHandle]); static::assertSame($session->did, $resolved['did']); $currentSession = $this->authenticated($session)->get('com.atproto.server.getSession'); static::assertSame($newHandle, $currentSession['handle']); }
public function testSessionRefreshAndRevocation(): void { self::assertXrpcError( fn () => $this->anonymous->post('com.atproto.server.createSession', [ 'identifier' => 'nobody.test', 'password' => 'incorrect password', ]), 'AuthenticationRequired', 401, );
$session = $this->createAccount('bob'); $refreshClient = $this->authenticatedWithToken($session, $session->refreshJwt); $refreshed = AtprotoSession::fromRefreshSessionResponse( $refreshClient->requestWithoutBody('POST', 'com.atproto.server.refreshSession')->data, self::serviceUrl(), ); static::assertSame($session->did, $refreshed->did); static::assertNotSame('', $refreshed->accessJwt); static::assertNotSame($session->refreshJwt, $refreshed->refreshJwt); static::assertSame( $session->did, $this->authenticated($refreshed)->get('com.atproto.server.getSession')['did'], );
$refreshedTokenClient = $this->authenticatedWithToken($refreshed, $refreshed->refreshJwt); $refreshedTokenClient->requestWithoutBody('POST', 'com.atproto.server.deleteSession'); self::assertXrpcError( fn () => $refreshedTokenClient->requestWithoutBody('POST', 'com.atproto.server.refreshSession'), 'ExpiredToken', 400, ); }
public function testInvalidAccessTokenIsRefreshedAndRetriedOnce(): void { $session = $this->createAccount('retry'); $refreshable = new class($session) implements RefreshableAuthenticatedSessionInterface {
public int $refreshCount = 0;
public bool $invalidated = FALSE;
private string $accessToken = 'invalid-access-token';
public function __construct(private readonly AtprotoSession $session) {}
public function getAccessToken(): string { return $this->accessToken; }
public function sign(RequestInterface $request): RequestInterface { return $request->withHeader('Authorization', 'Bearer ' . $this->accessToken); }
public function getSubjectDid(): ?string { return $this->session->did; }
public function getPdsUrl(): ?string { return $this->session->pdsUrl; }
public function refresh(): bool { $this->refreshCount++; $this->accessToken = $this->session->accessJwt; return TRUE; }
public function invalidate(): void { $this->invalidated = TRUE; }
};
$client = $this->clientFactory->createAuthenticated( $refreshable, urlPolicy: $this->urlPolicy, ); $currentSession = $client->get('com.atproto.server.getSession'); static::assertSame($session->did, $currentSession['did']); static::assertSame(1, $refreshable->refreshCount); static::assertFalse($refreshable->invalidated); }
private function createAccount(string $name): AtprotoSession { $handle = $name . '.test'; $created = $this->anonymous->post('com.atproto.server.createAccount', [ 'handle' => $handle, 'email' => $name . '@example.com', 'password' => self::PASSWORD, ]); static::assertSame($handle, $created['handle']); static::assertIsString($created['did']);
$session = AtprotoSession::fromCreateSessionResponse( $this->anonymous->post('com.atproto.server.createSession', [ 'identifier' => $handle, 'password' => self::PASSWORD, ]), self::serviceUrl(), ); static::assertSame($created['did'], $session->did); static::assertSame(self::serviceUrl(), $session->pdsUrl); return $session; }
private function authenticated(AtprotoSession $session): AtprotoClient { return $this->clientFactory->createAuthenticated( new AtprotoAuthenticatedSession($session), urlPolicy: $this->urlPolicy, ); }
private function authenticatedWithToken(AtprotoSession $session, string $token): AtprotoClient { return $this->authenticated(new AtprotoSession( did: $session->did, handle: $session->handle, accessJwt: $token, refreshJwt: $session->refreshJwt, pdsUrl: $session->pdsUrl, )); }
/** * @return array<string, string> */ private static function record(string $message): array { return [ '$type' => 'com.example.e2e', 'message' => $message, 'createdAt' => '2026-01-02T03:04:05.000Z', ]; }
private static function assertXrpcError(\Closure $request, string $error, int $statusCode): void { try { $request(); static::fail('Expected the PDS to return an XRPC error.'); } catch (XrpcHttpException $exception) { static::assertSame($statusCode, $exception->statusCode); static::assertSame($error, $exception->xrpcError); static::assertIsArray($exception->decodedBody); } }
private static function serviceUrl(): string { $serviceUrl = \getenv('ATPROTO_E2E_PDS_URL'); return \is_string($serviceUrl) && $serviceUrl !== '' ? \rtrim($serviceUrl, '/') : 'https://pds.atproto-php.wotnak.dev'; }
}