splinter 0.6.14

Splinter is a privacy-focused platform for distributed applications that provides a blockchain-inspired networking environment for communication and transactions between organizations.
Documentation
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
// Copyright 2018-2022 Cargill Incorporated
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

pub(in crate::biome) mod models;
mod operations;
pub(in crate::biome) mod schema;

use std::sync::{Arc, RwLock};

use diesel::r2d2::{ConnectionManager, Pool};

use crate::store::pool::ConnectionPool;

use super::{
    Credentials, CredentialsStore, CredentialsStoreError, PasswordEncryptionCost, UsernameId,
};

use models::CredentialsModel;
use operations::add_credentials::CredentialsStoreAddCredentialsOperation as _;
use operations::fetch_credential_by_id::CredentialsStoreFetchCredentialByIdOperation as _;
use operations::fetch_credential_by_username::CredentialsStoreFetchCredentialByUsernameOperation as _;
use operations::fetch_username::CredentialsStoreFetchUsernameOperation as _;
use operations::list_usernames::CredentialsStoreListUsernamesOperation as _;
use operations::remove_credentials::CredentialsStoreRemoveCredentialsOperation as _;
use operations::update_credentials::CredentialsStoreUpdateCredentialsOperation as _;
use operations::CredentialsStoreOperations;

/// Manages creating, updating and fetching SplinterCredentials from the database
pub struct DieselCredentialsStore<C: diesel::Connection + 'static> {
    connection_pool: ConnectionPool<C>,
}

impl<C: diesel::Connection> DieselCredentialsStore<C> {
    /// Creates a new DieselCredentialsStore
    ///
    /// # Arguments
    ///
    ///  * `connection_pool`: connection pool to the database
    pub fn new(connection_pool: Pool<ConnectionManager<C>>) -> Self {
        DieselCredentialsStore {
            connection_pool: connection_pool.into(),
        }
    }

    /// Create a new `DieselCredentialsStore` with write exclusivity enabled.
    ///
    /// Write exclusivity is enforced by providing a connection pool that is wrapped in a
    /// [`RwLock`]. This ensures that there may be only one writer, but many readers.
    ///
    /// # Arguments
    ///
    ///  * `connection_pool`: read-write lock-guarded connection pool for the database
    pub fn new_with_write_exclusivity(
        connection_pool: Arc<RwLock<Pool<ConnectionManager<C>>>>,
    ) -> Self {
        DieselCredentialsStore {
            connection_pool: connection_pool.into(),
        }
    }
}

#[cfg(feature = "postgres")]
impl CredentialsStore for DieselCredentialsStore<diesel::pg::PgConnection> {
    fn add_credentials(&self, credentials: Credentials) -> Result<(), CredentialsStoreError> {
        self.connection_pool.execute_write(|conn| {
            CredentialsStoreOperations::new(conn).add_credentials(credentials)
        })
    }

    fn update_credentials(
        &self,
        user_id: &str,
        username: &str,
        password: &str,
        password_encryption_cost: PasswordEncryptionCost,
    ) -> Result<(), CredentialsStoreError> {
        self.connection_pool.execute_write(|conn| {
            CredentialsStoreOperations::new(conn).update_credentials(
                user_id,
                username,
                password,
                password_encryption_cost,
            )
        })
    }

    fn remove_credentials(&self, user_id: &str) -> Result<(), CredentialsStoreError> {
        self.connection_pool
            .execute_write(|conn| CredentialsStoreOperations::new(conn).remove_credentials(user_id))
    }

    fn fetch_credential_by_user_id(
        &self,
        user_id: &str,
    ) -> Result<Credentials, CredentialsStoreError> {
        self.connection_pool.execute_read(|conn| {
            CredentialsStoreOperations::new(conn).fetch_credential_by_id(user_id)
        })
    }

    fn fetch_credential_by_username(
        &self,
        username: &str,
    ) -> Result<Credentials, CredentialsStoreError> {
        self.connection_pool.execute_read(|conn| {
            CredentialsStoreOperations::new(conn).fetch_credential_by_username(username)
        })
    }

    fn fetch_username_by_id(&self, user_id: &str) -> Result<UsernameId, CredentialsStoreError> {
        self.connection_pool.execute_read(|conn| {
            CredentialsStoreOperations::new(conn).fetch_username_by_id(user_id)
        })
    }

    fn list_usernames(&self) -> Result<Vec<UsernameId>, CredentialsStoreError> {
        self.connection_pool
            .execute_read(|conn| CredentialsStoreOperations::new(conn).list_usernames())
    }
}

#[cfg(feature = "sqlite")]
impl CredentialsStore for DieselCredentialsStore<diesel::sqlite::SqliteConnection> {
    fn add_credentials(&self, credentials: Credentials) -> Result<(), CredentialsStoreError> {
        self.connection_pool.execute_write(|conn| {
            CredentialsStoreOperations::new(conn).add_credentials(credentials)
        })
    }

    fn update_credentials(
        &self,
        user_id: &str,
        username: &str,
        password: &str,
        password_encryption_cost: PasswordEncryptionCost,
    ) -> Result<(), CredentialsStoreError> {
        self.connection_pool.execute_write(|conn| {
            CredentialsStoreOperations::new(conn).update_credentials(
                user_id,
                username,
                password,
                password_encryption_cost,
            )
        })
    }

    fn remove_credentials(&self, user_id: &str) -> Result<(), CredentialsStoreError> {
        self.connection_pool
            .execute_write(|conn| CredentialsStoreOperations::new(conn).remove_credentials(user_id))
    }

    fn fetch_credential_by_user_id(
        &self,
        user_id: &str,
    ) -> Result<Credentials, CredentialsStoreError> {
        self.connection_pool.execute_read(|conn| {
            CredentialsStoreOperations::new(conn).fetch_credential_by_id(user_id)
        })
    }

    fn fetch_credential_by_username(
        &self,
        username: &str,
    ) -> Result<Credentials, CredentialsStoreError> {
        self.connection_pool.execute_read(|conn| {
            CredentialsStoreOperations::new(conn).fetch_credential_by_username(username)
        })
    }

    fn fetch_username_by_id(&self, user_id: &str) -> Result<UsernameId, CredentialsStoreError> {
        self.connection_pool.execute_read(|conn| {
            CredentialsStoreOperations::new(conn).fetch_username_by_id(user_id)
        })
    }

    fn list_usernames(&self) -> Result<Vec<UsernameId>, CredentialsStoreError> {
        self.connection_pool
            .execute_read(|conn| CredentialsStoreOperations::new(conn).list_usernames())
    }
}

impl From<CredentialsModel> for UsernameId {
    fn from(user_credentials: CredentialsModel) -> Self {
        Self {
            user_id: user_credentials.user_id,
            username: user_credentials.username,
        }
    }
}

impl From<CredentialsModel> for Credentials {
    fn from(user_credentials: CredentialsModel) -> Self {
        Self {
            user_id: user_credentials.user_id,
            username: user_credentials.username,
            password: user_credentials.password,
        }
    }
}

#[cfg(all(test, feature = "sqlite"))]
pub mod tests {
    use super::*;

    use crate::biome::credentials::store::CredentialsBuilder;
    use crate::migrations::run_sqlite_migrations;

    use diesel::{
        r2d2::{ConnectionManager, Pool},
        sqlite::SqliteConnection,
    };

    /// Verify that a SQLite-backed `DieselCredentialsStore` correctly supports fetching
    /// credentials by user ID.
    ///
    /// 1. Create a connection pool for an in-memory SQLite database and run migrations.
    /// 2. Create the `DieselCredentialsStore`.
    /// 3. Add some credentials.
    /// 4. Verify that the `fetch_credential_by_user_id` method returns correct values for all
    ///    existing credentials.
    /// 5. Verify that the `fetch_credential_by_user_id` method returns a
    ///    `CredentialsStoreError::NotFoundError` for non-existent credentials.
    #[test]
    fn sqlite_fetch_credential_by_user_id() {
        let pool = create_connection_pool_and_migrate();

        let store = DieselCredentialsStore::new(pool);

        let cred1 = CredentialsBuilder::default()
            .with_user_id("id1")
            .with_username("user1")
            .with_password("pwd1")
            .with_password_encryption_cost(PasswordEncryptionCost::Low)
            .build()
            .expect("Failed to build cred1");
        store
            .add_credentials(cred1.clone())
            .expect("Failed to add cred1");
        let cred2 = CredentialsBuilder::default()
            .with_user_id("id2")
            .with_username("user2")
            .with_password("pwd2")
            .with_password_encryption_cost(PasswordEncryptionCost::Medium)
            .build()
            .expect("Failed to build cred2");
        store
            .add_credentials(cred2.clone())
            .expect("Failed to add cred2");
        let cred3 = CredentialsBuilder::default()
            .with_user_id("id3")
            .with_username("user3")
            .with_password("pwd3")
            .with_password_encryption_cost(PasswordEncryptionCost::High)
            .build()
            .expect("Failed to build cred3");
        store
            .add_credentials(cred3.clone())
            .expect("Failed to add cred3");

        assert_eq!(
            store
                .fetch_credential_by_user_id("id1")
                .expect("Failed to fetch cred1"),
            cred1,
        );
        assert_eq!(
            store
                .fetch_credential_by_user_id("id2")
                .expect("Failed to fetch cred2"),
            cred2,
        );
        assert_eq!(
            store
                .fetch_credential_by_user_id("id3")
                .expect("Failed to fetch cred3"),
            cred3,
        );

        match store.fetch_credential_by_user_id("cred4") {
            Err(CredentialsStoreError::NotFoundError(_)) => {}
            res => panic!(
                "Expected Err(CredentialsStoreError::NotFoundError), got {:?} instead",
                res
            ),
        }
    }

    /// Verify that a SQLite-backed `DieselCredentialsStore` correctly supports fetching
    /// credentials by username.
    ///
    /// 1. Create a connection pool for an in-memory SQLite database and run migrations.
    /// 2. Create the `DieselCredentialsStore`.
    /// 3. Add some credentials.
    /// 4. Verify that the `fetch_credential_by_username` method returns correct values for all
    ///    existing credentials.
    /// 5. Verify that the `fetch_credential_by_username` method returns a
    ///    `CredentialsStoreError::NotFoundError` for non-existent credentials.
    #[test]
    fn sqlite_fetch_credential_by_username() {
        let pool = create_connection_pool_and_migrate();

        let store = DieselCredentialsStore::new(pool);

        let cred1 = CredentialsBuilder::default()
            .with_user_id("id1")
            .with_username("user1")
            .with_password("pwd1")
            .with_password_encryption_cost(PasswordEncryptionCost::Low)
            .build()
            .expect("Failed to build cred1");
        store
            .add_credentials(cred1.clone())
            .expect("Failed to add cred1");
        let cred2 = CredentialsBuilder::default()
            .with_user_id("id2")
            .with_username("user2")
            .with_password("pwd2")
            .with_password_encryption_cost(PasswordEncryptionCost::Medium)
            .build()
            .expect("Failed to build cred2");
        store
            .add_credentials(cred2.clone())
            .expect("Failed to add cred2");
        let cred3 = CredentialsBuilder::default()
            .with_user_id("id3")
            .with_username("user3")
            .with_password("pwd3")
            .with_password_encryption_cost(PasswordEncryptionCost::High)
            .build()
            .expect("Failed to build cred3");
        store
            .add_credentials(cred3.clone())
            .expect("Failed to add cred3");

        assert_eq!(
            store
                .fetch_credential_by_username("user1")
                .expect("Failed to fetch cred1"),
            cred1,
        );
        assert_eq!(
            store
                .fetch_credential_by_username("user2")
                .expect("Failed to fetch cred2"),
            cred2,
        );
        assert_eq!(
            store
                .fetch_credential_by_username("user3")
                .expect("Failed to fetch cred3"),
            cred3,
        );

        match store.fetch_credential_by_username("user4") {
            Err(CredentialsStoreError::NotFoundError(_)) => {}
            res => panic!(
                "Expected Err(CredentialsStoreError::NotFoundError), got {:?} instead",
                res
            ),
        }
    }

    /// Verify that a SQLite-backed `DieselCredentialsStore` correctly supports fetching
    /// usernames by IDs.
    ///
    /// 1. Create a connection pool for an in-memory SQLite database and run migrations.
    /// 2. Create the `DieselCredentialsStore`.
    /// 3. Add some credentials.
    /// 4. Verify that the `fetch_username_by_id` method returns correct values for all existing
    ///    credentials.
    /// 5. Verify that the `fetch_username_by_id` method returns a
    ///    `CredentialsStoreError::NotFoundError` for non-existent credentials.
    #[test]
    fn sqlite_fetch_username_by_id() {
        let pool = create_connection_pool_and_migrate();

        let store = DieselCredentialsStore::new(pool);

        let cred1 = CredentialsBuilder::default()
            .with_user_id("id1")
            .with_username("user1")
            .with_password("pwd1")
            .with_password_encryption_cost(PasswordEncryptionCost::Low)
            .build()
            .expect("Failed to build cred1");
        store.add_credentials(cred1).expect("Failed to add cred1");
        let cred2 = CredentialsBuilder::default()
            .with_user_id("id2")
            .with_username("user2")
            .with_password("pwd2")
            .with_password_encryption_cost(PasswordEncryptionCost::Medium)
            .build()
            .expect("Failed to build cred2");
        store.add_credentials(cred2).expect("Failed to add cred2");
        let cred3 = CredentialsBuilder::default()
            .with_user_id("id3")
            .with_username("user3")
            .with_password("pwd3")
            .with_password_encryption_cost(PasswordEncryptionCost::High)
            .build()
            .expect("Failed to build cred3");
        store.add_credentials(cred3).expect("Failed to add cred3");

        assert_eq!(
            store
                .fetch_username_by_id("id1")
                .expect("Failed to fetch id1"),
            UsernameId {
                username: "user1".into(),
                user_id: "id1".into(),
            },
        );
        assert_eq!(
            store
                .fetch_username_by_id("id2")
                .expect("Failed to fetch id2"),
            UsernameId {
                username: "user2".into(),
                user_id: "id2".into(),
            },
        );
        assert_eq!(
            store
                .fetch_username_by_id("id3")
                .expect("Failed to fetch id3"),
            UsernameId {
                username: "user3".into(),
                user_id: "id3".into(),
            },
        );

        match store.fetch_username_by_id("id4") {
            Err(CredentialsStoreError::NotFoundError(_)) => {}
            res => panic!(
                "Expected Err(CredentialsStoreError::NotFoundError), got {:?} instead",
                res
            ),
        }
    }

    /// Verify that a SQLite-backed `DieselCredentialsStore` correctly supports listing usernames.
    ///
    /// 1. Create a connection pool for an in-memory SQLite database and run migrations.
    /// 2. Create the `DieselCredentialsStore`.
    /// 3. Add some credentials.
    /// 4. Verify that the `list_usernames` method returns correct values for all credentials.
    #[test]
    fn sqlite_list_usernames() {
        let pool = create_connection_pool_and_migrate();

        let store = DieselCredentialsStore::new(pool);

        let cred1 = CredentialsBuilder::default()
            .with_user_id("id1")
            .with_username("user1")
            .with_password("pwd1")
            .with_password_encryption_cost(PasswordEncryptionCost::Low)
            .build()
            .expect("Failed to build cred1");
        store.add_credentials(cred1).expect("Failed to add cred1");
        let cred2 = CredentialsBuilder::default()
            .with_user_id("id2")
            .with_username("user2")
            .with_password("pwd2")
            .with_password_encryption_cost(PasswordEncryptionCost::Medium)
            .build()
            .expect("Failed to build cred2");
        store.add_credentials(cred2).expect("Failed to add cred2");
        let cred3 = CredentialsBuilder::default()
            .with_user_id("id3")
            .with_username("user3")
            .with_password("pwd3")
            .with_password_encryption_cost(PasswordEncryptionCost::High)
            .build()
            .expect("Failed to build cred3");
        store.add_credentials(cred3).expect("Failed to add cred3");

        let usernames = store.list_usernames().expect("Failed to list usernames");
        assert_eq!(usernames.len(), 3);
        assert!(usernames.contains(&UsernameId {
            username: "user1".into(),
            user_id: "id1".into(),
        }));
        assert!(usernames.contains(&UsernameId {
            username: "user2".into(),
            user_id: "id2".into(),
        }));
        assert!(usernames.contains(&UsernameId {
            username: "user3".into(),
            user_id: "id3".into(),
        }));
    }

    /// Verify that a SQLite-backed `DieselCredentialsStore` correctly supports updating
    /// credentials.
    ///
    /// 1. Create a connection pool for an in-memory SQLite database and run migrations.
    /// 2. Create the `DieselCredentialsStore`.
    /// 3. Add a credential and verify its value.
    /// 4. Update the credential and verify that the username and password are updated in the
    ///    store.
    #[test]
    fn sqlite_update() {
        let pool = create_connection_pool_and_migrate();

        let store = DieselCredentialsStore::new(pool);

        let cred = CredentialsBuilder::default()
            .with_user_id("id")
            .with_username("user1")
            .with_password("pwd1")
            .with_password_encryption_cost(PasswordEncryptionCost::Low)
            .build()
            .expect("Failed to build cred");
        store
            .add_credentials(cred.clone())
            .expect("Failed to add cred");
        assert_eq!(
            store
                .fetch_credential_by_user_id("id")
                .expect("Failed to fetch cred"),
            cred,
        );

        store
            .update_credentials("id", "user2", "pwd2", PasswordEncryptionCost::Low)
            .expect("Failed to update cred");
        let cred = store
            .fetch_credential_by_user_id("id")
            .expect("Failed to fetch cred");
        assert_eq!(cred.username, "user2");
        assert!(cred
            .verify_password("pwd2")
            .expect("Failed to verify password"));
    }

    /// Verify that a SQLite-backed `DieselCredentialsStore` correctly supports removing
    /// credentials.
    ///
    /// 1. Create a connection pool for an in-memory SQLite database and run migrations.
    /// 2. Create the `DieselCredentialsStore`.
    /// 3. Add some credentials.
    /// 4. Remove a credential and verify that the credential no longer appears with any of the
    ///    fetch or list methods.
    #[test]
    fn sqlite_remove() {
        let pool = create_connection_pool_and_migrate();

        let store = DieselCredentialsStore::new(pool);

        let cred1 = CredentialsBuilder::default()
            .with_user_id("id1")
            .with_username("user1")
            .with_password("pwd1")
            .with_password_encryption_cost(PasswordEncryptionCost::Low)
            .build()
            .expect("Failed to build cred1");
        store.add_credentials(cred1).expect("Failed to add cred1");
        let cred2 = CredentialsBuilder::default()
            .with_user_id("id2")
            .with_username("user2")
            .with_password("pwd2")
            .with_password_encryption_cost(PasswordEncryptionCost::Medium)
            .build()
            .expect("Failed to build cred2");
        store.add_credentials(cred2).expect("Failed to add cred2");
        let cred3 = CredentialsBuilder::default()
            .with_user_id("id3")
            .with_username("user3")
            .with_password("pwd3")
            .with_password_encryption_cost(PasswordEncryptionCost::High)
            .build()
            .expect("Failed to build cred3");
        store.add_credentials(cred3).expect("Failed to add cred3");

        store
            .remove_credentials("id3")
            .expect("Failed to remove cred3");
        match store.fetch_credential_by_user_id("id3") {
            Err(CredentialsStoreError::NotFoundError(_)) => {}
            res => panic!(
                "Expected Err(KeyStoreError::NotFoundError), got {:?} instead",
                res
            ),
        }
        match store.fetch_credential_by_username("user3") {
            Err(CredentialsStoreError::NotFoundError(_)) => {}
            res => panic!(
                "Expected Err(KeyStoreError::NotFoundError), got {:?} instead",
                res
            ),
        }
        match store.fetch_username_by_id("id3") {
            Err(CredentialsStoreError::NotFoundError(_)) => {}
            res => panic!(
                "Expected Err(KeyStoreError::NotFoundError), got {:?} instead",
                res
            ),
        }
        let usernames = store.list_usernames().expect("Failed to list usernames");
        assert_eq!(usernames.len(), 2);
        assert!(!usernames.contains(&UsernameId {
            username: "user3".into(),
            user_id: "id3".into(),
        }));
    }

    /// Creates a conneciton pool for an in-memory SQLite database with only a single connection
    /// available. Each connection is backed by a different in-memory SQLite database, so limiting
    /// the pool to a single connection insures that the same DB is used for all operations.
    fn create_connection_pool_and_migrate() -> Pool<ConnectionManager<SqliteConnection>> {
        let connection_manager = ConnectionManager::<SqliteConnection>::new(":memory:");
        let pool = Pool::builder()
            .max_size(1)
            .build(connection_manager)
            .expect("Failed to build connection pool");

        run_sqlite_migrations(&*pool.get().expect("Failed to get connection for migrations"))
            .expect("Failed to run migrations");

        pool
    }
}