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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
//!
//! Postgres is the database used by MalwareDB.
//! However, SQLite will be used for unit testing. This option can be allowed by using the `sqlite`
//! feature flag. When using SQLite, any similarity functions must be calculated by MalwareDB.

#[cfg(any(test, feature = "admin"))]
mod admin;
mod pg;
#[cfg(any(test, feature = "sqlite"))]
pub(crate) mod sqlite;
pub mod types;

use crate::db::pg::Postgres;
#[cfg(any(test, feature = "sqlite"))]
use crate::db::sqlite::Sqlite;
use crate::db::types::{FileMetadata, FileType};
use malwaredb_api::{digest::HashType, GetUserInfoResponse, Labels};
use malwaredb_types::KnownType;

#[cfg(any(test, feature = "admin"))]
use std::collections::HashMap;

use anyhow::{bail, Result};
use argon2::password_hash::{rand_core::OsRng, SaltString};
use argon2::{Argon2, PasswordHasher};
#[cfg(any(test, feature = "admin"))]
use chrono::Local;

#[derive(Debug)]
pub enum DatabaseType {
    Postgres(Postgres),
    #[cfg(any(test, feature = "sqlite"))]
    SQLite(Sqlite),
}

#[derive(Debug)]
pub struct DatabaseInformation {
    pub version: String,
    pub size: String,
    pub num_files: u64,
    pub num_users: u32,
    pub num_groups: u32,
    pub num_sources: u32,
}

impl DatabaseType {
    pub async fn from_string(arg: &str) -> Result<Self> {
        #[cfg(any(test, feature = "sqlite"))]
        if arg.starts_with("file:") {
            let new_conn_str = arg.trim_start_matches("file:");
            return Ok(DatabaseType::SQLite(Sqlite::new(new_conn_str)?));
        }

        if arg.starts_with("postgres") {
            let new_conn_str = arg.trim_start_matches("postgres");
            return Ok(DatabaseType::Postgres(Postgres::new(new_conn_str).await?));
        }

        bail!("unknown database type `{arg}`")
    }

    /// Check user credentials, return API key. Generate if it doesn't exist.
    pub async fn authenticate(&self, uname: &str, password: &str) -> Result<String> {
        match self {
            DatabaseType::Postgres(pg) => pg.authenticate(uname, password).await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.authenticate(uname, password),
        }
    }

    /// Get the user's ID from their API key
    pub async fn get_uid(&self, apikey: &str) -> Result<i32> {
        match self {
            DatabaseType::Postgres(pg) => pg.get_uid(apikey).await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.get_uid(apikey),
        }
    }

    /// Retrieve information about the database
    pub async fn db_info(&self) -> Result<DatabaseInformation> {
        match self {
            DatabaseType::Postgres(pg) => pg.db_info().await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.db_info(),
        }
    }

    /// Retrieve the names of the groups and sources the user is part of and has access to
    pub async fn get_user_info(&self, uid: i32) -> Result<GetUserInfoResponse> {
        match self {
            DatabaseType::Postgres(pg) => pg.get_user_info(uid).await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.get_user_info(uid),
        }
    }

    /// Let the user clear their own API key to log out from all systems
    pub async fn reset_own_api_key(&self, uid: i32) -> Result<()> {
        match self {
            DatabaseType::Postgres(pg) => pg.reset_own_api_key(uid).await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.reset_own_api_key(uid),
        }
    }

    /// Retrieve the supported data type information
    pub async fn get_known_data_types(&self) -> Result<Vec<FileType>> {
        match self {
            DatabaseType::Postgres(pg) => pg.get_known_data_types().await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.get_known_data_types(),
        }
    }

    /// Get all labels from MalwareDB
    pub async fn get_labels(&self) -> Result<Labels> {
        match self {
            DatabaseType::Postgres(pg) => pg.get_labels().await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.get_labels(),
        }
    }

    /// Get the corresponding type ID for a buffer representing a file
    pub async fn get_type_id_for_bytes(&self, data: &[u8]) -> Result<i32> {
        match self {
            DatabaseType::Postgres(pg) => pg.get_type_id_for_bytes(data).await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.get_type_id_for_bytes(data),
        }
    }

    /// Check that a user has been granted access data for the specific source
    pub async fn allowed_user_source(&self, uid: i32, sid: i32) -> Result<bool> {
        match self {
            DatabaseType::Postgres(pg) => pg.allowed_user_source(uid, sid).await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.allowed_user_source(uid, sid),
        }
    }

    /// Check to see if the user is an administrator. The user must be a member of the the
    /// admin group (group ID 0), or a one group below (a group with the parent group id of 0).
    pub async fn user_is_admin(&self, uid: i32) -> Result<bool> {
        match self {
            DatabaseType::Postgres(pg) => pg.user_is_admin(uid).await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.user_is_admin(uid),
        }
    }

    /// Add a file's metadata to the database, returning true if this is a new entry
    pub async fn add_file(
        &self,
        meta: &FileMetadata,
        known_type: KnownType<'_>,
        uid: i32,
        sid: i32,
        ftype: i32,
        parent: Option<i64>,
    ) -> Result<bool> {
        match self {
            DatabaseType::Postgres(pg) => {
                pg.add_file(meta, known_type, uid, sid, ftype, parent).await
            }
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.add_file(meta, known_type, uid, sid, ftype, parent),
        }
    }

    /// Retrieve the SHA-256 hash of the sample while checking that the user is permitted
    /// to access to it
    pub async fn retrieve_sample(&self, uid: i32, hash: HashType) -> Result<String> {
        match self {
            DatabaseType::Postgres(pg) => pg.retrieve_sample(uid, hash).await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.retrieve_sample(uid, hash),
        }
    }

    /// Retrieve a report for a given sample, if allowed.
    pub async fn get_sample_report(
        &self,
        uid: i32,
        hash: HashType,
    ) -> Result<malwaredb_api::Report> {
        match self {
            DatabaseType::Postgres(pg) => pg.get_sample_report(uid, hash).await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.get_sample_report(uid, hash),
        }
    }

    /// Given a collection of similarity hashes, find samples which are similar.
    pub async fn find_similar_samples(
        &self,
        uid: i32,
        sim: &[(malwaredb_api::SimilarityHashType, String)],
    ) -> Result<Vec<malwaredb_api::SimilarSample>> {
        match self {
            DatabaseType::Postgres(pg) => pg.find_similar_samples(uid, sim).await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.find_similar_samples(uid, sim),
        }
    }

    // Administrative functions

    /// Create a user account, return the user ID.
    #[cfg(any(test, feature = "admin"))]
    pub async fn create_user(
        &self,
        uname: &str,
        fname: &str,
        lname: &str,
        email: &str,
        password: Option<String>,
        organisation: Option<String>,
    ) -> Result<u64> {
        match self {
            DatabaseType::Postgres(pg) => {
                pg.create_user(uname, fname, lname, email, password, organisation)
                    .await
            }
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => {
                sl.create_user(uname, fname, lname, email, password, organisation)
            }
        }
    }

    /// Clear all API keys, either in case of suspected activity, or part of policy
    #[cfg(any(test, feature = "admin"))]
    pub async fn reset_api_keys(&self) -> Result<u64> {
        match self {
            DatabaseType::Postgres(pg) => pg.reset_api_keys().await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.reset_api_keys(),
        }
    }

    /// Set a user's password
    #[cfg(any(test, feature = "admin"))]
    pub async fn set_password(&self, uname: &str, password: &str) -> Result<()> {
        match self {
            DatabaseType::Postgres(pg) => pg.set_password(uname, password).await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.set_password(uname, password),
        }
    }

    /// Get the complete list of users
    #[cfg(any(test, feature = "admin"))]
    pub async fn list_users(&self) -> Result<Vec<admin::User>> {
        match self {
            DatabaseType::Postgres(pg) => pg.list_users().await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.list_users(),
        }
    }

    /// Get the complete list of groups
    #[cfg(any(test, feature = "admin"))]
    pub async fn list_groups(&self) -> Result<Vec<admin::Group>> {
        match self {
            DatabaseType::Postgres(pg) => pg.list_groups().await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.list_groups(),
        }
    }

    /// Grant a user membership to a group, both by id.
    #[cfg(any(test, feature = "admin"))]
    pub async fn add_user_to_group(&self, uid: i32, gid: i32) -> Result<()> {
        match self {
            DatabaseType::Postgres(pg) => pg.add_user_to_group(uid, gid).await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.add_user_to_group(uid, gid),
        }
    }

    /// Grand a group access to a source, both by id.
    #[cfg(any(test, feature = "admin"))]
    pub async fn add_group_to_source(&self, gid: i32, sid: i32) -> Result<()> {
        match self {
            DatabaseType::Postgres(pg) => pg.add_group_to_source(gid, sid).await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.add_group_to_source(gid, sid),
        }
    }

    /// Create a new group, returning the group ID
    #[cfg(any(test, feature = "admin"))]
    pub async fn create_group(
        &self,
        name: &str,
        description: &str,
        parent: Option<i32>,
    ) -> Result<i32> {
        match self {
            DatabaseType::Postgres(pg) => pg.create_group(name, description, parent).await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.create_group(name, description, parent),
        }
    }

    /// Get the complete list of sources
    #[cfg(any(test, feature = "admin"))]
    pub async fn list_sources(&self) -> Result<Vec<admin::Source>> {
        match self {
            DatabaseType::Postgres(pg) => pg.list_sources().await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.list_sources(),
        }
    }

    /// Create a source, returning the source ID
    #[cfg(any(test, feature = "admin"))]
    pub async fn create_source(
        &self,
        name: &str,
        description: Option<&str>,
        url: Option<&str>,
        date: chrono::DateTime<Local>,
        releasable: bool,
    ) -> Result<i32> {
        match self {
            DatabaseType::Postgres(pg) => {
                pg.create_source(name, description, url, date, releasable)
                    .await
            }
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.create_source(name, description, url, date, releasable),
        }
    }

    #[cfg(any(test, feature = "admin"))]
    pub async fn edit_user(
        &self,
        uid: i32,
        uname: &str,
        fname: &str,
        lname: &str,
        email: &str,
    ) -> Result<()> {
        match self {
            DatabaseType::Postgres(pg) => pg.edit_user(uid, uname, fname, lname, email).await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.edit_user(uid, uname, fname, lname, email),
        }
    }

    #[cfg(any(test, feature = "admin"))]
    pub async fn deactivate_user(&self, uid: i32) -> Result<()> {
        match self {
            DatabaseType::Postgres(pg) => pg.deactivate_user(uid).await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.deactivate_user(uid),
        }
    }

    #[cfg(any(test, feature = "admin"))]
    pub async fn file_types_counts(&self) -> Result<HashMap<String, u32>> {
        match self {
            DatabaseType::Postgres(pg) => pg.file_types_counts().await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.file_types_counts(),
        }
    }

    #[cfg(any(test, feature = "admin"))]
    pub async fn create_label(&self, name: &str, parent: Option<i64>) -> Result<u64> {
        match self {
            DatabaseType::Postgres(pg) => pg.create_label(name, parent).await,
            #[cfg(any(test, feature = "sqlite"))]
            DatabaseType::SQLite(sl) => sl.create_label(name, parent),
        }
    }
}

pub fn hash_password(password: &str) -> Result<String> {
    let salt = SaltString::generate(&mut OsRng);
    let argon2 = Argon2::default();
    Ok(argon2
        .hash_password(password.as_bytes(), &salt)?
        .to_string())
}

pub fn random_bytes_api_key() -> String {
    let key = uuid::Uuid::new_v4();
    key.to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    use anyhow::{Context, Result};
    use fuzzyhash::FuzzyHash;
    use malwaredb_lzjd::{LZDict, Murmur3HashState};
    use tlsh_fixed::TlshBuilder;
    use uuid::Uuid;

    fn generate_similarity_request(data: &[u8]) -> malwaredb_api::SimilarSamplesRequest {
        let mut hash = vec![];

        hash.push((
            malwaredb_api::SimilarityHashType::SSDeep,
            FuzzyHash::new(data).to_string(),
        ));

        let mut builder = TlshBuilder::new(
            tlsh_fixed::BucketKind::Bucket256,
            tlsh_fixed::ChecksumKind::ThreeByte,
            tlsh_fixed::Version::Version4,
        );

        builder.update(data);

        if let Ok(hasher) = builder.build() {
            hash.push((malwaredb_api::SimilarityHashType::TLSH, hasher.hash()));
        }

        let build_hasher = Murmur3HashState::default();
        let lzjd_str = LZDict::from_bytes_stream(data.iter().copied(), &build_hasher).to_string();
        hash.push((malwaredb_api::SimilarityHashType::LZJD, lzjd_str));

        malwaredb_api::SimilarSamplesRequest {
            key: "not used".into(),
            hash,
        }
    }

    #[tokio::test]
    #[ignore]
    async fn pg() {
        // create user malwaredbtesting with password 'malwaredbtesting';
        // create database malwaredbtesting owner malwaredbtesting;
        const CONNECTION_STRING: &str =
            "user=malwaredbtesting password=malwaredbtesting dbname=malwaredbtesting host=localhost";

        let psql = if let Ok(pg_port) = std::env::var("PG_PORT") {
            // Get the port number to run in Github CI
            let mut conn_string = CONNECTION_STRING.to_string();
            conn_string.push_str(&format!(" port={pg_port}"));
            Postgres::new(&conn_string)
                .await
                .context(format!(
                    "failed to connect to postgres with specified port {pg_port}"
                ))
                .unwrap()
        } else {
            Postgres::new(CONNECTION_STRING).await.unwrap()
        };

        psql.delete_init().await.unwrap();

        let db = DatabaseType::Postgres(psql);
        everything(&db).await.unwrap();

        if let DatabaseType::Postgres(pg) = db {
            pg.delete_init().await.unwrap();
        }
    }

    #[tokio::test]
    async fn sqlite() {
        const DB_FILE: &str = "testing_sqlite.db";
        if std::path::Path::new(DB_FILE).exists() {
            fs::remove_file(DB_FILE)
                .context(format!("failed to delete old SQLite file {DB_FILE}"))
                .unwrap();
        }

        let sqlite = Sqlite::new(DB_FILE)
            .context(format!("failed to create SQLite instance for {DB_FILE}"))
            .unwrap();

        let db = DatabaseType::SQLite(sqlite);
        everything(&db).await.unwrap();

        fs::remove_file(DB_FILE)
            .context(format!("failed to delete SQLite file {DB_FILE}"))
            .unwrap();
    }

    async fn everything(db: &DatabaseType) -> Result<()> {
        const ADMIN_UNAME: &str = "admin";
        const ADMIN_PASSWORD: &str = "super_secure_password_dont_tell_anyone!";

        assert!(
            db.authenticate(ADMIN_UNAME, ADMIN_PASSWORD).await.is_err(),
            "Authentication without password should have failed."
        );

        db.set_password(ADMIN_UNAME, ADMIN_PASSWORD)
            .await
            .context("failed to set admin password")?;

        let admin_api_key = db
            .authenticate(ADMIN_UNAME, ADMIN_PASSWORD)
            .await
            .context("unable to get api key for admin")?;
        println!("API key: {admin_api_key}");

        assert_eq!(
            db.get_uid(&admin_api_key).await?,
            0,
            "Unable to get UID given the API key"
        );

        let admin_api_key_again = db
            .authenticate(ADMIN_UNAME, ADMIN_PASSWORD)
            .await
            .context("unable to get api key a second time for admin")?;

        assert_eq!(
            admin_api_key, admin_api_key_again,
            "API keys didn't match the second time."
        );

        let bad_password = "this_is_totally_not_my_password!!";
        eprintln!("Testing API login with incorrect password.");
        assert!(
            db.authenticate(ADMIN_UNAME, bad_password).await.is_err(),
            "Authenticating as admin with a bad password should have failed."
        );

        let admin_is_admin = db
            .user_is_admin(0)
            .await
            .context("unable to see if admin (uid 0) is an admin")?;
        assert!(admin_is_admin);

        let new_user_uname = "testuser";
        let new_user_email = "test@example.com";
        let new_user_password = "some_awesome_password_++";
        let new_id = db
            .create_user(
                new_user_uname,
                new_user_uname,
                new_user_uname,
                new_user_email,
                Some(new_user_password.into()),
                None,
            )
            .await
            .context(format!("failed to create user {new_user_uname}"))?;

        let passwordless_user_id = db
            .create_user(
                "passwordless_user",
                "passwordless_user",
                "passwordless_user",
                "passwordless_user@example.com",
                None,
                None,
            )
            .await
            .context("failed to create passwordless_user")?;

        for user in db
            .list_users()
            .await
            .context("failed to list users")?
            .iter()
        {
            if user.id == passwordless_user_id as i32 {
                assert_eq!(user.uname, "passwordless_user");
            }
        }

        db.edit_user(
            passwordless_user_id as i32,
            "passwordless_user_2",
            "passwordless_user_2",
            "passwordless_user_2",
            "passwordless_user_2@something.com",
        )
        .await
        .context(format!(
            "failed to alter 'passwordless' user, id {passwordless_user_id}"
        ))?;

        for user in db
            .list_users()
            .await
            .context("failed to list users")?
            .iter()
        {
            if user.id == passwordless_user_id as i32 {
                assert_eq!(user.uname, "passwordless_user_2");
            }
        }

        assert!(
            new_id > 0,
            "Weird UID created for user {}: {}",
            new_user_uname,
            new_id
        );

        assert!(
            db.create_user(
                new_user_uname,
                new_user_uname,
                new_user_uname,
                new_user_email,
                Some(new_user_password.into()),
                None,
            )
            .await
            .is_err(),
            "Creating a new user with the same user name should fail"
        );

        let new_user_password_change = "some_new_awesomer_password!_++";
        db.set_password(new_user_uname, new_user_password_change)
            .await
            .context("failed to change the password for testuser")?;

        let new_user_api_key = db
            .authenticate(new_user_uname, new_user_password_change)
            .await
            .context("unable to get api key for testuser")?;
        eprintln!("{new_user_uname} got API key {new_user_api_key}");

        assert_eq!(admin_api_key.len(), new_user_api_key.len());

        let users = db.list_users().await.context("failed to list users")?;
        assert_eq!(
            users.len(),
            3,
            "Three users were created, yet there are {} users",
            users.len()
        );
        eprintln!("DB has {} users:", users.len());
        let mut passwordless_user_found = false;
        for user in users {
            println!("{user}");
            if user.uname == "passwordless_user_2" {
                assert!(!user.has_api_key);
                assert!(!user.has_password);
                passwordless_user_found = true;
            } else {
                assert!(user.has_api_key);
                assert!(user.has_password);
            }
        }
        assert!(passwordless_user_found);

        let new_group_name = "some_new_group";
        let new_group_desc = "some_new_group_description";
        let new_group_id = 1;
        assert_eq!(
            db.create_group(new_group_name, new_group_desc, None)
                .await
                .context("failed to create group")?,
            new_group_id,
            "New group didn't have the expected ID, expected {}",
            new_group_id
        );

        assert!(
            db.create_group(new_group_name, new_group_desc, None)
                .await
                .is_err(),
            "Duplicate group name should have failed"
        );

        db.add_user_to_group(1, 1)
            .await
            .context("Unable to add uid 1 to gid 1")?;

        let new_admin_group_name = "admin_subgroup";
        let new_admin_group_desc = "admin_subgroup_description";
        let new_admin_group_id = 2;
        // TODO: Figure out why SQLite makes the group_id = 2, but with Postgres it's 3.
        assert!(
            db.create_group(new_admin_group_name, new_admin_group_desc, Some(0))
                .await
                .context("failed to create admin sub-group")?
                >= new_admin_group_id,
            "New group didn't have the expected ID, expected >= {}",
            new_admin_group_id
        );

        let groups = db.list_groups().await.context("failed to list groups")?;
        assert_eq!(
            groups.len(),
            3,
            "Three groups were created, yet there are {} groups",
            groups.len()
        );
        eprintln!("DB has {} groups:", groups.len());
        for group in groups {
            println!("{group}");
            if group.id == new_admin_group_id {
                assert_eq!(group.parent, Some("admin".to_string()));
            }
            if group.id == 1 {
                let test_user_str = String::from(new_user_uname);
                let mut found = false;
                for member in group.members {
                    if member.uname == test_user_str {
                        found = true;
                        break;
                    }
                }
                assert!(found, "new user {} wasn't in the group", test_user_str);
            }
        }

        let default_source_name = "default_source".to_string();
        db.create_source(
            &default_source_name,
            Some("desc_default_source"),
            None,
            Local::now(),
            true,
        )
        .await
        .context("failed to create source `default_source`")?;

        db.add_group_to_source(1, 1)
            .await
            .context("failed to add group 1 to source 1")?;

        let sources = db.list_sources().await.context("failed to list sources")?;
        eprintln!("DB has {} sources:", sources.len());
        for source in sources {
            println!("{source}");
            assert_eq!(source.files, 0);
            if source.id == 1 {
                assert_eq!(source.groups, 1, "groups should show be 1");
            } else {
                assert_eq!(source.groups, 0, "groups should show be zero");
            }
        }

        let uid = db
            .get_uid(&new_user_api_key)
            .await
            .context("failed to user uid from apikey")?;
        let user_info = db
            .get_user_info(uid)
            .await
            .context("failed to get user's available groups and sources")?;
        assert!(user_info.sources.contains(&default_source_name));
        assert!(!user_info.is_admin);
        println!("UserInfoResponse: {user_info:?}");

        assert!(
            db.allowed_user_source(1, 1)
                .await
                .context("failed to check that user 1 has access to source 1")?,
            "User 1 should should have had access to source 1"
        );

        assert!(
            !db.allowed_user_source(1, 5)
                .await
                .context("failed to check that user 1 has access to source 5")?,
            "User 1 should should not have had access to source 5"
        );

        let test_elf = include_bytes!("../../../types/testdata/elf/elf_linux_ppc64le").to_vec();
        let test_elf_meta = FileMetadata::new(&test_elf, Some("elf_linux_ppc64le"));
        let elf_type = db.get_type_id_for_bytes(&test_elf).await.unwrap();

        let known_type =
            KnownType::new(&test_elf).context("failed to parse elf from test crate's test data")?;

        assert!(db
            .add_file(&test_elf_meta, known_type, 1, 1, elf_type, None)
            .await
            .context("failed to insert a test elf")?);
        eprintln!("Added ELF to the DB");

        let mut test_elf_modified = test_elf.clone();
        let random_bytes = Uuid::new_v4();
        let mut random_bytes = random_bytes.into_bytes().to_vec();
        test_elf_modified.append(&mut random_bytes);
        let similarity_request = generate_similarity_request(&test_elf_modified);
        let similarity_response = db
            .find_similar_samples(1, &similarity_request.hash)
            .await
            .context("failed to get similarity response")?;
        eprintln!("Similarity response: {similarity_response:?}");
        let similarity_response = similarity_response.first().unwrap();
        assert_eq!(
            similarity_response.sha256, test_elf_meta.sha256,
            "Similarity response should have had the hash of the original ELF"
        );
        for (algo, sim) in similarity_response.algorithms.iter() {
            match *algo {
                malwaredb_api::SimilarityHashType::LZJD => {
                    assert!(*sim > 0.0f32);
                }
                malwaredb_api::SimilarityHashType::SSDeep => {
                    assert!(*sim > 90.0f32);
                }
                malwaredb_api::SimilarityHashType::TLSH => {
                    assert!(*sim <= 10f32);
                }
                _ => {}
            }
        }

        let test_elf_hashtype = HashType::try_from(test_elf_meta.sha1)
            .context("failed to get `HashType::SHA1` from string")?;
        let response_sha256 = db
            .retrieve_sample(1, test_elf_hashtype)
            .await
            .context("could not get SHA-256 hash from test sample")?;
        assert_eq!(response_sha256, test_elf_meta.sha256);

        let test_bogus_hash = HashType::try_from(String::from(
            "d154b8420fc56a629df2e6d918be53310d8ac39a926aa5f60ae59a66298969a0",
        ))
        .context("failed to get `HashType` from static string")?;
        assert!(
            db.retrieve_sample(1, test_bogus_hash).await.is_err(),
            "Getting a file with a bogus hash should have failed."
        );

        let test_pdf = include_bytes!("../../../types/testdata/pdf/test.pdf").to_vec();
        let test_pdf_meta = FileMetadata::new(&test_pdf, Some("test.pdf"));
        let pdf_type = db.get_type_id_for_bytes(&test_pdf).await.unwrap();

        let known_type =
            KnownType::new(&test_pdf).context("failed to parse pdf from test crate's test data")?;

        assert!(db
            .add_file(&test_pdf_meta, known_type, 1, 1, pdf_type, None)
            .await
            .context("failed to insert a test pdf")?);
        eprintln!("Added PDF to the DB");

        let test_rtf = include_bytes!("../../../types/testdata/rtf/hello.rtf").to_vec();
        let test_rtf_meta = FileMetadata::new(&test_rtf, Some("test.rtf"));
        let rtf_type = db
            .get_type_id_for_bytes(&test_rtf)
            .await
            .context("failed to get file type id for rtf")?;

        let known_type =
            KnownType::new(&test_rtf).context("failed to parse pdf from test crate's test data")?;

        assert!(db
            .add_file(&test_rtf_meta, known_type, 1, 1, rtf_type, None)
            .await
            .context("failed to insert a test rtf")?);
        eprintln!("Added RTF to the DB");

        let report = db
            .get_sample_report(1, HashType::try_from(test_rtf_meta.sha256.clone())?)
            .await
            .context("failed to get report for test rtf")?;
        assert!(report.filecommand.unwrap().contains("Rich Text Format"));

        assert!(db
            .get_sample_report(999, HashType::try_from(test_rtf_meta.sha256)?)
            .await
            .is_err());

        let reset = db
            .reset_api_keys()
            .await
            .context("failed to reset all API keys")?;
        eprintln!("Cleared {reset} api keys.");

        let db_info = db.db_info().await.context("failed to get database info")?;
        eprintln!("DB Info: {db_info:?}");

        let data_types = db
            .get_known_data_types()
            .await
            .context("failed to get data types")?;
        for data_type in data_types {
            println!("{data_type:?}");
        }

        let sources = db
            .list_sources()
            .await
            .context("failed to list sources second time")?;
        eprintln!("DB has {} sources:", sources.len());
        for source in sources {
            println!("{source}");
        }

        let file_types_counts = db
            .file_types_counts()
            .await
            .context("failed to get file types and counts")?;
        for (name, count) in file_types_counts {
            println!("{name}: {count}");
            assert_ne!(name, "Mach-O", "No Mach-O files have been inserted yet!");
        }

        let fatmacho =
            include_bytes!("../../../types/testdata/macho/macho_fat_arm64_ppc_ppc64_x86_64")
                .to_vec();
        let fatmacho_meta = FileMetadata::new(&fatmacho, Some("macho_fat_arm64_ppc_ppc64_x86_64"));
        let fatmacho_type = db
            .get_type_id_for_bytes(&fatmacho)
            .await
            .context("failed to get file type for Fat Mach-O")?;
        let known_type = KnownType::new(&fatmacho)
            .context("failed to parse Fat Mach-O from type crate's test data")?;

        assert!(db
            .add_file(&fatmacho_meta, known_type, 1, 1, fatmacho_type, None)
            .await
            .context("failed to insert a test Fat Mach-O")?);
        eprintln!("Added Fat Mach-O to the DB");

        let file_types_counts = db
            .file_types_counts()
            .await
            .context("failed to get file types and counts")?;
        for (name, count) in &file_types_counts {
            println!("{name}: {count}");
        }

        assert_eq!(
            *file_types_counts.get("Mach-O").unwrap(),
            4,
            "Expected 4 Mach-O files, got {:?}",
            file_types_counts.get("Mach-O")
        );

        const MALWARE_LABEL: &str = "malware";
        const RANSOMWARE_LABEL: &str = "ransomware";
        let malware_label_id = db
            .create_label(MALWARE_LABEL, None)
            .await
            .context("failed to create first label")?;
        let ransomware_label_id = db
            .create_label(RANSOMWARE_LABEL, Some(malware_label_id as i64))
            .await
            .context("failed to create malware sub-label")?;
        let labels = db.get_labels().await.context("failed to get labels")?;

        assert_eq!(labels.len(), 2);
        for label in labels.0 {
            if label.name == RANSOMWARE_LABEL {
                assert_eq!(label.id, ransomware_label_id);
                assert_eq!(label.parent.unwrap(), MALWARE_LABEL);
            }
        }

        db.reset_own_api_key(0)
            .await
            .context("failed to clear own API key uid 0")?;

        db.deactivate_user(0)
            .await
            .context("failed to clear password and API key for uid 0")?;

        Ok(())
    }
}