@@ -135,17 +135,20 @@ public function get_keyring(): WP_Secrets_Keyring {
135135 *
136136 * @since 7.2.0
137137 *
138- * @param string $scope 'site' or 'network'.
139- * @param int|null $site_id Blog ID for site scope. Defaults to the current blog.
140- * Ignored for network scope.
138+ * @param string $scope 'site' or 'network'.
139+ * @param int|null $site_id Blog ID for site scope. Defaults to the current blog.
140+ * Ignored for network scope.
141+ * @param bool $create_root_key Optional. Whether to generate and store a root key
142+ * if none exists. Pass false when only reading
143+ * secrets. Default true.
141144 * @return string|WP_Error 32-byte master key on success. WP_Error on failure,
142145 * including when a caller passes an invalid scope or
143146 * site ID – see WP_Secrets_Cipher::validate_common()
144147 * for why that is a WP_Error and not an exception.
145148 *
146149 * @phpstan-param 'site'|'network' $scope
147150 */
148- public function get_master_key ( string $ scope , ?int $ site_id = null ) {
151+ public function get_master_key ( string $ scope , ?int $ site_id = null , bool $ create_root_key = true ) {
149152 if ( ! in_array ( $ scope , array ( 'site ' , 'network ' ), true ) ) {
150153 $ message = __ ( 'The scope must be "site" or "network". ' );
151154
@@ -171,7 +174,7 @@ public function get_master_key( string $scope, ?int $site_id = null ) {
171174 $ context = self ::SITE_KDF_CONTEXT ;
172175 }
173176
174- $ root_key = $ this ->get_root_key ();
177+ $ root_key = $ this ->get_root_key ( $ create_root_key );
175178
176179 if ( is_wp_error ( $ root_key ) ) {
177180 return $ root_key ;
@@ -196,15 +199,36 @@ public function get_master_key( string $scope, ?int $site_id = null ) {
196199 /**
197200 * Returns the root key, generating and persisting one on first use.
198201 *
202+ * get_site_option() also returns false when its query fails, so a false result is
203+ * checked against the database before a new root key is generated. Generating one
204+ * while another is stored would make every existing secret undecryptable.
205+ *
199206 * @since 7.2.0
200207 *
208+ * @param bool $create Optional. Whether to generate and store a root key if none
209+ * exists. Default true.
201210 * @return string|WP_Error 32 raw bytes on success. WP_Error on failure.
202211 */
203- public function get_root_key () {
212+ public function get_root_key ( bool $ create = true ) {
204213 $ wrapped = $ this ->get_wrapped_root_key ();
205214
206215 if ( false === $ wrapped ) {
207- return $ this ->generate_root_key ();
216+ $ wrapped = $ this ->read_stored_root_key ();
217+
218+ if ( is_wp_error ( $ wrapped ) ) {
219+ return $ wrapped ;
220+ }
221+
222+ if ( false === $ wrapped ) {
223+ if ( ! $ create ) {
224+ return new WP_Error (
225+ WP_SECRETS_ERROR_KEY_UNAVAILABLE ,
226+ __ ( 'No root key is stored. ' )
227+ );
228+ }
229+
230+ return $ this ->generate_root_key ();
231+ }
208232 }
209233
210234 if ( ! is_string ( $ wrapped ) ) {
@@ -338,9 +362,13 @@ private function get_wrapped_root_key() {
338362 *
339363 * @since 7.2.0
340364 *
365+ * @global wpdb $wpdb WordPress database abstraction object.
366+ *
341367 * @return string|WP_Error
342368 */
343369 private function generate_root_key () {
370+ global $ wpdb ;
371+
344372 $ candidate = random_bytes ( 32 );
345373
346374 $ wrapped = $ this ->keyring ->wrap ( $ candidate );
@@ -351,7 +379,12 @@ private function generate_root_key() {
351379 return $ wrapped ;
352380 }
353381
354- if ( add_site_option ( self ::ROOT_KEY_OPTION , $ wrapped ) ) {
382+ $ inserted_row_id = $ this ->insert_root_key ( $ wrapped );
383+
384+ // Use whichever root key is stored now: this one, or one another request stored first.
385+ $ existing = $ this ->read_stored_root_key ();
386+
387+ if ( is_string ( $ existing ) && hash_equals ( $ existing , $ wrapped ) ) {
355388 $ this ->cached_wrapped = $ wrapped ;
356389 $ this ->cached_root_key = $ candidate ;
357390
@@ -361,12 +394,18 @@ private function generate_root_key() {
361394 // Lost the race: another request created one first. Use theirs, not ours.
362395 wp_secrets_memzero ( $ candidate );
363396
364- $ existing = get_site_option ( self ::ROOT_KEY_OPTION );
397+ if ( $ inserted_row_id ) {
398+ $ wpdb ->delete ( $ wpdb ->sitemeta , array ( 'meta_id ' => $ inserted_row_id ) );
399+ }
365400
366- if ( ! is_string ( $ existing ) ) {
401+ if ( is_wp_error ( $ existing ) ) {
402+ return $ existing ;
403+ }
404+
405+ if ( false === $ existing ) {
367406 return new WP_Error (
368407 WP_SECRETS_ERROR_STORE_UNAVAILABLE ,
369- __ ( 'Could not read the root key after losing the creation race . ' )
408+ __ ( 'Could not store the root key. ' )
370409 );
371410 }
372411
@@ -379,4 +418,139 @@ private function generate_root_key() {
379418
380419 return $ root_key ;
381420 }
421+
422+ /**
423+ * Stores a new wrapped root key unless one is already stored.
424+ *
425+ * This does not use add_site_option(). On a single site that is add_option(), which
426+ * skips its existence check for an option cached as missing and then overwrites the
427+ * stored row, so a failed read followed by add_option() would replace the root key.
428+ *
429+ * @since 7.2.0
430+ *
431+ * @global wpdb $wpdb WordPress database abstraction object.
432+ *
433+ * @param string $wrapped The wrapped root key.
434+ * @return int ID of the inserted wp_sitemeta row on multisite, 0 otherwise.
435+ */
436+ private function insert_root_key ( string $ wrapped ): int {
437+ global $ wpdb ;
438+
439+ $ value = maybe_serialize ( $ wrapped );
440+
441+ if ( ! is_multisite () ) {
442+ // The unique key on option_name makes this a no-op when a root key exists.
443+ $ wpdb ->query (
444+ $ wpdb ->prepare (
445+ "INSERT IGNORE INTO ` $ wpdb ->options ` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, 'off') " ,
446+ self ::ROOT_KEY_OPTION ,
447+ $ value
448+ )
449+ );
450+
451+ return 0 ;
452+ }
453+
454+ /*
455+ * wp_sitemeta has no unique key on meta_key, so two requests can both insert a
456+ * row. read_stored_root_key() returns the oldest row, so both end up with the
457+ * same root key, and the request that lost deletes its own row.
458+ */
459+ $ inserted = $ wpdb ->insert (
460+ $ wpdb ->sitemeta ,
461+ array (
462+ 'site_id ' => get_current_network_id (),
463+ 'meta_key ' => self ::ROOT_KEY_OPTION ,
464+ 'meta_value ' => $ value ,
465+ )
466+ );
467+
468+ return $ inserted ? (int ) $ wpdb ->insert_id : 0 ;
469+ }
470+
471+ /**
472+ * Reads the wrapped root key from the database, bypassing the options cache.
473+ *
474+ * get_site_option() returns false both when the root key does not exist and when
475+ * its query failed, and caches the option as missing either way. This read tells
476+ * the two apart. When the row exists, it also clears that cache entry.
477+ *
478+ * @since 7.2.0
479+ *
480+ * @global wpdb $wpdb WordPress database abstraction object.
481+ *
482+ * @return string|false|WP_Error The wrapped root key, false if none is stored, or
483+ * WP_Error if the read failed or the row is malformed.
484+ */
485+ private function read_stored_root_key () {
486+ global $ wpdb ;
487+
488+ if ( is_multisite () ) {
489+ $ value = $ wpdb ->get_var (
490+ $ wpdb ->prepare (
491+ "SELECT meta_value FROM $ wpdb ->sitemeta WHERE meta_key = %s AND site_id = %d ORDER BY meta_id ASC LIMIT 1 " ,
492+ self ::ROOT_KEY_OPTION ,
493+ get_current_network_id ()
494+ )
495+ );
496+ } else {
497+ $ value = $ wpdb ->get_var (
498+ $ wpdb ->prepare (
499+ "SELECT option_value FROM $ wpdb ->options WHERE option_name = %s LIMIT 1 " ,
500+ self ::ROOT_KEY_OPTION
501+ )
502+ );
503+ }
504+
505+ if ( '' !== $ wpdb ->last_error ) {
506+ return new WP_Error (
507+ WP_SECRETS_ERROR_STORE_UNAVAILABLE ,
508+ __ ( 'Could not read the root key. ' )
509+ );
510+ }
511+
512+ if ( null === $ value ) {
513+ return false ;
514+ }
515+
516+ $ this ->forget_missing_root_key ();
517+
518+ $ value = maybe_unserialize ( $ value );
519+
520+ if ( ! is_string ( $ value ) ) {
521+ return new WP_Error (
522+ WP_SECRETS_ERROR_RECORD_MALFORMED ,
523+ __ ( 'The stored root key is not a string. ' )
524+ );
525+ }
526+
527+ return $ value ;
528+ }
529+
530+ /**
531+ * Removes the root key from the cache of options that do not exist.
532+ *
533+ * @since 7.2.0
534+ */
535+ private function forget_missing_root_key (): void {
536+ if ( is_multisite () ) {
537+ $ network_id = get_current_network_id ();
538+ $ group = 'site-options ' ;
539+ $ notoptions_key = "$ network_id:notoptions " ;
540+
541+ wp_cache_delete ( "$ network_id: " . self ::ROOT_KEY_OPTION , $ group );
542+ } else {
543+ $ group = 'options ' ;
544+ $ notoptions_key = 'notoptions ' ;
545+
546+ wp_cache_delete ( self ::ROOT_KEY_OPTION , $ group );
547+ }
548+
549+ $ notoptions = wp_cache_get ( $ notoptions_key , $ group );
550+
551+ if ( is_array ( $ notoptions ) && isset ( $ notoptions [ self ::ROOT_KEY_OPTION ] ) ) {
552+ unset( $ notoptions [ self ::ROOT_KEY_OPTION ] );
553+ wp_cache_set ( $ notoptions_key , $ notoptions , $ group );
554+ }
555+ }
382556}
0 commit comments