1
use std::{collections::HashMap, sync::Arc, time::Duration};
2

            
3
#[cfg(feature = "async-std")]
4
use async_lock::RwLock;
5
#[cfg(feature = "tokio")]
6
use tokio::sync::RwLock;
7

            
8
use crate::{AsAttributes, Result, Secret, dbus, file};
9

            
10
/// A [Secret Service](crate::dbus) or [file](crate::file) backed keyring
11
/// implementation.
12
///
13
/// It will automatically use the file backend if the application is sandboxed
14
/// and otherwise falls back to the DBus service using it [default
15
/// collection](crate::dbus::Service::default_collection).
16
///
17
/// The File backend requires a [`org.freedesktop.portal.Secret`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Secret.html) implementation
18
/// to retrieve the key that will be used to encrypt the backend file.
19
#[derive(Debug)]
20
pub enum Keyring {
21
    #[doc(hidden)]
22
    File(Arc<RwLock<Option<file::Keyring>>>, Secret),
23
    #[doc(hidden)]
24
    DBus(dbus::Collection),
25
}
26

            
27
2
fn require_unlocked_keyring(kg: &Option<file::Keyring>) -> Result<&file::UnlockedKeyring> {
28
2
    match kg.as_ref() {
29
2
        Some(file::Keyring::Unlocked(backend)) => Ok(backend),
30
2
        Some(file::Keyring::Locked(_)) => Err(file::Error::Locked.into()),
31
        None => unreachable!("A keyring must exist"),
32
    }
33
}
34

            
35
2
fn require_unlocked_item(item: &file::Item) -> Result<&file::UnlockedItem> {
36
2
    match item {
37
2
        file::Item::Unlocked(unlocked) => Ok(unlocked),
38
2
        file::Item::Locked(_) => Err(file::Error::Locked.into()),
39
    }
40
}
41

            
42
2
fn require_unlocked_item_mut(item: &mut file::Item) -> Result<&mut file::UnlockedItem> {
43
2
    match item {
44
2
        file::Item::Unlocked(unlocked) => Ok(unlocked),
45
2
        file::Item::Locked(_) => Err(file::Error::Locked.into()),
46
    }
47
}
48

            
49
impl Keyring {
50
    /// Create a new instance of the Keyring.
51
    ///
52
    /// Auto-detects whether the application is sandboxed and uses the
53
    /// appropriate backend (file backend for sandboxed apps, D-Bus service
54
    /// for host apps). Falls back to D-Bus if the secret portal is not
55
    /// available.
56
    pub async fn new() -> Result<Self> {
57
        if ashpd::is_sandboxed() {
58
            match Self::sandboxed().await {
59
                Ok(keyring) => Ok(keyring),
60
                // Fallback to host keyring if portal is not available
61
                Err(crate::Error::File(err))
62
                    if matches!(*err, file::Error::Portal(ashpd::Error::PortalNotFound(_))) =>
63
                {
64
                    #[cfg(feature = "tracing")]
65
                    tracing::debug!(
66
                        "org.freedesktop.portal.Secrets is not available, falling back to the Secret Service backend"
67
                    );
68
                    Self::host().await
69
                }
70
                Err(e) => Err(e),
71
            }
72
        } else {
73
            Self::host().await
74
        }
75
    }
76

            
77
    /// Use the file backend with secret portal (for sandboxed apps).
78
    pub async fn sandboxed() -> Result<Self> {
79
        #[cfg(feature = "tracing")]
80
        tracing::debug!("Using file backend (sandboxed mode)");
81

            
82
        let secret = Secret::sandboxed().await?;
83
        let path = crate::file::api::Keyring::default_path()?;
84
        Self::sandboxed_with_path(&path, secret).await
85
    }
86

            
87
    /// Use the file backend with a custom path.
88
    ///
89
    /// # Arguments
90
    /// * `path` - Path to the keyring file
91
    /// * `secret` - Secret to unlock the keyring (use `Secret::sandboxed()` or
92
    ///   `Secret::random()` for tests)
93
2
    pub async fn sandboxed_with_path(
94
        path: impl AsRef<std::path::Path>,
95
        secret: Secret,
96
    ) -> Result<Self> {
97
        #[cfg(feature = "tracing")]
98
        tracing::debug!("Using file backend with custom path");
99

            
100
10
        let file = file::UnlockedKeyring::load(path, Some(secret.clone())).await?;
101
5
        Ok(Self::File(
102
8
            Arc::new(RwLock::new(Some(file::Keyring::Unlocked(file)))),
103
3
            secret,
104
        ))
105
    }
106

            
107
    /// Variant of [`new`](Self::new) that skips existing items validation
108
    /// when using the file backend.
109
    ///
110
    /// See [`sandboxed_with_path_unchecked`](Self::sandboxed_with_path_unchecked)
111
    /// for details.
112
    pub async fn new_unchecked() -> Result<Self> {
113
        if ashpd::is_sandboxed() {
114
            match Self::sandboxed_unchecked().await {
115
                Ok(keyring) => Ok(keyring),
116
                Err(crate::Error::File(err))
117
                    if matches!(*err, file::Error::Portal(ashpd::Error::PortalNotFound(_))) =>
118
                {
119
                    #[cfg(feature = "tracing")]
120
                    tracing::debug!(
121
                        "org.freedesktop.portal.Secrets is not available, falling back to the Secret Service backend"
122
                    );
123
                    Self::host().await
124
                }
125
                Err(e) => Err(e),
126
            }
127
        } else {
128
            Self::host().await
129
        }
130
    }
131

            
132
    /// Variant of [`sandboxed`](Self::sandboxed) that skips existing items
133
    /// validation.
134
    ///
135
    /// See [`sandboxed_with_path_unchecked`](Self::sandboxed_with_path_unchecked)
136
    /// for details.
137
    pub async fn sandboxed_unchecked() -> Result<Self> {
138
        #[cfg(feature = "tracing")]
139
        tracing::debug!("Using file backend (sandboxed unchecked mode)");
140

            
141
        let secret = Secret::sandboxed().await?;
142
        let path = crate::file::api::Keyring::default_path()?;
143
        Self::sandboxed_with_path_unchecked(&path, secret).await
144
    }
145

            
146
    /// Variant of [`sandboxed_with_path`](Self::sandboxed_with_path) that does
147
    /// not verify that existing items can be decrypted with the provided
148
    /// secret.
149
    ///
150
    /// Items encrypted with a previous secret will fail to decrypt individually
151
    /// but won't prevent the keyring from being used. Use
152
    /// [`UnlockedKeyring::delete_broken_items`](file::UnlockedKeyring::delete_broken_items)
153
    /// to remove unreadable items.
154
    #[allow(unsafe_code)]
155
    pub async fn sandboxed_with_path_unchecked(
156
        path: impl AsRef<std::path::Path>,
157
        secret: Secret,
158
    ) -> Result<Self> {
159
        #[cfg(feature = "tracing")]
160
        tracing::debug!("Using file backend with custom path (unchecked mode)");
161

            
162
        // SAFETY: this is not truly unsafe in the memory-safety sense;
163
        // `load_unchecked` merely skips item validation.
164
        let file = unsafe { file::UnlockedKeyring::load_unchecked(path, secret.clone()).await? };
165
        Ok(Self::File(
166
            Arc::new(RwLock::new(Some(file::Keyring::Unlocked(file)))),
167
            secret,
168
        ))
169
    }
170

            
171
    /// Use the D-Bus Secret Service.
172
    pub async fn host() -> Result<Self> {
173
        #[cfg(feature = "tracing")]
174
        tracing::debug!("Using D-Bus Secret Service (host mode)");
175

            
176
        let service = dbus::Service::new().await?;
177
        let collection = service.default_collection().await?;
178
        Ok(Self::DBus(collection))
179
    }
180

            
181
    /// Use the D-Bus Secret Service with a custom connection.
182
21
    pub async fn host_with_connection(connection: zbus::Connection) -> Result<Self> {
183
        #[cfg(feature = "tracing")]
184
        tracing::debug!("Using D-Bus Secret Service with custom connection (test mode)");
185

            
186
11
        let service = dbus::Service::new_with_connection(&connection).await?;
187
15
        let collection = service.default_collection().await?;
188
6
        Ok(Self::DBus(collection))
189
    }
190

            
191
    /// Unlock the used collection.
192
8
    pub async fn unlock(&self) -> Result<()> {
193
2
        match self {
194
6
            Self::DBus(backend) => backend.unlock(None).await?,
195
2
            Self::File(keyring, secret) => {
196
4
                let mut kg = keyring.write().await;
197
4
                let kg_value = kg.take();
198
6
                if let Some(file::Keyring::Locked(locked)) = kg_value {
199
                    #[cfg(feature = "tracing")]
200
                    tracing::debug!("Unlocking file backend keyring");
201

            
202
4
                    let unlocked = locked.unlock(secret.clone()).await?;
203
2
                    *kg = Some(file::Keyring::Unlocked(unlocked));
204
                } else {
205
2
                    *kg = kg_value;
206
                }
207
            }
208
        };
209
2
        Ok(())
210
    }
211

            
212
    /// Lock the used collection.
213
8
    pub async fn lock(&self) -> Result<()> {
214
2
        match self {
215
6
            Self::DBus(backend) => backend.lock(None).await?,
216
2
            Self::File(keyring, _) => {
217
4
                let mut kg = keyring.write().await;
218
4
                let kg_value = kg.take();
219
6
                if let Some(file::Keyring::Unlocked(unlocked)) = kg_value {
220
                    #[cfg(feature = "tracing")]
221
                    tracing::debug!("Locking file backend keyring");
222

            
223
2
                    let locked = unlocked.lock();
224
2
                    *kg = Some(file::Keyring::Locked(locked));
225
                } else {
226
2
                    *kg = kg_value;
227
                }
228
            }
229
        };
230
2
        Ok(())
231
    }
232

            
233
    /// Whether the keyring is locked or not.
234
8
    pub async fn is_locked(&self) -> Result<bool> {
235
2
        match self {
236
6
            Self::DBus(collection) => collection.is_locked().await.map_err(From::from),
237
2
            Self::File(keyring, _) => {
238
4
                let keyring_guard = keyring.read().await;
239
4
                Ok(keyring_guard
240
2
                    .as_ref()
241
2
                    .expect("Keyring must exist")
242
2
                    .is_locked())
243
            }
244
        }
245
    }
246

            
247
    /// Remove items that matches the attributes.
248
37
    pub async fn delete(&self, attributes: &impl AsAttributes) -> Result<()> {
249
6
        match self {
250
6
            Self::DBus(backend) => {
251
18
                let items = backend.search_items(attributes).await?;
252
24
                for item in items {
253
30
                    item.delete(None).await?;
254
                }
255
            }
256
6
            Self::File(keyring, _) => {
257
12
                let kg = keyring.read().await;
258
14
                let backend = require_unlocked_keyring(&kg)?;
259
14
                backend.delete(attributes).await?;
260
            }
261
        };
262
7
        Ok(())
263
    }
264

            
265
    /// Retrieve all the items.
266
8
    pub async fn items(&self) -> Result<Vec<Item>> {
267
2
        let items = match self {
268
2
            Self::DBus(backend) => {
269
6
                let items = backend.items().await?;
270
5
                items.into_iter().map(Item::for_dbus).collect::<Vec<_>>()
271
            }
272
2
            Self::File(keyring, _) => {
273
4
                let kg = keyring.read().await;
274
6
                let backend = require_unlocked_keyring(&kg)?;
275
4
                let items = backend.items().await?;
276
2
                items
277
                    .into_iter()
278
6
                    .map(|i| Item::for_file(i.into(), Arc::clone(keyring)))
279
                    .collect::<Vec<_>>()
280
            }
281
        };
282
2
        Ok(items)
283
    }
284

            
285
    /// Create a new item.
286
7
    pub async fn create_item(
287
        &self,
288
        label: &str,
289
        attributes: &impl AsAttributes,
290
        secret: impl Into<Secret>,
291
        replace: bool,
292
    ) -> Result<()> {
293
8
        match self {
294
8
            Self::DBus(backend) => {
295
22
                backend
296
8
                    .create_item(label, attributes, secret, replace, None)
297
38
                    .await?;
298
            }
299
8
            Self::File(keyring, _) => {
300
16
                let kg = keyring.read().await;
301
18
                let backend = require_unlocked_keyring(&kg)?;
302
20
                backend
303
8
                    .create_item(label, attributes, secret, replace)
304
35
                    .await?;
305
            }
306
        };
307
6
        Ok(())
308
    }
309

            
310
    /// Find items based on their attributes.
311
24
    pub async fn search_items(&self, attributes: &impl AsAttributes) -> Result<Vec<Item>> {
312
6
        let items = match self {
313
6
            Self::DBus(backend) => {
314
18
                let items = backend.search_items(attributes).await?;
315
12
                items.into_iter().map(Item::for_dbus).collect::<Vec<_>>()
316
            }
317
6
            Self::File(keyring, _) => {
318
12
                let kg = keyring.read().await;
319
14
                let backend = require_unlocked_keyring(&kg)?;
320
12
                let items = backend.search_items(attributes).await?;
321
6
                items
322
                    .into_iter()
323
18
                    .map(|i| Item::for_file(i.into(), Arc::clone(keyring)))
324
                    .collect::<Vec<_>>()
325
            }
326
        };
327
6
        Ok(items)
328
    }
329
}
330

            
331
/// A generic secret with a label and attributes.
332
#[derive(Debug)]
333
pub enum Item {
334
    #[doc(hidden)]
335
    File(
336
        RwLock<Option<file::Item>>,
337
        Arc<RwLock<Option<file::Keyring>>>,
338
    ),
339
    #[doc(hidden)]
340
    DBus(dbus::Item),
341
}
342

            
343
impl Item {
344
2
    fn for_file(item: file::Item, backend: Arc<RwLock<Option<file::Keyring>>>) -> Self {
345
4
        Self::File(RwLock::new(Some(item)), backend)
346
    }
347

            
348
3
    fn for_dbus(item: dbus::Item) -> Self {
349
3
        Self::DBus(item)
350
    }
351

            
352
    /// The item label.
353
10
    pub async fn label(&self) -> Result<String> {
354
2
        let label = match self {
355
2
            Self::File(item, _) => {
356
4
                let item_guard = item.read().await;
357
4
                let file_item = item_guard.as_ref().expect("Item must exist");
358
2
                require_unlocked_item(file_item)?.label().to_owned()
359
            }
360
6
            Self::DBus(item) => item.label().await?,
361
        };
362
2
        Ok(label)
363
    }
364

            
365
    /// Sets the item label.
366
12
    pub async fn set_label(&self, label: &str) -> Result<()> {
367
2
        match self {
368
2
            Self::File(item, keyring) => {
369
4
                let mut item_guard = item.write().await;
370
4
                let file_item = item_guard.as_mut().expect("Item must exist");
371
4
                let unlocked = require_unlocked_item_mut(file_item)?;
372
2
                unlocked.set_label(label);
373

            
374
2
                let kg = keyring.read().await;
375
6
                let backend = require_unlocked_keyring(&kg)?;
376
6
                backend
377
                    .create_item(
378
2
                        unlocked.label(),
379
2
                        &unlocked.attributes(),
380
2
                        unlocked.secret(),
381
                        true,
382
                    )
383
10
                    .await?;
384
            }
385
6
            Self::DBus(item) => item.set_label(label).await?,
386
        };
387
2
        Ok(())
388
    }
389

            
390
    /// Retrieve the item attributes.
391
10
    pub async fn attributes(&self) -> Result<HashMap<String, String>> {
392
2
        let attributes = match self {
393
2
            Self::File(item, _) => {
394
4
                let item_guard = item.read().await;
395
4
                let file_item = item_guard.as_ref().expect("Item must exist");
396
2
                require_unlocked_item(file_item)?
397
                    .attributes()
398
                    .iter()
399
6
                    .map(|(k, v)| (k.to_owned(), v.to_string()))
400
                    .collect::<HashMap<_, _>>()
401
            }
402
6
            Self::DBus(item) => item.attributes().await?,
403
        };
404
2
        Ok(attributes)
405
    }
406

            
407
    /// Retrieve the item attributes as a typed schema.
408
    ///
409
    /// # Example
410
    ///
411
    /// ```no_run
412
    /// # use oo7::{SecretSchema, Item};
413
    /// # #[derive(SecretSchema, Debug)]
414
    /// # #[schema(name = "org.example.Password")]
415
    /// # struct PasswordSchema {
416
    /// #     username: String,
417
    /// #     server: String,
418
    /// # }
419
    /// # async fn example(item: &Item) -> Result<(), oo7::Error> {
420
    /// let schema = item.attributes_as::<PasswordSchema>().await?;
421
    /// println!("Username: {}", schema.username);
422
    /// # Ok(())
423
    /// # }
424
    /// ```
425
    #[cfg(feature = "schema")]
426
    #[cfg_attr(docsrs, doc(cfg(feature = "schema")))]
427
4
    pub async fn attributes_as<T>(&self) -> Result<T>
428
    where
429
        T: for<'a> std::convert::TryFrom<&'a HashMap<String, String>, Error = crate::SchemaError>,
430
    {
431
2
        match self {
432
4
            Self::File(..) => T::try_from(&self.attributes().await?)
433
2
                .map_err(crate::file::Error::Schema)
434
2
                .map_err(Into::into),
435
4
            Self::DBus(_) => T::try_from(&self.attributes().await?)
436
2
                .map_err(crate::dbus::Error::Schema)
437
2
                .map_err(Into::into),
438
        }
439
    }
440

            
441
    /// Sets the item attributes.
442
24
    pub async fn set_attributes(&self, attributes: &impl AsAttributes) -> Result<()> {
443
4
        match self {
444
4
            Self::File(item, keyring) => {
445
8
                let kg = keyring.read().await;
446
10
                let backend = require_unlocked_keyring(&kg)?;
447

            
448
4
                let mut item_guard = item.write().await;
449
8
                let file_item = item_guard.as_mut().expect("Item must exist");
450
6
                let unlocked = require_unlocked_item_mut(file_item)?;
451

            
452
2
                let index = backend.lookup_item_index(&unlocked.attributes()).await?;
453

            
454
2
                unlocked.set_attributes(attributes);
455

            
456
4
                if let Some(index) = index {
457
6
                    backend.replace_item_index(index, unlocked).await?;
458
                } else {
459
8
                    backend
460
4
                        .create_item(unlocked.label(), attributes, unlocked.secret(), true)
461
10
                        .await?;
462
                }
463
            }
464
12
            Self::DBus(item) => item.set_attributes(attributes).await?,
465
        };
466
2
        Ok(())
467
    }
468

            
469
    /// Sets a new secret.
470
12
    pub async fn set_secret(&self, secret: impl Into<Secret>) -> Result<()> {
471
2
        match self {
472
2
            Self::File(item, keyring) => {
473
4
                let mut item_guard = item.write().await;
474
4
                let file_item = item_guard.as_mut().expect("Item must exist");
475
4
                let unlocked = require_unlocked_item_mut(file_item)?;
476
2
                unlocked.set_secret(secret);
477

            
478
2
                let kg = keyring.read().await;
479
6
                let backend = require_unlocked_keyring(&kg)?;
480
6
                backend
481
                    .create_item(
482
2
                        unlocked.label(),
483
2
                        &unlocked.attributes(),
484
2
                        unlocked.secret(),
485
                        true,
486
                    )
487
10
                    .await?;
488
            }
489
8
            Self::DBus(item) => item.set_secret(secret).await?,
490
        };
491
2
        Ok(())
492
    }
493

            
494
    /// Retrieves the stored secret.
495
10
    pub async fn secret(&self) -> Result<Secret> {
496
2
        let secret = match self {
497
2
            Self::File(item, _) => {
498
4
                let item_guard = item.read().await;
499
4
                let file_item = item_guard.as_ref().expect("Item must exist");
500
2
                require_unlocked_item(file_item)?.secret()
501
            }
502
6
            Self::DBus(item) => item.secret().await?,
503
        };
504
2
        Ok(secret)
505
    }
506

            
507
    /// Whether the item is locked or not
508
11
    pub async fn is_locked(&self) -> Result<bool> {
509
3
        match self {
510
6
            Self::DBus(item) => item.is_locked().await.map_err(From::from),
511
3
            Self::File(item, _) => {
512
6
                let item_guard = item.read().await;
513
6
                let file_item = item_guard.as_ref().expect("Item must exist");
514
3
                Ok(file_item.is_locked())
515
            }
516
        }
517
    }
518

            
519
    /// Lock the item
520
8
    pub async fn lock(&self) -> Result<()> {
521
2
        match self {
522
8
            Self::DBus(item) => item.lock(None).await?,
523
2
            Self::File(item, keyring) => {
524
4
                let mut item_guard = item.write().await;
525
4
                let item_value = item_guard.take();
526
6
                if let Some(file::Item::Unlocked(unlocked)) = item_value {
527
4
                    let kg = keyring.read().await;
528
4
                    match require_unlocked_keyring(&kg) {
529
2
                        Ok(backend) => {
530
4
                            let locked = backend.lock_item(unlocked).await?;
531
2
                            *item_guard = Some(file::Item::Locked(locked));
532
                        }
533
2
                        Err(e) => {
534
2
                            *item_guard = Some(file::Item::Unlocked(unlocked));
535
2
                            return Err(e);
536
                        }
537
                    }
538
                } else {
539
2
                    *item_guard = item_value;
540
                }
541
            }
542
        }
543
2
        Ok(())
544
    }
545

            
546
    /// Unlock the item
547
8
    pub async fn unlock(&self) -> Result<()> {
548
2
        match self {
549
6
            Self::DBus(item) => item.unlock(None).await?,
550
2
            Self::File(item, keyring) => {
551
4
                let mut item_guard = item.write().await;
552
4
                let item_value = item_guard.take();
553
6
                if let Some(file::Item::Locked(locked)) = item_value {
554
4
                    let kg = keyring.read().await;
555
4
                    match require_unlocked_keyring(&kg) {
556
2
                        Ok(backend) => {
557
4
                            let unlocked = backend.unlock_item(locked).await?;
558
2
                            *item_guard = Some(file::Item::Unlocked(unlocked));
559
                        }
560
                        Err(e) => {
561
                            *item_guard = Some(file::Item::Locked(locked));
562
                            return Err(e);
563
                        }
564
                    }
565
                } else {
566
2
                    *item_guard = item_value;
567
                }
568
            }
569
        }
570
2
        Ok(())
571
    }
572

            
573
    /// Delete the item.
574
12
    pub async fn delete(&self) -> Result<()> {
575
2
        match self {
576
2
            Self::File(item, keyring) => {
577
4
                let item_guard = item.read().await;
578
4
                let file_item = item_guard.as_ref().expect("Item must exist");
579
2
                let unlocked = require_unlocked_item(file_item)?;
580

            
581
2
                let kg = keyring.read().await;
582
6
                let backend = require_unlocked_keyring(&kg)?;
583
4
                backend.delete(&unlocked.attributes()).await?;
584
            }
585
2
            Self::DBus(item) => {
586
6
                item.delete(None).await?;
587
            }
588
        };
589
2
        Ok(())
590
    }
591

            
592
    /// The UNIX time when the item was created.
593
8
    pub async fn created(&self) -> Result<Duration> {
594
2
        match self {
595
8
            Self::DBus(item) => Ok(item.created().await?),
596
2
            Self::File(item, _) => {
597
4
                let item_guard = item.read().await;
598
4
                let file_item = item_guard.as_ref().expect("Item must exist");
599
2
                Ok(require_unlocked_item(file_item)?.created())
600
            }
601
        }
602
    }
603

            
604
    /// The UNIX time when the item was modified.
605
8
    pub async fn modified(&self) -> Result<Duration> {
606
2
        match self {
607
8
            Self::DBus(item) => Ok(item.modified().await?),
608
2
            Self::File(item, _) => {
609
4
                let item_guard = item.read().await;
610
4
                let file_item = item_guard.as_ref().expect("Item must exist");
611
2
                Ok(require_unlocked_item(file_item)?.modified())
612
            }
613
        }
614
    }
615
}