'yes'], '{"ok":true}')]); $factory = new HttpFactory(); $client = new XrpcClient($requestSender, $factory, $factory, 'https://pds.example', self::testUrlPolicy()); $response = $client->request('GET', 'com.atproto.repo.getRecord', [ 'repo' => 'did:plc:abc', 'collection' => 'com.example.post', 'rkey' => 'self', ]); static::assertSame(['ok' => TRUE], $response->data); static::assertSame(200, $response->statusCode); static::assertSame(['yes'], $response->headers['X-Test']); $request = $requestSender->lastRequest; static::assertNotNull($request); static::assertSame('GET', $request->getMethod()); static::assertSame( 'https://pds.example/xrpc/com.atproto.repo.getRecord?repo=did%3Aplc%3Aabc&collection=com.example.post&rkey=self', (string) $request->getUri(), ); } public function testRejectsNonEmptyJsonListResponse(): void { $requestSender = new TestXrpcRequestSender([new Response(200, [], '[{"ok":true}]')]); $factory = new HttpFactory(); $client = new XrpcClient($requestSender, $factory, $factory, 'https://pds.example', self::testUrlPolicy()); $this->expectException(XrpcResponseException::class); $client->get('com.atproto.server.getSession'); } public function testRejectsEmptyJsonListResponse(): void { $requestSender = new TestXrpcRequestSender([new Response(200, [], '[]')]); $factory = new HttpFactory(); $client = new XrpcClient($requestSender, $factory, $factory, 'https://pds.example', self::testUrlPolicy()); $this->expectException(XrpcResponseException::class); $client->get('com.atproto.server.getSession'); } public function testPreservesEmptyObjectsAndListsInJsonResponses(): void { $requestSender = new TestXrpcRequestSender([new Response(200, [], '{"object":{},"array":[]}')]); $factory = new HttpFactory(); $client = new XrpcClient($requestSender, $factory, $factory, 'https://pds.example', self::testUrlPolicy()); $data = $client->get('com.atproto.server.getSession'); static::assertInstanceOf(\stdClass::class, $data['object']); static::assertSame([], $data['array']); static::assertSame('{"object":{},"array":[]}', \json_encode($data, JSON_THROW_ON_ERROR)); } public function testGetRepeatsArrayQueryParameters(): void { $requestSender = new TestXrpcRequestSender([new Response(200, [], '{"ok":true}')]); $factory = new HttpFactory(); $client = new XrpcClient($requestSender, $factory, $factory, 'https://pds.example', self::testUrlPolicy()); $client->get('app.bsky.actor.getProfiles', [ 'actors' => ['did:plc:one', 'did:plc:two'], 'active' => TRUE, ]); static::assertSame( 'https://pds.example/xrpc/app.bsky.actor.getProfiles?actors=did%3Aplc%3Aone&actors=did%3Aplc%3Atwo&active=true', (string) $requestSender->lastRequest?->getUri(), ); } #[DataProvider('invalidXrpcMethodProvider')] public function testRejectsInvalidXrpcMethod(string $method): void { $requestSender = new TestXrpcRequestSender([new Response(200, [], '{}')]); $factory = new HttpFactory(); $client = new XrpcClient($requestSender, $factory, $factory, 'https://pds.example', self::testUrlPolicy()); $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Invalid NSID'); $client->get($method); } /** * @return array */ public static function invalidXrpcMethodProvider(): array { return [ 'path traversal' => ['../admin'], 'query injection' => ['com.example.method?admin=true'], 'fragment injection' => ['com.example.method#fragment'], 'path separator' => ['com.example.method/extra'], ]; } public function testPostUsesJsonBodyAndCustomHeaders(): void { $requestSender = new TestXrpcRequestSender([new Response( 200, [], '{"uri":"at://did:plc:abc/com.example.post/self"}', )]); $factory = new HttpFactory(); $client = new XrpcClient($requestSender, $factory, $factory, 'https://pds.example', self::testUrlPolicy()); $client->post('com.atproto.repo.putRecord', ['repo' => 'did:plc:abc'], new XrpcOptions( headers: ['X-Custom' => 'custom-value'], )); $request = $requestSender->lastRequest; static::assertNotNull($request); static::assertSame('custom-value', $request->getHeaderLine('X-Custom')); static::assertSame('application/json', $request->getHeaderLine('Content-Type')); static::assertSame('{"repo":"did:plc:abc"}', (string) $request->getBody()); } public function testPostEncodesEmptyPayloadAsJsonObject(): void { $requestSender = new TestXrpcRequestSender([new Response(200, [], '{}')]); $factory = new HttpFactory(); $client = new XrpcClient($requestSender, $factory, $factory, 'https://pds.example', self::testUrlPolicy()); $client->post('com.atproto.server.refreshSession'); static::assertSame('{}', (string) $requestSender->lastRequest?->getBody()); } public function testPostRawUsesCallerProvidedBodyAndContentType(): void { $requestSender = new TestXrpcRequestSender([new Response(200, [], '{"blob":{"mimeType":"image/jpeg"}}')]); $factory = new HttpFactory(); $client = new XrpcClient($requestSender, $factory, $factory, 'https://pds.example', self::testUrlPolicy()); $response = $client->postRaw('com.atproto.repo.uploadBlob', "\xff\xd8raw", 'image/jpeg'); static::assertSame(['blob' => ['mimeType' => 'image/jpeg']], $response); $request = $requestSender->lastRequest; static::assertNotNull($request); static::assertSame('POST', $request->getMethod()); static::assertSame('image/jpeg', $request->getHeaderLine('Content-Type')); static::assertSame("\xff\xd8raw", (string) $request->getBody()); } public function testPostRawPreservesCallerProvidedStream(): void { $requestSender = new TestXrpcRequestSender([new Response(200, [], '{}')]); $factory = new HttpFactory(); $client = new XrpcClient($requestSender, $factory, $factory, 'https://pds.example', self::testUrlPolicy()); $stream = new NoSeekStream(Utils::streamFor('streamed-body')); $client->postRaw('com.atproto.repo.uploadBlob', $stream, 'application/octet-stream'); static::assertSame($stream, $requestSender->lastRequest?->getBody()); static::assertFalse($requestSender->lastRequest?->getBody()->isSeekable()); } public function testAuthenticatedSenderDoesNotRetryNonSeekableRequestBody(): void { $inner = new TestXrpcRequestSender([ new Response(400, ['DPoP-Nonce' => 'nonce-value'], '{"error":"use_dpop_nonce"}'), ]); $factory = new HttpFactory(); $client = new XrpcClient( new AuthenticatedXrpcRequestSender($inner, new TestDpopNonceAwareSession()), $factory, $factory, 'https://pds.example', self::testUrlPolicy(), ); $stream = new NoSeekStream(Utils::streamFor('streamed-body')); try { $client->postRaw('com.atproto.repo.uploadBlob', $stream); static::fail('Expected the nonce challenge response.'); } catch (XrpcHttpException $exception) { static::assertSame(400, $exception->statusCode); } static::assertSame(1, $inner->requestCount); static::assertSame($stream, $inner->lastRequest?->getBody()); } public function testAuthenticatedRequestSenderAppliesSession(): void { $inner = new TestXrpcRequestSender([new Response(200, [], '{}')]); $factory = new HttpFactory(); $client = new XrpcClient( new AuthenticatedXrpcRequestSender( $inner, new TestAuthenticatedSession('did:plc:abc', 'https://pds.example', 'token-value'), ), $factory, $factory, 'https://pds.example', self::testUrlPolicy(), ); $client->get('com.atproto.server.getSession'); $request = $inner->lastRequest; static::assertNotNull($request); static::assertSame('Bearer token-value', $request->getHeaderLine('Authorization')); static::assertSame('did:plc:abc', $request->getHeaderLine('X-Subject')); } public function testAuthenticatedRequestSenderRejectsCrossOriginServiceOverride(): void { $inner = new TestXrpcRequestSender([new Response(200, [], '{}')]); $factory = new HttpFactory(); $client = new XrpcClient( new AuthenticatedXrpcRequestSender( $inner, new TestAuthenticatedSession('did:plc:abc', 'https://pds.example', 'token-value'), ), $factory, $factory, 'https://pds.example', self::testUrlPolicy(), ); try { $client->get( 'com.atproto.server.getSession', options: new XrpcOptions(serviceUrl: 'https://attacker.example'), ); static::fail('Expected cross-origin credential forwarding to be rejected.'); } catch (\InvalidArgumentException $exception) { static::assertSame('Refusing to send authenticated credentials to a different origin.', $exception->getMessage()); } static::assertSame(0, $inner->requestCount); } public function testAuthenticatedRequestSenderRetriesDpopNonceChallengeOnce(): void { $inner = new TestXrpcRequestSender([ new Response(400, ['DPoP-Nonce' => 'nonce-value'], '{"error":"use_dpop_nonce"}'), new Response(200, ['DPoP-Nonce' => 'rotated-nonce'], '{}'), ]); $factory = new HttpFactory(); $client = new XrpcClient( new AuthenticatedXrpcRequestSender($inner, new TestDpopNonceAwareSession()), $factory, $factory, 'https://pds.example', self::testUrlPolicy(), ); $client->post('com.atproto.repo.putRecord', ['repo' => 'did:plc:abc']); static::assertSame(2, $inner->requestCount); static::assertSame('nonce-value', $inner->requests[1]->getHeaderLine('X-DPoP-Nonce')); static::assertSame('{"repo":"did:plc:abc"}', (string) $inner->requests[1]->getBody()); } public function testAuthenticatedRequestSenderRetriesStandardDpopNonceChallenge(): void { $inner = new TestXrpcRequestSender([ new Response(401, [ 'WWW-Authenticate' => 'DPoP error="use_dpop_nonce"', 'DPoP-Nonce' => 'nonce-value', ]), new Response(200, ['DPoP-Nonce' => 'rotated-nonce'], '{}'), ]); $factory = new HttpFactory(); $client = new XrpcClient( new AuthenticatedXrpcRequestSender($inner, new TestDpopNonceAwareSession()), $factory, $factory, 'https://pds.example', self::testUrlPolicy(), ); $client->get('com.atproto.server.getSession'); static::assertSame(2, $inner->requestCount); static::assertSame('nonce-value', $inner->requests[1]->getHeaderLine('X-DPoP-Nonce')); } public function testAuthenticatedRequestSenderRefreshesAfterDpopNonceRetry(): void { $inner = new TestXrpcRequestSender([ new Response(401, [ 'WWW-Authenticate' => 'DPoP error="use_dpop_nonce"', 'DPoP-Nonce' => 'nonce-value', ]), new Response(401, [ 'WWW-Authenticate' => 'DPoP error="invalid_token"', 'DPoP-Nonce' => 'nonce-value', ]), new Response(200, ['DPoP-Nonce' => 'rotated-nonce'], '{}'), ]); $session = new TestRefreshableDpopSession(); $factory = new HttpFactory(); $client = new XrpcClient( new AuthenticatedXrpcRequestSender($inner, $session), $factory, $factory, 'https://pds.example', self::testUrlPolicy(), ); $client->get('com.atproto.server.getSession'); static::assertSame(3, $inner->requestCount); static::assertSame(1, $session->refreshCount); static::assertFalse($session->invalidated); static::assertSame('DPoP refreshed-token', $inner->requests[2]->getHeaderLine('Authorization')); static::assertSame('nonce-value', $inner->requests[2]->getHeaderLine('X-DPoP-Nonce')); static::assertSame('rotated-nonce', $session->rememberedNonce); } public function testAuthenticatedRequestSenderDoesNotInvalidateAfterTransientRefreshFailure(): void { $inner = new TestXrpcRequestSender([ new Response(401, [ 'WWW-Authenticate' => 'DPoP error="invalid_token"', 'DPoP-Nonce' => 'nonce-value', ]), ]); $failure = new \RuntimeException('Authorization server temporarily unavailable.'); $session = new TestRefreshableDpopSession(refreshFailure: $failure); $factory = new HttpFactory(); $client = new XrpcClient( new AuthenticatedXrpcRequestSender($inner, $session), $factory, $factory, 'https://pds.example', self::testUrlPolicy(), ); try { $client->get('com.atproto.server.getSession'); static::fail('Expected the transient refresh failure.'); } catch (\RuntimeException $exception) { static::assertSame($failure, $exception); } static::assertSame(1, $session->refreshCount); static::assertFalse($session->invalidated); } public function testAuthenticatedRequestSenderInvalidatesAfterDefinitiveRefreshRejection(): void { $inner = new TestXrpcRequestSender([ new Response(401, [ 'WWW-Authenticate' => 'DPoP error="invalid_token"', 'DPoP-Nonce' => 'nonce-value', ]), ]); $session = new TestRefreshableDpopSession(refreshSucceeds: FALSE); $factory = new HttpFactory(); $client = new XrpcClient( new AuthenticatedXrpcRequestSender($inner, $session), $factory, $factory, 'https://pds.example', self::testUrlPolicy(), ); try { $client->get('com.atproto.server.getSession'); static::fail('Expected the original invalid-token response.'); } catch (XrpcHttpException $exception) { static::assertSame(401, $exception->statusCode); } static::assertSame(1, $session->refreshCount); static::assertTrue($session->invalidated); } public function testAuthenticatedRequestSenderDoesNotReplayUnreadableApplicationError(): void { $body = new NoSeekStream(Utils::streamFor('{"error":"InvalidRequest"}')); $inner = new TestXrpcRequestSender([ new Response(400, ['DPoP-Nonce' => 'nonce-value'], $body), ]); $factory = new HttpFactory(); $client = new XrpcClient( new AuthenticatedXrpcRequestSender($inner, new TestDpopNonceAwareSession()), $factory, $factory, 'https://pds.example', self::testUrlPolicy(), ); try { $client->post('com.atproto.repo.putRecord', ['repo' => 'did:plc:abc']); static::fail('Expected the application error response.'); } catch (XrpcHttpException $exception) { static::assertSame(400, $exception->statusCode); } static::assertSame(1, $inner->requestCount); } public function testAuthenticatedRequestSenderRemembersDpopNonceWhenSupported(): void { $inner = new TestXrpcRequestSender([ new Response(400, ['DPoP-Nonce' => 'nonce-value'], '{"error":"use_dpop_nonce"}'), new Response(200, ['DPoP-Nonce' => 'rotated-nonce'], '{}'), ]); $session = new TestRememberingDpopNonceSession(); $factory = new HttpFactory(); $client = new XrpcClient( new AuthenticatedXrpcRequestSender($inner, $session), $factory, $factory, 'https://pds.example', self::testUrlPolicy(), ); $client->post('com.atproto.repo.putRecord', ['repo' => 'did:plc:abc']); static::assertSame('rotated-nonce', $session->rememberedNonce); } public function testAuthenticatedRequestSenderRemembersNonceFromSuccessfulResponse(): void { $inner = new TestXrpcRequestSender([ new Response(200, ['DPoP-Nonce' => 'rotated-nonce'], '{}'), ]); $session = new TestRememberingDpopNonceSession(); $factory = new HttpFactory(); $client = new XrpcClient( new AuthenticatedXrpcRequestSender($inner, $session), $factory, $factory, 'https://pds.example', self::testUrlPolicy(), ); $client->get('com.atproto.server.getSession'); static::assertSame('rotated-nonce', $session->rememberedNonce); } public function testAuthenticatedRequestSenderAcceptsSuccessfulResponseWithoutDpopNonce(): void { $inner = new TestXrpcRequestSender([new Response(200, [], '{}')]); $factory = new HttpFactory(); $client = new XrpcClient( new AuthenticatedXrpcRequestSender($inner, new TestDpopNonceAwareSession()), $factory, $factory, 'https://pds.example', self::testUrlPolicy(), ); $response = $client->get('com.atproto.server.getSession'); static::assertSame([], $response); static::assertSame(1, $inner->requestCount); } public function testAuthenticatedRequestSenderDoesNotReplayNonceChallengeWithoutFreshNonce(): void { $inner = new TestXrpcRequestSender([ new Response(401, ['WWW-Authenticate' => 'DPoP error="use_dpop_nonce"'], '{}'), ]); $request = new HttpFactory()->createRequest('GET', 'https://pds.example/xrpc/com.example.get'); $response = new AuthenticatedXrpcRequestSender($inner, new TestDpopNonceAwareSession())->send($request); static::assertSame(401, $response->getStatusCode()); static::assertSame(1, $inner->requestCount); } public function testHttpErrorParsesXrpcErrorBody(): void { $requestSender = new TestXrpcRequestSender([new Response( 400, ['X-RateLimit' => 'no'], '{"error":"InvalidRequest","message":"Bad repo"}', )]); $factory = new HttpFactory(); $client = new XrpcClient($requestSender, $factory, $factory, 'https://pds.example', self::testUrlPolicy()); try { $client->get('com.atproto.repo.getRecord'); static::fail('Expected an XRPC HTTP exception.'); } catch (XrpcHttpException $e) { static::assertSame('com.atproto.repo.getRecord', $e->method); static::assertSame('https://pds.example', $e->serviceUrl); static::assertSame(400, $e->statusCode); static::assertSame('InvalidRequest', $e->xrpcError); static::assertSame('Bad repo', $e->xrpcMessage); static::assertSame(['error' => 'InvalidRequest', 'message' => 'Bad repo'], $e->decodedBody); static::assertSame(['no'], $e->headers['X-RateLimit']); } } public function testInvalidJsonThrowsDecodeException(): void { $requestSender = new TestXrpcRequestSender([new Response(200, [], 'not json')]); $factory = new HttpFactory(); $client = new XrpcClient($requestSender, $factory, $factory, 'https://pds.example', self::testUrlPolicy()); $this->expectException(XrpcDecodeException::class); $client->get('com.atproto.repo.getRecord'); } public function testWrongSuccessfulContentTypeThrowsProtocolException(): void { $requestSender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'text/plain'], '{"ok":true}'), ]); $factory = new HttpFactory(); $client = new XrpcClient($requestSender, $factory, $factory, 'https://pds.example', self::testUrlPolicy()); $this->expectException(XrpcProtocolException::class); $this->expectExceptionMessage('expected "application/json"'); $client->get('com.atproto.server.getSession'); } public function testMalformedJsonErrorBodyRemainsAnHttpException(): void { $requestSender = new TestXrpcRequestSender([ new Response(500, ['Content-Type' => 'application/json'], 'not-json'), ]); $factory = new HttpFactory(); $client = new XrpcClient($requestSender, $factory, $factory, 'https://pds.example', self::testUrlPolicy()); try { $client->get('com.atproto.server.getSession'); static::fail('Expected an XRPC HTTP exception.'); } catch (XrpcHttpException $exception) { static::assertSame(500, $exception->statusCode); static::assertSame('not-json', $exception->responseBody); static::assertNull($exception->decodedBody); } } public function testHttpExceptionMessageDoesNotEmbedRawResponseBody(): void { $body = \str_repeat('sensitive-response-', 100); $requestSender = new TestXrpcRequestSender([new Response(500, ['Content-Type' => 'text/plain'], $body)]); $factory = new HttpFactory(); $client = new XrpcClient($requestSender, $factory, $factory, 'https://pds.example', self::testUrlPolicy()); try { $client->get('com.atproto.server.getSession'); static::fail('Expected an XRPC HTTP exception.'); } catch (XrpcHttpException $exception) { static::assertSame($body, $exception->responseBody); static::assertStringNotContainsString('sensitive-response-', $exception->getMessage()); } } public function testRejectsResponseLargerThanConfiguredBudget(): void { $requestSender = new TestXrpcRequestSender([ new Response(200, ['Content-Length' => '1024'], \str_repeat('x', 1024)), ]); $factory = new HttpFactory(); $client = new XrpcClient($requestSender, $factory, $factory, 'https://pds.example', self::testUrlPolicy()); $this->expectException(XrpcException::class); $this->expectExceptionMessage('exceeds the 128-byte limit'); $client->get('com.atproto.repo.listRecords', options: new XrpcOptions(maxResponseBytes: 128)); } public function testRejectsJsonBeyondConfiguredDepth(): void { $requestSender = new TestXrpcRequestSender([ new Response(200, [], '{"one":{"two":{"three":true}}}'), ]); $factory = new HttpFactory(); $client = new XrpcClient($requestSender, $factory, $factory, 'https://pds.example', self::testUrlPolicy()); $this->expectException(XrpcDecodeException::class); $client->get('com.atproto.repo.listRecords', options: new XrpcOptions(maxJsonDepth: 2)); } public function testRejectsPrivateIpLiteralServiceUrl(): void { $requestSender = new TestXrpcRequestSender([new Response(200, [], '{}')]); $factory = new HttpFactory(); $client = new XrpcClient( $requestSender, $factory, $factory, 'https://127.0.0.1', new OutboundUrlPolicy(), ); $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Refusing disallowed URL'); $client->get('com.atproto.server.getSession'); } #[DataProvider('nonOriginServiceUrlProvider')] public function testRejectsNonOriginServiceUrl(string $serviceUrl): void { $requestSender = new TestXrpcRequestSender([new Response(200, [], '{}')]); $factory = new HttpFactory(); $client = new XrpcClient($requestSender, $factory, $factory, $serviceUrl, self::testUrlPolicy()); $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('must be an origin'); $client->get('com.atproto.server.getSession'); } /** * @return array */ public static function nonOriginServiceUrlProvider(): array { return [ 'path' => ['https://pds.example/xrpc'], 'query' => ['https://pds.example?tenant=one'], 'fragment' => ['https://pds.example#fragment'], ]; } private static function testUrlPolicy(): OutboundUrlPolicy { return new OutboundUrlPolicy(); } }