'application/json', 'DPoP-Nonce' => 'par-nonce'], \json_encode(['request_uri' => 'urn:ietf:params:oauth:request_uri:abc'], JSON_THROW_ON_ERROR), ), ]); $client = new OAuthClient( $oauthHttpClient, $factory, $factory, new DidResolver($oauthHttpClient, $factory, urlPolicy: self::testUrlPolicy()), new HandleResolver($oauthHttpClient, $factory, urlPolicy: self::testUrlPolicy()), self::testUrlPolicy(), ); $config = new OAuthConfig( clientId: 'https://client.example/metadata.json', redirectUris: ['https://client.example/callback'], ); $request = $client->createAuthorizationRequest( $config, 'https://client.example/callback', 'https://pds.example', ); static::assertSame('par-nonce', $request->state->authorizationServerNonce); static::assertStringContainsString( 'request_uri=urn%3Aietf%3Aparams%3Aoauth%3Arequest_uri%3Aabc', $request->authorizationUrl, ); $parParameters = []; \parse_str((string) $oauthHttpClient->lastRequest?->getBody(), $parParameters); static::assertArrayNotHasKey('login_hint', $parParameters); } public function testAccountStartedAuthorizationRequestIncludesLoginHint(): void { $factory = new HttpFactory(); $oauthHttpClient = new OAuthTestHttpClient([ self::jsonResponse(self::didDocument('did:plc:abc', 'https://pds.example')), self::jsonResponse(self::resourceMetadata('https://pds.example', 'https://auth.example')), self::jsonResponse(self::metadata('https://auth.example')), new Response( 201, ['Content-Type' => 'application/json', 'DPoP-Nonce' => 'par-nonce'], \json_encode(['request_uri' => 'urn:ietf:params:oauth:request_uri:abc'], JSON_THROW_ON_ERROR), ), ]); $client = self::client($oauthHttpClient, $factory); $client->createAuthorizationRequest( self::config(), 'https://client.example/callback', 'did:plc:abc', ); $parParameters = []; \parse_str((string) $oauthHttpClient->lastRequest?->getBody(), $parParameters); static::assertSame('did:plc:abc', $parParameters['login_hint'] ?? NULL); } public function testAuthorizationRequestRetainsAuthorizationEndpointQuery(): void { $factory = new HttpFactory(); $oauthHttpClient = new OAuthTestHttpClient([ self::jsonResponse(self::resourceMetadata('https://pds.example', 'https://auth.example')), self::jsonResponse(self::metadata('https://auth.example', [ 'authorization_endpoint' => 'https://auth.example/authorize?tenant=one', ])), new Response( 201, ['Content-Type' => 'application/json', 'DPoP-Nonce' => 'par-nonce'], \json_encode(['request_uri' => 'urn:ietf:params:oauth:request_uri:abc'], JSON_THROW_ON_ERROR), ), ]); $client = self::client($oauthHttpClient, $factory); $request = $client->createAuthorizationRequest( self::config(), 'https://client.example/callback', 'https://pds.example', ); static::assertStringStartsWith('https://auth.example/authorize?tenant=one&client_id=', $request->authorizationUrl); $query = \parse_url($request->authorizationUrl, PHP_URL_QUERY); static::assertIsString($query); $parameters = []; \parse_str($query, $parameters); static::assertSame('one', $parameters['tenant']); static::assertSame('https://client.example/metadata.json', $parameters['client_id']); static::assertSame('urn:ietf:params:oauth:request_uri:abc', $parameters['request_uri']); } public function testAuthorizationRequestRejectsEndpointFragment(): void { $factory = new HttpFactory(); $oauthHttpClient = new OAuthTestHttpClient([ self::jsonResponse(self::resourceMetadata('https://pds.example', 'https://auth.example')), self::jsonResponse(self::metadata('https://auth.example', [ 'authorization_endpoint' => 'https://auth.example/authorize#fragment', ])), ]); $client = self::client($oauthHttpClient, $factory); $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('without a fragment'); $client->createAuthorizationRequest( self::config(), 'https://client.example/callback', 'https://pds.example', ); } public function testServerStartedExchangeRejectsSubjectBoundToDifferentIssuer(): void { $factory = new HttpFactory(); $oauthHttpClient = new OAuthTestHttpClient([ self::jsonResponse(self::metadata('https://auth.example')), self::dpopResponse([ 'sub' => 'did:plc:abc', 'access_token' => 'access', 'token_type' => 'DPoP', 'scope' => 'atproto', ]), self::jsonResponse(self::resourceMetadata('https://pds.example', 'https://other-auth.example')), self::jsonResponse(self::metadata('https://other-auth.example')), ]); $didHttpClient = new OAuthTestHttpClient([ self::jsonResponse(self::didDocument('did:plc:abc', 'https://pds.example')), ]); $client = new OAuthClient( $oauthHttpClient, $factory, $factory, new DidResolver($didHttpClient, $factory, urlPolicy: self::testUrlPolicy()), new HandleResolver($oauthHttpClient, $factory, urlPolicy: self::testUrlPolicy()), self::testUrlPolicy(), ); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('OAuth token subject is not authoritative for the callback issuer.'); $client->exchangeAuthorizationCode(self::serverStartedState(), 'code-value', 'https://auth.example'); } public function testServerStartedExchangeAcceptsSubjectBoundToCallbackIssuer(): void { $factory = new HttpFactory(); $oauthHttpClient = new OAuthTestHttpClient([ self::jsonResponse(self::metadata('https://auth.example')), self::dpopResponse([ 'sub' => 'did:plc:abc', 'access_token' => 'access', 'refresh_token' => 'refresh', 'token_type' => 'DPoP', 'scope' => 'atproto', ]), self::jsonResponse(self::resourceMetadata('https://pds.example', 'https://auth.example')), self::jsonResponse(self::metadata('https://auth.example')), ]); $didHttpClient = new OAuthTestHttpClient([ self::jsonResponse(self::didDocument('did:plc:abc', 'https://pds.example')), ]); $client = new OAuthClient( $oauthHttpClient, $factory, $factory, new DidResolver($didHttpClient, $factory, urlPolicy: self::testUrlPolicy()), new HandleResolver($oauthHttpClient, $factory, urlPolicy: self::testUrlPolicy()), self::testUrlPolicy(), ); $session = $client->exchangeAuthorizationCode(self::serverStartedState(), 'code-value', 'https://auth.example'); static::assertSame('did:plc:abc', $session->did); static::assertSame('https://pds.example', $session->pdsUrl); static::assertSame('https://auth.example', $session->authorizationServer); static::assertSame('access', $session->tokens->accessToken); static::assertSame(4, $oauthHttpClient->requestCount); } public function testExchangeRejectsMismatchedAuthorizationServerMetadataIssuer(): void { $factory = new HttpFactory(); $oauthHttpClient = new OAuthTestHttpClient([ self::jsonResponse(self::metadata('https://different-auth.example')), ]); $client = new OAuthClient( $oauthHttpClient, $factory, $factory, new DidResolver($oauthHttpClient, $factory, urlPolicy: self::testUrlPolicy()), new HandleResolver($oauthHttpClient, $factory, urlPolicy: self::testUrlPolicy()), self::testUrlPolicy(), ); $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Authorization Server metadata issuer does not match the discovery URL.'); $client->exchangeAuthorizationCode(self::serverStartedState(), 'code-value', 'https://auth.example'); } public function testExchangeRejectsPrivateAuthorizationServerMetadataEndpoint(): void { $factory = new HttpFactory(); $oauthHttpClient = new OAuthTestHttpClient([ self::jsonResponse(self::metadata('https://auth.example', [ 'token_endpoint' => 'https://10.0.0.1/token', ])), ]); $client = new OAuthClient( $oauthHttpClient, $factory, $factory, new DidResolver($oauthHttpClient, $factory, urlPolicy: self::testUrlPolicy()), new HandleResolver($oauthHttpClient, $factory, urlPolicy: self::testUrlPolicy()), self::testUrlPolicy(), ); $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Refusing disallowed URL'); $client->exchangeAuthorizationCode(self::serverStartedState(), 'code-value', 'https://auth.example'); } public function testExchangeAcceptsTokenResponseWithoutDpopNonce(): void { $factory = new HttpFactory(); $oauthHttpClient = new OAuthTestHttpClient([ self::jsonResponse(self::metadata('https://auth.example')), self::jsonResponse([ 'sub' => 'did:plc:abc', 'access_token' => 'access', 'token_type' => 'DPoP', 'scope' => 'atproto', ]), self::jsonResponse(self::resourceMetadata('https://pds.example', 'https://auth.example')), self::jsonResponse(self::metadata('https://auth.example')), ]); $didHttpClient = new OAuthTestHttpClient([ self::jsonResponse(self::didDocument('did:plc:abc', 'https://pds.example')), ]); $client = new OAuthClient( $oauthHttpClient, $factory, $factory, new DidResolver($didHttpClient, $factory, urlPolicy: self::testUrlPolicy()), new HandleResolver($oauthHttpClient, $factory, urlPolicy: self::testUrlPolicy()), self::testUrlPolicy(), ); $session = $client->exchangeAuthorizationCode(self::serverStartedState(), 'code-value', 'https://auth.example'); static::assertSame('access', $session->tokens->accessToken); static::assertNull($session->authorizationServerNonce); } public function testTokenErrorWithoutDpopNonceIsNotMasked(): void { $factory = new HttpFactory(); $oauthHttpClient = new OAuthTestHttpClient([ self::jsonResponse(self::metadata('https://auth.example')), self::jsonResponse([ 'error' => 'invalid_grant', 'error_description' => 'Refresh token was already used.', ], 400), ]); $client = self::client($oauthHttpClient, $factory); $dpopKey = DpopPrivateKey::generate('ES256'); $session = new OAuthSession( did: 'did:plc:abc', handle: NULL, pdsUrl: 'https://pds.example', authorizationServer: 'https://auth.example', tokens: new TokenSet('old-access', 'old-refresh'), dpopPrivateJwk: $dpopKey->privateJwk(), dpopAlgorithm: $dpopKey->algorithm, ); try { $client->refreshSession(self::config(), $session); static::fail('Expected invalid_grant.'); } catch (OAuthHttpException $exception) { static::assertSame('invalid_grant', $exception->oauthError); } } public function testRefreshPreservesRefreshTokenWhenNotRotated(): void { $factory = new HttpFactory(); $oauthHttpClient = new OAuthTestHttpClient([ self::jsonResponse(self::metadata('https://auth.example')), self::dpopResponse([ 'access_token' => 'new-access', 'token_type' => 'DPoP', 'scope' => 'atproto', ], 'new-auth-nonce'), ]); $client = new OAuthClient( $oauthHttpClient, $factory, $factory, new DidResolver($oauthHttpClient, $factory, urlPolicy: self::testUrlPolicy()), new HandleResolver($oauthHttpClient, $factory, urlPolicy: self::testUrlPolicy()), self::testUrlPolicy(), ); $dpopKey = DpopPrivateKey::generate('ES256'); $session = new OAuthSession( did: 'did:plc:abc', handle: 'alice.example', pdsUrl: 'https://pds.example', authorizationServer: 'https://auth.example', tokens: new TokenSet('old-access', 'old-refresh'), dpopPrivateJwk: $dpopKey->privateJwk(), dpopAlgorithm: $dpopKey->algorithm, ); $config = new OAuthConfig( clientId: 'https://client.example/metadata.json', redirectUris: ['https://client.example/callback'], ); $refreshed = $client->refreshSession($config, $session); static::assertSame('new-access', $refreshed->tokens->accessToken); static::assertSame('old-refresh', $refreshed->tokens->refreshToken); static::assertSame('new-auth-nonce', $refreshed->authorizationServerNonce); } public function testRefreshExposesDefinitiveInvalidGrant(): void { $factory = new HttpFactory(); $oauthHttpClient = new OAuthTestHttpClient([ self::jsonResponse(self::metadata('https://auth.example')), self::dpopResponse([ 'error' => 'invalid_grant', 'error_description' => 'Refresh token was already used.', ], status: 400), ]); $client = self::client($oauthHttpClient, $factory); $dpopKey = DpopPrivateKey::generate('ES256'); $session = new OAuthSession( did: 'did:plc:abc', handle: 'alice.example', pdsUrl: 'https://pds.example', authorizationServer: 'https://auth.example', tokens: new TokenSet('old-access', 'old-refresh'), dpopPrivateJwk: $dpopKey->privateJwk(), dpopAlgorithm: $dpopKey->algorithm, ); try { $client->refreshSession(self::config(), $session); static::fail('Expected invalid_grant.'); } catch (OAuthHttpException $exception) { static::assertSame(400, $exception->statusCode); static::assertSame('invalid_grant', $exception->oauthError); static::assertSame('refresh_token', $exception->grantType); static::assertTrue($exception->definitivelyRejectsRefreshToken()); } } public function testOnlyRefreshGrantRejectionDefinitivelyRejectsRefreshToken(): void { static::assertTrue( new OAuthHttpException( endpoint: 'token', statusCode: 400, oauthError: 'invalid_grant', oauthErrorDescription: NULL, responseData: [], grantType: 'refresh_token', )->definitivelyRejectsRefreshToken(), ); foreach ([ ['PAR', 400, 'invalid_grant', NULL], ['token', 400, 'invalid_grant', 'authorization_code'], ['token', 503, 'invalid_grant', 'refresh_token'], ['token', 400, 'invalid_token', 'refresh_token'], ] as [$endpoint, $statusCode, $oauthError, $grantType]) { static::assertFalse( new OAuthHttpException( endpoint: $endpoint, statusCode: $statusCode, oauthError: $oauthError, oauthErrorDescription: NULL, responseData: [], grantType: $grantType, )->definitivelyRejectsRefreshToken(), ); } } public function testAuthorizationRequestRejectsMismatchedResourceMetadata(): void { $factory = new HttpFactory(); $oauthHttpClient = new OAuthTestHttpClient([ self::jsonResponse(self::resourceMetadata('https://different-pds.example', 'https://auth.example')), ]); $client = self::client($oauthHttpClient, $factory); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('does not match the resource server origin'); $client->createAuthorizationRequest( self::config(), 'https://client.example/callback', 'https://pds.example', ); } public function testAuthorizationRequestRejectsMultipleAuthorizationServers(): void { $factory = new HttpFactory(); $metadata = self::resourceMetadata('https://pds.example', 'https://auth.example'); $metadata['authorization_servers'] = ['https://auth.example', 'https://other-auth.example']; $oauthHttpClient = new OAuthTestHttpClient([self::jsonResponse($metadata)]); $client = self::client($oauthHttpClient, $factory); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('exactly one authorization server'); $client->createAuthorizationRequest( self::config(), 'https://client.example/callback', 'https://pds.example', ); } public function testAuthorizationRequestFallsBackOnlyWhenResourceMetadataIsNotFound(): void { $factory = new HttpFactory(); $oauthHttpClient = new OAuthTestHttpClient([ new Response(404), self::jsonResponse(self::metadata('https://pds.example')), new Response( 201, ['Content-Type' => 'application/json'], \json_encode(['request_uri' => 'urn:ietf:params:oauth:request_uri:fallback'], JSON_THROW_ON_ERROR), ), ]); $client = self::client($oauthHttpClient, $factory); $request = $client->createAuthorizationRequest( self::config(), 'https://client.example/callback', 'https://pds.example', ); static::assertStringStartsWith('https://pds.example/authorize?', $request->authorizationUrl); static::assertSame(3, $oauthHttpClient->requestCount); } public function testAuthorizationRequestRejectsResourceMetadataServerErrorWithoutFallback(): void { $factory = new HttpFactory(); $oauthHttpClient = new OAuthTestHttpClient([new Response(500)]); $client = self::client($oauthHttpClient, $factory); try { $client->createAuthorizationRequest( self::config(), 'https://client.example/callback', 'https://pds.example', ); static::fail('Expected protected-resource discovery to fail.'); } catch (OAuthException $exception) { static::assertSame('OAuth metadata request failed with HTTP 500.', $exception->getMessage()); static::assertSame(1, $oauthHttpClient->requestCount); } } public function testAuthorizationRequestRejectsResourceMetadataNetworkErrorWithoutFallback(): void { $factory = new HttpFactory(); $failure = new class('Network unavailable.') extends \RuntimeException implements ClientExceptionInterface {}; $oauthHttpClient = new OAuthTestHttpClient([$failure]); $client = self::client($oauthHttpClient, $factory); try { $client->createAuthorizationRequest( self::config(), 'https://client.example/callback', 'https://pds.example', ); static::fail('Expected protected-resource discovery to fail.'); } catch (OAuthException $exception) { static::assertSame('OAuth metadata request failed: Network unavailable.', $exception->getMessage()); static::assertSame($failure, $exception->getPrevious()); static::assertSame(1, $oauthHttpClient->requestCount); } } public function testAuthorizationRequestRejectsMissingAuthorizationServer(): void { $factory = new HttpFactory(); $metadata = self::resourceMetadata('https://pds.example', 'https://auth.example'); $metadata['authorization_servers'] = []; $oauthHttpClient = new OAuthTestHttpClient([self::jsonResponse($metadata)]); $client = self::client($oauthHttpClient, $factory); $this->expectException(OAuthException::class); $this->expectExceptionMessage('exactly one authorization server'); $client->createAuthorizationRequest( self::config(), 'https://client.example/callback', 'https://pds.example', ); } public function testMalformedMetadataJsonUsesOAuthExceptionHierarchy(): void { $factory = new HttpFactory(); $oauthHttpClient = new OAuthTestHttpClient([ new Response(200, ['Content-Type' => 'application/json'], 'not-json'), ]); $client = self::client($oauthHttpClient, $factory); try { $client->createAuthorizationRequest( self::config(), 'https://client.example/callback', 'https://pds.example', ); static::fail('Expected metadata decoding to fail.'); } catch (OAuthException $exception) { static::assertInstanceOf(\JsonException::class, $exception->getPrevious()); } } public function testAuthorizationRequestAcceptsMatchingProtectedResources(): void { $factory = new HttpFactory(); $oauthHttpClient = new OAuthTestHttpClient([ self::jsonResponse(self::resourceMetadata('https://pds.example', 'https://auth.example')), self::jsonResponse(self::metadata('https://auth.example', [ 'protected_resources' => ['https://pds.example'], ])), new Response( 201, ['Content-Type' => 'application/json'], \json_encode(['request_uri' => 'urn:ietf:params:oauth:request_uri:protected'], JSON_THROW_ON_ERROR), ), ]); $client = self::client($oauthHttpClient, $factory); $request = $client->createAuthorizationRequest( self::config(), 'https://client.example/callback', 'https://pds.example', ); static::assertStringStartsWith('https://auth.example/authorize?', $request->authorizationUrl); } public function testAuthorizationRequestRejectsMismatchedProtectedResources(): void { $factory = new HttpFactory(); $oauthHttpClient = new OAuthTestHttpClient([ self::jsonResponse(self::resourceMetadata('https://pds.example', 'https://auth.example')), self::jsonResponse(self::metadata('https://auth.example', [ 'protected_resources' => ['https://other-pds.example'], ])), ]); $client = self::client($oauthHttpClient, $factory); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('not protected by issuer'); $client->createAuthorizationRequest( self::config(), 'https://client.example/callback', 'https://pds.example', ); } public function testAuthorizationRequestRejectsIncompleteAtprotoServerMetadata(): void { $factory = new HttpFactory(); $oauthHttpClient = new OAuthTestHttpClient([ self::jsonResponse(self::resourceMetadata('https://pds.example', 'https://auth.example')), self::jsonResponse([ 'issuer' => 'https://auth.example', 'authorization_endpoint' => 'https://auth.example/authorize', 'token_endpoint' => 'https://auth.example/token', 'pushed_authorization_request_endpoint' => 'https://auth.example/par', ]), ]); $client = self::client($oauthHttpClient, $factory); $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('response_types_supported'); $client->createAuthorizationRequest( self::config(), 'https://client.example/callback', 'https://pds.example', ); } /** * @param array $tokenResponse */ #[\PHPUnit\Framework\Attributes\DataProvider('invalidRefreshTokenResponseProvider')] public function testRefreshRejectsInvalidAtprotoTokenResponse(array $tokenResponse, string $message): void { $factory = new HttpFactory(); $oauthHttpClient = new OAuthTestHttpClient([ self::jsonResponse(self::metadata('https://auth.example')), self::dpopResponse($tokenResponse), ]); $client = self::client($oauthHttpClient, $factory); $dpopKey = DpopPrivateKey::generate('ES256'); $session = new OAuthSession( did: 'did:plc:abc', handle: NULL, pdsUrl: 'https://pds.example', authorizationServer: 'https://auth.example', tokens: new TokenSet('old-access', 'old-refresh'), dpopPrivateJwk: $dpopKey->privateJwk(), dpopAlgorithm: $dpopKey->algorithm, ); $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage($message); $client->refreshSession(self::config(), $session); } /** * @return array, string}> */ public static function invalidRefreshTokenResponseProvider(): array { return [ 'missing scope' => [ [ 'access_token' => 'new-access', 'token_type' => 'DPoP', ], 'atproto scope', ], 'wrong token type' => [ [ 'access_token' => 'new-access', 'token_type' => 'Bearer', 'scope' => 'atproto', ], 'DPoP token type', ], ]; } private static function serverStartedState(): AuthorizationState { $dpopKey = DpopPrivateKey::generate('ES256'); return new AuthorizationState( state: 'state-value', codeVerifier: 'code-verifier', redirectUri: 'https://client.example/callback', authorizationServer: 'https://auth.example', clientId: 'https://client.example/metadata.json', pdsUrl: 'https://entry.example', dpopPrivateJwk: $dpopKey->privateJwk(), dpopAlgorithm: $dpopKey->algorithm, ); } /** * @param array $overrides * @return array */ private static function metadata(string $issuer, array $overrides = []): array { return \array_replace([ 'issuer' => $issuer, 'authorization_endpoint' => $issuer . '/authorize', 'token_endpoint' => $issuer . '/token', 'pushed_authorization_request_endpoint' => $issuer . '/par', 'response_types_supported' => ['code'], 'grant_types_supported' => ['authorization_code', 'refresh_token'], 'code_challenge_methods_supported' => ['S256'], 'token_endpoint_auth_methods_supported' => ['none', 'private_key_jwt'], 'token_endpoint_auth_signing_alg_values_supported' => ['ES256'], 'scopes_supported' => ['atproto'], 'authorization_response_iss_parameter_supported' => TRUE, 'require_pushed_authorization_requests' => TRUE, 'dpop_signing_alg_values_supported' => ['ES256'], 'client_id_metadata_document_supported' => TRUE, ], $overrides); } /** * @return array */ private static function resourceMetadata(string $resource, string $authorizationServer): array { return [ 'resource' => $resource, 'authorization_servers' => [$authorizationServer], ]; } private static function config(): OAuthConfig { return new OAuthConfig( clientId: 'https://client.example/metadata.json', redirectUris: ['https://client.example/callback'], ); } private static function client(OAuthTestHttpClient $httpClient, HttpFactory $factory): OAuthClient { return new OAuthClient( $httpClient, $factory, $factory, new DidResolver($httpClient, $factory, urlPolicy: self::testUrlPolicy()), new HandleResolver($httpClient, $factory, urlPolicy: self::testUrlPolicy()), self::testUrlPolicy(), ); } /** * @return array */ private static function didDocument(string $did, string $pdsUrl): array { return [ 'id' => $did, 'service' => [ [ 'id' => '#atproto_pds', 'type' => 'AtprotoPersonalDataServer', 'serviceEndpoint' => $pdsUrl, ], ], ]; } /** * @param array $data */ private static function jsonResponse(array $data, int $status = 200): Response { return new Response($status, ['Content-Type' => 'application/json'], \json_encode($data, JSON_THROW_ON_ERROR)); } /** * @param array $data */ private static function dpopResponse(array $data, string $nonce = 'token-nonce', int $status = 200): Response { return new Response( $status, [ 'Content-Type' => 'application/json', 'DPoP-Nonce' => $nonce, ], \json_encode($data, JSON_THROW_ON_ERROR), ); } private static function testUrlPolicy(): OutboundUrlPolicy { return new OutboundUrlPolicy(); } }