From f8d7a2d222460bda7261ddf117c760129ae26968 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 15 Sep 2026 18:38:59 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix:=20the=20boot=20seed=20survi?= =?UTF-8?q?ves=20a=20rival=20boot;=20a=20failed=20create=20drops=20its=20d?= =?UTF-8?q?atabase?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two more members of the class the template fix opened — a statement issued where a rival process may already have written the same row. `service::builder::ensure` raced on `builder_username`: find-then-insert is not a guard, and the loser's raw `23505` killed the boot (measured: four boots racing a fresh control database, three died, only the winner stayed up). The insert is now `INSERT … ON CONFLICT (username) DO NOTHING`, so the loser neither raises nor logs — a refused insert is logged by the server even when the client handles it — and the winner's credential stands. The same 4-way probe now reports 4/4 up with zero server-side error lines. `Tenants::create`'s rollback deleted the registry rows but left the database it had just created: names are minted per create and never replayed, so that is an unreachable 70-table database nothing can name again. The rollback now drops it best-effort and warns when even that fails, so the one leak this path can produce is at least visible. `.sqlx` regenerated for the changed statement (scripts/prepare_db.sh + cargo sqlx prepare). --- ...333a540b4f26a2dde89da4f42122c9628d64.json} | 4 +- src/db/builder.rs | 24 +++++---- src/service/builder.rs | 49 +++++++++++++++++-- src/tenant.rs | 20 +++++++- 4 files changed, 81 insertions(+), 16 deletions(-) rename .sqlx/{query-f033efcb08101eb7c3873abe1b079ccb175dc1dcacf75910ad9aa45d23210583.json => query-82c64e3fbc3349bcf1579d7021b9333a540b4f26a2dde89da4f42122c9628d64.json} (63%) diff --git a/.sqlx/query-f033efcb08101eb7c3873abe1b079ccb175dc1dcacf75910ad9aa45d23210583.json b/.sqlx/query-82c64e3fbc3349bcf1579d7021b9333a540b4f26a2dde89da4f42122c9628d64.json similarity index 63% rename from .sqlx/query-f033efcb08101eb7c3873abe1b079ccb175dc1dcacf75910ad9aa45d23210583.json rename to .sqlx/query-82c64e3fbc3349bcf1579d7021b9333a540b4f26a2dde89da4f42122c9628d64.json index 12a89d5..f32ff9c 100644 --- a/.sqlx/query-f033efcb08101eb7c3873abe1b079ccb175dc1dcacf75910ad9aa45d23210583.json +++ b/.sqlx/query-82c64e3fbc3349bcf1579d7021b9333a540b4f26a2dde89da4f42122c9628d64.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO builder (id, username, password_hash, created_at) VALUES ($1, $2, $3, $4)", + "query": "INSERT INTO builder (id, username, password_hash, created_at) VALUES ($1, $2, $3, $4)\n ON CONFLICT (username) DO NOTHING", "describe": { "columns": [], "parameters": { @@ -13,5 +13,5 @@ }, "nullable": [] }, - "hash": "f033efcb08101eb7c3873abe1b079ccb175dc1dcacf75910ad9aa45d23210583" + "hash": "82c64e3fbc3349bcf1579d7021b9333a540b4f26a2dde89da4f42122c9628d64" } diff --git a/src/db/builder.rs b/src/db/builder.rs index b523dbb..13dca58 100644 --- a/src/db/builder.rs +++ b/src/db/builder.rs @@ -39,14 +39,20 @@ pub async fn read(db: &Database, id: &BuilderId) -> Result, AppE Ok(builder) } -/// The raw account insert behind [`crate::service::builder::ensure`]'s seed. -/// The unique index on `username` is the whole availability check: a racing -/// second seed is a `23505` on `builder_username`, and the seed's -/// find-then-insert order makes that unreachable in practice — but the -/// constraint stands guard regardless. -pub async fn create(db: &Database, builder: Builder) -> Result<(), AppError> { - sqlx::query!( - "INSERT INTO builder (id, username, password_hash, created_at) VALUES ($1, $2, $3, $4)", +/// Seed one builder account: the insert that leaves an existing row alone. +/// `true` when this call created it, `false` when the username was already +/// taken. +/// +/// `ON CONFLICT DO NOTHING` rather than find-then-insert-then-catch: the seed +/// runs on every boot, two boots of a fresh deployment collide on it, and an +/// insert that is *refused* is logged by the server as an `ERROR` line even +/// when the client handles it (measured: four boots racing a fresh control +/// database, three of them lost the race). The conflict target is the +/// username index alone, so every other insert failure still surfaces. +pub async fn create(db: &Database, builder: Builder) -> Result { + let result = sqlx::query!( + "INSERT INTO builder (id, username, password_hash, created_at) VALUES ($1, $2, $3, $4) + ON CONFLICT (username) DO NOTHING", builder.id.uuid(), builder.username.as_str(), builder.password_hash.as_str(), @@ -54,7 +60,7 @@ pub async fn create(db: &Database, builder: Builder) -> Result<(), AppError> { ) .execute(db) .await?; - Ok(()) + Ok(result.rows_affected() == 1) } /// Mint and store one builder login session. diff --git a/src/service/builder.rs b/src/service/builder.rs index abf4b73..65a1c3e 100644 --- a/src/service/builder.rs +++ b/src/service/builder.rs @@ -28,10 +28,15 @@ pub async fn ensure(db: &Database, username: Username, password: Password) -> Re password_hash: password.hash_async().await?, username, }; - builder::create(db, builder).await?; - // The account name stays out of the event: exported log records must - // name no person (see `telemetry`). - tracing::info!("seeded the builder account named by BUILDER_USERNAME"); + // A rival boot that seeded the same username between the read above and + // this insert loses the race silently — `create` reports "already there" + // instead of raising, so the second container of a fresh deployment boots + // instead of dying on a duplicate key. The winner's credential stands. + if builder::create(db, builder).await? { + // The account name stays out of the event: exported log records must + // name no person (see `telemetry`). + tracing::info!("seeded the builder account named by BUILDER_USERNAME"); + } Ok(()) } @@ -92,4 +97,40 @@ mod tests { first.get_password_hash().as_str() ); } + + /// Two boots of one deployment seed the same username in the same instant. + /// The loser must adopt the winner's row instead of dying on its own + /// insert — measured on a fresh control database: four boots racing, three + /// died on `23505 builder_username` and only the winner stayed up. + #[tokio::test] + async fn a_racing_seed_adopts_the_row_it_lost_to() { + let tenants = crate::database::init_test_tenants().await; + let control = tenants.control(); + let name = Username::try_new("builder_race").unwrap(); + let (first, second) = tokio::join!( + ensure(control, name.clone(), Password::try_new("secret1").unwrap()), + ensure(control, name.clone(), Password::try_new("secret2").unwrap()), + ); + first.expect("the first seed"); + second.expect("the racing seed adopts the account the winner seeded"); + + // One account, and the credential is whichever writer won the insert — + // neither seed rewrites the other's row. + let row = find_by_username(control, "builder_race") + .await + .unwrap() + .expect("seeded"); + let matches_offered = row + .get_password_hash() + .verify_async(&Password::try_new("secret1").unwrap()) + .await + || row + .get_password_hash() + .verify_async(&Password::try_new("secret2").unwrap()) + .await; + assert!( + matches_offered, + "the stored hash belongs to no offered password" + ); + } } diff --git a/src/tenant.rs b/src/tenant.rs index 4bc08da..99a3256 100644 --- a/src/tenant.rs +++ b/src/tenant.rs @@ -470,6 +470,25 @@ impl Tenants { .bind(id.uuid()) .execute(&self.control) .await; + // The rows go first — a slug taken by a school that never came + // to exist is wedged for good — then the database, which is the + // expensive half and whose name nothing will ever reuse (the id + // is minted per create, never replayed). Best-effort, but not + // silent: a failure here is a half-provisioned database nobody + // can see or reach, so it earns the one log line this path has. + if let Err(leak) = sqlx::query(sqlx::AssertSqlSafe( + create_database_sql( + "DROP DATABASE IF EXISTS", + &school_db_name(&self.control_db, id.uuid()), + ) + " WITH (FORCE)", + )) + .execute(&self.control) + .await + { + tracing::warn!( + "failed to drop the database of a school whose create failed: {leak}" + ); + } return Err(err); } }; @@ -651,7 +670,6 @@ impl Tenants { mod tests { use super::*; - #[test] fn a_slug_names_a_school_and_nothing_reserved() { for good in ["demo", "a1", "ata-koleji", &"x".repeat(32)] {