Skip to content

Commit a8468b5

Browse files
authored
Add randomized SQLite database storage (#502)
## Summary > [!NOTE] > This is an alternative approach to #494. It keeps the same randomized storage design, but delegates coordination to SQLite's VFS and locking protocol through a dedicated SQLite database. This PR adds **randomized storage** for SQLite databases as an additional layer of protection against direct web access. - **Randomized paths:** New managed databases are stored in a directory generated from 128 bits of randomness. - **Portable discovery:** `db-path.php` records the database location relative to the managed database root. - **SQLite-backed locking:** Setup and maintenance are coordinated through a dedicated SQLite locking database. - **Database isolation:** Maintenance also acquires an exclusive lock on an existing database before changing it. - **Automatic migration:** Existing `.ht.sqlite` and `.ht.sqlite.php` databases are moved to the randomized layout. - **Explicit path compatibility:** User-configured database paths and `:memory:` continue to work unchanged. - **Retryable setup:** Another request can complete setup after an interruption. - **Safer failures:** Filesystem errors do not expose the randomized database path. ## Managed storage When no explicit database path is configured, the default layout is: ```text wp-content/ └── database/ ├── .htaccess ├── index.php ├── .ht.sqlite.lock ├── db-path.php └── .ht.<32-hex-char-random-key>/ ├── .htaccess ├── index.php └── .ht.sqlite ``` The `db-path.php` file returns the database location using `__DIR__`, so copying or moving the complete `database` directory keeps the reference valid. If setup is interrupted after the path is published, another request can finish creating the protected directory and database. ## Storage locking The storage implements a locking mechanism for initialization and maintenance. Locking uses a dedicated empty SQLite database and a maintenance file: 1. An exclusive lock is acquired on the locking database at ".ht.sqlite.lock". 2. A maintenance marker file is created at ".ht.sqlite.maintenance": - When requests see the file, they use the locking database. - Its absence provides a fast path for normal traffic. 3. When the lock is released, the maintenance file is automatically removed. ## Legacy migration Migration is serialized across concurrent requests. Before moving a legacy database, the storage manager checkpoints WAL data, switches to `DELETE` journal mode, and acquires an exclusive SQLite lock. If the database remains busy or migration otherwise fails, the original database file stays in place. ## Why A SQLite database at a predictable location under the document root may be served directly when the web server does not honor `.htaccess` or equivalent denial rules. The randomized directory makes accidental exposure substantially harder while retaining a stable discovery mechanism for WordPress and external tools. This is an additional safeguard, not a replacement for private storage. Keeping the database outside the document root or configuring the web server to deny access remains the strongest protection. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added managed SQLite storage with randomized and in-memory database locations. * Added support for migrating existing SQLite databases. * Improved database protection and concurrent-access handling, including stale-lock recovery. * **Bug Fixes** * Improved handling of database initialization failures with clearer failure responses. * Added safeguards for invalid database paths and storage-operation failures. * Improved cleanup of WordPress database files during test environment resets. * **Tests** * Expanded coverage for initialization, migration, permissions, locking, concurrency, recovery, and in-memory databases. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent 085ea60 commit a8468b5

6 files changed

Lines changed: 1480 additions & 81 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: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
*/
2929
if ( ! defined( 'FQDBDIR' ) ) {
3030
if ( defined( 'DB_DIR' ) ) {
31-
define( 'FQDBDIR', trailingslashit( DB_DIR ) );
31+
define( 'FQDBDIR', rtrim( DB_DIR, '/\\' ) . '/' );
3232
} elseif ( defined( 'WP_CONTENT_DIR' ) ) {
3333
define( 'FQDBDIR', WP_CONTENT_DIR . '/database/' );
3434
} else {
@@ -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 & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -432,25 +432,6 @@ public function db_connect( $allow_bail = true ) {
432432
$this->init_charset();
433433
}
434434

435-
// Migrate the database file from a legacy path, if it exists.
436-
if ( ! defined( 'DB_FILE' ) && ! file_exists( FQDB ) ) {
437-
$old_db_path = FQDBDIR . '.ht.sqlite.php';
438-
439-
if ( file_exists( $old_db_path ) ) {
440-
if ( ! rename( $old_db_path, FQDB ) ) {
441-
wp_die( 'Failed to rename database file.', 'Error!' );
442-
}
443-
444-
foreach ( array( '-wal', '-shm', '-journal' ) as $suffix ) {
445-
if ( file_exists( $old_db_path . $suffix ) ) {
446-
if ( ! rename( $old_db_path . $suffix, FQDB . $suffix ) ) {
447-
wp_die( 'Failed to rename database file.', 'Error!' );
448-
}
449-
}
450-
}
451-
}
452-
}
453-
454435
if ( null === $this->dbname || '' === $this->dbname ) {
455436
$this->bail(
456437
'The database name was not set. The SQLite driver requires a database name to be set to emulate MySQL information schema tables.',
@@ -459,8 +440,6 @@ public function db_connect( $allow_bail = true ) {
459440
return false;
460441
}
461442

462-
$this->ensure_database_directory( FQDB );
463-
464443
try {
465444
$options = array(
466445
'sqlite_journal_mode' => defined( 'SQLITE_JOURNAL_MODE' ) ? SQLITE_JOURNAL_MODE : null,
@@ -785,54 +764,6 @@ public function db_server_info() {
785764
return $this->dbh->getAttribute( PDO::ATTR_SERVER_VERSION ); // phpcs:ignore WordPress.DB.RestrictedClasses.mysql__PDO
786765
}
787766

788-
/**
789-
* Make sure the SQLite database directory exists and is writable.
790-
* Create .htaccess and index.php files to prevent direct access.
791-
*
792-
* @param string $database_path The path to the SQLite database file.
793-
*/
794-
private function ensure_database_directory( string $database_path ) {
795-
$dir = dirname( $database_path );
796-
797-
// Set the umask to 0000 to apply permissions exactly as specified.
798-
// A non-zero umask affects new file and directory permissions.
799-
$umask = umask( 0 );
800-
801-
// Ensure database directory.
802-
if ( ! is_dir( $dir ) ) {
803-
if ( ! @mkdir( $dir, 0700, true ) ) {
804-
wp_die( sprintf( 'Failed to create database directory: %s', $dir ), 'Error!' );
805-
}
806-
}
807-
if ( ! is_writable( $dir ) ) {
808-
wp_die( sprintf( 'Database directory is not writable: %s', $dir ), 'Error!' );
809-
}
810-
811-
// Ensure .htaccess file to prevent direct access.
812-
$path = $dir . DIRECTORY_SEPARATOR . '.htaccess';
813-
if ( ! is_file( $path ) ) {
814-
$result = file_put_contents( $path, 'DENY FROM ALL', 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-
// Ensure index.php file to prevent direct access.
822-
$path = $dir . DIRECTORY_SEPARATOR . 'index.php';
823-
if ( ! is_file( $path ) ) {
824-
$result = file_put_contents( $path, '<?php // Silence is gold. ?>', LOCK_EX );
825-
if ( false === $result ) {
826-
wp_die( sprintf( 'Failed to create file: %s', $path ), 'Error!' );
827-
}
828-
chmod( $path, 0600 );
829-
}
830-
831-
// Restore the original umask value.
832-
umask( $umask );
833-
}
834-
835-
836767
/**
837768
* Format MySQL-on-SQLite driver error message.
838769
*

0 commit comments

Comments
 (0)