PluginProbe
Yoast SEO – Advanced SEO with real-time guidance and built-in AI / 28.0
Yoast SEO – Advanced SEO with real-time guidance and built-in AI v28.0
28.5 28.4 28.3 28.2 28.1 28.0 27.9 27.8 27.7 27.6 27.5 trunk 18.0 18.1 18.2 18.3 18.4 18.4.1 18.5 18.5.1 18.6 18.7 18.8 18.9 19.0 All 129 releases
wordpress-seo / src / myyoast-client / infrastructure / crypto / key-pair-manager.php

key-pair-manager.php in Yoast SEO – Advanced SEO with real-time guidance and built-in AI 28.0, at src/myyoast-client/infrastructure/crypto/key-pair-manager.php

295 lines 9.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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 SodiumException;
7 use Yoast\WP\SEO\MyYoast_Client\Infrastructure\Encoding\Base64url;
8 use Yoast\WP\SEO\MyYoast_Client\Infrastructure\OIDC\Issuer_Config;
9 use YoastSEO_Vendor\Psr\Log\LoggerAwareInterface;
10 use YoastSEO_Vendor\Psr\Log\LoggerAwareTrait;
11 use YoastSEO_Vendor\Psr\Log\NullLogger;
12
13 /**
14 * Manages Ed25519 key pairs for DPoP proofs and private_key_jwt authentication.
15 *
16 * Generates, stores (encrypted), retrieves, and rotates key pairs.
17 * Two independent key pairs are maintained:
18 * - 'registration': for private_key_jwt client_assertion signing
19 * - 'dpop': for DPoP proof signing
20 */
21 class Key_Pair_Manager implements LoggerAwareInterface {
22 use LoggerAwareTrait;
23
24 public const PURPOSE_REGISTRATION = 'registration';
25 public const PURPOSE_DPOP = 'dpop';
26
27 private const OPTION_PREFIX = 'wpseo_myyoast_key_pair_';
28 private const CONTEXT_PREFIX = 'yoast-myyoast-key-';
29
30 private const JWK_KTY = 'OKP';
31 private const JWK_CRV = 'Ed25519';
32 private const JWK_ALG = 'EdDSA';
33
34 /**
35 * The encryption service.
36 *
37 * @var Encryption
38 */
39 private $encryption;
40
41 /**
42 * The issuer configuration.
43 *
44 * @var Issuer_Config
45 */
46 private $issuer_config;
47
48 /**
49 * In-memory cache for decrypted key pairs, keyed by purpose.
50 *
51 * @var array<string, Key_Pair|null>
52 */
53 private $cached_key_pairs = [];
54
55 /**
56 * Key_Pair_Manager constructor.
57 *
58 * @param Encryption $encryption The encryption service.
59 * @param Issuer_Config $issuer_config The issuer configuration.
60 */
61 public function __construct( Encryption $encryption, Issuer_Config $issuer_config ) {
62 $this->encryption = $encryption;
63 $this->issuer_config = $issuer_config;
64 $this->logger = new NullLogger();
65 }
66
67 /**
68 * Gets an existing key pair or creates a new one for the given purpose.
69 * Creates a new key pair if none exists or if decryption of the stored private key fails (e.g. due to corruption or missing/rotated key).
70 *
71 * @param string $purpose One of the PURPOSE_* constants.
72 *
73 * @return Key_Pair The key pair value object.
74 *
75 * @throws Encryption_Exception If encryption fails.
76 */
77 public function get_or_create_key_pair( string $purpose ): Key_Pair {
78 $option_key = $this->get_option_key( $purpose );
79 if ( \array_key_exists( $option_key, $this->cached_key_pairs ) ) {
80 $cached = $this->cached_key_pairs[ $option_key ];
81 if ( $cached !== null ) {
82 return $cached;
83 }
84
85 return $this->generate_and_store_key_pair( $purpose );
86 }
87
88 try {
89 $stored = $this->get_stored_key_pair( $purpose );
90 } catch ( Encryption_Exception $e ) {
91 $this->logger->warning(
92 'Failed to decrypt {purpose} key pair, auto-rotating: {error}',
93 [
94 'purpose' => $purpose,
95 'error' => $e->getMessage(),
96 ],
97 );
98 return $this->rotate_key_pair( $purpose );
99 }
100
101 return ( $stored ?? $this->generate_and_store_key_pair( $purpose ) );
102 }
103
104 /**
105 * Generates a new key pair, replacing any existing one for the given purpose.
106 *
107 * @param string $purpose One of the PURPOSE_* constants.
108 *
109 * @return Key_Pair The key pair value object.
110 *
111 * @throws Encryption_Exception If encryption fails.
112 */
113 public function rotate_key_pair( string $purpose ): Key_Pair {
114 return $this->generate_and_store_key_pair( $purpose );
115 }
116
117 /**
118 * Returns the public key as a JWK (JSON Web Key) for the given key pair.
119 *
120 * @param Key_Pair $key_pair The key pair to extract the public JWK from.
121 *
122 * @return array<string, string> The JWK array with kty, crv, x, kid, use, and alg fields.
123 */
124 public function get_public_key_jwk( Key_Pair $key_pair ): array {
125 return [
126 'kty' => self::JWK_KTY,
127 'crv' => self::JWK_CRV,
128 'x' => Base64url::encode( $key_pair->get_public_key() ),
129 'kid' => $key_pair->get_kid(),
130 'use' => 'sig',
131 'alg' => self::JWK_ALG,
132 ];
133 }
134
135 /**
136 * Generates a new Ed25519 key pair in memory without persisting it.
137 *
138 * Use store_key_pair() to persist after confirming success of external operations.
139 *
140 * @return Key_Pair The generated key pair.
141 *
142 * @throws Encryption_Exception If key generation fails.
143 */
144 public function generate_key_pair(): Key_Pair {
145 $keypair = '';
146
147 try {
148 $keypair = \sodium_crypto_sign_keypair();
149 $public_key = \sodium_crypto_sign_publickey( $keypair );
150 $private_key = \sodium_crypto_sign_secretkey( $keypair );
151 $kid = Base64url::encode( \hash( 'sha256', $public_key, true ) );
152
153 return new Key_Pair( $public_key, $private_key, $kid );
154 }
155 catch ( SodiumException $e ) {
156 // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal exception message.
157 throw new Encryption_Exception( 'Key pair generation failed: ' . $e->getMessage(), 0, $e );
158 }
159 finally {
160 if ( $keypair !== '' ) {
161 try {
162 \sodium_memzero( $keypair );
163 }
164 catch ( SodiumException $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch -- Best-effort cleanup.
165 // Best-effort: keypair will be freed when it goes out of scope.
166 }
167 }
168 }
169 }
170
171 /**
172 * Builds a JWK from a raw public key without requiring it to be stored.
173 *
174 * @param string $public_key The 32-byte Ed25519 public key.
175 *
176 * @return array<string, string> The JWK array.
177 */
178 public function build_public_key_jwk( string $public_key ): array {
179 $kid = Base64url::encode( \hash( 'sha256', $public_key, true ) );
180
181 return [
182 'kty' => self::JWK_KTY,
183 'crv' => self::JWK_CRV,
184 'x' => Base64url::encode( $public_key ),
185 'kid' => $kid,
186 'use' => 'sig',
187 'alg' => self::JWK_ALG,
188 ];
189 }
190
191 /**
192 * Persists a key pair (encrypting the private key).
193 *
194 * @param string $purpose One of the PURPOSE_* constants.
195 * @param Key_Pair $key_pair The key pair to store.
196 *
197 * @return void
198 *
199 * @throws Encryption_Exception If encryption fails.
200 */
201 public function store_key_pair( string $purpose, Key_Pair $key_pair ): void {
202 $option_key = $this->get_option_key( $purpose );
203 $encrypted_private = $this->encryption->encrypt(
204 $key_pair->get_private_key(),
205 self::CONTEXT_PREFIX . $purpose,
206 );
207
208 \update_option(
209 $option_key,
210 [
211 // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- Binary Ed25519 key needs safe encoding.
212 'public_key' => \base64_encode( $key_pair->get_public_key() ),
213 'private_key_encrypted' => $encrypted_private,
214 'kid' => $key_pair->get_kid(),
215 'created_at' => \time(),
216 ],
217 false,
218 );
219 $this->cached_key_pairs[ $option_key ] = $key_pair;
220 }
221
222 /**
223 * Deletes the key pair for the given purpose.
224 *
225 * @param string $purpose One of the PURPOSE_* constants.
226 *
227 * @return void
228 */
229 public function delete_key_pair( string $purpose ): void {
230 unset( $this->cached_key_pairs[ $this->get_option_key( $purpose ) ] );
231 \delete_option( $this->get_option_key( $purpose ) );
232 }
233
234 /**
235 * Returns the issuer-scoped option key for the given purpose.
236 *
237 * @param string $purpose One of the PURPOSE_* constants.
238 *
239 * @return string The option key.
240 */
241 private function get_option_key( string $purpose ): string {
242 return self::OPTION_PREFIX . $purpose . '_' . $this->issuer_config->get_issuer_key();
243 }
244
245 /**
246 * Retrieves a stored key pair, decrypting the private key.
247 *
248 * @param string $purpose One of the PURPOSE_* constants.
249 *
250 * @return Key_Pair|null The key pair or null if not stored.
251 *
252 * @throws Encryption_Exception If decryption fails.
253 */
254 private function get_stored_key_pair( string $purpose ): ?Key_Pair {
255 $stored = \get_option( $this->get_option_key( $purpose ), [] );
256 if ( ! \is_array( $stored ) || empty( $stored['public_key'] ) || empty( $stored['private_key_encrypted'] ) || empty( $stored['kid'] ) ) {
257 $this->cached_key_pairs[ $this->get_option_key( $purpose ) ] = null;
258 return null;
259 }
260
261 // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- Decoding our own base64-encoded key.
262 $public_key = \base64_decode( $stored['public_key'], true );
263 $private_key = $this->encryption->decrypt(
264 $stored['private_key_encrypted'],
265 self::CONTEXT_PREFIX . $purpose,
266 );
267
268 if ( $public_key === false || \strlen( $public_key ) !== \SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES ) {
269 $this->cached_key_pairs[ $this->get_option_key( $purpose ) ] = null;
270 return null;
271 }
272
273 $key_pair = new Key_Pair( $public_key, $private_key, $stored['kid'] );
274 $this->cached_key_pairs[ $this->get_option_key( $purpose ) ] = $key_pair;
275 return $key_pair;
276 }
277
278 /**
279 * Generates a new Ed25519 key pair and stores it (private key encrypted).
280 *
281 * @param string $purpose One of the PURPOSE_* constants.
282 *
283 * @return Key_Pair The key pair value object.
284 *
285 * @throws Encryption_Exception If encryption or key generation fails.
286 */
287 private function generate_and_store_key_pair( string $purpose ): Key_Pair {
288 $key_pair = $this->generate_key_pair();
289 $this->store_key_pair( $purpose, $key_pair );
290 $this->logger->info( 'Generated and stored new {purpose} key pair.', [ 'purpose' => $purpose ] );
291
292 return $key_pair;
293 }
294 }
295