| 1 |
<?php |
| 2 |
// phpcs:disable Yoast.NamingConventions.NamespaceName.TooLong -- Needed in the folder structure. |
| 3 |
|
| 4 |
namespace Yoast\WP\SEO\MyYoast_Client\Infrastructure\Crypto; |
| 5 |
|
| 6 |
use Yoast\WP\SEO\MyYoast_Client\Application\Exceptions\Client_Authentication_Exception; |
| 7 |
use Yoast\WP\SEO\MyYoast_Client\Application\Ports\Client_Authenticator_Interface; |
| 8 |
|
| 9 |
/** |
| 10 |
* Creates signed client_assertion JWTs for private_key_jwt authentication. |
| 11 |
* |
| 12 |
* Wraps Key_Pair_Manager and JWT_Signer to provide a single method for |
| 13 |
* generating client assertions, hiding key pair lifecycle from the application layer. |
| 14 |
*/ |
| 15 |
class Client_Authenticator implements Client_Authenticator_Interface { |
| 16 |
|
| 17 |
/** |
| 18 |
* The key pair manager. |
| 19 |
* |
| 20 |
* @var Key_Pair_Manager |
| 21 |
*/ |
| 22 |
private $key_pair_manager; |
| 23 |
|
| 24 |
/** |
| 25 |
* The JWT signer. |
| 26 |
* |
| 27 |
* @var JWT_Signer |
| 28 |
*/ |
| 29 |
private $jwt_signer; |
| 30 |
|
| 31 |
/** |
| 32 |
* Client_Authenticator constructor. |
| 33 |
* |
| 34 |
* @param Key_Pair_Manager $key_pair_manager The key pair manager. |
| 35 |
* @param JWT_Signer $jwt_signer The JWT signer. |
| 36 |
*/ |
| 37 |
public function __construct( Key_Pair_Manager $key_pair_manager, JWT_Signer $jwt_signer ) { |
| 38 |
$this->key_pair_manager = $key_pair_manager; |
| 39 |
$this->jwt_signer = $jwt_signer; |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* Creates a signed client_assertion JWT for the given audience. |
| 44 |
* |
| 45 |
* @param string $client_id The registered client_id. |
| 46 |
* @param string $audience The audience URL (typically the token endpoint). |
| 47 |
* |
| 48 |
* @return string The signed client_assertion JWT. |
| 49 |
* |
| 50 |
* @throws Client_Authentication_Exception If key retrieval or signing fails. |
| 51 |
*/ |
| 52 |
public function create_client_assertion( string $client_id, string $audience ): string { |
| 53 |
try { |
| 54 |
$key_pair = $this->key_pair_manager->get_or_create_key_pair( Key_Pair_Manager::PURPOSE_REGISTRATION ); |
| 55 |
|
| 56 |
return $this->jwt_signer->create_client_assertion( $client_id, $audience, $key_pair ); |
| 57 |
} catch ( Encryption_Exception |JWT_Signing_Exception $e ) { |
| 58 |
// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal exception message. |
| 59 |
throw new Client_Authentication_Exception( 'Client assertion signing failed: ' . $e->getMessage(), 0, $e ); |
| 60 |
} |
| 61 |
} |
| 62 |
} |
| 63 |
|