1
use super::*;
2
use crate::command::transaction_edit_tests::lock_wait::wait_for_blocked_on;
3
use crate::db::{get_connection, install_test_pool};
4
use argon2::{Argon2, PasswordHasher};
5
use sqlx::PgPool;
6
use supp_macro::local_db_sqlx_test;
7
use tokio::sync::OnceCell;
8

            
9
static CONTEXT: OnceCell<()> = OnceCell::const_new();
10

            
11
/// A hash the `argon2` CLI produced, with cost parameters deliberately
12
/// unlike `Argon2::default()`.
13
///
14
/// The break-glass admin is promoted by hand with a hash generated
15
/// out-of-band (doc/ops/0006, Phase 4a), and that runbook tells the operator
16
/// the cost settings need not match the seeded row. This is what makes that
17
/// true: verification reads the parameters out of the PHC string. If it ever
18
/// stops being true, the operator finds out during an outage, locked out of
19
/// the account they just promoted.
20
const CLI_GENERATED_HASH: &str = "$argon2id$v=19$m=4096,t=3,p=1$\
21
aTltTkFWR2paUHY5Y2pYbVNlR2Rsdz09$QKPc9TsnwNUm7fgdz/JqzHyrYyo4/x2pMvehw5upb8g";
22

            
23
#[test]
24
1
fn fold_email_trims_and_lowers_ascii_only() {
25
1
    assert_eq!(
26
1
        fold_email("  Ab\u{c4}@EXAMPLE.com\t"),
27
1
        "ab\u{c4}@example.com"
28
    );
29
1
}
30

            
31
#[test]
32
1
fn a_hash_with_foreign_cost_parameters_still_verifies() {
33
1
    let parsed = PasswordHash::new(CLI_GENERATED_HASH).expect("PHC string parses");
34

            
35
1
    assert!(
36
1
        Argon2::default()
37
1
            .verify_password(b"correct horse", &parsed)
38
1
            .is_ok(),
39
        "the promotion runbook depends on a hash made with other parameters verifying"
40
    );
41
1
    assert!(
42
1
        Argon2::default()
43
1
            .verify_password(b"wrong horse", &parsed)
44
1
            .is_err()
45
    );
46
1
}
47

            
48
13
async fn setup() {
49
13
    CONTEXT
50
13
        .get_or_init(|| async {
51
13
            crate::telemetry::init_test_logging();
52
26
        })
53
13
        .await;
54
13
}
55

            
56
8
async fn insert_user_with_password(id: Uuid, email: &str, plaintext: &str) -> anyhow::Result<()> {
57
8
    let hash = Argon2::default()
58
8
        .hash_password(plaintext.as_bytes())
59
8
        .unwrap()
60
8
        .to_string();
61
8
    let mut conn = get_connection().await.unwrap();
62
8
    sqlx::query!(
63
        "INSERT INTO users (
64
            id, user_name, email, photo, verified,
65
            user_password, user_role, database_name, created_at
66
         ) VALUES (
67
            $1, 'Test', $2, 'default.png', TRUE,
68
            $3, 'user', 'db', NOW()
69
         )",
70
        id,
71
        email,
72
        hash,
73
    )
74
8
    .execute(&mut *conn)
75
8
    .await?;
76
8
    Ok(())
77
8
}
78

            
79
#[local_db_sqlx_test]
80
async fn verify_returns_user_on_correct_password(pool: PgPool) -> anyhow::Result<()> {
81
    let uid = Uuid::new_v4();
82
    insert_user_with_password(uid, "good@example.com", "hunter2").await?;
83
    let v = verify_user_password("good@example.com", "hunter2")
84
        .await?
85
        .expect("match");
86
    assert_eq!(v.user_id, uid);
87
    assert!(!v.ssh_enabled);
88
}
89

            
90
#[local_db_sqlx_test]
91
async fn verify_returns_none_on_wrong_password(pool: PgPool) -> anyhow::Result<()> {
92
    let uid = Uuid::new_v4();
93
    insert_user_with_password(uid, "wrong@example.com", "hunter2").await?;
94
    let v = verify_user_password("wrong@example.com", "nope").await?;
95
    assert!(v.is_none());
96
}
97

            
98
#[local_db_sqlx_test]
99
async fn verify_returns_none_for_unknown_email(pool: PgPool) -> anyhow::Result<()> {
100
    let _ = pool;
101
    let v = verify_user_password("nobody@example.com", "whatever").await?;
102
    assert!(v.is_none());
103
}
104

            
105
/// Disable is `verified = FALSE`, and it must close the password path on
106
/// both surfaces at once: this function is shared by web login and the SSH
107
/// daemon's password auth.
108
#[local_db_sqlx_test]
109
async fn verify_returns_none_for_a_disabled_user(pool: PgPool) -> anyhow::Result<()> {
110
    let uid = Uuid::new_v4();
111
    insert_user_with_password(uid, "off@example.com", "hunter2").await?;
112
    assert!(
113
        verify_user_password("off@example.com", "hunter2")
114
            .await?
115
            .is_some()
116
    );
117

            
118
    sqlx::query("UPDATE users SET verified = FALSE WHERE id = $1")
119
        .bind(uid)
120
        .execute(&pool)
121
        .await?;
122

            
123
    assert!(
124
        verify_user_password("off@example.com", "hunter2")
125
            .await?
126
            .is_none()
127
    );
128
}
129

            
130
/// A password change must replace the hash and bump the generation in one
131
/// go: every token carrying the old value stops verifying the moment it
132
/// commits.
133
#[local_db_sqlx_test]
134
async fn change_password_bumps_the_generation(pool: PgPool) -> anyhow::Result<()> {
135
    let uid = Uuid::new_v4();
136
    insert_user_with_password(uid, "bump@example.com", "hunter2").await?;
137
    assert_eq!(generation_of(&pool, uid).await?, 0);
138

            
139
    change_password(uid, "hunter2", "hunter3").await?;
140

            
141
    assert_eq!(generation_of(&pool, uid).await?, 1);
142
    assert!(
143
        verify_user_password("bump@example.com", "hunter3")
144
            .await?
145
            .is_some(),
146
        "the new password must work"
147
    );
148
    assert!(
149
        verify_user_password("bump@example.com", "hunter2")
150
            .await?
151
            .is_none(),
152
        "the old password must not"
153
    );
154
}
155

            
156
/// A wrong current password must change nothing — in particular it must not
157
/// bump the generation, which would log the user out of every session.
158
#[local_db_sqlx_test]
159
async fn change_password_refuses_a_wrong_current(pool: PgPool) -> anyhow::Result<()> {
160
    let uid = Uuid::new_v4();
161
    insert_user_with_password(uid, "wrongcur@example.com", "hunter2").await?;
162

            
163
    assert!(change_password(uid, "not-it", "hunter3").await.is_err());
164

            
165
    assert_eq!(generation_of(&pool, uid).await?, 0);
166
    assert!(
167
        verify_user_password("wrongcur@example.com", "hunter2")
168
            .await?
169
            .is_some(),
170
        "the original password must still work"
171
    );
172
}
173

            
174
/// A disabled account must not be able to change its own password: doing so
175
/// would let it mint a fresh session generation.
176
#[local_db_sqlx_test]
177
async fn change_password_refuses_a_disabled_user(pool: PgPool) -> anyhow::Result<()> {
178
    let uid = Uuid::new_v4();
179
    insert_user_with_password(uid, "offpw@example.com", "hunter2").await?;
180
    sqlx::query("UPDATE users SET verified = FALSE WHERE id = $1")
181
        .bind(uid)
182
        .execute(&pool)
183
        .await?;
184

            
185
    assert!(change_password(uid, "hunter2", "hunter3").await.is_err());
186
    assert_eq!(generation_of(&pool, uid).await?, 0);
187
}
188

            
189
/// The current-password check authorises the write, so it must be part of
190
/// it. Two changes racing on the same old password would otherwise both
191
/// verify, and the loser's new password would be silently overwritten by a
192
/// caller that never knew it.
193
#[local_db_sqlx_test]
194
async fn change_password_serialises_a_concurrent_change(pool: PgPool) -> anyhow::Result<()> {
195
    let uid = Uuid::new_v4();
196
    insert_user_with_password(uid, "race@example.com", "hunter2").await?;
197

            
198
    // Hold the row, so the command blocks on the lock rather than racing it.
199
    let mut blocker = pool.begin().await?;
200
    sqlx::query("SELECT user_password FROM users WHERE id = $1 FOR UPDATE")
201
        .bind(uid)
202
        .fetch_one(&mut *blocker)
203
        .await?;
204

            
205
1
    let racing = tokio::spawn(async move { change_password(uid, "hunter2", "loser").await });
206

            
207
    let mut probe = pool.acquire().await?;
208
    wait_for_blocked_on(&mut probe, 1).await?;
209
    let winner = Argon2::default()
210
        .hash_password(b"winner")
211
        .expect("hash")
212
        .to_string();
213
    sqlx::query(
214
        "UPDATE users SET user_password = $2, session_generation = session_generation + 1 \
215
         WHERE id = $1",
216
    )
217
    .bind(uid)
218
    .bind(&winner)
219
    .execute(&mut *blocker)
220
    .await?;
221
    blocker.commit().await?;
222

            
223
    assert!(
224
        matches!(racing.await?, Err(CmdError::Args(_))),
225
        "the old password must not authorise a write once another change has committed"
226
    );
227
    assert!(
228
        verify_user_password("race@example.com", "winner")
229
            .await?
230
            .is_some(),
231
        "the committed change must survive"
232
    );
233
    assert!(
234
        verify_user_password("race@example.com", "loser")
235
            .await?
236
            .is_none()
237
    );
238
}
239

            
240
4
async fn generation_of(pool: &PgPool, user_id: Uuid) -> anyhow::Result<i32> {
241
    Ok(
242
4
        sqlx::query_scalar("SELECT session_generation FROM users WHERE id = $1")
243
4
            .bind(user_id)
244
4
            .fetch_one(pool)
245
4
            .await?,
246
    )
247
4
}
248

            
249
#[local_db_sqlx_test]
250
async fn verify_is_case_insensitive_on_email(pool: PgPool) -> anyhow::Result<()> {
251
    let uid = Uuid::new_v4();
252
    insert_user_with_password(uid, "mixed@example.com", "pw").await?;
253
    let v = verify_user_password("MIXED@EXAMPLE.COM", "pw")
254
        .await?
255
        .expect("match");
256
    assert_eq!(v.user_id, uid);
257
}
258

            
259
6
async fn register(email: &str) -> Result<Account, CmdError> {
260
6
    let hash = Argon2::default()
261
6
        .hash_password(b"pw")
262
        .map_err(|_| CmdError::Server(ServerError::PasswordHash))?
263
        .to_string();
264
6
    create_user(NewUser {
265
6
        id: Uuid::new_v4(),
266
6
        name: "Reg",
267
6
        email,
268
6
        password_hash: &hash,
269
6
        database_name: "db",
270
6
        jwt_public_key: "key",
271
6
    })
272
6
    .await
273
6
}
274

            
275
#[local_db_sqlx_test]
276
async fn registration_stores_the_folded_email_and_finds_it_taken(
277
    pool: PgPool,
278
) -> anyhow::Result<()> {
279
    let account = register("  Mixed@EXAMPLE.com ").await?;
280

            
281
    assert_eq!(account.email, "mixed@example.com");
282
    assert!(email_taken("mixed@example.COM").await?);
283
    assert!(email_taken(" MIXED@example.com ").await?);
284
    assert!(!email_taken("other@example.com").await?);
285
}
286

            
287
/// Whether `lower()` folds non-ASCII letters depends on the database locale;
288
/// the taken check must give the verdict the unique index gives.
289
#[local_db_sqlx_test]
290
async fn email_taken_agrees_with_the_unique_index(pool: PgPool) -> anyhow::Result<()> {
291
    register("\u{c4}@example.com").await?;
292

            
293
    let taken = email_taken("\u{e4}@example.com").await?;
294
    let second = register("\u{e4}@example.com").await;
295

            
296
    assert_eq!(
297
        taken,
298
        matches!(second, Err(CmdError::Config(ConfigError::EmailTaken)))
299
    );
300
    assert!(taken || second.is_ok());
301
}
302

            
303
#[local_db_sqlx_test]
304
async fn a_padded_email_is_the_same_account(pool: PgPool) -> anyhow::Result<()> {
305
    register("pad@example.com").await?;
306

            
307
    assert!(matches!(
308
        register("  pad@example.com  ").await,
309
        Err(CmdError::Config(ConfigError::EmailTaken))
310
    ));
311
}
312

            
313
#[local_db_sqlx_test]
314
async fn a_blank_email_is_refused_at_creation(pool: PgPool) -> anyhow::Result<()> {
315
    assert!(matches!(
316
        register("   ").await,
317
        Err(CmdError::Config(ConfigError::EmailBlank))
318
    ));
319
    assert!(matches!(validate_email(""), Err(ConfigError::EmailBlank)));
320
    assert_eq!(validate_email(" A@X ")?, "a@x");
321
}