Repository navigation
fix: create SQLite database files 0600 and set wider ones to 0600 when opened - #691
LeeroyHannigan wants to merge 38 commits into
Conversation
…QLite opens it `extenddb init --backend sqlite` left the database file and its -wal and -shm files at mode 0644. SQLite's unix VFS creates a database file with mode 0644 less the umask and gives each new sidecar the mode of the database file, and the bootstrapper pool that init and migrate use never changed either mode. The engine set the modes after connecting, on the configured string with a suffix appended, and ignored failures. Every pool opener on a file database (the bootstrapper, the engine and the catalog pool) now creates a missing database file with mode 0600 before it connects, when the connection would create the file, and sets the file and any -wal, -shm and -journal file present to 0600 before and after it connects. The sidecar names come from the resolved path, because SQLite follows symlinks before naming them. A mode that cannot be set is an error, as it is for the lock file. Other platforms are unchanged.
…fter init, serve and a write Unit tests for file_mode: prepare creates a missing database at 0600 and sets an existing database and its sidecars to 0600; a sqlite: URL without mode=rwc, or with mode=ro, creates nothing; a WAL pool opened after prepare gets 0600 sidecars from SQLite; a dangling symlink has its target created. An integration test binary sets a umask of 022 in its own process and runs the bootstrapper sequence init uses, the server components factory, a management write, CreateTable and TagResource, a clean stop and a second start, checking that every file in the deployment directory is 0600 with the WAL sidecars present while a server is up. It also covers a dev-mode serve on a missing path, and serve and migrate over files left at 0644. A control test shows a connection opened outside the crate's openers leaves 0644 files under that umask.
…ly connect The bootstrapper pool, the serve engine and the catalog pool now open their pools through file_mode::connect. It runs prepare before the pool's first connection and restrict after it, so an opener cannot run one step without the other. The new unit tests read the modes of the database file and its -wal and -shm files inside the connection setup, before restrict runs. A database left at 0644 with no sidecars gets 0600 sidecars only because prepare set it to 0600 before SQLite opened it.
…ons prepare leaves to SQLite A pool whose connection setup sets the database file and its sidecars to 0644 finds them at 0600 once connect returns. prepare creates nothing for a file: URI with its own query or for a VFS outside the unix family.
…ation A configured sqlite: URL names the same database file and sidecars as the path inside it. The engine's old post-connect chmod appended the suffixes to the configured string, which for a URL named files that do not exist.
The tests move unchanged from file_mode.rs to file_mode/tests.rs, so the module stays under 600 lines as the tests grow.
…gh a handle that follows no link The mode was set by path on whatever the database name and each sidecar name resolved to. A database path naming a directory set the directory to 0600, a symlink planted at a sidecar name set its target to 0600, and a read-only mount failed the read-only commands although every file was already 0600. Each name is now opened with O_PATH | O_NOFOLLOW on Linux, which opens no file for reading or writing: a symlink yields a handle on the link itself and a FIFO or a device is not opened, so nothing waits. The type and mode are read from that handle, and only a regular file with a permission bit outside 0600 is changed, by chmod of /proc/self/fd/<n>, so the check and the change act on the same file. Closing an O_PATH handle keeps the POSIX locks the process's SQLite connections hold on the file, which closing a descriptor opened for reading would release. On other Unix systems the type and mode come from lstat and the change is fchmodat with AT_SYMLINK_NOFOLLOW, which opens nothing. A regular file wider than 0600 that cannot be narrowed is still an error. The calls that change a mode can be replaced in tests, which use that to check the error without changing any file the test did not create.
…he locks of its open connection A WAL connection holds a read lock on the database file's shared range and on the DMS byte of the -shm file. The test narrows the files of a database whose connection is open and asks, with an open file description lock, whether a write lock on either range would still conflict.
…se file is created with The integration tests opened every pool in sequence and checked the end state, so a later opener's narrowing hid an opener that skipped its own. Three tests now open one pool each on a missing path and read the modes before any other pool opens the file: the bootstrapper's pool, the engine's pool and the catalog pool through the settings store factory. A unit test reads the mode of the database file prepare creates as the file is created, before prepare narrows it, and compares it with a file the test creates with mode 0600 under the same umask.
…ad them before creating the database prepare decided whether to create the database file, and which file, from a reading of the location that differed from sqlx's and SQLite's in four ways. With several vfs values it required all of them to be in the unix family, where sqlx uses the last. It left every file: URI with its own query to SQLite, which created the file at 0644 when that query did not narrow the open. database_file did not decode %HH in a file: URI path, so prepare created a stray file and the database SQLite opened stayed 0644; it matched mode=memory with a raw split, so an encoded key such as mod%65 made prepare create a file SQLite never used; and a file: name combined with vfs or immutable, which sqlx wraps in a second file: URI so that SQLite opens a relative path spelled file:..., got a stray file at the path the URI names. A new module, sqlite_uri, reads a file: URI as the bundled SQLite does: the authority, the path and query split at raw separators, %HH decoded, %00 ending a part, the last vfs, and each mode applied in order with the rule that a mode may not ask for more access than the one before it. prepare creates the file only when SQLite would create it on disk. database_file reads the path through sqlite_uri and mode through form_urlencoded, and file_mode leaves a file: name with vfs or immutable alone. The lock file moves only where the decoding changes the path: for a file: URI with %HH in its path it is now next to the file SQLite opens, and an encoded mode=memory takes no lock, as every other in-memory form.
…hen one cannot be set The security model left file permissions to the operator and did not mention the SQLite database files, and the troubleshooting guide described settings and verify as commands that only read. With the SQLite backend, init, migrate, settings, verify and serve now create the database file with mode 0600 and set it and its -wal, -shm and -journal files to 0600 when they are wider, and they fail when a mode cannot be set. The security model now names those files. The lock entry in the troubleshooting guide says that settings and verify set these modes although they take no lock. A new entry covers the errors "cannot set the mode of SQLite file" and "cannot set the mode of SQLite database" and their causes: a read-only mount holding files wider than 0600, and database files that belong to another user.
creates_file and the SQLITE_OPEN_* flags it reads are used only by the Unix file mode code, so a Windows build reported seven dead-code warnings for them. They are now compiled on Unix only, and the options field they read allows dead code on other platforms.
The SQLite file message also appears when the database file or one of its sidecars cannot be looked up, for example when the user cannot search the directory that holds the database. The SQLite database message comes from a filesystem that refuses to set the mode of the file the command created. The troubleshooting entry now says so, and lists the directory case with its fix.
Cargo.lock: main added tracing-subscriber to the dependencies of extenddb-storage-sqlite, and this branch added url. The merged file is main's, with url added back by cargo. crates/storage-sqlite/Cargo.toml: main added libsqlite3-sys and this branch added url. The merged file keeps both. crates/storage-sqlite/src/bootstrapper.rs: main replaced the pool's pragmas with set_connection_pragmas, and this branch opens the pool through file_mode::connect. The merged pool runs main's pragmas and opens through file_mode::connect. crates/storage-sqlite/src/lib.rs: main moved catalog_pool onto set_connection_pragmas, and this branch opens it through file_mode::connect and returns its error as a String. The merged catalog_pool keeps main's pragmas and this branch's opener. crates/storage-sqlite/src/store.rs: main moved the engine's pragmas onto set_connection_pragmas and dropped the CATALOG_VERSION import. This branch opens the engine's pool through file_mode::connect and removes the chmod loop and the sqlite_url import. The merged engine keeps main's pragmas and imports and this branch's opener, without the chmod loop. docs/troubleshooting.md: main names migrate --yes as the command that takes the lock and adds migrate without --yes to the read-only commands. This branch added a sentence on the modes settings and verify set. The merged entry keeps main's text with this branch's sentence at the end. Main moved migrate --yes, and the first open of a dev-mode serve, onto the migration runner's own connection, which this branch's openers do not cover. SqliteMigrations::open_with now calls file_mode::prepare and file_mode::restrict around that connection when it opens the database for writing, so migrate --yes sets files left at 0644 to 0600 as this branch describes. The read-only status connection is unchanged. file_mode::prepare and file_mode::restrict are pub(crate) for this. tests/file_modes.rs called bootstrapper methods that main removed. Its init step now follows main's init (the migrations under the lock, then the rows a server needs), its migrate step takes the lock and calls run_locked, and the bootstrapper pool test opens the pool through list_table_names. The new troubleshooting entry and the security model name migrate --yes where they named migrate, and say that a command that creates a missing database file creates it with mode 0600. On main, migrate and verify create no missing database file.
crates/storage-sqlite/src/store.rs keeps from main the new_for_server constructor and the pool connect through connect_options, which bounds the row buffer. It keeps from this branch the owner-only file modes: file_mode::prepare runs before the connect and file_mode::restrict after it, in place of the chmod loop. docs/manuals/10-security-model.md keeps both sentences in the operating system security item. Main's names the export file and directory modes. This branch's names the SQLite database file modes.
…mode module doc Main connects the engine pool through connect_options, which bounds the driver's row buffer. So store.rs calls prepare and restrict around that connect instead of going through file_mode::connect. The module doc said every pool goes through connect. It now names the engine pool beside the migration runner.
The file_mode module doc said every pool on a file database opens through connect, then named the engine pool as one that does not. It now names the bootstrapper and catalog pools, the two callers of connect. The comment above the engine pool's prepare and restrict calls no longer repeats the module doc.
The file_mode unit tests and the file_modes integration tests removed their directory as their last step. A test that failed left its directory under the temporary directory. Each test now holds a tempfile::TempDir, which removes the directory when the test ends, also when it panics. tempfile becomes a dev-dependency of the crate. Seven other crates of the workspace use it for the same purpose.
connect ran restrict after the pool connected. Before the connect, prepare creates a missing database at 0600 or narrows an existing one. The sidecars SQLite creates take the database file's mode. So restrict found nothing to narrow on any production path. The engine pool and the migration runner dropped the same call for that reason. connect now calls prepare only, and the module no longer has restrict or restrict_with. The unit tests that called restrict call prepare in its place. This commit deletes the test that set the files to 0644 inside its own after_connect: no production connection setup does that. The decoded file: URI test now sets its files to 0644 after the connect and checks that prepare narrows them.
prepare, the migration runner and init each created a missing database file with create_new and mode 0600: file_mode::create_owner_only, migrations::open::create_private and SqliteBootstrapper::create_catalog_db. Only the first then set the new file to 0600 through its descriptor. The kernel applies the umask to the mode that create_new passes. So under a umask that removes owner bits, such as 0o277, the runner and init left the file at 0400. SQLite then opens it read-only, and the runner's first write fails. file_mode::create_owner_only is now the one creator of the three. It returns the create's own result for each caller to judge. prepare leaves a failed create to SQLite's open, the runner accepts an existing file, and init refuses one. A new file whose mode cannot be set is an error for each of them: cannot set the mode of SQLite database <path>: <error>. This commit removes create_private. The descriptor call is serve_lock::set_owner_only, which the lock file's restrict_to_owner also uses. tests/file_mode_umask.rs sets umask 0o277 in its own process. It checks that create_catalog_db and the runner's open of a missing database leave the database file and its -wal and -shm files at 0600. It also checks that the runner's open succeeds.
No test failed without the fchmod that create_owner_only makes on the file it creates: under the tests' umask the create already gives 0600. prepare_creates_the_database_file_with_mode_0600 now sets the new file to 0400, the mode a umask of 0o200 leaves, before that call. It still expects 0600. a_file_that_cannot_be_narrowed_is_an_error now compares each message with the whole expected text. It also covers a missing database whose new file's mode cannot be set. That case gives cannot set the mode of SQLite database <path>: Read-only file system (os error 30).
prepare and the file: URI reader took any vfs whose name starts with unix for a VFS that opens a file on disk. SQLite refuses a name it does not have, such as unixfoo, with no such vfs. So prepare created an empty 0600 database file for an open that then failed. sqlite_uri::is_unix_vfs now also asks the linked SQLite for the name with sqlite3_vfs_find. It first cuts the name at its first NUL, as SQLite does. Both readers call it in place of their own prefix checks.
The file_mode module doc said that file_mode never follows a symlink at any of the names it checks. restrict_files canonicalizes the database name first. So file_mode follows a symlink at the database name to the file SQLite opens, and leaves only a symlink at a sidecar name alone. The doc now says so. A comment in tests/file_modes.rs named the manage command as the opener of the management store. manage is a client of the management API and opens no store. The encryption-key commands open it.
… upgrade note The troubleshooting entries and the security model named five commands that set the database file and its sidecars to 0600. They were init, migrate --yes, settings, verify and serve. The encryption-key and backup commands open the database through the same openers and set the modes too. status, rewrap and set-data-connection open the catalog pool. switch, rotate and reset open the migration runner. The backup commands list, purge, sync and remove-target open the engine pool and the catalog pool through the server components. The entries now name them. The troubleshooting entry also names a /proc that is not mounted on Linux as a cause. It says that a new database file is 0600 also under a umask that removes the owner's bits. The upgrade manual gains a v1.1.0 entry beside the export file entry. It says what 1.0.0 did, what this release does and which deployments see a change, and it gives the two remedies of the troubleshooting entry.
The file mode tests now hold their directory as a tempfile::TempDir and name it by its &Path. Clippy's needless_borrow and needless_borrows_for_generic_args lints refused the &dir left in the calls. The calls now pass dir.
Main added the WebAssembly build (#1009). Git stopped on three files. crates/storage-sqlite/Cargo.toml: main moved libc and libsqlite3-sys to the dependencies of native targets and added web-time. This branch added url. The merged manifest keeps main's sections and adds url to the dependencies of both targets. database_file, which the wasm32 build calls, reads a location's query with it. crates/storage-sqlite/src/lib.rs: main moved the backend registration, the factories and catalog_pool to server_backend.rs. It also compiled off wasm32 the modules that wasm32 does not build. This branch added the file_mode and sqlite_uri modules and opened catalog_pool through file_mode::connect. The merged lib.rs keeps main's text and both new modules, with a comment on what wasm32 compiles of file_mode. In server_backend.rs, catalog_pool opens through file_mode::connect and returns its error as a String. crates/storage-sqlite/src/serve_lock.rs: main compiled resolve_dangling_symlinks off wasm32, because its only caller was ServeLock::lock_path. This branch made it pub(crate) for file_mode::prepare and the migration runner. The merged function is pub(crate) and compiled off wasm32, where none of its three callers is. For the rules in the lib.rs module doc, the merge also compiles file_mode::connect and the non-Unix create_owner_only off wasm32, as their callers are. Of file_mode, wasm32 compiles only the non-Unix prepare, which SqliteEngine::new_for_server calls. The options field of sqlite_uri::FileUri, which only Unix reads outside the tests, now expects dead_code on other targets. The comment on the migrations module open no longer says that the module creates database files.
database_file and opened_file read a location's query with url::form_urlencoded, a re-export of the form_urlencoded crate. The wasm32 build now compiles database_file, and url is not in that build's graph otherwise. cargo tree of extenddb-wasm-adapter for wasm32-unknown-unknown lists 164 crates with url and 139 with form_urlencoded: url also brings idna and the ICU4X crates it uses. The crate now names form_urlencoded 1, which Cargo.lock already holds at 1.2.2 through url. The native build compiles the same code.
| /// SQLite resolves symlinks before it names them. | ||
| #[cfg(unix)] | ||
| fn restrict_files(path: &Path, calls: &ModeCalls<'_>) -> Result<(), String> { | ||
| let base = std::fs::canonicalize(path).unwrap_or_else(|_| resolve_dangling_symlinks(path)); |
There was a problem hiding this comment.
Please add a regression test for an existing 0644 database reached through a symlink. The code correctly canonicalizes the path and narrows the target to 0600, but when I changed the database-name case to use the unresolved path, all 361 focused tests still passed. A scratch test using real.sqlite (0644) behind link.sqlite passed at this head and failed under that mutation: the target remained 0644 instead of 0600. That test would protect the upgrade path.
There was a problem hiding this comment.
Added in 29ba451. prepare_sets_an_existing_database_behind_a_symlink_to_0600 makes link.sqlite a symlink to real.sqlite, with real.sqlite and real.sqlite-wal at 0644, and calls prepare on link.sqlite. It expects both files at 0600 and link.sqlite still a symlink.
With restrict_files taking the unresolved path for the database file, the test fails with real.sqlite at 0644. Without the test, every file_mode, file_modes and file_mode_umask test passed with that change, as you found.
restrict_files narrows the database file at its resolved path. Through a symlink at the database name, the name as given is the link, and restrict_file follows no link. With that name in place of the resolved path, the target stayed at 0644. Every test in file_mode, file_modes and file_mode_umask still passed. prepare_sets_an_existing_database_behind_a_symlink_to_0600 puts a 0644 database and its -wal file behind link.sqlite, then calls prepare on link.sqlite. It expects both files at 0600 and link.sqlite still a symlink. With the name as given for the database file, the test fails with the target at 0644.
LJMart11
left a comment
There was a problem hiding this comment.
Checked at 29ba451 against 46fd13e. The symlink regression case is fixed: the new test passes at the head and fails under the original mutation (0644 remains instead of 0600). No new findings.
Main is at c8e66fb. This branch last had main at a417b2f. Since then, 40 PRs merged into main, #1482 among them, which fixes the WebAssembly build, and #1166, which moves the SQLite crate to sqlx 0.9.1. Git merged every file with no conflict. Main also changed nine files of this PR, in lines that this branch does not change. They are Cargo.lock, crates/storage-sqlite/Cargo.toml, bootstrapper.rs, lib.rs, migrations/backend.rs and migrations/mod.rs of crates/storage-sqlite, docs/manuals/07-upgrade-manual.md, docs/manuals/10-security-model.md and docs/troubleshooting.md.
The v1.1.0 release of 27 Nov 2026 does not include this change. Its entry in the upgrade manual is now a v1.2.0 entry at the top of Behavior Changes by Release. It comes after the two v1.2.0 entries of main. Before, it sat among the v0.1.15 entries. The entry names 1.1.0 as the release before the change, in the five sentences that named 1.0.0. Main changed no file mode code after a417b2f, the main that this branch merged last, so these sentences hold for 1.1.0. The entry also gets the PR and the issue numbers, as the other entries have.
|
Checked at Fixed:
Disputed: none. Needs-human: none. |
Main is at 44a7b79, six commits past c8e66fb: #1446, #1531, #1466, #1087, #768 and #1296. In docs/manuals/07-upgrade-manual.md, #1446 and #1531 add v1.2.0 entries at the top of "Behavior Changes by Release", and git merged them with no conflict. #1087 adds its v1.2.0 entry after the other v1.2.0 entries of main, where this branch has its entry. That is the one conflict. The merge keeps both entries without change: the entry of #1087 first, then the entry of this branch, before the v1.1.0 entries. Git merged four other files with no conflict: - Cargo.lock: #1087 adds crc32fast to the dependencies of extenddb-storage, and this branch adds form_urlencoded and tempfile to the dependencies of extenddb-storage-sqlite. - crates/storage-sqlite/Cargo.toml: #1087 rewrites the comments of libsqlite3-sys and sqlite-wasm-rs. This branch adds form_urlencoded and the tempfile dev-dependency. - crates/storage-sqlite/src/lib.rs: #1087 declares the scan_segment_tests module, and this branch declares file_mode and sqlite_uri. - crates/storage-sqlite/src/store.rs: #1087 registers extenddb_scan_segment on each connection of the pool, in after_connect. This branch calls file_mode::prepare before the pool connects, and it removes the mode change after the connect. The pool keeps the after_connect of main.
Changes since the last review
LJMart11 reviewed
29ba45112. The commits after it:e85d869 merges main at c8e66fb, 40 PRs after the last merge, fix(core): read the latency segment clock through web_time #1482 and fix(deps): move to sqlx 0.9.1 for the SQLite fix of RUSTSEC-2026-0459 #1166 (sqlx 0.9.1) among them. Git merged every file with no conflict. Main also changed nine files of this branch, in lines that this branch does not change.
141cbd0 moves the entry of this PR in the upgrade manual to the v1.2.0 group at the top of "Behavior Changes by Release". The entry sits after the v1.2.0 entries of main. v1.1.0 shipped without this change. The entry names 1.1.0 as the release before the change, in the five sentences that named 1.0.0. Main changed no file mode code after
a417b2f82, the main that this branch merged last, so these sentences hold for 1.1.0.8369db4 merges main at 44a7b79, which brings fix(storage-mongodb): keep a DELETING table's tags until its document goes #1446, fix(storage-cassandra): retry a lost UpdateItem version check over the PutItem and DeleteItem window #1531, ci(release): add devtools/freeze-migrations #1466, fix(storage-sqlite): keep each partition key in one parallel Scan segment #1087, fix(bin): rerun the build script when the checked-out commit changes #768 and fix(server): ignore a TableName sent to an operation without one #1296. In
docs/manuals/07-upgrade-manual.md, fix(storage-mongodb): keep a DELETING table's tags until its document goes #1446 and fix(storage-cassandra): retry a lost UpdateItem version check over the PutItem and DeleteItem window #1531 add v1.2.0 entries at the top of "Behavior Changes by Release", and git merged them with no conflict. fix(storage-sqlite): keep each partition key in one parallel Scan segment #1087 adds its v1.2.0 entry after the other v1.2.0 entries of main, where this PR has its entry. That is the one conflict. The merge keeps both entries without change: the entry of fix(storage-sqlite): keep each partition key in one parallel Scan segment #1087 first, then the entry of this PR, above the v1.1.0 entries. Git merged four other files that both sides change, each at other lines:Cargo.lock: fix(storage-sqlite): keep each partition key in one parallel Scan segment #1087 addscrc32fastto the dependencies ofextenddb-storage, and this PR addsform_urlencodedandtempfileto those ofextenddb-storage-sqlite.crates/storage-sqlite/Cargo.toml: fix(storage-sqlite): keep each partition key in one parallel Scan segment #1087 rewrites the comments oflibsqlite3-sysandsqlite-wasm-rs. This PR addsform_urlencodedand thetempfiledev-dependency.crates/storage-sqlite/src/lib.rs: fix(storage-sqlite): keep each partition key in one parallel Scan segment #1087 declares thescan_segment_testsmodule, and this PR declaresfile_modeandsqlite_uri.crates/storage-sqlite/src/store.rs: fix(storage-sqlite): keep each partition key in one parallel Scan segment #1087 registersextenddb_scan_segmenton each connection of the engine pool, in itsafter_connect. This PR callsfile_mode::preparebefore that pool connects, and it removes the mode change after the connect. The pool keeps theafter_connectof main.The lines that this PR changes against main are the same before and after the merge. The gates on 8369db4:
cargo +1.97.0 fmt --all -- --checkgives no changes. The two clippy commands of.github/workflows/clippy.ymlwith-D warnings, on the whole workspace as CI runs them, give no warnings.extenddb-storage-sqlite359 passed and 1 ignored. On this host, the twobackup_catalog::write_lock_testsfail, as on main (storage-sqlite: the two write_lock_tests fail when an ancestor of the Cargo target directory is owned by another user #1414).file_modes(9 tests) andfile_mode_umask(1) pass.cargo test -p extenddb-wasm-adapter, with itsparitycorpus test: 4 passed.cargo test -p extenddb-storage-postgres --test doc_version_literals: passed.python3 -m pytest --collect-onlycollects 7347 tests intests/and 820 intests/python, with no error.No code of this PR changed after
29ba45112.LJMart11 reviewed
46fd13eafbefore that. The commits between46fd13eafand29ba45112:79febe7a4merges main ata417b2f82. Main's two new commits, fix(storage-cassandra): extenddb destroy removes only a deployment's own keyspaces #1173 and UpdateExpression ADD creates no missing map on its path #596, change no file of this branch.29ba45112addsprepare_sets_an_existing_database_behind_a_symlink_to_0600, the test that LJMart11 asked for on thefile_mode.rsthread. In the test, a symlink at the database name points to a 0644 database with a 0644-walfile. Afterprepare, both files are 0600 and the name is still a symlink. Whenrestrict_filestakes the unresolved path for the database file, the test fails with the target at 0644.jcshepherd reviewed
efb64f374.8c59d1e29,0c70affa1and584001536followed on 20 November, as the reply on thebackend.rsthread describes. The commits after584001536:11867db6dandf6870f48dmerge main at89fc9717band at3534c9e4d. The second merge includes the WebAssembly build (feat(wasm): [Add WebAssembly browser support for ExtendDB #1009). It resolves the conflicts incrates/storage-sqlite/Cargo.toml,lib.rsandserve_lock.rs. It also compiles off wasm32 the file mode code that wasm32 does not call (see "The WebAssembly build" below).eb3a5825f:connectno longer narrows the files after the pool connects.preparecreates or narrows the database file before the connect, so that call changed no mode. This commit removesrestrictandrestrict_with.d891fb059:file_mode::create_owner_onlyis the one creator of a missing database file, forprepare, the migration runner andinit. It sets each new file to 0600 through its descriptor. Before, the runner andinitcreated the file with mode 0600 less the umask: 0400 under umask 0o277, which SQLite opens read-only. It removesmigrations::open::create_private. The descriptor call isserve_lock::set_owner_only, which the lock file uses too.0ed070943: a unit test fails without that descriptor call, and the test of the two mode errors compares each message by equality.850d7e819: avfsname that SQLite does not have, such asunixfoo, no longer makespreparecreate a database file.6debd68ee: the module doc says wherepreparefollows a symlink, and a test comment no longer namesmanageas an opener.bb179bf1e: the docs name every command that sets the modes, theencryption-keyandbackupcommands included. The troubleshooting entry names a/procthat is not mounted, and the upgrade manual has an entry.85c24241aand46c2d3659: the file mode tests remove their temporary directory also when they fail.46fd13eaf: the crate reads the location query withform_urlencoded, the crate thaturlre-exports.urlwould add its IDNA (internationalized domain names) and ICU4X crates to the wasm32 build.What
crates/storage-sqlite/src/file_mode.rsaddsconnect(location, SqlitePoolOptions), and the bootstrapper pool andcatalog_poolopen their pools through it. It runspreparebefore the pool's first connection.SqliteEngine::new_for_serverconnects with its own connection options and callspreparebefore that connect. Its connect creates a missing database only when its URL carriesmode=rwc, whichsqlite_urladds to a plain path, andpreparethen creates it at 0600. The migration runner opens its own connection when it writes. That connection creates a missing database whatever the location asks. So the runner first creates the file withcreate_owner_only, through a dangling symlink to its target too, and callspreparebefore the connect. Its read-only connection for the catalog status changes no mode.initcreates the database file withcreate_owner_onlyas well.preparecreates the database file with mode 0600 when the connection would create it. It then narrows the file and any-wal,-shmor-journalfile left by an earlier run. As a result, the sidecars SQLite creates on this connection take 0600 from the database file.preparecreates the file withcreate_new, which refuses any existing entry, a symlink included. For a dangling symlink at the database name, it creates the link's target.create_owner_onlycreates the file withcreate_newand mode 0600, and then sets it to 0600 through its descriptor. The kernel applies the umask to the mode that thecreate_newopen passes, and the umask can remove owner bits as well.Which commands reach these openers
initcreates the database file withcreate_owner_only, then writes through the migration runner and the bootstrapper pool.migrate --yes, the first open of a dev-modeserve, andencryption-key switch,rotateandresetopen the migration runner for writing.serveand thebackupcommandslist,purge,syncandremove-targetopen the engine pool and the catalog pool through the server components factory.settings,verify, andencryption-key status,rewrapandset-data-connectionopen the catalog pool through the settings, management and diagnostics store factories.destroyopens the bootstrapper pool.Which files
preparechangespreparechanges only a regular file with a permission bit outside 0600, and sets it to 0600. A regular file at 0600, 0400, 0200 or 0000 keeps its mode, andpreparemakes no attempt to change it. So a read-only mount whose files are already 0600 opens as before.preparefollows a symlink at the database name, as SQLite follows it. It does not change a symlink at a sidecar name, and its target keeps its mode. SQLite opens its files withO_NOFOLLOW, so if it needs that sidecar, its own open fails and the command reports SQLite's error.O_PATH | O_NOFOLLOW, which opens no file for reading or writing, so nothing waits on a FIFO or a device. It reads the type and mode from that handle. It changes the mode withchmodof/proc/self/fd/<n>, so the check and the change act on the same file. Closing anO_PATHhandle keeps the POSIX locks the process's SQLite connections hold on the file. Closing a descriptor opened for reading releases them, which section 2.2 of How To Corrupt An SQLite Database File lists as a cause of corruption.serveopens the catalog pool, whosepreparenarrows the files, while the engine's pool holds its connections. So the narrowing runs while connections hold locks on the file.lstatand changes the mode withfchmodat(AT_SYMLINK_NOFOLLOW), which opens nothing.cannot set the mode of SQLite file <path>: <error>. A database file thatprepare, the migration runner orinitcreated whose mode cannot be set givescannot set the mode of SQLite database <path>: <error>. The.lockfile already follows this policy (fix(sqlite): one extenddb process per database file #391).preparedoes nothing, andcreate_owner_onlycreates the file with the platform's default permissions.Which file the connection opens
preparefinds the file the connection opens and decides whether the connection creates it. To do this, it reads the location as sqlx 0.8.6 and the bundled SQLite 3.46.0 read it. sqlx reads the connection string's query as form-urlencoded:mode=rwccreates unless amode=rois also given, and the lastvfsand the lastimmutablewin. Thevfsmust name a unix VFS that the linked SQLite has.prepareasks SQLite withsqlite3_vfs_find, because SQLite refuses an open with a name it does not have.A new module,
crates/storage-sqlite/src/sqlite_uri.rs, reads afile:URI's own query. It follows SQLite'ssqlite3ParseUri: it decodes%HH, and?,#,&and=separate only when they appear raw. The lastvfswins, and the module applies eachmodein order. As in SQLite, amodethat asks for more access than the one before it fails the open, so SQLite creates no file.prepareleaves afile:name combined withvfsorimmutableto the connection, because sqlx then wraps it so that SQLite opens a relative path spelledfile:....serve_lock::database_filereads afile:path throughsqlite_uriand findsmode=memorythrough the same form-urlencoded parse. For afile:URI with%HHin its path, the lock file is now next to the file SQLite opens. An encodedmode=memory(for examplemod%65=memory) now takes no lock, like the other in-memory forms. For other locations the lock path stays where it was, and the existing lock path tests pass without changes.This branch removes the chmod loop in
SqliteEngine::new_for_serverandmigrations::open::create_private.catalog_poolreturns its error as aString.serve_lock::resolve_dangling_symlinksispub(crate), andserve_lock::set_owner_onlysets both the lock file and a new database file to 0600. The crate takesform_urlencoded1, whichCargo.lockalready had at 1.2.2 throughurl.docs/troubleshooting.mdgains an entry for the two errors and names the commands that set these modes.docs/manuals/10-security-model.mdnames the database files, anddocs/manuals/07-upgrade-manual.mdhas a v1.2.0 entry.The WebAssembly build
On wasm32 the crate opens only in-memory databases (#1009). The code this branch adds for files follows the rules in the module doc of
crates/storage-sqlite/src/lib.rs. The Unix items compile undercfg(unix).connect, the non-Unixcreate_owner_onlyandresolve_dangling_symlinkscompile off wasm32, because none of their callers compiles there. wasm32 compiles the non-Unixprepare, which does nothing and whichSqliteEngine::new_for_servercalls. It also compilesdatabase_fileand thesqlite_urireader that it uses. Theoptionsfield ofFileUri, which only Unix reads outside the tests, expectsdead_codeon other targets.Why
The database holds the encryption key next to the access-key secrets and password hashes it protects. So its files must be readable by their owner only. On main,
initand the migration runner create the database file with mode 0600 less the umask (#666). So a new deployment starts at 0600 under umask 022. These gaps remain on main. The tests named in the first five bullets fail with main's production code. They ran on 24 November with the production files ofa60c2b9f3, the base before the two merges of main above. The umask test ran with main's two creators.migrate --yesleaves files that an earlier version left at 0644 at 0644 (serve_and_migrate_restrict_files_left_at_0644:x.sqlite is 644after the migration). Over a 0644 database without sidecars, the runner's open also creates its-waland-shmat 0644 (the_migration_runner_creates_its_sidecars_at_0600_over_a_0644_database).the_bootstrapper_pool_alone_creates_owner_only_files,the_catalog_pool_alone_creates_owner_only_files).the_migration_runner_creates_the_target_of_a_dangling_symlink_owner_only).initand the runner create the file at 0400. SQLite then opens it read-only, and the runner's open fails withattempt to write a readonly database(tests/file_mode_umask.rs).file:path without decoding%HH, and misses an encodedmodekey (a_file_uri_path_is_decoded_as_sqlite_decodes_it,an_encoded_mode_key_is_read_as_sqlx_reads_it).-waland-shmto the configured string, which for asqlite:URL names files that do not exist, and it ignores errors.SQLite gives a new
-walor-shmfile the mode of the database file, and it resolves symlinks before it names them. So a database file narrowed before the connection opens it also gives its mode to the sidecars that connection creates.The copy that
migrate --yestakes before it applies a migration keeps the umask gap.create_partialincrates/storage-sqlite/src/migrations/copy.rsis code this PR does not change (#1452).Closes #657
Overlaps
#1009 (amrith, the WebAssembly build) merged on 24 November and conflicted with this branch in
crates/storage-sqlite/Cargo.toml,lib.rsandserve_lock.rs. The mergef6870f48dresolves them. On 4 December 2026,git merge-treecompared 8369db4 and main with each of the 219 open PRs. This branch conflicts with these open PRs in files where they do not conflict with main:docs/manuals/10-security-model.md.crates/storage-sqlite/src/lib.rs. This branch declaresfile_modewhere fix: report Backfilling on a CREATING GSI and refuse its reads by phase #454 declaresgsi_backfilling_testsand fix: answer requests during a table's DELETING window as the service does #550, fix(cassandra): fence concurrent DeleteTable with a lease #598 and fix: answer TTL and tag calls during a table's DELETING window #599 declaredeleting_window_data_tests. The PR that merges second keeps both declarations.docs/manuals/07-upgrade-manual.md, where each adds a v1.2.0 entry at the same place as this branch. The PR that merges second keeps both entries. 23 other open PRs conflict with this branch there and with main there too.#666 (merged 2 November) came first. It creates the database file with mode 0600 in
initand the runner. This branch keeps that and closes the gaps listed under Why.Testing done
Measured with a binary built from this branch on 31 October 2026, under umask 022 and 002. After
initall five files are 600. They stay 600 through the firstserve, management writes, CreateTable, PutItem, a clean stop, a secondserveandmigrate.migrateover copies at 0600 and 0644 with no sidecars leaves the database and its new sidecars at 600.Unit and integration tests
Unit tests in
crates/storage-sqlite/src/file_mode/tests.rs, independent of the test process's umask:preparecreates a missing database at 0600, also at the target of a dangling symlink. The test reads the new file's mode through its descriptor before the narrowing. That mode equals the mode of a file the test creates with mode 0600 under the same umask. The test then sets the new file to 0400, the mode a umask of 0o200 leaves, and the file is 0600 whenpreparereturns.sqlite:URL. Through a symlink at the database name, the target and its-walfile become 0600, and the name stays a symlink. Insideafter_connect, the database and the sidecars SQLite created are 0600, for a missing database and for an existing 0644 one./. A symlink to a 0644 file at-journal, a FIFO at-waland a socket node at-shmkeep theirs, and the link's target stays 0644.preparereturns within ten seconds.EROFS,preparesucceeds on files at 0600 and 0400 without making the call. A 0644 file givescannot set the mode of SQLite file <path>: Read-only file system (os error 30), and the file stays at 0644. A missing database whose new file's mode cannot be set givescannot set the mode of SQLite database <path>: Read-only file system (os error 30). The test compares both messages by equality. It puts the failing calls in place of the system calls. So it changes no file outside its own temporary directory, also when it runs as root.preparetakes its files from 0644 to 0600. Afterwards anF_OFD_GETLKquery still finds the connection's read lock on the database file's shared range and on the-shmfile's DMS byte.preparecreates nothing forsqlite:///pathwithout a query,mode=ro,mode=rwc&mode=ro,vfs=memdb,vfs=unixfoo,:memory:, an encodedmod%65=memory, afile:name withvfsorimmutable, andfile:URIs whose own query does not create (mode=ro,mode=rw,mode=memory,vfs=memdb,vfs=unixfoo, andmode=rofollowed bymode=rwc). A repeatedvfsthat ends withunix, avfsofunix%00x, andfile:URIs whose own query (written with%3F) iscache=sharedormode=rwc, create the database at 0600 with its sidecars.file:<dir>/a%2520b.sqlitereachesa b.sqliteand leaves no straya%20b.sqlite.tempfile::TempDir, which removes it also when the test fails.sqlite_uri.rshas unit tests for the decoding, the separators,%00, empty option names, the authority, andcreates_fileover 15 queries.serve_lock.rshas new tests for the lock path of a decodedfile:path, an encodedmodekey, and afile:name withvfs(unchanged).Integration test binary
crates/storage-sqlite/tests/file_modes.rs, which sets umask 022 in its own process:init(the bootstrapper sequence the CLI runs),servethrough the server components factory, a first write (create-account, CreateTable, TagResource), a stop and a secondserve. After each step each regular file in the deployment directory is 0600.servethat bootstraps a missing database creates 0600 files.initare 0600 after aserveand aftermigrate --yes.-waland-shmmodes for as long as the open runs, and every read is 0600.sqlite:URL withoutmode=rwcwhose path is a dangling symlink. The runner creates the target at 0600, and the target and its sidecars are 0600 once the open returns.Integration test binary
crates/storage-sqlite/tests/file_mode_umask.rsholds one test, which sets umask 0o277 in its own process.create_catalog_dband the migration runner's open of a missing database leave the database file and its-waland-shmfiles at 0600, and the runner's open succeeds.Negative controls
I made each mutation on a clean committed tree and reverted it afterwards.
With
restrict_filestaking the unresolved path for the database file, every test infile_mode,file_modesandfile_mode_umaskpassed on79febe7a4. On29ba45112, this mutation fails the new symlink test, with the target at 0644.These ran on
46fd13eaf:connectwithoutprepareafter_connect(0644), and the bootstrapper pool and catalog pool integration testsprepareserveandmigratetest over files left at 0644 (x.sqliteat 0644 after the migration) and the sidecar test (x.sqlite-shmat 0644 during the open)SqliteEngine::new_for_serverwithoutpreparex.sqliteat 0644)opened_filewithout the VFS conditioncreate_owner_onlywithout its descriptor callserve_lock::set_owner_onlymaking no callserveandmigratetest (x.sqlite.lockat 0644) and the umask testtarget.sqliteat 0644)is_unix_vfswithoutsqlite3_vfs_findcreates_filetable (vfs=unixfoo)is_unix_vfswithout the cut at the first NULvfs=unix%00xWith the creators of
eb3a5825f, which are main's, the umask test fails withattempt to write a readonly database. It fails on the file ofinitwith both creators or with the one ofinitalone, and on the runner's file with the runner's alone.These ran on earlier commits of this branch, the commits that change how
preparenarrows files and reads locations. The lines they change are the same at46fd13eaf, apart from the move ofcatalog_pooltoserver_backend.rsand the switch fromurl::form_urlencodedtoform_urlencoded:O_PATHwithoutO_NOFOLLOW-journallink followed)O_PATHO_NOFOLLOW | O_NONBLOCKENXIOon the socket node)catalog_poolwithoutfile_modeprepareafter its connectvfswinsvfs=memdb&vfs=unixfile:URI with its own query left to SQLite%3Fcache=shared%HHdecoding%2520tests for the file and the lock path, and twosqlite_uritestsmode=memoryfound with a raw splitmodekey tests for the file and the lock pathfile:name withvfsorimmutablenot left aloneGate
On 141cbd0, merged with main at c8e66fb:
cargo +1.97.0 fmt --all -- --checkgives no changes.cargo +1.97.0 clippy -p extenddb-storage-sqlite -p extenddb-app -p extenddb-server --all-targets -- -D warningsandcargo +1.94.0 checkon the same crates give no warnings.extenddb-storage-sqlite358 passed and 1 ignored,extenddb-app106 passed,extenddb-server521 passed. On this host, the twobackup_catalog::write_lock_testsofextenddb-storage-sqliteand fivebackup_storetests ofextenddb-serverfail, as on main (storage-sqlite: the two write_lock_tests fail when an ancestor of the Cargo target directory is owned by another user #1414).file_modes(9 tests) andfile_mode_umask(1) pass.cargo test -p extenddb-wasm-adapter, with itsparitycorpus test: 4 passed. The clippy step of the WebAssembly workflow gives no warnings.cargo test -p extenddb-storage-postgres --test doc_version_literals: passed.python3 -m pytest --collect-onlycollects 7304 tests intests/and 820 intests/python, with no error.The runs below are from earlier rounds.
On
29ba45112, merged with main ata417b2f82:cargo +1.97.0 fmt --all -- --checkgives no changes. The crate's two clippy runs, the 1.91.1 check and the clippy step of the WebAssembly workflow give no warnings.cargo +1.97.0 test --locked -p extenddb-storage-sqlite: 350 unit tests pass and 1 is ignored.file_modes(9 tests),file_mode_umask(1) andwasm_shim(3) pass, and the 4 tests named below fail on the host where these tests ran.python3 -m pytest --collect-onlycollects 6660 tests intests/and 672 intests/python, with no error.The other checks below ran only on
46fd13eaf. After46fd13eaf, this branch changes onlycrates/storage-sqlite/src/file_mode/tests.rs, apart from the merge of main. That file compiles only for the tests on Unix.On
46fd13eaf, merged with main at3534c9e4d:cargo +1.97.0 fmt --all -- --check: no changes.cargo +1.97.0 clippy --locked -p extenddb-storage-sqlite --all-targets -- -D warnings, and the same with--features extenddb-engine/backup-test-hooks: no warnings.cargo +1.91.1 check --locked -p extenddb-storage-sqlite --all-targets: passes.cargo +1.97.0 test --locked -p extenddb-storage-sqlite: 349 unit tests pass and 1 is ignored.file_modes(9 tests),file_mode_umask(1) andwasm_shim(3) pass. 4 tests fail on the host where these tests ran: the 2backup_catalog::write_lock_tests, which storage-sqlite: the two write_lock_tests fail when an ancestor of the Cargo target directory is owned by another user #1414 tracks,backup_job_panicandrestore_job_resume. Each stops atPermissionDenied("/local/home (an ancestor of the backup root) is owned by uid 65534; ..."), because of how that host maps file ownership. CI passed all four at584001536.python3 -m pytest --collect-onlycollects 6637 tests intests/and 672 intests/python, with no error.file_mode.rsandsqlite_uri.rscompile withrustc +1.97.0 -D warningsforwasm32-unknown-unknownandx86_64-pc-windows-msvc, beside callers as the crate's code calls them (with stand-ins forsqlxandsqlite_utilon Windows): no warnings, with and without--test.cargo +1.97.0 clippy --locked -p extenddb-engine --no-default-features --lib --release --target wasm32-unknown-unknownwith-D warnings, and withCLIPPY_CONF_DIRset todevtools/wasm-clippy: no warnings. That build of the engine does not include this crate.cargo +1.97.0 clippy --locked -p extenddb-wasm-adapter --all-targetswith-D warnings: no warnings.devtools/run-wasm-step clippy): no warnings. It ran with the C compile of the bundled SQLite skipped, because the host has no clang, and clippy does not link. On fix(expressions): validate in the service's order, with its messages #399's headcdafc6ff7, the same run gave the two errors that the WebAssembly job of that PR gave.devtools/generate-software-license-notices --check, also with--backend mongodband--backend cassandra, anddevtools/generate-dev-license-notices --check: each notices file is current.These tests ran on Linux. No run covered the macOS version of the narrowing. The npm build workflow on this pull request compiled it for both macOS targets at
584001536, and both builds passed. The wasm32 build of the adapter needs clang, which the host where these tests ran does not have. So the build step did not run there. The WebAssembly workflow runs it on this pull request.Checklist
cargo test --workspace)cargo fmt --check)cargo clippy -- -W clippy::pedantic)Storagetrait, auth model, on-diskformat, or public CLI surface, an RFC has been accepted or is linked
below. Otherwise, an ADR captures the decision (link below).
Clippy ran with
-D warnings. With-W clippy::pedanticat 141cbd0 it reports 51 warnings on lines this branch adds. 47 are missing backticks in doc comments. The other 4, infile_mode/tests.rs, are 3 casts and 1 lifetime that can be elided. The change sets file modes and adds no command, flag or file format.ADR / RFC: n/a
Breaking changes
init,migrate --yes,serve,settings,verify, theencryption-keycommands (status,switch,rewrap,rotate,resetandset-data-connection) and thebackupcommands (list,purge,syncandremove-target). On main,initand the migration runner create the database file with mode 0600 less the umask. The serve engine, which thebackupcommands open too, sets the modes after its pool connects and ignores a failed chmod. The bootstrapper and catalog pools set no mode.destroycontinues when its catalog read fails, as on main, and then removes the files while holding the lock file.serve,migrate --yes,encryption-key switch,rotateandreset, and thebackupcommands other thanlistandpurgewithout--confirm, this happens when no lock file is present. On main the lock file already refused that user forserve,migrate,destroyand the other commands that take it, whenever it existed.chmod 600, sets the files so that the read-only mount opens.settingsandverifynow fail withcannot set the mode of SQLite file <path>: Permission denied (os error 13), where main printed SQLite'sunable to open database file. Both exit 1 and leave the files' modes unchanged.initand a dev-modeserveon a missing database now create a database they can write. On main they create it at 0400, and the migration runner's open then fails withattempt to write a readonly database, astests/file_mode_umask.rsshows with main's creators.Measured on 31 October 2026 with a main binary (
1c0523c9) and a binary built from this branch. Each command ran in anamazonlinux:2023container on a bind mount of a deployment directory the owner created withinit. The read-only rows ran as the owner. The group member is uid 65534 with the owner's group, and the other user is uid 65532.-waland-shmpresentsettings list,settings get,verifysettings list,verifyRead-only file system (os error 30)verifyon a writable mountsettings list,verifychmod 600settings list-walor-shmsettings listunable to open database filesettings list,verifyOperation not permitted (os error 1)migrate --yes,serve,destroy --yescannot set the mode of lock filemigrate --yescannot set the mode of SQLite fileservecannot set the mode of SQLite filesettings list,verifyOperation not permitted (os error 1)For a read-only mount, the new troubleshooting entry has the owner run one command on a writable mount or
chmod 600the files. For files that belong to another user, it has extenddb run as that user.By submitting this pull request, I confirm that my contribution is made under
the terms of the Apache License 2.0 and I agree to the Developer Certificate of
Origin (DCO). See CONTRIBUTING.md for details.