1
use super::*;
2
use crate::command::transaction_edit_tests::lock_wait::wait_for_blocked_on;
3
use crate::db::install_test_pool;
4
use crate::user::User;
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
static USER: OnceCell<User> = OnceCell::const_new();
11

            
12
17
async fn setup() {
13
17
    CONTEXT
14
12
        .get_or_init(|| async {
15
12
            crate::telemetry::init_test_logging();
16
24
        })
17
17
        .await;
18
24
    USER.get_or_init(|| async { User { id: Uuid::new_v4() } })
19
17
        .await;
20
17
}
21

            
22
const TEST_KEY_TYPE: &str = "ssh-ed25519";
23
const TEST_FP_ALICE: &str = "SHA256:alicefingerprint000000000000000000000000000";
24
const TEST_FP_BOB: &str = "SHA256:bobfingerprint00000000000000000000000000000";
25

            
26
#[local_db_sqlx_test]
27
async fn adds_and_lists_a_key(pool: PgPool) -> anyhow::Result<()> {
28
    let user = USER.get().unwrap();
29
    user.commit().await.unwrap();
30
    AddSshKey::new()
31
        .user_id(user.id)
32
        .key_type(TEST_KEY_TYPE.to_string())
33
        .key_blob(vec![1, 2, 3, 4])
34
        .fingerprint(TEST_FP_ALICE.to_string())
35
        .annotation("alice laptop".to_string())
36
        .run()
37
        .await?;
38

            
39
    let Some(CmdResult::SshKeys(keys)) = ListSshKeys::new().user_id(user.id).run().await? else {
40
        panic!("expected SshKeys");
41
    };
42
    assert_eq!(keys.len(), 1);
43
    assert_eq!(keys[0].fingerprint, TEST_FP_ALICE);
44
    assert_eq!(keys[0].annotation, "alice laptop");
45
    assert_eq!(keys[0].key_blob, vec![1, 2, 3, 4]);
46
}
47

            
48
#[local_db_sqlx_test]
49
async fn add_is_idempotent_on_fingerprint(pool: PgPool) -> anyhow::Result<()> {
50
    let user = USER.get().unwrap();
51
    user.commit().await.unwrap();
52
    AddSshKey::new()
53
        .user_id(user.id)
54
        .key_type(TEST_KEY_TYPE.to_string())
55
        .key_blob(vec![1, 2, 3])
56
        .fingerprint(TEST_FP_ALICE.to_string())
57
        .annotation("first".to_string())
58
        .run()
59
        .await?;
60
    AddSshKey::new()
61
        .user_id(user.id)
62
        .key_type(TEST_KEY_TYPE.to_string())
63
        .key_blob(vec![1, 2, 3])
64
        .fingerprint(TEST_FP_ALICE.to_string())
65
        .annotation("second".to_string())
66
        .run()
67
        .await?;
68

            
69
    let Some(CmdResult::SshKeys(keys)) = ListSshKeys::new().user_id(user.id).run().await? else {
70
        panic!("expected SshKeys");
71
    };
72
    assert_eq!(keys.len(), 1, "second add should update in place");
73
    assert_eq!(keys[0].annotation, "second");
74
}
75

            
76
#[local_db_sqlx_test]
77
async fn add_flips_ssh_enabled(pool: PgPool) -> anyhow::Result<()> {
78
    let user = USER.get().unwrap();
79
    user.commit().await.unwrap();
80
    AddSshKey::new()
81
        .user_id(user.id)
82
        .key_type(TEST_KEY_TYPE.to_string())
83
        .key_blob(vec![7])
84
        .fingerprint(TEST_FP_ALICE.to_string())
85
        .run()
86
        .await?;
87
    let Some(CmdResult::Uuid(uid)) = LookupUserBySshKey::new()
88
        .fingerprint(TEST_FP_ALICE.to_string())
89
        .run()
90
        .await?
91
    else {
92
        panic!("expected Uuid");
93
    };
94
    assert_eq!(uid, user.id);
95
}
96

            
97
#[local_db_sqlx_test]
98
async fn remove_flips_ssh_enabled_when_last_key_goes(pool: PgPool) -> anyhow::Result<()> {
99
    let user = USER.get().unwrap();
100
    user.commit().await.unwrap();
101
    AddSshKey::new()
102
        .user_id(user.id)
103
        .key_type(TEST_KEY_TYPE.to_string())
104
        .key_blob(vec![1])
105
        .fingerprint(TEST_FP_ALICE.to_string())
106
        .run()
107
        .await?;
108
    RemoveSshKey::new()
109
        .user_id(user.id)
110
        .fingerprint(TEST_FP_ALICE.to_string())
111
        .run()
112
        .await?;
113
    let lookup = LookupUserBySshKey::new()
114
        .fingerprint(TEST_FP_ALICE.to_string())
115
        .run()
116
        .await?;
117
    assert!(lookup.is_none(), "deleted key should not resolve");
118
}
119

            
120
#[local_db_sqlx_test]
121
async fn removing_a_key_the_user_does_not_hold_is_not_found(pool: PgPool) -> anyhow::Result<()> {
122
    let user = USER.get().unwrap();
123
    user.commit().await.unwrap();
124
    AddSshKey::new()
125
        .user_id(user.id)
126
        .key_type(TEST_KEY_TYPE.to_string())
127
        .key_blob(vec![1])
128
        .fingerprint(TEST_FP_ALICE.to_string())
129
        .run()
130
        .await?;
131

            
132
    let result = RemoveSshKey::new()
133
        .user_id(user.id)
134
        .fingerprint(TEST_FP_BOB.to_string())
135
        .run()
136
        .await;
137

            
138
    assert!(matches!(result, Err(CmdError::NotFound(_))), "{result:?}");
139
    let lookup = LookupUserBySshKey::new()
140
        .fingerprint(TEST_FP_ALICE.to_string())
141
        .run()
142
        .await?;
143
    assert!(matches!(lookup, Some(CmdResult::Uuid(_))));
144
}
145

            
146
#[local_db_sqlx_test]
147
async fn remove_keeps_ssh_enabled_when_other_keys_remain(pool: PgPool) -> anyhow::Result<()> {
148
    let user = USER.get().unwrap();
149
    user.commit().await.unwrap();
150
    AddSshKey::new()
151
        .user_id(user.id)
152
        .key_type(TEST_KEY_TYPE.to_string())
153
        .key_blob(vec![1])
154
        .fingerprint(TEST_FP_ALICE.to_string())
155
        .run()
156
        .await?;
157
    AddSshKey::new()
158
        .user_id(user.id)
159
        .key_type(TEST_KEY_TYPE.to_string())
160
        .key_blob(vec![2])
161
        .fingerprint(TEST_FP_BOB.to_string())
162
        .run()
163
        .await?;
164
    RemoveSshKey::new()
165
        .user_id(user.id)
166
        .fingerprint(TEST_FP_ALICE.to_string())
167
        .run()
168
        .await?;
169
    // Bob still resolves — ssh_enabled must still be true.
170
    let lookup = LookupUserBySshKey::new()
171
        .fingerprint(TEST_FP_BOB.to_string())
172
        .run()
173
        .await?;
174
    assert!(matches!(lookup, Some(CmdResult::Uuid(_))));
175
}
176

            
177
/// `ssh_enabled` stays TRUE — it tracks key presence, not usability.
178
#[local_db_sqlx_test]
179
async fn lookup_refuses_a_disabled_user(pool: PgPool) -> anyhow::Result<()> {
180
    setup().await;
181
    let user = User { id: Uuid::new_v4() };
182
    user.commit().await?;
183
    AddSshKey::new()
184
        .user_id(user.id)
185
        .key_type(TEST_KEY_TYPE.to_string())
186
        .key_blob(vec![9, 9])
187
        .fingerprint(TEST_FP_ALICE.to_string())
188
        .run()
189
        .await?;
190
    assert!(matches!(
191
        LookupUserBySshKey::new()
192
            .fingerprint(TEST_FP_ALICE.to_string())
193
            .run()
194
            .await?,
195
        Some(CmdResult::Uuid(_))
196
    ));
197

            
198
    disable(&pool, user.id).await?;
199

            
200
    assert!(
201
        LookupUserBySshKey::new()
202
            .fingerprint(TEST_FP_ALICE.to_string())
203
            .run()
204
            .await?
205
            .is_none()
206
    );
207
}
208

            
209
/// `AddSshKey` is covered by the lock-ordering test below.
210
#[local_db_sqlx_test]
211
async fn remove_refuses_a_disabled_user(pool: PgPool) -> anyhow::Result<()> {
212
    setup().await;
213
    let user = User { id: Uuid::new_v4() };
214
    user.commit().await?;
215
    disable(&pool, user.id).await?;
216

            
217
    let removed = RemoveSshKey::new()
218
        .user_id(user.id)
219
        .fingerprint(TEST_FP_BOB.to_string())
220
        .run()
221
        .await;
222
    assert!(matches!(removed, Err(CmdError::Disabled)));
223
}
224

            
225
/// The window a plain `SELECT` then `INSERT` would leave open: the check
226
/// reads TRUE, the disable commits, and the key lands anyway.
227
#[local_db_sqlx_test]
228
async fn add_refuses_a_disable_that_lands_mid_write(pool: PgPool) -> anyhow::Result<()> {
229
    setup().await;
230
    let user = User { id: Uuid::new_v4() };
231
    user.commit().await?;
232

            
233
    // Take the row first so the command blocks rather than races: the
234
    // assertion is about ordering, not timing.
235
    let mut blocker = pool.begin().await?;
236
    sqlx::query("SELECT verified FROM users WHERE id = $1 FOR UPDATE")
237
        .bind(user.id)
238
        .fetch_one(&mut *blocker)
239
        .await?;
240

            
241
    let user_id = user.id;
242
1
    let adding = tokio::spawn(async move {
243
1
        AddSshKey::new()
244
1
            .user_id(user_id)
245
1
            .key_type(TEST_KEY_TYPE.to_string())
246
1
            .key_blob(vec![4, 2])
247
1
            .fingerprint(TEST_FP_ALICE.to_string())
248
1
            .run()
249
1
            .await
250
1
    });
251

            
252
    // Let the command reach the lock, then switch the account off under it.
253
    let mut probe = pool.acquire().await?;
254
    wait_for_blocked_on(&mut probe, 1).await?;
255
    sqlx::query("UPDATE users SET verified = FALSE WHERE id = $1")
256
        .bind(user.id)
257
        .execute(&mut *blocker)
258
        .await?;
259
    blocker.commit().await?;
260

            
261
    assert!(matches!(adding.await?, Err(CmdError::Disabled)));
262

            
263
    let keys: i64 = sqlx::query_scalar("SELECT count(*) FROM user_ssh_keys WHERE user_id = $1")
264
        .bind(user.id)
265
        .fetch_one(&pool)
266
        .await?;
267
    assert_eq!(keys, 0, "the key must not have landed");
268
}
269

            
270
2
async fn disable(pool: &PgPool, user_id: Uuid) -> anyhow::Result<()> {
271
2
    sqlx::query("UPDATE users SET verified = FALSE WHERE id = $1")
272
2
        .bind(user_id)
273
2
        .execute(pool)
274
2
        .await?;
275
2
    Ok(())
276
2
}
277

            
278
#[local_db_sqlx_test]
279
async fn lookup_unknown_fingerprint_returns_none(pool: PgPool) -> anyhow::Result<()> {
280
    let _ = USER.get().unwrap();
281
    let lookup = LookupUserBySshKey::new()
282
        .fingerprint("SHA256:ghost-never-registered".to_string())
283
        .run()
284
        .await?;
285
    assert!(lookup.is_none());
286
}
287

            
288
/// A public key names one account: a second account cannot claim a key the
289
/// first already holds, and the first keeps authenticating with it.
290
#[local_db_sqlx_test]
291
async fn add_refuses_a_key_another_account_holds(pool: PgPool) -> anyhow::Result<()> {
292
    setup().await;
293
    let owner = User { id: Uuid::new_v4() };
294
    owner.commit().await?;
295
    // `User::commit` always inserts the same email, which is unique, so a
296
    // second account in one test needs its own.
297
    let other = Uuid::new_v4();
298
    sqlx::query(
299
            "INSERT INTO users (id, user_name, email, photo, verified, user_password, user_role, database_name, created_at)
300
             VALUES ($1, 'Other User', 'other@example.com', 'default.png', TRUE, 'password123', 'user', 'database', NOW())",
301
        )
302
        .bind(other)
303
        .execute(&pool)
304
        .await?;
305
    AddSshKey::new()
306
        .user_id(owner.id)
307
        .key_type(TEST_KEY_TYPE.to_string())
308
        .key_blob(vec![7])
309
        .fingerprint(TEST_FP_BOB.to_string())
310
        .run()
311
        .await?;
312

            
313
    let claimed = AddSshKey::new()
314
        .user_id(other)
315
        .key_type(TEST_KEY_TYPE.to_string())
316
        .key_blob(vec![7])
317
        .fingerprint(TEST_FP_BOB.to_string())
318
        .run()
319
        .await;
320
    assert!(matches!(claimed, Err(CmdError::Args(_))), "{claimed:?}");
321

            
322
    assert!(matches!(
323
        LookupUserBySshKey::new()
324
            .fingerprint(TEST_FP_BOB.to_string())
325
            .run()
326
            .await?,
327
        Some(CmdResult::Uuid(id)) if id == owner.id
328
    ));
329
}
330

            
331
/// Re-adding your own key must still update its annotation: the insert's
332
/// `ON CONFLICT (user_id, fingerprint)` has to win over the new unique index.
333
#[local_db_sqlx_test]
334
async fn re_adding_your_own_key_updates_its_annotation(pool: PgPool) -> anyhow::Result<()> {
335
    setup().await;
336
    let user = User { id: Uuid::new_v4() };
337
    user.commit().await?;
338
    for annotation in ["first", "second"] {
339
        AddSshKey::new()
340
            .user_id(user.id)
341
            .key_type(TEST_KEY_TYPE.to_string())
342
            .key_blob(vec![5])
343
            .fingerprint(TEST_FP_ALICE.to_string())
344
            .annotation(annotation.to_string())
345
            .run()
346
            .await?;
347
    }
348

            
349
    let Some(CmdResult::SshKeys(keys)) = ListSshKeys::new().user_id(user.id).run().await? else {
350
        panic!("expected SshKeys");
351
    };
352
    assert_eq!(keys.len(), 1);
353
    assert_eq!(keys[0].annotation, "second");
354
}