'did:plc:abc', 'handle' => 'example.com', 'accessJwt' => 'access', 'refreshJwt' => 'refresh', 'email' => 'user@example.com', 'emailConfirmed' => TRUE, 'active' => TRUE, 'status' => 'active', ], 'https://pds.example'); static::assertSame('did:plc:abc', $session->did); static::assertSame('example.com', $session->handle); static::assertSame('access', $session->accessJwt); static::assertSame('refresh', $session->refreshJwt); static::assertSame('https://pds.example', $session->pdsUrl); static::assertEquals($session, AtprotoSession::fromArray($session->toArray())); } public function testTokenSetParsesOAuthResponse(): void { $tokens = TokenSet::fromResponse([ 'access_token' => 'access', 'refresh_token' => 'refresh', 'token_type' => 'DPoP', 'scope' => 'atproto transition:generic', 'expires_in' => 3600, ], 1000); static::assertSame('access', $tokens->accessToken); static::assertSame('refresh', $tokens->refreshToken); static::assertSame('DPoP', $tokens->tokenType); static::assertSame('atproto transition:generic', $tokens->scope); static::assertSame(4600, $tokens->expiresAt); static::assertArrayNotHasKey('access_token', $tokens->raw); static::assertArrayNotHasKey('refresh_token', $tokens->raw); } public function testNullableDpopAlgorithmsSurvivePersistenceRoundTrips(): void { $state = new AuthorizationState( state: 'state-value', codeVerifier: 'verifier-value', redirectUri: 'https://client.example/callback', authorizationServer: 'https://auth.example', clientId: 'https://client.example/metadata.json', dpopAlgorithm: NULL, ); $session = new OAuthSession( did: 'did:plc:abc', handle: NULL, pdsUrl: NULL, authorizationServer: 'https://auth.example', tokens: new TokenSet('access'), dpopAlgorithm: NULL, ); static::assertNull(AuthorizationState::fromArray($state->toArray())->dpopAlgorithm); static::assertNull(OAuthSession::fromArray($session->toArray())->dpopAlgorithm); } /** @param array $data */ #[DataProvider('invalidAuthorizationStateDataProvider')] public function testAuthorizationStateRejectsMalformedPersistedOptionalValues(array $data): void { $this->expectException(\InvalidArgumentException::class); AuthorizationState::fromArray($data); } /** @return array}> */ public static function invalidAuthorizationStateDataProvider(): array { $valid = [ 'state' => 'state-value', 'codeVerifier' => 'verifier-value', 'redirectUri' => 'https://client.example/callback', 'authorizationServer' => 'https://auth.example', 'clientId' => 'https://client.example/metadata.json', ]; return [ 'non-list scopes' => [$valid + ['scopes' => ['scope' => 'atproto']]], 'empty scopes' => [$valid + ['scopes' => []]], 'invalid scope item' => [$valid + ['scopes' => ['atproto', 1]]], 'missing atproto scope' => [$valid + ['scopes' => ['transition:generic']]], 'invalid optional string' => [$valid + ['handle' => 1]], 'invalid JWK' => [$valid + ['dpopPrivateJwk' => 'secret']], 'invalid algorithm' => [$valid + ['dpopAlgorithm' => FALSE]], 'invalid timestamp' => [$valid + ['createdAt' => 'now']], ]; } /** @param array $change */ #[DataProvider('invalidOAuthSessionDataProvider')] public function testOAuthSessionRejectsMalformedPersistedOptionalValues(array $change): void { $data = new OAuthSession( did: 'did:plc:abc', handle: NULL, pdsUrl: NULL, authorizationServer: 'https://auth.example', tokens: new TokenSet('access'), )->toArray(); $this->expectException(\InvalidArgumentException::class); OAuthSession::fromArray(\array_replace($data, $change)); } /** @return array}> */ public static function invalidOAuthSessionDataProvider(): array { return [ 'invalid optional string' => [['handle' => 1]], 'empty optional string' => [['pdsUrl' => '']], 'invalid JWK' => [['dpopPrivateJwk' => 'secret']], 'invalid algorithm' => [['dpopAlgorithm' => FALSE]], 'invalid token field' => [['tokens' => ['accessToken' => 'access', 'expiresAt' => 'later']]], 'wrong persisted token type' => [['tokens' => ['accessToken' => 'access', 'tokenType' => 'Bearer']]], 'missing persisted atproto scope' => [[ 'tokens' => ['accessToken' => 'access', 'tokenType' => 'DPoP', 'scope' => 'transition:generic'], ]], 'list-shaped raw response' => [['tokens' => ['accessToken' => 'access', 'raw' => ['invalid']]]], ]; } public function testDebugOutputRedactsPersistedSecrets(): void { $tokens = new TokenSet('access-secret', 'refresh-secret', raw: ['extra' => 'safe']); $session = new OAuthSession( did: 'did:plc:abc', handle: NULL, pdsUrl: NULL, authorizationServer: 'https://auth.example', tokens: $tokens, dpopPrivateJwk: ['d' => 'private-secret'], ); static::assertStringNotContainsString('access-secret', \print_r($tokens, TRUE)); static::assertStringNotContainsString('refresh-secret', \print_r($tokens, TRUE)); static::assertStringNotContainsString('private-secret', \print_r($session, TRUE)); } public function testOAuthSessionProvidesAccessToken(): void { $session = new OAuthSession( did: 'did:plc:abc', handle: 'example.com', pdsUrl: 'https://pds.example', authorizationServer: 'https://auth.example', tokens: new TokenSet('access'), ); static::assertSame('access', $session->getAccessToken()); } public function testOAuthSessionCanBeWrappedAsAuthenticatedSession(): void { $session = new OAuthSession( did: 'did:plc:abc', handle: 'example.com', pdsUrl: 'https://pds.example', authorizationServer: 'https://auth.example', tokens: new TokenSet('access'), resourceServerNonce: 'stored-nonce', ); $authenticated = $session->withSigner(new AuthTestRequestSigner()); static::assertSame($session, $authenticated->getSession()); static::assertSame('access', $authenticated->getAccessToken()); static::assertSame('did:plc:abc', $authenticated->getSubjectDid()); static::assertSame('https://pds.example', $authenticated->getPdsUrl()); $request = new HttpFactory()->createRequest('GET', 'https://pds.example/xrpc/com.atproto.server.getSession'); $initial = $authenticated->sign($request); static::assertSame('signed', $initial->getHeaderLine('X-Signed')); static::assertSame('stored-nonce', $initial->getHeaderLine('X-DPoP-Nonce')); $signed = $authenticated->signWithDpopNonce($request, 'custom-nonce'); static::assertSame('signed', $signed->getHeaderLine('X-Signed')); static::assertSame('custom-nonce', $signed->getHeaderLine('X-DPoP-Nonce')); } public function testOAuthSessionBuildsDpopAuthenticatedSession(): void { $key = DpopPrivateKey::fromPem(self::createRsaPrivateKeyPem(), 'RS256'); $session = new OAuthSession( did: 'did:plc:abc', handle: 'example.com', pdsUrl: 'https://pds.example', authorizationServer: 'https://auth.example', tokens: new TokenSet('access-token'), dpopPrivateJwk: $key->privateJwk(), dpopAlgorithm: 'RS256', resourceServerNonce: 'stored-nonce', ); $request = new HttpFactory()->createRequest('GET', 'https://pds.example/xrpc/com.atproto.server.getSession'); $signed = $session->authenticatedSession()->sign($request); [, $payload] = self::decodeJwt($signed->getHeaderLine('DPoP')); static::assertSame('DPoP access-token', $signed->getHeaderLine('Authorization')); static::assertSame('stored-nonce', $payload['nonce']); } public function testOAuthSessionCanBeCopiedWithResourceServerNonce(): void { $session = new OAuthSession( did: 'did:plc:abc', handle: 'example.com', pdsUrl: 'https://pds.example', authorizationServer: 'https://auth.example', tokens: new TokenSet('access'), resourceServerNonce: 'old', ); $updated = $session->withResourceServerNonce('new'); static::assertSame('old', $session->resourceServerNonce); static::assertSame('new', $updated->resourceServerNonce); } public function testClientMetadataBuilderBuildsAtprotoMetadata(): void { $metadata = new ClientMetadataBuilder()->build(new OAuthConfig( clientId: 'https://client.example/metadata.json', redirectUris: ['https://client.example/callback'], scopes: ['atproto', 'transition:generic'], clientName: 'Example client', clientUri: 'https://client.example', logoUri: 'https://client.example/logo.png', jwksUri: 'https://client.example/jwks.json', )); static::assertSame('https://client.example/metadata.json', $metadata['client_id']); static::assertSame(['authorization_code', 'refresh_token'], $metadata['grant_types']); static::assertSame(['code'], $metadata['response_types']); static::assertSame(['https://client.example/callback'], $metadata['redirect_uris']); static::assertSame('atproto transition:generic', $metadata['scope']); static::assertSame('none', $metadata['token_endpoint_auth_method']); static::assertTrue($metadata['dpop_bound_access_tokens']); static::assertSame('https://client.example/jwks.json', $metadata['jwks_uri']); } /** * @param array{clientId: string, redirectUris: list, scopes?: list, clientUri?: string, logoUri?: string} $arguments */ #[DataProvider('invalidOAuthConfigProvider')] public function testOAuthConfigRejectsInvalidPublicWebMetadata(array $arguments, string $message): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage($message); new OAuthConfig( clientId: $arguments['clientId'], redirectUris: $arguments['redirectUris'], scopes: $arguments['scopes'] ?? ['atproto'], clientUri: $arguments['clientUri'] ?? NULL, logoUri: $arguments['logoUri'] ?? NULL, ); } /** * @return array, string}> */ public static function invalidOAuthConfigProvider(): array { return [ 'non-url client id' => [ [ 'clientId' => 'not-a-url', 'redirectUris' => ['https://client.example/callback'], ], 'client ID', ], 'client id port' => [ [ 'clientId' => 'https://client.example:8443/metadata.json', 'redirectUris' => ['https://client.example/callback'], ], 'client ID', ], 'non-https redirect' => [ [ 'clientId' => 'https://client.example/metadata.json', 'redirectUris' => ['javascript:alert(1)'], ], 'redirect URI', ], 'default redirect port' => [ [ 'clientId' => 'https://client.example/metadata.json', 'redirectUris' => ['https://client.example:443/callback'], ], 'redirect URI', ], 'different client URI hostname' => [ [ 'clientId' => 'https://client.example/metadata.json', 'redirectUris' => ['https://client.example/callback'], 'clientUri' => 'https://other.example', ], 'client ID hostname', ], 'non-https logo' => [ [ 'clientId' => 'https://client.example/metadata.json', 'redirectUris' => ['https://client.example/callback'], 'logoUri' => 'http://client.example/logo.png', ], 'logo URI', ], 'invalid scope token' => [ [ 'clientId' => 'https://client.example/metadata.json', 'redirectUris' => ['https://client.example/callback'], 'scopes' => ['atproto', 'bad scope'], ], 'scope-token', ], ]; } public function testDpopProofFactoryBuildsSignedProof(): void { $key = DpopPrivateKey::fromPem(self::createRsaPrivateKeyPem(), 'RS256'); $factory = new DpopProofFactory( $key, static fn (): string => 'fixed-jti', static fn (): int => 1_234_567_890, ); $request = new HttpFactory()->createRequest( 'GET', 'https://pds.example/xrpc/com.atproto.server.getSession?ignored=true', ); $jwt = $factory->createProof($request, 'access-token', 'nonce-value'); [$header, $payload] = self::decodeJwt($jwt); static::assertSame('dpop+jwt', $header['typ']); static::assertSame('RS256', $header['alg']); static::assertIsArray($header['jwk']); static::assertSame('RSA', $header['jwk']['kty']); static::assertSame('GET', $payload['htm']); static::assertSame('https://pds.example/xrpc/com.atproto.server.getSession', $payload['htu']); static::assertSame(1_234_567_890, $payload['iat']); static::assertSame('fixed-jti', $payload['jti']); static::assertSame(self::base64UrlEncode(\hash('sha256', 'access-token', TRUE)), $payload['ath']); static::assertSame('nonce-value', $payload['nonce']); } public function testDpopRequestSignerReplacesBearerAuthorization(): void { $key = DpopPrivateKey::fromPem(self::createRsaPrivateKeyPem(), 'RS256'); $factory = new DpopProofFactory( $key, static fn (): string => 'fixed-jti', static fn (): int => 1_234_567_890, ); $request = new HttpFactory() ->createRequest('POST', 'https://pds.example/xrpc/com.atproto.repo.putRecord') ->withHeader('Authorization', 'Bearer access-token'); $signed = new DpopRequestSigner($factory)->sign($request); static::assertSame('DPoP access-token', $signed->getHeaderLine('Authorization')); static::assertNotSame('', $signed->getHeaderLine('DPoP')); } private static function createRsaPrivateKeyPem(): string { $pem = ''; $key = \openssl_pkey_new([ 'private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA, ]); // Keep the defensive output check for the OpenSSL by-reference call even // though Mago retains the initialized string type. // @mago-expect analysis:redundant-type-comparison(2),redundant-logical-operation if ($key === FALSE || !\openssl_pkey_export($key, $pem) || !\is_string($pem)) { throw new \RuntimeException('Unable to create test RSA key.'); } return $pem; } /** * @return array{0: array, 1: array} */ private static function decodeJwt(string $jwt): array { $parts = \explode('.', $jwt); if (\count($parts) !== 3) { throw new \RuntimeException('Invalid test JWT.'); } $header = \json_decode(self::base64UrlDecode($parts[0]), TRUE, flags: JSON_THROW_ON_ERROR); $payload = \json_decode(self::base64UrlDecode($parts[1]), TRUE, flags: JSON_THROW_ON_ERROR); if (!\is_array($header) || !\is_array($payload)) { throw new \RuntimeException('Invalid test JWT payload.'); } /** @var array $header */ /** @var array $payload */ return [$header, $payload]; } private static function base64UrlEncode(string $value): string { return \rtrim(\strtr(\base64_encode($value), '+/', '-_'), '='); } private static function base64UrlDecode(string $value): string { $padding = \strlen($value) % 4; if ($padding !== 0) { $value .= \str_repeat('=', 4 - $padding); } $decoded = \base64_decode(\strtr($value, '-_', '+/'), TRUE); return \is_string($decoded) ? $decoded : ''; } }