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 $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; } }