Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230<?php
declare(strict_types=1);
namespace Wotnak\Atproto\Client;
use Psr\Http\Message\RequestInterface;use Psr\Http\Message\ResponseInterface;use Wotnak\Atproto\Http\BoundedResponseBody;
/** * Applies an authenticated session before sending XRPC requests. * * @api */final readonly class AuthenticatedXrpcRequestSender implements XrpcRequestSenderInterface {
private const MAX_AUTH_ERROR_BYTES = 65_536;
private string $credentialOrigin;
public function __construct( private XrpcRequestSenderInterface $inner, private AuthenticatedSessionInterface $session, ?string $credentialOrigin = NULL, ) { $credentialOrigin ??= $this->session->getPdsUrl(); if ($credentialOrigin === NULL || $credentialOrigin === '') { throw new \InvalidArgumentException('Authenticated request sender requires a credential origin.'); } $this->credentialOrigin = self::normalizeOrigin($credentialOrigin); }
/** * Signs and sends an XRPC request to the credential origin. */ public function send(RequestInterface $request): ResponseInterface { if (self::normalizeOrigin((string) $request->getUri()) !== $this->credentialOrigin) { throw new \InvalidArgumentException('Refusing to send authenticated credentials to a different origin.'); } $response = $this->inner->send($this->session->sign($request)); $nonceRetried = FALSE; $refreshRetried = FALSE;
while (TRUE) { $responseNonce = $this->rememberResponseDpopNonce($response); if ( !$nonceRetried && $this->session instanceof DpopNonceAwareAuthenticatedSessionInterface && $this->isDpopNonceResponse($response) && $this->canReplay($request) ) { if ($responseNonce !== NULL) { $nonceRetried = TRUE; $this->rewindBody($request); $response = $this->inner->send($this->session->signWithDpopNonce($request, $responseNonce)); continue; } }
if ( !$refreshRetried && $this->session instanceof RefreshableAuthenticatedSessionInterface && $this->isInvalidTokenResponse($response) && $this->canReplay($request) ) { $refreshRetried = TRUE; if (!$this->session->refresh()) { $this->session->invalidate(); return $response; }
$this->rewindBody($request); $response = $this->inner->send($this->session->sign($request)); continue; }
if ( $refreshRetried && $this->session instanceof RefreshableAuthenticatedSessionInterface && $this->isInvalidTokenResponse($response) ) { $this->session->invalidate(); } return $response; } }
private function rememberResponseDpopNonce(ResponseInterface $response): ?string { if (!$this->session instanceof DpopNonceAwareAuthenticatedSessionInterface) { return NULL; }
$nonce = \trim($response->getHeaderLine('DPoP-Nonce')); if ($nonce === '') { return NULL; } if ($this->session instanceof RememberingDpopNonceAuthenticatedSessionInterface) { $this->session->rememberDpopNonce($nonce); } return $nonce; }
private static function canReplay(RequestInterface $request): bool { if (\in_array(\strtoupper($request->getMethod()), ['GET', 'HEAD', 'OPTIONS'], TRUE)) { return TRUE; }
return $request->getBody()->isSeekable(); }
private static function normalizeOrigin(string $url): string { try { $parts = \parse_url($url); } // ValueError is an expected invalid-input result at this API boundary. // @mago-expect analysis:avoid-catching-error catch (\ValueError) { $parts = FALSE; } if (!\is_array($parts) || !isset($parts['scheme'], $parts['host'])) { throw new \InvalidArgumentException('Credential origin must be an absolute URL.'); }
$scheme = \strtolower($parts['scheme']); $host = \strtolower($parts['host']); $port = \is_int($parts['port'] ?? NULL) ? $parts['port'] : NULL; if ($scheme === 'https' && $port === 443 || $scheme === 'http' && $port === 80) { $port = NULL; } if (\str_contains($host, ':') && !\str_starts_with($host, '[')) { $host = '[' . $host . ']'; } return $scheme . '://' . $host . ($port !== NULL ? ':' . $port : ''); }
private static function rewindBody(RequestInterface $request): void { $body = $request->getBody(); if ($body->isSeekable()) { $body->rewind(); } }
private function isInvalidTokenResponse(ResponseInterface $response): bool { if ( $response->getStatusCode() === 401 && $this->hasInvalidTokenChallenge($response->getHeaderLine('WWW-Authenticate')) ) { return TRUE; }
if (!\in_array($response->getStatusCode(), [400, 401], TRUE)) { return FALSE; }
$contents = $this->readAuthErrorBody($response); if ($contents === NULL || $contents === '') { return FALSE; }
try { $decoded = \json_decode($contents, TRUE, 16, JSON_THROW_ON_ERROR); } catch (\JsonException) { return FALSE; }
return \is_array($decoded) && \in_array($decoded['error'] ?? NULL, ['ExpiredToken', 'InvalidToken'], TRUE); }
private function isDpopNonceResponse(ResponseInterface $response): bool { if (!\in_array($response->getStatusCode(), [400, 401], TRUE) || $response->getHeaderLine('DPoP-Nonce') === '') { return FALSE; } if ($this->hasDpopNonceChallenge($response->getHeaderLine('WWW-Authenticate'))) { return TRUE; }
$contents = $this->readAuthErrorBody($response); if ($contents === NULL || $contents === '') { return FALSE; }
try { $decoded = \json_decode($contents, TRUE, 16, JSON_THROW_ON_ERROR); } catch (\JsonException) { return FALSE; }
return \is_array($decoded) && ($decoded['error'] ?? NULL) === 'use_dpop_nonce'; }
/** * Reads a bounded authentication error while preserving the stream position. */ private static function readAuthErrorBody(ResponseInterface $response): ?string { return BoundedResponseBody::readPreservingPosition($response, self::MAX_AUTH_ERROR_BYTES); }
private static function hasInvalidTokenChallenge(string $challenge): bool { return self::hasChallengeError($challenge, ['bearer', 'dpop'], 'invalid_token'); }
private static function hasDpopNonceChallenge(string $challenge): bool { return self::hasChallengeError($challenge, ['dpop'], 'use_dpop_nonce'); }
/** * @param list<string> $schemes */ private static function hasChallengeError(string $header, array $schemes, string $error): bool { $challenges = WwwAuthenticateParser::parse($header); if ($challenges === NULL) { return FALSE; } foreach ($challenges as $scheme => $parameters) { if ( \in_array(\strtolower($scheme), $schemes, TRUE) && \is_array($parameters) && ($parameters['error'] ?? NULL) === $error ) { return TRUE; } } return FALSE; }
}