-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathhandler.rs
More file actions
684 lines (571 loc) · 26.8 KB
/
handler.rs
File metadata and controls
684 lines (571 loc) · 26.8 KB
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
//! This module implements the `KeysHandler` service
//!
//! It's responsible for managing authentication keys for the `BitTorrent` tracker.
//!
//! The service handles both persistent and in-memory storage of peer keys, and
//! supports adding new keys (either pre-generated or randomly created),
//! removing keys, and loading keys from the database into memory. Keys can be
//! either permanent or expire after a configurable duration per key.
use std::sync::Arc;
use std::time::Duration;
use torrust_tracker_clock::clock::Time;
use torrust_tracker_located_error::Located;
use torrust_tracker_primitives::DurationSinceUnixEpoch;
use super::key::repository::in_memory::InMemoryKeyRepository;
use super::key::repository::persisted::DatabaseKeyRepository;
use super::{key, CurrentClock, Key, PeerKey};
use crate::databases;
use crate::error::PeerKeyError;
/// Contains the information needed to add a new tracker key.
///
/// A new key can either be a pre-generated key provided by the user or can be
/// randomly generated by the application. Additionally, the key may be set to
/// expire after a certain number of seconds, or be permanent (if no expiration
/// is specified).
#[derive(Debug)]
pub struct AddKeyRequest {
/// The pre-generated key as a string. If `None` the service will generate a
/// random key.
pub opt_key: Option<String>,
/// The duration (in seconds) for which the key is valid. Use `None` for
/// permanent keys.
pub opt_seconds_valid: Option<u64>,
}
/// The `KeysHandler` service manages the creation, addition, removal, and loading
/// of authentication keys for the tracker.
///
/// It uses both a persistent (database) repository and an in-memory repository
/// to manage keys.
pub struct KeysHandler {
/// The database repository for storing authentication keys persistently.
db_key_repository: Arc<DatabaseKeyRepository>,
/// The in-memory repository for caching authentication keys.
in_memory_key_repository: Arc<InMemoryKeyRepository>,
}
impl KeysHandler {
/// Creates a new instance of the `KeysHandler` service.
///
/// # Parameters
///
/// - `db_key_repository`: A shared reference to the database key repository.
/// - `in_memory_key_repository`: A shared reference to the in-memory key
/// repository.
#[must_use]
pub fn new(db_key_repository: &Arc<DatabaseKeyRepository>, in_memory_key_repository: &Arc<InMemoryKeyRepository>) -> Self {
Self {
db_key_repository: db_key_repository.clone(),
in_memory_key_repository: in_memory_key_repository.clone(),
}
}
/// Adds a new peer key to the tracker.
///
/// The key may be pre-generated or generated on-the-fly.
///
/// Depending on whether an expiration duration is specified, the key will
/// be either expiring or permanent.
///
/// # Parameters
///
/// - `add_key_req`: The request containing options for key creation.
///
/// # Errors
///
/// Returns an error if:
///
/// - The provided key duration exceeds the maximum allowed value.
/// - The provided pre-generated key is invalid.
/// - There is an error persisting the key in the database.
pub async fn add_peer_key(&self, add_key_req: AddKeyRequest) -> Result<PeerKey, PeerKeyError> {
if let Some(pre_existing_key) = add_key_req.opt_key {
// Pre-generated key
if let Some(seconds_valid) = add_key_req.opt_seconds_valid {
// Expiring key
let Some(valid_until) = CurrentClock::now_add(&Duration::from_secs(seconds_valid)) else {
return Err(PeerKeyError::DurationOverflow { seconds_valid });
};
let key = pre_existing_key.parse::<Key>();
match key {
Ok(key) => match self.add_expiring_peer_key(key, Some(valid_until)).await {
Ok(auth_key) => Ok(auth_key),
Err(err) => Err(PeerKeyError::DatabaseError {
source: Located(err).into(),
}),
},
Err(err) => Err(PeerKeyError::InvalidKey {
key: pre_existing_key,
source: Located(err).into(),
}),
}
} else {
// Permanent key
let key = pre_existing_key.parse::<Key>();
match key {
Ok(key) => match self.add_permanent_peer_key(key).await {
Ok(auth_key) => Ok(auth_key),
Err(err) => Err(PeerKeyError::DatabaseError {
source: Located(err).into(),
}),
},
Err(err) => Err(PeerKeyError::InvalidKey {
key: pre_existing_key,
source: Located(err).into(),
}),
}
}
} else {
// New randomly generate key
if let Some(seconds_valid) = add_key_req.opt_seconds_valid {
// Expiring key
match self
.generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid)))
.await
{
Ok(auth_key) => Ok(auth_key),
Err(err) => Err(PeerKeyError::DatabaseError {
source: Located(err).into(),
}),
}
} else {
// Permanent key
match self.generate_permanent_peer_key().await {
Ok(auth_key) => Ok(auth_key),
Err(err) => Err(PeerKeyError::DatabaseError {
source: Located(err).into(),
}),
}
}
}
}
/// Generates a new permanent authentication key.
///
/// Permanent keys do not expire.
///
/// # Errors
///
/// Returns a `databases::error::Error` if the key cannot be persisted in
/// the database.
pub(crate) async fn generate_permanent_peer_key(&self) -> Result<PeerKey, databases::error::Error> {
self.generate_expiring_peer_key(None).await
}
/// Generates a new authentication key with an optional expiration lifetime.
///
/// If a `lifetime` is provided, the generated key will expire after that
/// duration. The new key is stored both in the database and in memory.
///
/// # Parameters
///
/// - `lifetime`: An optional duration specifying how long the key is valid.
///
/// # Errors
///
/// Returns a `databases::error::Error` if there is an issue adding the key
/// to the database.
pub async fn generate_expiring_peer_key(&self, lifetime: Option<Duration>) -> Result<PeerKey, databases::error::Error> {
let peer_key = key::generate_key(lifetime);
self.db_key_repository.add(&peer_key)?;
self.in_memory_key_repository.insert(&peer_key).await;
Ok(peer_key)
}
/// Adds a pre-generated permanent authentication key.
///
/// Internally, this calls `add_expiring_peer_key` with no expiration.
///
/// # Parameters
///
/// - `key`: The pre-generated key.
///
/// # Errors
///
/// Returns a `databases::error::Error` if there is an issue persisting the
/// key.
pub(crate) async fn add_permanent_peer_key(&self, key: Key) -> Result<PeerKey, databases::error::Error> {
self.add_expiring_peer_key(key, None).await
}
/// Adds a pre-generated authentication key with an optional expiration.
///
/// The key is stored in both the database and the in-memory repository.
///
/// # Parameters
///
/// - `key`: The pre-generated key.
/// - `valid_until`: An optional timestamp (as a duration since the Unix
/// epoch) after which the key expires.
///
/// # Errors
///
/// Returns a `databases::error::Error` if there is an issue adding the key
/// to the database.
pub(crate) async fn add_expiring_peer_key(
&self,
key: Key,
valid_until: Option<DurationSinceUnixEpoch>,
) -> Result<PeerKey, databases::error::Error> {
let peer_key = PeerKey { key, valid_until };
// code-review: should we return a friendly error instead of the DB
// constrain error when the key already exist? For now, it's returning
// the specif error for each DB driver when a UNIQUE constrain fails.
self.db_key_repository.add(&peer_key)?;
self.in_memory_key_repository.insert(&peer_key).await;
Ok(peer_key)
}
/// Removes an authentication key.
///
/// The key is removed from both the database and the in-memory repository.
///
/// # Parameters
///
/// - `key`: A reference to the key to be removed.
///
/// # Errors
///
/// Returns a `databases::error::Error` if the key cannot be removed from
/// the database.
pub async fn remove_peer_key(&self, key: &Key) -> Result<(), databases::error::Error> {
self.db_key_repository.remove(key)?;
self.remove_in_memory_auth_key(key).await;
Ok(())
}
/// Removes an authentication key from the in-memory repository.
///
/// This function does not interact with the database.
///
/// # Parameters
///
/// - `key`: A reference to the key to be removed.
pub(crate) async fn remove_in_memory_auth_key(&self, key: &Key) {
self.in_memory_key_repository.remove(key).await;
}
/// Loads all authentication keys from the database into the in-memory
/// repository.
///
/// This is useful during tracker startup to ensure that all persisted keys
/// are available in memory.
///
/// # Errors
///
/// Returns a `databases::error::Error` if there is an issue loading the keys from the database.
pub async fn load_peer_keys_from_database(&self) -> Result<(), databases::error::Error> {
let keys_from_database = self.db_key_repository.load_keys()?;
self.in_memory_key_repository.reset_with(keys_from_database).await;
Ok(())
}
}
#[cfg(test)]
mod tests {
mod the_keys_handler_when_the_tracker_is_configured_as_private {
use std::sync::Arc;
use torrust_tracker_configuration::Configuration;
use torrust_tracker_test_helpers::configuration;
use crate::authentication::handler::KeysHandler;
use crate::authentication::key::repository::in_memory::InMemoryKeyRepository;
use crate::authentication::key::repository::persisted::DatabaseKeyRepository;
use crate::databases::setup::initialize_database;
use crate::databases::Database;
fn instantiate_keys_handler() -> KeysHandler {
let config = configuration::ephemeral_private();
instantiate_keys_handler_with_configuration(&config)
}
fn instantiate_keys_handler_with_database(database: &Arc<Box<dyn Database>>) -> KeysHandler {
let db_key_repository = Arc::new(DatabaseKeyRepository::new(database));
let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default());
KeysHandler::new(&db_key_repository, &in_memory_key_repository)
}
fn instantiate_keys_handler_with_configuration(config: &Configuration) -> KeysHandler {
// todo: pass only Core configuration
let database = initialize_database(&config.core);
let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database));
let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default());
KeysHandler::new(&db_key_repository, &in_memory_key_repository)
}
mod handling_expiring_peer_keys {
use std::time::Duration;
use torrust_tracker_clock::clock::Time;
use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::instantiate_keys_handler;
use crate::CurrentClock;
#[tokio::test]
async fn it_should_generate_the_key() {
let keys_handler = instantiate_keys_handler();
let peer_key = keys_handler
.generate_expiring_peer_key(Some(Duration::from_secs(100)))
.await
.unwrap();
assert_eq!(
peer_key.valid_until,
Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap())
);
}
mod randomly_generated {
use std::panic::Location;
use std::sync::Arc;
use std::time::Duration;
use mockall::predicate::function;
use torrust_tracker_clock::clock::stopped::Stopped;
use torrust_tracker_clock::clock::{self, Time};
use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::{
instantiate_keys_handler, instantiate_keys_handler_with_database,
};
use crate::authentication::handler::AddKeyRequest;
use crate::authentication::PeerKey;
use crate::databases::driver::Driver;
use crate::databases::{self, Database, MockDatabase};
use crate::error::PeerKeyError;
use crate::CurrentClock;
#[tokio::test]
async fn it_should_add_a_randomly_generated_key() {
let keys_handler = instantiate_keys_handler();
let peer_key = keys_handler
.add_peer_key(AddKeyRequest {
opt_key: None,
opt_seconds_valid: Some(100),
})
.await
.unwrap();
assert_eq!(
peer_key.valid_until,
Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap())
);
}
#[tokio::test]
async fn it_should_fail_adding_a_randomly_generated_key_when_there_is_a_database_error() {
clock::Stopped::local_set(&Duration::from_secs(0));
// The key should be valid the next 60 seconds.
let expected_valid_until = clock::Stopped::now_add(&Duration::from_secs(60)).unwrap();
let mut database_mock = MockDatabase::default();
database_mock
.expect_add_key_to_keys()
.with(function(move |peer_key: &PeerKey| {
peer_key.valid_until == Some(expected_valid_until)
}))
.times(1)
.returning(|_peer_key| {
Err(databases::error::Error::InsertFailed {
location: Location::caller(),
driver: Driver::Sqlite3,
})
});
let database_mock: Arc<Box<dyn Database>> = Arc::new(Box::new(database_mock));
let keys_handler = instantiate_keys_handler_with_database(&database_mock);
let result = keys_handler
.add_peer_key(AddKeyRequest {
opt_key: None,
opt_seconds_valid: Some(60), // The key is valid for 60 seconds.
})
.await;
assert!(matches!(result.unwrap_err(), PeerKeyError::DatabaseError { .. }));
}
}
mod pre_generated {
use std::panic::Location;
use std::sync::Arc;
use std::time::Duration;
use mockall::predicate;
use torrust_tracker_clock::clock::stopped::Stopped;
use torrust_tracker_clock::clock::{self, Time};
use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::{
instantiate_keys_handler, instantiate_keys_handler_with_database,
};
use crate::authentication::handler::AddKeyRequest;
use crate::authentication::{Key, PeerKey};
use crate::databases::driver::Driver;
use crate::databases::{self, Database, MockDatabase};
use crate::error::PeerKeyError;
use crate::CurrentClock;
#[tokio::test]
async fn it_should_add_a_pre_generated_key() {
let keys_handler = instantiate_keys_handler();
let peer_key = keys_handler
.add_peer_key(AddKeyRequest {
opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()),
opt_seconds_valid: Some(100),
})
.await
.unwrap();
assert_eq!(
peer_key,
PeerKey {
key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(),
valid_until: Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()),
}
);
}
#[tokio::test]
async fn it_should_fail_adding_a_pre_generated_key_when_the_key_duration_exceeds_the_maximum_duration() {
let keys_handler = instantiate_keys_handler();
let result = keys_handler
.add_peer_key(AddKeyRequest {
opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()),
opt_seconds_valid: Some(u64::MAX),
})
.await;
assert!(matches!(result.unwrap_err(), PeerKeyError::DurationOverflow { .. }));
}
#[tokio::test]
async fn it_should_fail_adding_a_pre_generated_key_when_the_key_is_invalid() {
let keys_handler = instantiate_keys_handler();
let result = keys_handler
.add_peer_key(AddKeyRequest {
opt_key: Some("INVALID KEY".to_string()),
opt_seconds_valid: Some(100),
})
.await;
assert!(matches!(result.unwrap_err(), PeerKeyError::InvalidKey { .. }));
}
#[tokio::test]
async fn it_should_fail_adding_a_pre_generated_key_when_there_is_a_database_error() {
clock::Stopped::local_set(&Duration::from_secs(0));
// The key should be valid the next 60 seconds.
let expected_valid_until = clock::Stopped::now_add(&Duration::from_secs(60)).unwrap();
let expected_peer_key = PeerKey {
key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(),
valid_until: Some(expected_valid_until),
};
let mut database_mock = MockDatabase::default();
database_mock
.expect_add_key_to_keys()
.with(predicate::eq(expected_peer_key))
.times(1)
.returning(|_peer_key| {
Err(databases::error::Error::InsertFailed {
location: Location::caller(),
driver: Driver::Sqlite3,
})
});
let database_mock: Arc<Box<dyn Database>> = Arc::new(Box::new(database_mock));
let keys_handler = instantiate_keys_handler_with_database(&database_mock);
let result = keys_handler
.add_peer_key(AddKeyRequest {
opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()),
opt_seconds_valid: Some(60), // The key is valid for 60 seconds.
})
.await;
assert!(matches!(result.unwrap_err(), PeerKeyError::DatabaseError { .. }));
}
}
}
mod handling_permanent_peer_keys {
mod randomly_generated {
use std::panic::Location;
use std::sync::Arc;
use mockall::predicate::function;
use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::{
instantiate_keys_handler, instantiate_keys_handler_with_database,
};
use crate::authentication::handler::AddKeyRequest;
use crate::authentication::PeerKey;
use crate::databases::driver::Driver;
use crate::databases::{self, Database, MockDatabase};
use crate::error::PeerKeyError;
#[tokio::test]
async fn it_should_generate_the_key() {
let keys_handler = instantiate_keys_handler();
let peer_key = keys_handler.generate_permanent_peer_key().await.unwrap();
assert_eq!(peer_key.valid_until, None);
}
#[tokio::test]
async fn it_should_add_a_randomly_generated_key() {
let keys_handler = instantiate_keys_handler();
let peer_key = keys_handler
.add_peer_key(AddKeyRequest {
opt_key: None,
opt_seconds_valid: None,
})
.await
.unwrap();
assert_eq!(peer_key.valid_until, None);
}
#[tokio::test]
async fn it_should_fail_adding_a_randomly_generated_key_when_there_is_a_database_error() {
let mut database_mock = MockDatabase::default();
database_mock
.expect_add_key_to_keys()
.with(function(move |peer_key: &PeerKey| peer_key.valid_until.is_none()))
.times(1)
.returning(|_peer_key| {
Err(databases::error::Error::InsertFailed {
location: Location::caller(),
driver: Driver::Sqlite3,
})
});
let database_mock: Arc<Box<dyn Database>> = Arc::new(Box::new(database_mock));
let keys_handler = instantiate_keys_handler_with_database(&database_mock);
let result = keys_handler
.add_peer_key(AddKeyRequest {
opt_key: None,
opt_seconds_valid: None,
})
.await;
assert!(matches!(result.unwrap_err(), PeerKeyError::DatabaseError { .. }));
}
}
mod pre_generated_keys {
use std::panic::Location;
use std::sync::Arc;
use mockall::predicate;
use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::{
instantiate_keys_handler, instantiate_keys_handler_with_database,
};
use crate::authentication::handler::AddKeyRequest;
use crate::authentication::{Key, PeerKey};
use crate::databases::driver::Driver;
use crate::databases::{self, Database, MockDatabase};
use crate::error::PeerKeyError;
#[tokio::test]
async fn it_should_add_a_pre_generated_key() {
let keys_handler = instantiate_keys_handler();
let peer_key = keys_handler
.add_peer_key(AddKeyRequest {
opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()),
opt_seconds_valid: None,
})
.await
.unwrap();
assert_eq!(
peer_key,
PeerKey {
key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(),
valid_until: None,
}
);
}
#[tokio::test]
async fn it_should_fail_adding_a_pre_generated_key_when_the_key_is_invalid() {
let keys_handler = instantiate_keys_handler();
let result = keys_handler
.add_peer_key(AddKeyRequest {
opt_key: Some("INVALID KEY".to_string()),
opt_seconds_valid: None,
})
.await;
assert!(matches!(result.unwrap_err(), PeerKeyError::InvalidKey { .. }));
}
#[tokio::test]
async fn it_should_fail_adding_a_pre_generated_key_when_there_is_a_database_error() {
let expected_peer_key = PeerKey {
key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(),
valid_until: None,
};
let mut database_mock = MockDatabase::default();
database_mock
.expect_add_key_to_keys()
.with(predicate::eq(expected_peer_key))
.times(1)
.returning(|_peer_key| {
Err(databases::error::Error::InsertFailed {
location: Location::caller(),
driver: Driver::Sqlite3,
})
});
let database_mock: Arc<Box<dyn Database>> = Arc::new(Box::new(database_mock));
let keys_handler = instantiate_keys_handler_with_database(&database_mock);
let result = keys_handler
.add_peer_key(AddKeyRequest {
opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()),
opt_seconds_valid: None,
})
.await;
assert!(matches!(result.unwrap_err(), PeerKeyError::DatabaseError { .. }));
}
}
}
}
}