1
#[cfg(feature = "async-std")]
2
use std::io;
3
use std::{
4
    path::{Path, PathBuf},
5
    sync::Arc,
6
};
7

            
8
#[cfg(feature = "async-std")]
9
use async_fs as fs;
10
#[cfg(feature = "async-std")]
11
use async_lock::{Mutex, RwLock};
12
#[cfg(feature = "async-std")]
13
use futures_lite::AsyncReadExt;
14
#[cfg(feature = "tokio")]
15
use tokio::{
16
    fs,
17
    io::{self, AsyncReadExt},
18
    sync::{Mutex, RwLock},
19
};
20

            
21
use super::{Error, LockedItem, UnlockedKeyring, api};
22
use crate::{Key, Secret};
23

            
24
/// A locked keyring that requires a secret to unlock.
25
#[derive(Debug)]
26
pub struct LockedKeyring {
27
    pub(super) keyring: Arc<RwLock<api::Keyring>>,
28
    pub(super) path: Option<PathBuf>,
29
    pub(super) mtime: Mutex<Option<std::time::SystemTime>>,
30
}
31

            
32
impl LockedKeyring {
33
    /// Validate that a secret can decrypt the items in this keyring.
34
    ///
35
    /// For empty keyrings, this always returns `true` since there are no items
36
    /// to validate against.
37
    ///
38
    /// # Arguments
39
    ///
40
    /// * `secret` - The secret to validate.
41
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self, secret)))]
42
32
    pub async fn validate_secret(&self, secret: &Secret) -> Result<bool, Error> {
43
20
        let keyring = self.keyring.read().await;
44
16
        Ok(keyring.validate_secret(secret)?)
45
    }
46

            
47
    /// Validate that an already-derived key can decrypt at least one item in
48
    /// this keyring.
49
    ///
50
    /// Empty keyrings return `true` because they contain no item with which to
51
    /// authenticate the key. Callers that persist keys for empty keyrings must
52
    /// bind them to the exact keyring file separately.
53
    ///
54
    /// A partially corrupted keyring may return `true` here but still fail
55
    /// [`Self::unlock_with_key`] when broken items outnumber valid items.
56
8
    pub async fn validate_key(&self, key: &Key) -> Result<bool, Error> {
57
6
        key.validate_file_key()?;
58
3
        let keyring = self.keyring.read().await;
59
4
        Ok(keyring.validate_key(key))
60
    }
61

            
62
    pub async fn validate_unencrypted(&self) -> Result<bool, Error> {
63
        let keyring = self.keyring.read().await;
64
        Ok(keyring.validate_unencrypted())
65
    }
66

            
67
    /// Return the associated file if any.
68
4
    pub fn path(&self) -> Option<&std::path::Path> {
69
4
        self.path.as_deref()
70
    }
71

            
72
    /// Get the modification timestamp
73
16
    pub async fn modified_time(&self) -> std::time::Duration {
74
10
        self.keyring.read().await.modified_time()
75
    }
76

            
77
    /// Retrieve the list of available [`LockedItem`]s without decrypting them.
78
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
79
16
    pub async fn items(&self) -> Result<Vec<LockedItem>, Error> {
80
10
        let keyring = self.keyring.read().await;
81

            
82
12
        Ok(keyring
83
            .items
84
4
            .iter()
85
12
            .map(|encrypted_item| LockedItem {
86
4
                inner: encrypted_item.clone(),
87
            })
88
4
            .collect())
89
    }
90

            
91
    /// Unlocks a keyring and validates it
92
73
    pub async fn unlock(self, secret: Secret) -> Result<UnlockedKeyring, Error> {
93
47
        self.try_unlock(secret).await
94
    }
95

            
96
    /// Unlocks a keyring and validates it
97
    ///
98
    /// The keyring is left untouched when the secret does not decrypt it,
99
    /// unlike [`Self::unlock`] which consumes it.
100
78
    pub async fn try_unlock(&self, secret: Secret) -> Result<UnlockedKeyring, Error> {
101
49
        self.unlock_inner(secret, true).await
102
    }
103

            
104
    /// Unlocks a keyring with an already-derived key and validates it.
105
    ///
106
    /// An exact-length [`Key::new`] value is treated as direct key material and
107
    /// may be used for subsequent writes. The caller is responsible for
108
    /// supplying a key with sufficient entropy.
109
    ///
110
    /// Empty keyrings cannot authenticate the key and therefore accept any key
111
    /// of the required length, matching [`Self::validate_key`].
112
8
    pub async fn unlock_with_key(self, key: Key) -> Result<UnlockedKeyring, Error> {
113
6
        let key = key.into_file_key()?;
114
        let validation = {
115
5
            let inner_keyring = self.keyring.read().await;
116
4
            inner_keyring.validate_items(&key)
117
        };
118
        #[cfg(feature = "tracing")]
119
        Self::log_validation_error(&validation, false);
120
2
        validation?;
121

            
122
3
        Ok(self.to_unlocked(Some(Arc::new(key)), None).await)
123
    }
124

            
125
    /// Unlocks a keyring without validating it
126
    ///
127
    /// # Safety
128
    ///
129
    /// This method skips validation and doesn't verify that the secret can
130
    /// decrypt all items in the keyring. Use only for recovery scenarios where
131
    /// you need to access a partially corrupted keyring. The keyring may
132
    /// contain items that cannot be decrypted with the provided secret.
133
    #[allow(unsafe_code)]
134
11
    pub async unsafe fn unlock_unchecked(self, secret: Secret) -> Result<UnlockedKeyring, Error> {
135
8
        self.unlock_inner(secret, false).await
136
    }
137

            
138
20
    async fn unlock_inner(
139
        &self,
140
        secret: Secret,
141
        validate_items: bool,
142
    ) -> Result<UnlockedKeyring, Error> {
143
21
        let key = if validate_items {
144
50
            let inner_keyring = self.keyring.read().await;
145

            
146
39
            let key = inner_keyring.derive_key(&secret)?;
147
36
            let validation = inner_keyring.validate_items(&key);
148
            #[cfg(feature = "tracing")]
149
            Self::log_validation_error(&validation, true);
150
16
            validation?;
151

            
152
13
            Some(Arc::new(key))
153
        } else {
154
3
            None
155
        };
156

            
157
22
        Ok(self.to_unlocked(key, Some(Arc::new(secret))).await)
158
    }
159

            
160
    #[cfg(feature = "tracing")]
161
16
    fn log_validation_error(validation: &Result<(), Error>, source_secret: bool) {
162
18
        match validation {
163
8
            Err(Error::IncorrectSecret) if source_secret => {
164
20
                tracing::error!("Keyring cannot be decrypted. Invalid secret.");
165
            }
166
            Err(Error::IncorrectSecret) => {
167
4
                tracing::error!("Keyring cannot be decrypted. Invalid key material.");
168
            }
169
2
            Err(Error::PartiallyCorruptedKeyring {
170
                valid_items,
171
                broken_items,
172
            }) => {
173
4
                tracing::warn!(
174
                    "The file contains {broken_items} broken items and {valid_items} valid ones."
175
                );
176
2
                if source_secret {
177
4
                    tracing::info!(
178
                        "Please switch to `UnlockedKeyring::load_unchecked` to load the keyring without the secret validation.
179
                        `Keyring::delete_broken_items` can be used to remove them or alternatively with `oo7-cli --repair`."
180
                    );
181
                } else {
182
4
                    tracing::info!(
183
                        "Recover the keyring with its source secret; key-based unlock does not bypass validation."
184
                    );
185
                }
186
            }
187
            _ => {}
188
        }
189
    }
190

            
191
    /// An unlocked handle on the same keyring data.
192
15
    async fn to_unlocked(
193
        &self,
194
        key: Option<Arc<Key>>,
195
        secret: Option<Arc<Secret>>,
196
    ) -> UnlockedKeyring {
197
        UnlockedKeyring {
198
32
            keyring: Arc::clone(&self.keyring),
199
32
            path: self.path.clone(),
200
60
            mtime: Mutex::new(*self.mtime.lock().await),
201
18
            key: Mutex::new(key),
202
20
            secret: Mutex::new(secret),
203
        }
204
    }
205

            
206
    /// Unlocks a keyring without a secret, for unencrypted keyrings.
207
    ///
208
    /// Validates that existing items (if any) can be read without
209
    /// encryption. Returns [`Error::IncorrectSecret`] if encrypted items
210
    /// are found.
211
16
    pub async fn unlock_unencrypted(self) -> Result<UnlockedKeyring, Error> {
212
10
        self.try_unlock_unencrypted().await
213
    }
214

            
215
    /// Unlocks a keyring without a secret, for unencrypted keyrings.
216
    ///
217
    /// The keyring is left untouched when it holds encrypted items,
218
    /// unlike [`Self::unlock_unencrypted`] which consumes it.
219
32
    pub async fn try_unlock_unencrypted(&self) -> Result<UnlockedKeyring, Error> {
220
20
        let inner_keyring = self.keyring.read().await;
221
16
        for encrypted_item in &inner_keyring.items {
222
16
            if !encrypted_item.is_valid(None) {
223
2
                return Err(Error::IncorrectSecret);
224
            }
225
        }
226
8
        drop(inner_keyring);
227

            
228
12
        Ok(self.to_unlocked(None, None).await)
229
    }
230

            
231
    /// Load a keyring from a file path.
232
136
    pub async fn load(path: impl AsRef<Path>) -> Result<Self, Error> {
233
52
        let path = path.as_ref();
234
105
        let (mtime, keyring) = match fs::File::open(&path).await {
235
50
            Err(err) if err.kind() == io::ErrorKind::NotFound => {
236
                #[cfg(feature = "tracing")]
237
                tracing::debug!("Keyring file not found, creating a new one");
238
32
                (None, api::Keyring::new()?)
239
            }
240
            Err(err) => return Err(err.into()),
241
16
            Ok(mut file) => {
242
                #[cfg(feature = "tracing")]
243
                tracing::debug!("Keyring file found, loading its content");
244
52
                let metadata = file.metadata().await?;
245
16
                let mtime = metadata.modified().ok();
246

            
247
16
                let mut content = Vec::with_capacity(metadata.len() as usize);
248
69
                file.read_to_end(&mut content).await?;
249

            
250
21
                let keyring = api::Keyring::try_from(content.as_slice())?;
251

            
252
19
                (mtime, keyring)
253
            }
254
        };
255

            
256
23
        Ok(Self {
257
50
            keyring: Arc::new(RwLock::new(keyring)),
258
50
            path: Some(path.to_path_buf()),
259
27
            mtime: Mutex::new(mtime),
260
        })
261
    }
262

            
263
    /// Open a named keyring.
264
    pub async fn open(name: &str) -> Result<Self, Error> {
265
        let v1_path = api::Keyring::path(name, api::MAJOR_VERSION)?;
266
        Self::load(v1_path).await
267
    }
268

            
269
    /// Open a locked keyring at a specific data directory.
270
    ///
271
    /// This is useful for tests and cases where you want explicit control over
272
    /// where keyrings are stored, avoiding the default XDG_DATA_HOME location.
273
    ///
274
    /// # Arguments
275
    ///
276
    /// * `data_dir` - Base data directory (keyrings stored in
277
    ///   `data_dir/keyrings/v1/`)
278
    /// * `name` - The name of the keyring.
279
    #[cfg_attr(feature = "tracing", tracing::instrument(fields(data_dir = ?data_dir.as_ref())))]
280
20
    pub async fn open_at(data_dir: impl AsRef<std::path::Path>, name: &str) -> Result<Self, Error> {
281
4
        let path = api::Keyring::path_at(data_dir, name, api::MAJOR_VERSION);
282
8
        Self::load(path).await
283
    }
284
}