1
//! Slice A: per-user database provisioning, exercised end to end against a real
2
//! Postgres via `server::provision::create_user_database`.
3
//!
4
//! Gated on the `db` feature (which turns on `server/test-utils`). These tests
5
//! create real databases through the admin `DATABASE_URL` and drop each one in
6
//! teardown — `sqlx::test` only cleans up the database it created itself, not
7
//! ones the application creates.
8
//!
9
//! All scenarios run inside ONE `#[tokio::test]`. `server::db`'s admin pool is a
10
//! process-static `OnceCell<PgPool>` initialized lazily in the first runtime
11
//! that touches it; a separate `#[tokio::test]` per scenario would each spin up
12
//! its own runtime, and the pool bound to the first (now-dropped) runtime would
13
//! then time out for later tests. One runtime keeps the pool alive throughout —
14
//! and mirrors production, which provisions serially on one long-lived runtime.
15
//!
16
//! Run via:
17
//!   DATABASE_URL=postgres://… cargo test -p tests-integration --features db
18

            
19
#![cfg(feature = "db")]
20

            
21
use server::command::config::{GetConfig, SetConfig};
22
use sqlx::Row;
23
use sqlx::postgres::PgPoolOptions;
24
use tests_integration::tenant_guard::TestTenant;
25
use uuid::Uuid;
26

            
27
1
async fn admin_connect() -> sqlx::PgPool {
28
    let url =
29
1
        std::env::var("DATABASE_URL").expect("DATABASE_URL must be set for provisioning tests");
30
1
    PgPoolOptions::new()
31
1
        .max_connections(1)
32
1
        .connect(&url)
33
1
        .await
34
1
        .expect("connect to admin DB")
35
1
}
36

            
37
2
fn per_user_dsn(base: &str, database_name: &str) -> String {
38
2
    let (prefix, rest) = base.split_once("://").expect("scheme");
39
2
    let authority = rest.split('/').next().expect("authority");
40
2
    format!("{prefix}://{authority}/{database_name}")
41
2
}
42

            
43
#[tokio::test]
44
1
async fn per_user_provisioning_end_to_end() -> anyhow::Result<()> {
45
1
    let admin = admin_connect().await;
46

            
47
1
    provisions_a_migrated_isolated_db().await?;
48
1
    is_idempotent_on_retry().await?;
49
1
    bootstrap_seed_is_idempotent(&admin).await?;
50
1
    admin_has_backfilled_keypair(&admin).await?;
51
1
    two_users_get_distinct_databases().await?;
52
1
    private_key_is_stored_in_per_user_db().await?;
53
1
    per_user_config_is_isolated(&admin).await?;
54
1
    an_unregistered_user_has_no_tenant().await;
55

            
56
2
    Ok(())
57
1
}
58

            
59
/// A freshly provisioned DB has the full schema, is usable, and contains no
60
/// seeded signing keys (those live only in the admin DB via `bootstrap::seed`).
61
1
async fn provisions_a_migrated_isolated_db() -> anyhow::Result<()> {
62
1
    let user_id = Uuid::new_v4();
63
1
    let database_name = format!("nomi_user_{}", user_id.simple());
64
1
    let _tenant = TestTenant::database(database_name.clone());
65

            
66
    // Returns the database NAME, not a DSN: a connection string in
67
    // `users.database_name` would put a live credential in a row (ADR 0032).
68
1
    let returned = server::provision::create_user_database(user_id).await?;
69
1
    assert_eq!(
70
1
        returned, database_name,
71
        "provisioning must return the bare database name"
72
    );
73

            
74
1
    let base = std::env::var("DATABASE_URL")?;
75
1
    let user_pool = PgPoolOptions::new()
76
1
        .max_connections(1)
77
1
        .connect(&per_user_dsn(&base, &database_name))
78
1
        .await?;
79
1
    let accounts: i64 = sqlx::query("SELECT count(*) FROM accounts")
80
1
        .fetch_one(&user_pool)
81
1
        .await?
82
1
        .get(0);
83
1
    assert_eq!(
84
1
        accounts, 0,
85
        "fresh per-user DB has the accounts table, empty"
86
    );
87

            
88
    let secret_rows: i64 =
89
1
        sqlx::query("SELECT count(*) FROM config WHERE lower(field) LIKE '%token_private_key'")
90
1
            .fetch_one(&user_pool)
91
1
            .await?
92
1
            .get(0);
93
1
    assert_eq!(secret_rows, 0, "per-user DB must not contain signing keys");
94

            
95
1
    user_pool.close().await;
96
1
    Ok(())
97
1
}
98

            
99
/// A second provision for the same user id hits SQLSTATE 42P04 (duplicate
100
/// database) and succeeds, returning the same DSN.
101
1
async fn is_idempotent_on_retry() -> anyhow::Result<()> {
102
1
    let user_id = Uuid::new_v4();
103
1
    let database_name = format!("nomi_user_{}", user_id.simple());
104
1
    let _tenant = TestTenant::database(database_name.clone());
105

            
106
1
    let first = server::provision::create_user_database(user_id).await?;
107
1
    let second = server::provision::create_user_database(user_id).await?;
108
1
    assert_eq!(first, second);
109

            
110
1
    Ok(())
111
1
}
112

            
113
/// `seed()` is guarded by the `seed_complete` marker, so a second call is a
114
/// no-op and never duplicates rows (config has no UNIQUE(field) yet).
115
1
async fn bootstrap_seed_is_idempotent(admin: &sqlx::PgPool) -> anyhow::Result<()> {
116
1
    server::bootstrap::seed().await?;
117
1
    let after_first: i64 = sqlx::query("SELECT count(*) FROM config")
118
1
        .fetch_one(admin)
119
1
        .await?
120
1
        .get(0);
121

            
122
1
    server::bootstrap::seed().await?;
123
1
    let after_second: i64 = sqlx::query("SELECT count(*) FROM config")
124
1
        .fetch_one(admin)
125
1
        .await?
126
1
        .get(0);
127

            
128
1
    assert_eq!(
129
1
        after_first, after_second,
130
        "re-running seed must not change config row count"
131
    );
132
    let marker: i64 =
133
1
        sqlx::query("SELECT count(*) FROM config WHERE lower(field) = 'seed_complete'")
134
1
            .fetch_one(admin)
135
1
            .await?
136
1
            .get(0);
137
1
    assert_eq!(marker, 1, "exactly one seed_complete marker");
138

            
139
    // The admin's data lives in the admin database itself, so bootstrap points
140
    // its database_name at *this* database — a bare name, never the empty seed
141
    // placeholder and never a DSN, which would store a live credential in a row.
142
1
    let admin_db_name: String = sqlx::query(
143
1
        "SELECT database_name FROM users WHERE id = '22d36bde-d987-4927-b070-842efdcf9c59'",
144
1
    )
145
1
    .fetch_one(admin)
146
1
    .await?
147
1
    .get(0);
148
1
    let expected: String = sqlx::query("SELECT current_database()")
149
1
        .fetch_one(admin)
150
1
        .await?
151
1
        .get(0);
152
1
    assert_eq!(
153
1
        admin_db_name, expected,
154
        "admin database_name must be this database's name, not a placeholder or a DSN"
155
    );
156
1
    assert!(
157
1
        !admin_db_name.contains("://"),
158
        "database_name must never hold a connection string: {admin_db_name}"
159
    );
160
1
    Ok(())
161
1
}
162

            
163
/// After `bootstrap::seed`, the admin user has a public signing key in the
164
/// global directory and a matching private key in the admin DB — so admin login
165
/// keeps working once the global seed keys are retired (Slice B cutover).
166
1
async fn admin_has_backfilled_keypair(admin: &sqlx::PgPool) -> anyhow::Result<()> {
167
1
    server::bootstrap::seed().await?;
168

            
169
1
    let public_key: Option<String> = sqlx::query(
170
1
        "SELECT jwt_public_key FROM users WHERE id = '22d36bde-d987-4927-b070-842efdcf9c59'",
171
1
    )
172
1
    .fetch_one(admin)
173
1
    .await?
174
1
    .get(0);
175
1
    assert!(
176
1
        public_key.is_some_and(|k| !k.is_empty()),
177
        "admin must have a backfilled public key"
178
    );
179

            
180
1
    let private_keys: i64 = sqlx::query("SELECT count(*) FROM user_auth_keys")
181
1
        .fetch_one(admin)
182
1
        .await?
183
1
        .get(0);
184
1
    assert!(
185
1
        private_keys >= 1,
186
        "admin DB must hold the admin private key"
187
    );
188

            
189
    // Repair path: a prior run that wrote only the public key (then crashed
190
    // before the private insert) must be healed on the next seed, not skipped.
191
1
    sqlx::query("DELETE FROM user_auth_keys")
192
1
        .execute(admin)
193
1
        .await?;
194
1
    server::bootstrap::seed().await?;
195
1
    let repaired: i64 = sqlx::query("SELECT count(*) FROM user_auth_keys")
196
1
        .fetch_one(admin)
197
1
        .await?
198
1
        .get(0);
199
1
    assert_eq!(
200
1
        repaired, 1,
201
        "seed must repair a missing admin private key (public-set-but-private-missing)"
202
    );
203
1
    Ok(())
204
1
}
205

            
206
/// `store_user_private_key` writes the private key into the per-user DB only.
207
1
async fn private_key_is_stored_in_per_user_db() -> anyhow::Result<()> {
208
1
    let user_id = Uuid::new_v4();
209
1
    let database_name = format!("nomi_user_{}", user_id.simple());
210
1
    let _tenant = TestTenant::database(database_name.clone());
211

            
212
    // Both the provisioner and the key store speak database *names*; only
213
    // this test composes a DSN, to look inside the tenant database directly.
214
1
    let name = server::provision::create_user_database(user_id).await?;
215
1
    let keypair = server::auth_keys::generate().await?;
216
1
    server::provision::store_user_private_key(&name, &keypair.private_pem_b64).await?;
217

            
218
1
    let base = std::env::var("DATABASE_URL")?;
219
1
    let user_pool = PgPoolOptions::new()
220
1
        .max_connections(1)
221
1
        .connect(&per_user_dsn(&base, &database_name))
222
1
        .await?;
223
1
    let stored: String = sqlx::query("SELECT private_key FROM user_auth_keys")
224
1
        .fetch_one(&user_pool)
225
1
        .await?
226
1
        .get(0);
227
1
    assert_eq!(
228
1
        stored, keypair.private_pem_b64,
229
        "private key round-trips in per-user DB"
230
    );
231

            
232
    // Concurrent stores must never leave more than one key: the singleton
233
    // constraint (0005) forces them to collide-and-upsert, not duplicate. Each
234
    // store_user_private_key opens its own pool, so this is a real race.
235
1
    let kp2 = server::auth_keys::generate().await?;
236
1
    let kp3 = server::auth_keys::generate().await?;
237
1
    let (r2, r3) = tokio::join!(
238
1
        server::provision::store_user_private_key(&name, &kp2.private_pem_b64),
239
1
        server::provision::store_user_private_key(&name, &kp3.private_pem_b64),
240
    );
241
1
    r2?;
242
1
    r3?;
243
1
    let key_count: i64 = sqlx::query("SELECT count(*) FROM user_auth_keys")
244
1
        .fetch_one(&user_pool)
245
1
        .await?
246
1
        .get(0);
247
1
    assert_eq!(
248
1
        key_count, 1,
249
        "concurrent stores must keep exactly one private key"
250
    );
251
1
    user_pool.close().await;
252

            
253
1
    Ok(())
254
1
}
255

            
256
/// Two users in distinct provisioned databases set the SAME config key to
257
/// different values; each reads back only their own — per-user config is
258
/// isolated, and neither leaks into the other's DB.
259
1
async fn per_user_config_is_isolated(admin: &sqlx::PgPool) -> anyhow::Result<()> {
260
1
    let a = Uuid::new_v4();
261
1
    let b = Uuid::new_v4();
262
1
    let da = format!("nomi_user_{}", a.simple());
263
1
    let dbn = format!("nomi_user_{}", b.simple());
264
1
    let _tenants = [TestTenant::tenant(a, da), TestTenant::tenant(b, dbn)];
265

            
266
    for (id, dsn) in [
267
1
        (a, server::provision::create_user_database(a).await?),
268
1
        (b, server::provision::create_user_database(b).await?),
269
    ] {
270
        // Register in the global directory so User::get_connection routes to the
271
        // per-user DB.
272
2
        sqlx::query(
273
2
            // `verified` defaults FALSE and the tenant pool refuses a disabled
274
2
            // account, so this fixture must opt in explicitly.
275
2
            "INSERT INTO users (id, user_name, email, user_password, database_name, verified) \
276
2
             VALUES ($1, 'cfg-iso', $2, 'x', $3, TRUE)",
277
2
        )
278
2
        .bind(id)
279
2
        .bind(format!("cfg-iso-{id}@example.test"))
280
2
        .bind(&dsn)
281
2
        .execute(admin)
282
2
        .await?;
283
    }
284

            
285
1
    set_theme(a, "theme", "dark").await?;
286
1
    set_theme(b, "theme", "light").await?;
287

            
288
    // Re-set the same key (case-variant) on a freshly-provisioned DB: this
289
    // exercises the ON CONFLICT (LOWER(field)) upsert against the 0006 index
290
    // that provisioning installs, proving new per-user DBs carry the index.
291
1
    set_theme(a, "Theme", "midnight").await?;
292

            
293
1
    let a_val = get_theme(a).await?;
294
1
    let b_val = get_theme(b).await?;
295
1
    assert_eq!(a_val.map(|v| v.to_string()), Some("midnight".to_string()));
296
1
    assert_eq!(b_val.map(|v| v.to_string()), Some("light".to_string()));
297

            
298
1
    Ok(())
299
1
}
300

            
301
/// A user absent from the directory is an unknown tenant, not a missing row a caller could mistake for its own lookup.
302
1
async fn an_unregistered_user_has_no_tenant() {
303
1
    let outcome = server::user::User { id: Uuid::new_v4() }
304
1
        .get_connection()
305
1
        .await;
306
1
    assert!(
307
1
        matches!(outcome, Err(server::db::DBError::UnknownTenant)),
308
        "{:?}",
309
        outcome.err()
310
    );
311
1
}
312

            
313
/// Distinct users get distinct, deterministically-named databases.
314
1
async fn two_users_get_distinct_databases() -> anyhow::Result<()> {
315
1
    let a = Uuid::new_v4();
316
1
    let b = Uuid::new_v4();
317
1
    let da = format!("nomi_user_{}", a.simple());
318
1
    let db = format!("nomi_user_{}", b.simple());
319
1
    let _tenants = [
320
1
        TestTenant::database(da.clone()),
321
1
        TestTenant::database(db.clone()),
322
1
    ];
323

            
324
1
    let name_a = server::provision::create_user_database(a).await?;
325
1
    let name_b = server::provision::create_user_database(b).await?;
326
1
    assert_ne!(name_a, name_b, "distinct users must get distinct databases");
327

            
328
1
    assert_eq!(name_a, da);
329
1
    assert_eq!(name_b, db);
330

            
331
1
    Ok(())
332
1
}
333

            
334
3
async fn set_theme(user_id: Uuid, name: &str, value: &str) -> anyhow::Result<()> {
335
3
    SetConfig::new()
336
3
        .user_id(user_id)
337
3
        .name(name.to_string())
338
3
        .value(value.to_string())
339
3
        .run()
340
3
        .await?;
341
3
    Ok(())
342
3
}
343

            
344
2
async fn get_theme(user_id: Uuid) -> anyhow::Result<Option<server::command::CmdResult>> {
345
2
    Ok(GetConfig::new()
346
2
        .user_id(user_id)
347
2
        .name("theme".to_string())
348
2
        .run()
349
2
        .await?)
350
2
}