Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427<?php
declare(strict_types=1);
namespace Wotnak\Atproto\Tests\Unit;
use GuzzleHttp\Psr7\HttpFactory;use PHPUnit\Framework\Attributes\DataProvider;use PHPUnit\Framework\TestCase;use Wotnak\Atproto\Auth\AtprotoSession;use Wotnak\Atproto\Auth\OAuth\AuthorizationState;use Wotnak\Atproto\Auth\OAuth\ClientMetadataBuilder;use Wotnak\Atproto\Auth\OAuth\DpopPrivateKey;use Wotnak\Atproto\Auth\OAuth\DpopProofFactory;use Wotnak\Atproto\Auth\OAuth\DpopRequestSigner;use Wotnak\Atproto\Auth\OAuth\OAuthConfig;use Wotnak\Atproto\Auth\OAuth\OAuthSession;use Wotnak\Atproto\Auth\OAuth\TokenSet;use Wotnak\Atproto\Tests\Support\AuthTestRequestSigner;
/** * Tests authentication value objects and builders. */final class AuthTest extends TestCase {
public function testAtprotoSessionParsesServerResponse(): void { $session = AtprotoSession::fromCreateSessionResponse([ 'did' => '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<string, mixed> $data */ #[DataProvider('invalidAuthorizationStateDataProvider')] public function testAuthorizationStateRejectsMalformedPersistedOptionalValues(array $data): void { $this->expectException(\InvalidArgumentException::class); AuthorizationState::fromArray($data); }
/** @return array<string, array{array<string, mixed>}> */ 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<string, mixed> $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<string, array{array<string, mixed>}> */ 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<string>, scopes?: list<string>, 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, array{array<string, mixed>, 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<string, mixed>, 1: array<string, mixed>} */ 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<string, mixed> $header */ /** @var array<string, mixed> $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 : ''; }
}