Skip to content

Commit 170bc92

Browse files
committed
Add randomized SQLite database storage
Store new databases in a protected randomized directory and record the relative location in a portable manifest. Preserve existing fixed database paths for a separate migration step.
1 parent f3dfbc0 commit 170bc92

6 files changed

Lines changed: 601 additions & 80 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 & 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,
@@ -775,54 +754,6 @@ public function db_server_info() {
775754
return $this->dbh->getAttribute( PDO::ATTR_SERVER_VERSION ); // phpcs:ignore WordPress.DB.RestrictedClasses.mysql__PDO
776755
}
777756

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-
826757
/**
827758
* Format MySQL-on-SQLite driver error message.
828759
*
Lines changed: 260 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,260 @@
1+
<?php
2+
3+
/**
4+
* Manages the storage layout for the WordPress SQLite database.
5+
*
6+
* Filesystem warnings are suppressed to avoid exposing database paths:
7+
* phpcs:disable WordPress.PHP.NoSilencedErrors.Discouraged
8+
*/
9+
class WP_SQLite_Storage {
10+
/**
11+
* Filename of a script that returns the path to the database file.
12+
*/
13+
private const DATABASE_PATH_FILENAME = 'db-path.php';
14+
15+
/**
16+
* Filename of the database file.
17+
*/
18+
private const DATABASE_FILENAME = '.ht.sqlite';
19+
20+
/**
21+
* Filename of a lock file used for database storage setup.
22+
*/
23+
private const LOCK_FILENAME = '.ht.sqlite.lock';
24+
25+
/**
26+
* Number of bytes of a random token used in generated database paths.
27+
*/
28+
private const RANDOM_TOKEN_BYTE_LENGTH = 16;
29+
30+
/**
31+
* Managed database root directory.
32+
*
33+
* @var string
34+
*/
35+
private $database_root;
36+
37+
/**
38+
* Create a SQLite storage manager.
39+
*
40+
* @param string|null $database_root Managed database root. Defaults to FQDBDIR.
41+
*/
42+
public function __construct( ?string $database_root = null ) {
43+
$this->database_root = trailingslashit( $database_root ?? FQDBDIR );
44+
}
45+
46+
/**
47+
* Initialize the SQLite database storage.
48+
*
49+
* Uses an explicit file path or ":memory:" as provided. Otherwise, initializes
50+
* managed storage with a randomized path unless a legacy database already exists.
51+
*
52+
* @param string|null $database_path Optional explicit database path.
53+
* @return string Absolute path to the SQLite database file, or ":memory:".
54+
*/
55+
public function initialize( ?string $database_path = null ): string {
56+
if ( '' === $database_path ) {
57+
throw new RuntimeException( 'The SQLite database path is invalid.' );
58+
}
59+
60+
if ( ':memory:' === $database_path ) {
61+
return $database_path;
62+
}
63+
64+
// Explicitly provided database path.
65+
if ( null !== $database_path ) {
66+
$this->ensure_database( $database_path );
67+
return $database_path;
68+
}
69+
70+
// Reuse an initialized managed database without modifying its storage.
71+
$db_path_file = $this->database_root . self::DATABASE_PATH_FILENAME;
72+
if ( @is_file( $db_path_file ) ) {
73+
$database_path = $this->read_database_path( $db_path_file );
74+
if ( @is_file( $database_path ) ) {
75+
return $database_path;
76+
}
77+
} else {
78+
$legacy_path = $this->database_root . self::DATABASE_FILENAME;
79+
if ( ! @is_file( $legacy_path ) ) {
80+
$legacy_path .= '.php';
81+
}
82+
if ( @is_file( $legacy_path ) ) {
83+
return $legacy_path;
84+
}
85+
}
86+
87+
// Initialize or repair the managed database under a lock.
88+
$this->ensure_protected_directory( $this->database_root );
89+
$lock = $this->acquire_lock();
90+
try {
91+
// Publish a new database path.
92+
if ( ! @is_file( $db_path_file ) ) {
93+
$legacy_path = $this->database_root . self::DATABASE_FILENAME;
94+
if ( ! @is_file( $legacy_path ) ) {
95+
$legacy_path .= '.php';
96+
}
97+
if ( @is_file( $legacy_path ) ) {
98+
return $legacy_path;
99+
}
100+
$this->publish_database_path();
101+
}
102+
$database_path = $this->read_database_path( $db_path_file );
103+
104+
// Initialize a new database.
105+
$this->ensure_database( $database_path );
106+
return $database_path;
107+
} finally {
108+
fclose( $lock );
109+
}
110+
}
111+
112+
/**
113+
* Ensure that a database and its protected directory exist.
114+
*
115+
* @param string $database_path Absolute database path.
116+
*/
117+
private function ensure_database( string $database_path ) {
118+
$this->ensure_protected_directory( dirname( $database_path ) );
119+
120+
if ( ! @is_file( $database_path ) ) {
121+
// Create an empty database file with restricted permissions.
122+
$database_handle = @fopen( $database_path, 'c' );
123+
if ( false === $database_handle ) {
124+
throw new RuntimeException( 'Failed to create the SQLite database file.' );
125+
}
126+
fclose( $database_handle );
127+
@chmod( $database_path, 0600 );
128+
}
129+
}
130+
131+
/**
132+
* Read and validate the database path file.
133+
*
134+
* @param string $database_path_file Absolute database path file.
135+
* @return string Absolute path to the SQLite database file.
136+
*/
137+
private function read_database_path( string $database_path_file ): string {
138+
try {
139+
// Use include so an unreadable file can be handled without terminating on PHP 7.
140+
$database_path = @include $database_path_file;
141+
} catch ( Throwable $exception ) {
142+
throw new RuntimeException( 'Failed to read the SQLite database path file.', 0, $exception );
143+
}
144+
145+
if ( false === $database_path ) {
146+
throw new RuntimeException( 'Failed to read the SQLite database path file.' );
147+
}
148+
149+
if ( ! is_string( $database_path ) || '' === $database_path ) {
150+
throw new RuntimeException( 'The SQLite database path file is invalid.' );
151+
}
152+
153+
return $database_path;
154+
}
155+
156+
/**
157+
* Generate a randomized database path and publish it atomically.
158+
*/
159+
private function publish_database_path() {
160+
$directory_name = '.ht.' . bin2hex( random_bytes( self::RANDOM_TOKEN_BYTE_LENGTH ) );
161+
$directory_path = $this->database_root . $directory_name;
162+
163+
if ( @file_exists( $directory_path ) ) {
164+
throw new RuntimeException( 'Failed to generate a unique SQLite database path.' );
165+
}
166+
167+
$database_path_file = $this->database_root . self::DATABASE_PATH_FILENAME;
168+
$database_path_contents = sprintf(
169+
"<?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",
170+
$directory_name,
171+
self::DATABASE_FILENAME
172+
);
173+
$temporary_path = $this->database_root . '.ht.' . self::DATABASE_PATH_FILENAME;
174+
175+
if ( false === @file_put_contents( $temporary_path, $database_path_contents, LOCK_EX ) ) {
176+
throw new RuntimeException( 'Failed to write the SQLite database path file.' );
177+
}
178+
@chmod( $temporary_path, 0600 );
179+
180+
if ( ! @rename( $temporary_path, $database_path_file ) ) {
181+
@unlink( $temporary_path );
182+
throw new RuntimeException( 'Failed to publish the SQLite database path file.' );
183+
}
184+
185+
// This runs before wp_opcache_invalidate() is available.
186+
$opcache_restrict_api = ini_get( 'opcache.restrict_api' );
187+
$script_filename = isset( $_SERVER['SCRIPT_FILENAME'] ) ? realpath( $_SERVER['SCRIPT_FILENAME'] ) : false;
188+
if (
189+
function_exists( 'opcache_invalidate' )
190+
&& ( ! $opcache_restrict_api || ( $script_filename && 0 === stripos( $script_filename, $opcache_restrict_api ) ) )
191+
) {
192+
opcache_invalidate( $database_path_file, true );
193+
}
194+
}
195+
196+
/**
197+
* Ensure that a database directory exists and deny direct access.
198+
*
199+
* @param string $directory Absolute directory path.
200+
*/
201+
private function ensure_protected_directory( string $directory ) {
202+
if ( ! @is_dir( $directory ) ) {
203+
// Create the path one directory at a time to avoid changing the process-wide umask.
204+
$missing_directories = array();
205+
for ( $path = untrailingslashit( $directory ); ! @is_dir( $path ); $path = dirname( $path ) ) {
206+
$missing_directories[] = $path;
207+
if ( dirname( $path ) === $path ) {
208+
break;
209+
}
210+
}
211+
212+
foreach ( array_reverse( $missing_directories ) as $path ) {
213+
if ( ! @mkdir( $path, 0700 ) && ! @is_dir( $path ) ) {
214+
throw new RuntimeException( 'Failed to create the SQLite database directory.' );
215+
}
216+
@chmod( $path, 0700 );
217+
}
218+
}
219+
220+
$this->ensure_file( trailingslashit( $directory ) . '.htaccess', 'DENY FROM ALL' );
221+
$this->ensure_file( trailingslashit( $directory ) . 'index.php', '<?php // Silence is golden.' );
222+
}
223+
224+
/**
225+
* Create a protected file when it does not already exist.
226+
*
227+
* @param string $path Absolute file path.
228+
* @param string $contents File contents.
229+
*/
230+
private function ensure_file( string $path, string $contents ) {
231+
if ( @is_file( $path ) ) {
232+
return;
233+
}
234+
235+
if ( false === @file_put_contents( $path, $contents, LOCK_EX ) ) {
236+
throw new RuntimeException( 'Failed to create SQLite database protection file.' );
237+
}
238+
@chmod( $path, 0600 );
239+
}
240+
241+
/**
242+
* Open and acquire the database storage lock.
243+
*
244+
* @return resource Lock file handle.
245+
*/
246+
private function acquire_lock() {
247+
$lock_path = $this->database_root . self::LOCK_FILENAME;
248+
$lock_handle = @fopen( $lock_path, 'c' );
249+
if ( false === $lock_handle ) {
250+
throw new RuntimeException( 'Failed to open the SQLite database storage lock.' );
251+
}
252+
@chmod( $lock_path, 0600 );
253+
254+
if ( ! @flock( $lock_handle, LOCK_EX ) ) {
255+
fclose( $lock_handle );
256+
throw new RuntimeException( 'Failed to lock the SQLite database storage.' );
257+
}
258+
return $lock_handle;
259+
}
260+
}

0 commit comments

Comments
 (0)