Skip to content

Commit 5a6d8e7

Browse files
committed
Add randomized SQLite database storage
1 parent 18eff74 commit 5a6d8e7

6 files changed

Lines changed: 604 additions & 72 deletions

File tree

‎composer.json‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@
6666
],
6767
"wp-test-php": [
6868
"@wp-test-ensure-env @no_additional_args",
69-
"rm -rf wordpress/src/wp-content/database/.ht.sqlite @no_additional_args",
69+
"@wp-test-remove-database @no_additional_args",
7070
"npm --prefix wordpress run test:php -- @additional_args"
7171
],
7272
"wp-test-sqlite-plugin-php": [
@@ -80,8 +80,11 @@
8080
"npm --prefix wordpress run test:e2e -- @additional_args"
8181
],
8282
"wp-test-clean": [
83-
"npm --prefix wordpress run env:clean",
84-
"rm -rf wordpress/src/wp-content/database/.ht.sqlite"
83+
"@wp-test-remove-database",
84+
"npm --prefix wordpress run env:clean"
85+
],
86+
"wp-test-remove-database": [
87+
"cd wordpress && node tools/local-env/scripts/docker.js run --rm --no-deps --entrypoint rm php -rf /var/www/src/wp-content/database"
8588
]
8689
}
8790
}

‎packages/plugin-sqlite-database-integration/constants.php‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -37,15 +37,14 @@
3737
}
3838

3939
/**
40-
* FQDB is a database file name. If DB_FILE is defined, it is used
41-
* as FQDB.
40+
* FQDB is the absolute path to the SQLite database file.
41+
*
42+
* If DB_FILE is defined, FQDB is defined here using FQDBDIR. When SQLite is
43+
* used without DB_FILE, managed storage defines FQDB after resolving the
44+
* randomized database path.
4245
*
4346
* @deprecated 3.0.0 Define DB_DIR and DB_FILE instead of overriding FQDB.
4447
*/
45-
if ( ! defined( 'FQDB' ) ) {
46-
if ( defined( 'DB_FILE' ) ) {
47-
define( 'FQDB', FQDBDIR . DB_FILE );
48-
} else {
49-
define( 'FQDB', FQDBDIR . '.ht.sqlite' );
50-
}
48+
if ( ! defined( 'FQDB' ) && defined( 'DB_FILE' ) ) {
49+
define( 'FQDB', FQDBDIR . DB_FILE );
5150
}

‎packages/plugin-sqlite-database-integration/wp-includes/sqlite/class-wp-sqlite-db.php‎

Lines changed: 0 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -459,8 +459,6 @@ public function db_connect( $allow_bail = true ) {
459459
return false;
460460
}
461461

462-
$this->ensure_database_directory( FQDB );
463-
464462
try {
465463
$options = array(
466464
'sqlite_journal_mode' => defined( 'SQLITE_JOURNAL_MODE' ) ? SQLITE_JOURNAL_MODE : null,
@@ -775,54 +773,6 @@ public function db_server_info() {
775773
return $this->dbh->getAttribute( PDO::ATTR_SERVER_VERSION ); // phpcs:ignore WordPress.DB.RestrictedClasses.mysql__PDO
776774
}
777775

778-
/**
779-
* Make sure the SQLite database directory exists and is writable.
780-
* Create .htaccess and index.php files to prevent direct access.
781-
*
782-
* @param string $database_path The path to the SQLite database file.
783-
*/
784-
private function ensure_database_directory( string $database_path ) {
785-
$dir = dirname( $database_path );
786-
787-
// Set the umask to 0000 to apply permissions exactly as specified.
788-
// A non-zero umask affects new file and directory permissions.
789-
$umask = umask( 0 );
790-
791-
// Ensure database directory.
792-
if ( ! is_dir( $dir ) ) {
793-
if ( ! @mkdir( $dir, 0700, true ) ) {
794-
wp_die( sprintf( 'Failed to create database directory: %s', $dir ), 'Error!' );
795-
}
796-
}
797-
if ( ! is_writable( $dir ) ) {
798-
wp_die( sprintf( 'Database directory is not writable: %s', $dir ), 'Error!' );
799-
}
800-
801-
// Ensure .htaccess file to prevent direct access.
802-
$path = $dir . DIRECTORY_SEPARATOR . '.htaccess';
803-
if ( ! is_file( $path ) ) {
804-
$result = file_put_contents( $path, 'DENY FROM ALL', LOCK_EX );
805-
if ( false === $result ) {
806-
wp_die( sprintf( 'Failed to create file: %s', $path ), 'Error!' );
807-
}
808-
chmod( $path, 0600 );
809-
}
810-
811-
// Ensure index.php file to prevent direct access.
812-
$path = $dir . DIRECTORY_SEPARATOR . 'index.php';
813-
if ( ! is_file( $path ) ) {
814-
$result = file_put_contents( $path, '<?php // Silence is gold. ?>', LOCK_EX );
815-
if ( false === $result ) {
816-
wp_die( sprintf( 'Failed to create file: %s', $path ), 'Error!' );
817-
}
818-
chmod( $path, 0600 );
819-
}
820-
821-
// Restore the original umask value.
822-
umask( $umask );
823-
}
824-
825-
826776
/**
827777
* Format MySQL-on-SQLite driver error message.
828778
*

‎packages/plugin-sqlite-database-integration/wp-includes/sqlite/class-wp-sqlite-storage.php‎

Lines changed: 201 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
11
<?php
22

33
/**
4-
* Manages locking for the WordPress SQLite database storage.
4+
* Manages the storage for the WordPress SQLite database.
55
*
6+
* The storage handles the path of the SQLite database:
7+
* - An explicit database path is used as is.
8+
* - A managed database is stored under a randomized protected path.
9+
* - A database in a legacy path stays in use.
10+
*
11+
* The storage implements a locking mechanism for initialization and maintenance.
612
* Locking uses a dedicated empty SQLite database and a maintenance file:
713
* 1. An exclusive lock is acquired on the locking database at ".ht.sqlite.lock".
814
* 2. A maintenance marker file is created at ".ht.sqlite.maintenance":
@@ -17,6 +23,16 @@
1723
* phpcs:disable WordPress.PHP.NoSilencedErrors.Discouraged
1824
*/
1925
class WP_SQLite_Storage {
26+
/**
27+
* Filename of a script that returns the path to the database file.
28+
*/
29+
private const DATABASE_PATH_FILENAME = 'db-path.php';
30+
31+
/**
32+
* Filename of the database file.
33+
*/
34+
private const DATABASE_FILENAME = '.ht.sqlite';
35+
2036
/**
2137
* Filename of the SQLite locking database.
2238
*/
@@ -27,13 +43,32 @@ class WP_SQLite_Storage {
2743
*/
2844
private const MAINTENANCE_FILENAME = '.ht.sqlite.maintenance';
2945

46+
/**
47+
* Number of bytes in a generated random token.
48+
*/
49+
private const TOKEN_BYTE_LENGTH = 16;
50+
3051
/**
3152
* Managed database root directory.
3253
*
3354
* @var string
3455
*/
3556
private $database_root;
3657

58+
/**
59+
* Explicitly configured database path, if any.
60+
*
61+
* @var string|null
62+
*/
63+
private $database_path;
64+
65+
/**
66+
* Absolute path of the database path file.
67+
*
68+
* @var string
69+
*/
70+
private $database_path_file;
71+
3772
/**
3873
* Absolute path of the SQLite locking database.
3974
*
@@ -63,14 +98,84 @@ class WP_SQLite_Storage {
6398
private $database_lock_timeout = 10000;
6499

65100
/**
66-
* Create a SQLite storage lock.
101+
* Create a SQLite storage manager.
67102
*
68103
* @param string|null $database_root Managed database root. Defaults to FQDBDIR.
104+
* @param string|null $database_path Explicit database path or ":memory:". Managed storage is used when null.
105+
* @throws RuntimeException When the database path is invalid.
106+
*/
107+
public function __construct( ?string $database_root = null, ?string $database_path = null ) {
108+
if ( '' === $database_path ) {
109+
throw new RuntimeException( 'The SQLite database path is invalid.' );
110+
}
111+
$this->database_root = trailingslashit( $database_root ?? FQDBDIR );
112+
$this->database_path = $database_path;
113+
$this->database_path_file = $this->database_root . self::DATABASE_PATH_FILENAME;
114+
$this->lock_path = $this->database_root . self::LOCK_FILENAME;
115+
$this->maintenance_path = $this->database_root . self::MAINTENANCE_FILENAME;
116+
}
117+
118+
/**
119+
* Initialize the SQLite database storage.
120+
*
121+
* Uses an explicit file path or ":memory:" as configured. Otherwise, initializes
122+
* managed storage with a randomized path. A legacy database stays at its fixed path.
123+
*
124+
* @return string Absolute path to the SQLite database file, or ":memory:".
125+
* @throws RuntimeException When the storage cannot be initialized.
69126
*/
70-
public function __construct( ?string $database_root = null ) {
71-
$this->database_root = trailingslashit( $database_root ?? FQDBDIR );
72-
$this->lock_path = $this->database_root . self::LOCK_FILENAME;
73-
$this->maintenance_path = $this->database_root . self::MAINTENANCE_FILENAME;
127+
public function initialize(): string {
128+
// An in-memory database has no files.
129+
if ( ':memory:' === $this->database_path ) {
130+
return $this->database_path;
131+
}
132+
133+
// Never resolve a database path while storage maintenance is in progress.
134+
$this->wait_until_unlocked();
135+
136+
// Explicitly configured database path.
137+
if ( null !== $this->database_path ) {
138+
$this->ensure_database( $this->database_path );
139+
return $this->database_path;
140+
}
141+
142+
// Initialized managed database path.
143+
$database_path = $this->read_recorded_database_path();
144+
if ( null !== $database_path && @is_file( $database_path ) ) {
145+
return $database_path;
146+
}
147+
148+
// Keep using a legacy database at its fixed path.
149+
$legacy_path = $this->database_root . self::DATABASE_FILENAME;
150+
if ( ! @is_file( $legacy_path ) ) {
151+
$legacy_path = $this->database_root . self::DATABASE_FILENAME . '.php';
152+
}
153+
if ( @is_file( $legacy_path ) ) {
154+
return $legacy_path;
155+
}
156+
157+
// Initialize or repair the managed storage under the storage lock.
158+
// Preserve a lock already held by this instance for a larger operation.
159+
$keep_lock = null !== $this->storage_lock_connection;
160+
$this->lock();
161+
try {
162+
// Another process may have completed the initialization meanwhile.
163+
$database_path = $this->read_recorded_database_path();
164+
if ( null !== $database_path && @is_file( $database_path ) ) {
165+
return $database_path;
166+
}
167+
168+
if ( null === $database_path ) {
169+
$database_path = $this->publish_database_path();
170+
}
171+
172+
$this->ensure_database( $database_path );
173+
return $database_path;
174+
} finally {
175+
if ( ! $keep_lock ) {
176+
$this->unlock();
177+
}
178+
}
74179
}
75180

76181
/**
@@ -127,6 +232,96 @@ public function unlock(): void {
127232
}
128233
}
129234

235+
/**
236+
* Wait until no maintenance process holds an active storage lock.
237+
*/
238+
private function wait_until_unlocked(): void {
239+
// A lock held by this instance must not block its own work.
240+
if ( null !== $this->storage_lock_connection || ! @is_file( $this->maintenance_path ) ) {
241+
return;
242+
}
243+
244+
try {
245+
$this->ensure_database( $this->lock_path );
246+
$connection = new PDO( 'sqlite:' . $this->lock_path );
247+
$connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
248+
$connection->exec( 'PRAGMA busy_timeout = ' . $this->database_lock_timeout );
249+
$connection->exec( 'BEGIN EXCLUSIVE' );
250+
251+
// Clear a stale marker while the transaction prevents new maintenance from starting.
252+
@unlink( $this->maintenance_path );
253+
} catch ( Throwable $exception ) {
254+
throw new RuntimeException( 'Failed to check the SQLite storage lock.', 0, $exception );
255+
}
256+
}
257+
258+
/**
259+
* Reads the recorded database path.
260+
*
261+
* @return string|null Absolute database path, or null when none is recorded.
262+
*/
263+
private function read_recorded_database_path(): ?string {
264+
if ( ! @is_file( $this->database_path_file ) ) {
265+
return null;
266+
}
267+
268+
try {
269+
// Use include so an unreadable file can be handled without terminating on PHP 7.
270+
$database_path = @include $this->database_path_file;
271+
} catch ( Throwable $exception ) {
272+
throw new RuntimeException( 'Failed to read the SQLite database path file.', 0, $exception );
273+
}
274+
275+
if ( false === $database_path ) {
276+
throw new RuntimeException( 'Failed to read the SQLite database path file.' );
277+
}
278+
279+
if ( ! is_string( $database_path ) || '' === $database_path ) {
280+
throw new RuntimeException( 'The SQLite database path file is invalid.' );
281+
}
282+
283+
return $database_path;
284+
}
285+
286+
/**
287+
* Generate a randomized database path and publish it atomically.
288+
*
289+
* @return string Absolute path to the published SQLite database file.
290+
*/
291+
private function publish_database_path(): string {
292+
$directory_name = '.ht.' . bin2hex( random_bytes( self::TOKEN_BYTE_LENGTH ) );
293+
$temporary_path = $this->database_root . 'tmp.' . self::DATABASE_PATH_FILENAME;
294+
295+
$database_path_contents = sprintf(
296+
"<?php\n\n/**\n * SQLite database path.\n *\n * IMPORTANT: Keep this path secret. When possible, point it outside the document root.\n */\nreturn __DIR__ . '/%s/%s';\n",
297+
$directory_name,
298+
self::DATABASE_FILENAME
299+
);
300+
301+
// Publish the complete file atomically.
302+
if ( false === @file_put_contents( $temporary_path, $database_path_contents ) ) {
303+
throw new RuntimeException( 'Failed to write the SQLite database path file.' );
304+
}
305+
@chmod( $temporary_path, 0600 );
306+
307+
if ( ! @rename( $temporary_path, $this->database_path_file ) ) {
308+
@unlink( $temporary_path );
309+
throw new RuntimeException( 'Failed to publish the SQLite database path file.' );
310+
}
311+
312+
// This runs before wp_opcache_invalidate() is available.
313+
$opcache_restrict_api = ini_get( 'opcache.restrict_api' );
314+
$script_filename = isset( $_SERVER['SCRIPT_FILENAME'] ) ? realpath( $_SERVER['SCRIPT_FILENAME'] ) : false;
315+
if (
316+
function_exists( 'opcache_invalidate' )
317+
&& ( ! $opcache_restrict_api || ( $script_filename && 0 === stripos( $script_filename, $opcache_restrict_api ) ) )
318+
) {
319+
opcache_invalidate( $this->database_path_file, true );
320+
}
321+
322+
return $this->database_root . $directory_name . '/' . self::DATABASE_FILENAME;
323+
}
324+
130325
/**
131326
* Ensure that a database and its protected directory exist.
132327
*

‎packages/plugin-sqlite-database-integration/wp-includes/sqlite/db.php‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,20 @@
4444
);
4545
}
4646

47+
require_once __DIR__ . '/class-wp-sqlite-storage.php';
48+
49+
try {
50+
$database_storage = new WP_SQLite_Storage( FQDBDIR, defined( 'FQDB' ) ? FQDB : null );
51+
$database_path = $database_storage->initialize();
52+
} catch ( Throwable $exception ) {
53+
error_log( 'SQLite database error: ' . (string) $exception );
54+
wp_die( esc_html( $exception->getMessage() ), 'SQLite database error', array( 'response' => 503 ) );
55+
}
56+
57+
if ( ! defined( 'FQDB' ) ) {
58+
define( 'FQDB', $database_path );
59+
}
60+
4761
require_once __DIR__ . '/../database/load.php';
4862
require_once __DIR__ . '/class-wp-sqlite-db.php';
4963
require_once __DIR__ . '/install-functions.php';

0 commit comments

Comments
 (0)