heelonvault-core 1.1.0

Core cryptography and storage library for HeelonVault
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
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};

use secrecy::SecretString;
use tracing::warn;
use uuid::Uuid;

use crate::errors::AppError;
use crate::repositories::user_repository::UserRepository;
use crate::services::access_control::{check_permission, Action, Resource};
use crate::services::backup_service::{BackupMetadata, BackupService};

#[derive(Debug, Clone)]
pub struct RotationBackupTicket {
    pub backup_file_path: String,
    pub recovery_phrase: SecretString,
    pub metadata_sha256_hex: String,
    pub created_at: String,
}

/// Application-level authorization wrapper for backup operations.
/// Enforces access control before delegating to the underlying backup service.
#[trait_variant::make(BackupApplicationService: Send)]
pub trait LocalBackupApplicationService {
    /// Export backup with authorization check (admin-only).
    async fn export_backup_secured(
        &self,
        actor_id: Uuid,
        sqlite_db_path: &Path,
        backup_file_path: &Path,
        recovery_phrase: &SecretString,
    ) -> Result<BackupMetadata, AppError>;

    /// Restore backup with authorization check (admin-only).
    async fn restore_backup_secured(
        &self,
        actor_id: Uuid,
        backup_file_path: &Path,
        recovery_phrase: &SecretString,
        new_sqlite_db_path: &Path,
    ) -> Result<BackupMetadata, AppError>;

    /// Export backup for master-key rotation and keep recovery material in-memory.
    async fn export_rotation_backup_secured(
        &self,
        actor_id: Uuid,
        sqlite_db_path: &Path,
        backup_file_path: &Path,
    ) -> Result<RotationBackupTicket, AppError>;

    /// Restore backup from a previously created rotation backup ticket.
    async fn restore_rotation_backup_secured(
        &self,
        actor_id: Uuid,
        ticket: &RotationBackupTicket,
        new_sqlite_db_path: &Path,
    ) -> Result<BackupMetadata, AppError>;
}

pub struct BackupApplicationServiceImpl<TUserRepo, TBackupSvc>
where
    TUserRepo: UserRepository + Send + Sync,
    TBackupSvc: BackupService + Send + Sync,
{
    user_repo: TUserRepo,
    backup_service: TBackupSvc,
}

impl<TUserRepo, TBackupSvc> BackupApplicationServiceImpl<TUserRepo, TBackupSvc>
where
    TUserRepo: UserRepository + Send + Sync,
    TBackupSvc: BackupService + Send + Sync,
{
    pub fn new(user_repo: TUserRepo, backup_service: TBackupSvc) -> Self {
        Self {
            user_repo,
            backup_service,
        }
    }
}

impl<TUserRepo, TBackupSvc> BackupApplicationService
    for BackupApplicationServiceImpl<TUserRepo, TBackupSvc>
where
    TUserRepo: UserRepository + Send + Sync,
    TBackupSvc: BackupService + Send + Sync,
{
    async fn export_backup_secured(
        &self,
        actor_id: Uuid,
        sqlite_db_path: &Path,
        backup_file_path: &Path,
        recovery_phrase: &SecretString,
    ) -> Result<BackupMetadata, AppError> {
        let actor = self
            .user_repo
            .get_by_id(actor_id)
            .await?
            .ok_or_else(|| AppError::NotFound("actor user not found".to_string()))?;

        check_permission(&actor, Action::BackupExport, &Resource::Global).inspect_err(|_err| {
            warn!(actor_id = %actor_id, "backup export permission denied");
        })?;

        self.backup_service.export_hvb_with_recovery_key(
            sqlite_db_path,
            backup_file_path,
            recovery_phrase,
        )
    }

    async fn restore_backup_secured(
        &self,
        actor_id: Uuid,
        backup_file_path: &Path,
        recovery_phrase: &SecretString,
        new_sqlite_db_path: &Path,
    ) -> Result<BackupMetadata, AppError> {
        let actor = self
            .user_repo
            .get_by_id(actor_id)
            .await?
            .ok_or_else(|| AppError::NotFound("actor user not found".to_string()))?;

        check_permission(&actor, Action::BackupRestore, &Resource::Global).inspect_err(|_err| {
            warn!(actor_id = %actor_id, "backup restore permission denied");
        })?;

        self.backup_service.import_hvb_with_recovery_key(
            backup_file_path,
            recovery_phrase,
            new_sqlite_db_path,
        )
    }

    async fn export_rotation_backup_secured(
        &self,
        actor_id: Uuid,
        sqlite_db_path: &Path,
        backup_file_path: &Path,
    ) -> Result<RotationBackupTicket, AppError> {
        let recovery = self.backup_service.generate_recovery_key()?;
        let metadata = BackupApplicationService::export_backup_secured(
            self,
            actor_id,
            sqlite_db_path,
            backup_file_path,
            &recovery.recovery_phrase,
        )
        .await?;

        let created_at = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_err(|_err| AppError::Internal)?
            .as_secs()
            .to_string();

        Ok(RotationBackupTicket {
            backup_file_path: backup_file_path.to_string_lossy().to_string(),
            recovery_phrase: recovery.recovery_phrase,
            metadata_sha256_hex: metadata.sha256_hex,
            created_at,
        })
    }

    async fn restore_rotation_backup_secured(
        &self,
        actor_id: Uuid,
        ticket: &RotationBackupTicket,
        new_sqlite_db_path: &Path,
    ) -> Result<BackupMetadata, AppError> {
        BackupApplicationService::restore_backup_secured(
            self,
            actor_id,
            Path::new(ticket.backup_file_path.as_str()),
            &ticket.recovery_phrase,
            new_sqlite_db_path,
        )
        .await
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::disallowed_methods)]
    use std::collections::HashMap;
    use std::sync::MutexGuard;
    use std::sync::{Arc, Mutex};
    use uuid::Uuid;

    use crate::errors::AppError;
    use crate::models::{User, UserRole};
    use crate::repositories::user_repository::UserRepository;
    use crate::services::backup_service::{BackupMetadata, BackupService};

    use super::{BackupApplicationService, BackupApplicationServiceImpl};

    #[derive(Default, Clone)]
    struct StubUserRepo {
        users: Arc<Mutex<HashMap<Uuid, User>>>,
    }

    impl StubUserRepo {
        fn lock_users(&self) -> Result<MutexGuard<'_, HashMap<Uuid, User>>, AppError> {
            self.users.lock().map_err(|_| AppError::Internal)
        }

        fn insert_user(&self, id: Uuid, role: UserRole) {
            if let Ok(mut users) = self.users.lock() {
                users.insert(
                    id,
                    User {
                        id,
                        username: format!("user_{}", id),
                        role,
                        email: None,
                        display_name: None,
                        preferred_language: "fr".to_string(),
                        show_passwords_in_edit: false,
                        updated_at: None,
                    },
                );
            }
        }
    }

    impl UserRepository for StubUserRepo {
        async fn get_by_id(&self, id: Uuid) -> Result<Option<User>, AppError> {
            Ok(self.lock_users()?.get(&id).cloned())
        }
        async fn get_by_username(&self, _: &str) -> Result<Option<User>, AppError> {
            Ok(None)
        }
        async fn resolve_username_for_login_identifier(
            &self,
            _: &str,
        ) -> Result<Option<String>, AppError> {
            Ok(None)
        }
        async fn list_all(&self) -> Result<Vec<User>, AppError> {
            Ok(vec![])
        }
        async fn create_user_db(&self, _: Uuid, _: &str, _: &UserRole) -> Result<(), AppError> {
            Ok(())
        }
        async fn delete_user(&self, _: Uuid) -> Result<(), AppError> {
            Ok(())
        }
        async fn update_user_role(&self, _: Uuid, _: &UserRole) -> Result<(), AppError> {
            Ok(())
        }
        async fn list_all_password_envelopes(&self) -> Result<Vec<(String, Vec<u8>)>, AppError> {
            Ok(vec![])
        }
        async fn get_password_envelope_by_user_id(
            &self,
            _: Uuid,
        ) -> Result<Option<secrecy::SecretBox<Vec<u8>>>, AppError> {
            Ok(None)
        }
        async fn update_user_profile(
            &self,
            _: Uuid,
            _: Option<&str>,
            _: Option<&str>,
            _: Option<&str>,
            _: Option<bool>,
        ) -> Result<(), AppError> {
            Ok(())
        }
        async fn update_password_envelope(
            &self,
            _: Uuid,
            _: secrecy::SecretBox<Vec<u8>>,
        ) -> Result<(), AppError> {
            Ok(())
        }
        async fn update_totp_secret_envelope(
            &self,
            _: Uuid,
            _: secrecy::SecretBox<Vec<u8>>,
        ) -> Result<(), AppError> {
            Ok(())
        }
        async fn update_show_passwords_in_edit(&self, _: Uuid, _: bool) -> Result<(), AppError> {
            Ok(())
        }
    }

    #[derive(Default, Clone)]
    struct StubBackupService;

    impl BackupService for StubBackupService {
        fn generate_recovery_key(
            &self,
        ) -> Result<crate::services::backup_service::RecoveryKeyBundle, AppError> {
            Ok(crate::services::backup_service::RecoveryKeyBundle {
                recovery_phrase: secrecy::SecretString::new(
                    "test recovery phrase".to_string().into(),
                ),
            })
        }
        fn export_hvb_with_recovery_key(
            &self,
            _: &std::path::Path,
            _: &std::path::Path,
            _: &secrecy::SecretString,
        ) -> Result<BackupMetadata, AppError> {
            Ok(BackupMetadata {
                sha256_hex: "abc123".to_string(),
                plaintext_size: 1024,
            })
        }
        fn import_hvb_with_recovery_key(
            &self,
            _: &std::path::Path,
            _: &secrecy::SecretString,
            _: &std::path::Path,
        ) -> Result<BackupMetadata, AppError> {
            Ok(BackupMetadata {
                sha256_hex: "def456".to_string(),
                plaintext_size: 2048,
            })
        }
        fn export_backup(
            &self,
            _: &std::path::Path,
            _: &std::path::Path,
            _: secrecy::SecretBox<Vec<u8>>,
        ) -> Result<BackupMetadata, AppError> {
            Ok(BackupMetadata {
                sha256_hex: "ghi789".to_string(),
                plaintext_size: 512,
            })
        }
        fn import_backup(
            &self,
            _: &std::path::Path,
            _: &std::path::Path,
            _: secrecy::SecretBox<Vec<u8>>,
        ) -> Result<BackupMetadata, AppError> {
            Ok(BackupMetadata {
                sha256_hex: "jkl012".to_string(),
                plaintext_size: 4096,
            })
        }
    }

    #[tokio::test]
    async fn admin_can_export_backup() {
        let user_repo = StubUserRepo::default();
        let admin_id = Uuid::new_v4();
        user_repo.insert_user(admin_id, UserRole::Admin);

        let backup_service = StubBackupService;
        let app_service = BackupApplicationServiceImpl::new(user_repo, backup_service);

        let result = app_service
            .export_backup_secured(
                admin_id,
                std::path::Path::new("/tmp/db.db"),
                std::path::Path::new("/tmp/backup.hvb"),
                &secrecy::SecretString::new("recovery phrase".to_string().into()),
            )
            .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn non_admin_cannot_export_backup() {
        let user_repo = StubUserRepo::default();
        let user_id = Uuid::new_v4();
        user_repo.insert_user(user_id, UserRole::User);

        let backup_service = StubBackupService;
        let app_service = BackupApplicationServiceImpl::new(user_repo, backup_service);

        let result = app_service
            .export_backup_secured(
                user_id,
                std::path::Path::new("/tmp/db.db"),
                std::path::Path::new("/tmp/backup.hvb"),
                &secrecy::SecretString::new("recovery phrase".to_string().into()),
            )
            .await;

        assert!(matches!(result, Err(AppError::Authorization(_))));
    }

    #[tokio::test]
    async fn admin_can_restore_backup() {
        let user_repo = StubUserRepo::default();
        let admin_id = Uuid::new_v4();
        user_repo.insert_user(admin_id, UserRole::Admin);

        let backup_service = StubBackupService;
        let app_service = BackupApplicationServiceImpl::new(user_repo, backup_service);

        let result = app_service
            .restore_backup_secured(
                admin_id,
                std::path::Path::new("/tmp/backup.hvb"),
                &secrecy::SecretString::new("recovery phrase".to_string().into()),
                std::path::Path::new("/tmp/db_restored.db"),
            )
            .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn non_admin_cannot_restore_backup() {
        let user_repo = StubUserRepo::default();
        let user_id = Uuid::new_v4();
        user_repo.insert_user(user_id, UserRole::User);

        let backup_service = StubBackupService;
        let app_service = BackupApplicationServiceImpl::new(user_repo, backup_service);

        let result = app_service
            .restore_backup_secured(
                user_id,
                std::path::Path::new("/tmp/backup.hvb"),
                &secrecy::SecretString::new("recovery phrase".to_string().into()),
                std::path::Path::new("/tmp/db_restored.db"),
            )
            .await;

        assert!(matches!(result, Err(AppError::Authorization(_))));
    }

    #[tokio::test]
    async fn missing_user_returns_not_found() {
        let user_repo = StubUserRepo::default();
        let missing_id = Uuid::new_v4();

        let backup_service = StubBackupService;
        let app_service = BackupApplicationServiceImpl::new(user_repo, backup_service);

        let result = app_service
            .export_backup_secured(
                missing_id,
                std::path::Path::new("/tmp/db.db"),
                std::path::Path::new("/tmp/backup.hvb"),
                &secrecy::SecretString::new("recovery phrase".to_string().into()),
            )
            .await;

        assert!(matches!(result, Err(AppError::NotFound(_))));
    }

    #[tokio::test]
    async fn admin_can_export_rotation_backup_ticket() {
        let user_repo = StubUserRepo::default();
        let admin_id = Uuid::new_v4();
        user_repo.insert_user(admin_id, UserRole::Admin);

        let backup_service = StubBackupService;
        let app_service = BackupApplicationServiceImpl::new(user_repo, backup_service);

        let result = app_service
            .export_rotation_backup_secured(
                admin_id,
                std::path::Path::new("/tmp/db.db"),
                std::path::Path::new("/tmp/backup.hvb"),
            )
            .await;

        assert!(result.is_ok());
        let ticket = result.expect("rotation ticket should be returned");
        assert_eq!(ticket.backup_file_path, "/tmp/backup.hvb");
        assert_eq!(ticket.metadata_sha256_hex, "abc123");
    }

    #[tokio::test]
    async fn admin_can_restore_rotation_backup_ticket() {
        let user_repo = StubUserRepo::default();
        let admin_id = Uuid::new_v4();
        user_repo.insert_user(admin_id, UserRole::Admin);

        let backup_service = StubBackupService;
        let app_service = BackupApplicationServiceImpl::new(user_repo, backup_service);

        let ticket = app_service
            .export_rotation_backup_secured(
                admin_id,
                std::path::Path::new("/tmp/db.db"),
                std::path::Path::new("/tmp/backup.hvb"),
            )
            .await
            .expect("rotation backup export should succeed");

        let restore_result = app_service
            .restore_rotation_backup_secured(
                admin_id,
                &ticket,
                std::path::Path::new("/tmp/db_restored.db"),
            )
            .await;

        assert!(restore_result.is_ok());
    }
}