1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
// Copyright (C) 2022  Aravinth Manivannan <realaravinth@batsense.net>
// SPDX-FileCopyrightText: 2023 Aravinth Manivannan <realaravinth@batsense.net>
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! Test utilities
use crate::errors::*;
use crate::prelude::*;

/// easy traffic pattern
pub const TRAFFIC_PATTERN: TrafficPattern = TrafficPattern {
    avg_traffic: 500,
    peak_sustainable_traffic: 5_000,
    broke_my_site_traffic: Some(10_000),
};

/// levels for complex captcha config
pub const LEVELS: [Level; 3] = [
    Level {
        difficulty_factor: 1,
        visitor_threshold: 1,
    },
    Level {
        difficulty_factor: 2,
        visitor_threshold: 2,
    },
    Level {
        difficulty_factor: 3,
        visitor_threshold: 3,
    },
];

/// test all database functions
pub async fn database_works<'a, T: MCDatabase>(
    db: &T,
    p: &Register<'a>,
    c: &CreateCaptcha<'a>,
    l: &[Level],
    tp: &TrafficPattern,
    an: &AddNotification<'a>,
) {
    assert!(db.ping().await, "ping test");

    if db.username_exists(p.username).await.unwrap() {
        db.delete_user(p.username).await.unwrap();
        assert!(
            !db.username_exists(p.username).await.unwrap(),
            "user is deleted so username shouldn't exist"
        );
    }

    assert!(matches!(
        db.get_secret(&p.username).await,
        Err(DBError::AccountNotFound)
    ));

    db.register(p).await.unwrap();

    assert!(matches!(db.register(&p).await, Err(DBError::UsernameTaken)));

    // testing get secret
    let secret = db.get_secret(p.username).await.unwrap();
    assert_eq!(secret.secret, p.secret, "user secret matches");

    // testing update secret: setting secret = username
    db.update_secret(p.username, p.username).await.unwrap();

    let secret = db.get_secret(p.username).await.unwrap();
    assert_eq!(
        secret.secret, p.username,
        "user secret matches username; as set by previous step"
    );

    // testing get_password

    // with username
    let name_hash = db.get_password(&Login::Username(p.username)).await.unwrap();
    assert_eq!(name_hash.hash, p.hash, "user password matches");

    assert_eq!(name_hash.username, p.username, "username matches");

    // with email
    let mut name_hash = db
        .get_password(&Login::Email(p.email.as_ref().unwrap()))
        .await
        .unwrap();
    assert_eq!(name_hash.hash, p.hash, "user password matches");
    assert_eq!(name_hash.username, p.username, "username matches");

    // testing get_email
    assert_eq!(
        db.get_email(p.username)
            .await
            .unwrap()
            .as_ref()
            .unwrap()
            .as_str(),
        p.email.unwrap()
    );

    // testing email exists
    assert!(
        db.email_exists(p.email.as_ref().unwrap()).await.unwrap(),
        "user is registered so email should exist"
    );
    assert!(
        db.username_exists(p.username).await.unwrap(),
        "user is registered so username should exist"
    );

    // update password test. setting password = username
    name_hash.hash = name_hash.username.clone();
    db.update_password(&name_hash).await.unwrap();

    let name_hash = db.get_password(&Login::Username(p.username)).await.unwrap();
    assert_eq!(
        name_hash.hash, p.username,
        "user password matches with changed value"
    );
    assert_eq!(name_hash.username, p.username, "username matches");

    // update username to p.email
    assert!(
        !db.username_exists(p.email.as_ref().unwrap()).await.unwrap(),
        "user with p.email doesn't exist. pre-check to update username to p.email"
    );
    db.update_username(p.username, p.email.as_ref().unwrap())
        .await
        .unwrap();
    assert!(
        db.username_exists(p.email.as_ref().unwrap()).await.unwrap(),
        "user with p.email exist post-update"
    );

    // deleting user for re-registration with email = None
    db.delete_user(p.email.as_ref().unwrap()).await.unwrap();
    assert!(
        !db.username_exists(p.email.as_ref().unwrap()).await.unwrap(),
        "user is deleted so username shouldn't exist"
    );

    // register with email = None
    let mut p2 = p.clone();
    p2.email = None;
    db.register(&p2).await.unwrap();
    assert!(
        db.username_exists(p2.username).await.unwrap(),
        "user is registered so username should exist"
    );
    assert!(
        !db.email_exists(p.email.as_ref().unwrap()).await.unwrap(),
        "user registration with email is deleted; so email shouldn't exist"
    );

    // testing get_email = None
    assert_eq!(db.get_email(p.username).await.unwrap(), None);

    // testing update email
    let update_email = UpdateEmail {
        username: p.username,
        new_email: p.email.as_ref().unwrap(),
    };
    db.update_email(&update_email).await.unwrap();
    println!(
        "null user email: {}",
        db.email_exists(p.email.as_ref().unwrap()).await.unwrap()
    );
    assert!(
        db.email_exists(p.email.as_ref().unwrap()).await.unwrap(),
        "user was with empty email but email is set; so email should exist"
    );

    /*
     * test notification workflows
     * 1. Add notifications: a minimum of two, to mark as read and test if it has affected it
     * 2. Get unread notifications
     * 3. Mark a notification read, check if it has affected Step #2
     */

    // 1. add notification
    db.create_notification(an).await.unwrap();
    db.create_notification(an).await.unwrap();

    // 2. Get notifications
    let notifications = db.get_all_unread_notifications(an.to).await.unwrap();
    assert_eq!(notifications.len(), 2);
    assert_eq!(notifications[0].heading.as_ref().unwrap(), an.heading);

    // 3. mark a notification read
    db.mark_notification_read(an.to, notifications[0].id.unwrap())
        .await
        .unwrap();
    let new_notifications = db.get_all_unread_notifications(an.to).await.unwrap();
    assert_eq!(new_notifications.len(), 1);

    // create captcha
    db.create_captcha(p.username, c).await.unwrap();
    assert!(db.captcha_exists(None, c.key).await.unwrap());
    assert!(db.captcha_exists(Some(p.username), c.key).await.unwrap());

    // get secret from captcha key
    let secret_from_captcha = db.get_secret_from_captcha(&c.key).await.unwrap();
    assert_eq!(secret_from_captcha.secret, p.secret, "user secret matches");

    // get captcha configuration
    let captcha = db.get_captcha_config(p.username, c.key).await.unwrap();
    assert_eq!(captcha.key, c.key);
    assert_eq!(captcha.duration, c.duration);
    assert_eq!(captcha.description, c.description);

    // get all captchas that belong to user
    let all_user_captchas = db.get_all_user_captchas(p.username).await.unwrap();
    assert_eq!(all_user_captchas.len(), 1);
    assert_eq!(all_user_captchas[0], captcha);

    // get captcha cooldown duration
    assert_eq!(db.get_captcha_cooldown(c.key).await.unwrap(), c.duration);

    // add traffic pattern
    db.add_traffic_pattern(p.username, c.key, tp).await.unwrap();
    assert_eq!(
        &db.get_traffic_pattern(p.username, c.key).await.unwrap(),
        tp
    );

    // delete traffic pattern
    db.delete_traffic_pattern(p.username, c.key).await.unwrap();
    assert!(
        matches!(
            db.get_traffic_pattern(p.username, c.key).await,
            Err(DBError::TrafficPatternNotFound)
        ),
        "deletion successful; traffic pattern no longer exists"
    );

    // add captcha levels
    db.add_captcha_levels(p.username, c.key, l).await.unwrap();

    // get captcha levels with username
    let levels = db
        .get_captcha_levels(Some(p.username), c.key)
        .await
        .unwrap();
    assert_eq!(levels, l);
    // get captcha levels without username
    let levels = db.get_captcha_levels(None, c.key).await.unwrap();
    assert_eq!(levels, l);

    /*
     * Test stats
     * 1. record fetch config
     * 2. record solve
     * 3. record token verify
     * 4. fetch config fetches
     * 5. fetch solves
     * 6. fetch token verify
     */

    assert!(db
        .fetch_config_fetched(p.username, c.key)
        .await
        .unwrap()
        .is_empty());
    assert!(db.fetch_solve(p.username, c.key).await.unwrap().is_empty());
    assert!(db
        .fetch_confirm(p.username, c.key)
        .await
        .unwrap()
        .is_empty());

    db.record_fetch(c.key).await.unwrap();
    db.record_solve(c.key).await.unwrap();
    db.record_confirm(c.key).await.unwrap();

    // analytics start
    db.analytics_create_psuedo_id_if_not_exists(c.key)
        .await
        .unwrap();
    let psuedo_id = db
        .analytics_get_psuedo_id_from_capmaign_id(c.key)
        .await
        .unwrap();
    assert_eq!(
        vec![psuedo_id.clone()],
        db.analytics_get_all_psuedo_ids(0).await.unwrap()
    );
    assert!(db.analytics_get_all_psuedo_ids(1).await.unwrap().is_empty());

    db.analytics_create_psuedo_id_if_not_exists(c.key)
        .await
        .unwrap();
    assert_eq!(
        psuedo_id,
        db.analytics_get_psuedo_id_from_capmaign_id(c.key)
            .await
            .unwrap()
    );

    assert_eq!(
        c.key,
        db.analytics_get_capmaign_id_from_psuedo_id(&psuedo_id)
            .await
            .unwrap()
    );

    let analytics = CreatePerformanceAnalytics {
        time: 1,
        difficulty_factor: 1,
        worker_type: "wasm".into(),
    };

    assert_eq!(
        db.stats_get_num_logs_under_time(analytics.time)
            .await
            .unwrap(),
        0
    );

    db.analysis_save(c.key, &analytics).await.unwrap();
    assert_eq!(
        db.stats_get_num_logs_under_time(analytics.time)
            .await
            .unwrap(),
        1
    );
    assert_eq!(
        db.stats_get_num_logs_under_time(analytics.time - 1)
            .await
            .unwrap(),
        0
    );
    let limit = 50;
    let mut offset = 0;
    let a = db.analytics_fetch(c.key, limit, offset).await.unwrap();
    assert_eq!(a[0].time, analytics.time);
    assert_eq!(a[0].difficulty_factor, analytics.difficulty_factor);
    assert_eq!(a[0].worker_type, analytics.worker_type);
    offset += 1;
    assert!(db
        .analytics_fetch(c.key, limit, offset)
        .await
        .unwrap()
        .is_empty());

    db.analytics_delete_all_records_for_campaign(c.key)
        .await
        .unwrap();
    assert_eq!(db.analytics_fetch(c.key, 1000, 0).await.unwrap().len(), 0);
    assert!(!db.analytics_captcha_is_published(c.key).await.unwrap());

    let rest_analytics = [
        CreatePerformanceAnalytics {
            time: 2,
            difficulty_factor: 2,
            worker_type: "wasm".into(),
        },
        CreatePerformanceAnalytics {
            time: 3,
            difficulty_factor: 3,
            worker_type: "wasm".into(),
        },
        CreatePerformanceAnalytics {
            time: 4,
            difficulty_factor: 4,
            worker_type: "wasm".into(),
        },
        CreatePerformanceAnalytics {
            time: 5,
            difficulty_factor: 5,
            worker_type: "wasm".into(),
        },
    ];
    for a in rest_analytics.iter() {
        db.analysis_save(c.key, &a).await.unwrap();
    }
    assert!(db
        .stats_get_entry_at_location_for_time_limit_asc(1, 2)
        .await
        .unwrap()
        .is_none());
    assert_eq!(
        db.stats_get_entry_at_location_for_time_limit_asc(2, 1)
            .await
            .unwrap(),
        Some(2)
    );
    assert_eq!(
        db.stats_get_entry_at_location_for_time_limit_asc(3, 2)
            .await
            .unwrap(),
        Some(3)
    );

    db.analytics_delete_all_records_for_campaign(c.key)
        .await
        .unwrap();
    // analytics end

    // nonce tracking start
    assert_eq!(
        db.get_max_nonce_for_level(c.key, l[0].difficulty_factor)
            .await
            .unwrap(),
        0
    );
    db.update_max_nonce_for_level(c.key, l[0].difficulty_factor, 1000)
        .await
        .unwrap();
    assert_eq!(
        db.get_max_nonce_for_level(c.key, l[0].difficulty_factor)
            .await
            .unwrap(),
        1000
    );
    db.update_max_nonce_for_level(c.key, l[0].difficulty_factor, 10_000)
        .await
        .unwrap();
    assert_eq!(
        db.get_max_nonce_for_level(c.key, l[0].difficulty_factor)
            .await
            .unwrap(),
        10_000
    );
    // nonce tracking end

    assert_eq!(db.fetch_solve(p.username, c.key).await.unwrap().len(), 1);
    assert_eq!(
        db.fetch_config_fetched(p.username, c.key)
            .await
            .unwrap()
            .len(),
        1
    );
    assert_eq!(db.fetch_solve(p.username, c.key).await.unwrap().len(), 1);
    assert_eq!(db.fetch_confirm(p.username, c.key).await.unwrap().len(), 1);

    // update captcha key; set key = username;
    db.update_captcha_key(p.username, c.key, p.username)
        .await
        .unwrap();
    // checking for captcha with old key; shouldn't exist
    assert!(!db.captcha_exists(Some(p.username), c.key).await.unwrap());
    // checking for captcha with new key; shouldn exist
    assert!(db
        .captcha_exists(Some(p.username), p.username)
        .await
        .unwrap());

    // delete captcha levels
    db.delete_captcha_levels(p.username, c.key).await.unwrap();

    // update captcha; set description = username and duration *= duration;
    let mut c2 = c.clone();
    c2.duration *= c2.duration;
    c2.description = p.username;
    db.update_captcha_metadata(p.username, &c2).await.unwrap();

    // delete captcha; updated key = p.username so invoke delete with it
    db.delete_captcha(p.username, p.username).await.unwrap();
    assert!(!db.captcha_exists(Some(p.username), c.key).await.unwrap());
}