1
use std::{collections::HashMap, str::FromStr, time::Duration};
2

            
3
use serde::{Deserialize, Serialize};
4
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
5

            
6
use super::{
7
    Error, LockedItem,
8
    api::{EncryptedItem, GVARIANT_ENCODING},
9
};
10
use crate::{
11
    AsAttributes, CONTENT_TYPE_ATTRIBUTE, GENERIC_SCHEMA, Key, Mac, Secret, XDG_SCHEMA_ATTRIBUTE,
12
    crypto, secret::ContentType,
13
};
14

            
15
/// An item stored in the file backend.
16
#[derive(
17
    Deserialize, Serialize, zgvariant::Type, Clone, Debug, Zeroize, ZeroizeOnDrop, PartialEq,
18
)]
19
pub struct UnlockedItem {
20
    #[zeroize(skip)]
21
    attributes: HashMap<String, String>,
22
    #[zeroize(skip)]
23
    label: String,
24
    #[zeroize(skip)]
25
    created: u64,
26
    #[zeroize(skip)]
27
    modified: u64,
28
    #[serde(with = "serde_bytes")]
29
    secret: Vec<u8>,
30
}
31

            
32
impl UnlockedItem {
33
80
    pub(crate) fn new(
34
        label: impl ToString,
35
        attributes: &impl AsAttributes,
36
        secret: impl Into<Secret>,
37
    ) -> Self {
38
172
        let now = std::time::SystemTime::UNIX_EPOCH
39
            .elapsed()
40
            .unwrap()
41
            .as_secs();
42

            
43
80
        let mut item_attributes = attributes.as_attributes();
44

            
45
80
        let secret = secret.into();
46
        // Set default MIME type if not provided
47
159
        if !item_attributes.contains_key(CONTENT_TYPE_ATTRIBUTE) {
48
65
            item_attributes.insert(
49
127
                CONTENT_TYPE_ATTRIBUTE.to_owned(),
50
128
                secret.content_type().as_str().to_string(),
51
            );
52
        }
53

            
54
        Self {
55
            attributes: item_attributes,
56
82
            label: label.to_string(),
57
            created: now,
58
            modified: now,
59
162
            secret: secret.as_bytes().to_vec(),
60
        }
61
    }
62

            
63
    /// Retrieve the item attributes.
64
21
    pub fn attributes(&self) -> &HashMap<String, String> {
65
20
        &self.attributes
66
    }
67

            
68
    /// Check whether the attribute maps match.
69
8
    pub fn matches_exact(&self, attributes: &impl AsAttributes) -> bool {
70
        // The secret's content type does not identify the item.
71
8
        let requested = attributes.as_search_attributes();
72
16
        let mut count = self.attributes.len()
73
8
            - usize::from(self.attributes.contains_key(CONTENT_TYPE_ATTRIBUTE));
74
        // Items without a schema are implicitly generic
75
22
        let implicit_schema = !self.attributes.contains_key(XDG_SCHEMA_ATTRIBUTE)
76
16
            && requested.get(XDG_SCHEMA_ATTRIBUTE).map(String::as_str) == Some(GENERIC_SCHEMA);
77
12
        if implicit_schema {
78
4
            count += 1;
79
        }
80
16
        count == requested.len()
81
32
            && requested.iter().all(|(key, value)| {
82
12
                (implicit_schema && key == XDG_SCHEMA_ATTRIBUTE)
83
8
                    || self.attributes.get(key) == Some(value)
84
            })
85
    }
86

            
87
    /// Retrieve the item attributes as a typed schema.
88
    ///
89
    /// # Example
90
    ///
91
    /// ```no_run
92
    /// # use oo7::{SecretSchema, file::UnlockedItem};
93
    /// # #[derive(SecretSchema, Debug)]
94
    /// # #[schema(name = "org.example.Password")]
95
    /// # struct PasswordSchema {
96
    /// #     username: String,
97
    /// #     server: String,
98
    /// # }
99
    /// # fn example(item: &UnlockedItem) -> Result<(), oo7::file::Error> {
100
    /// let schema = item.attributes_as::<PasswordSchema>()?;
101
    /// println!("Username: {}", schema.username);
102
    /// # Ok(())
103
    /// # }
104
    /// ```
105
    #[cfg(feature = "schema")]
106
    #[cfg_attr(docsrs, doc(cfg(feature = "schema")))]
107
1
    pub fn attributes_as<T>(&self) -> Result<T, Error>
108
    where
109
        T: for<'a> std::convert::TryFrom<&'a HashMap<String, String>, Error = crate::SchemaError>,
110
    {
111
1
        T::try_from(&self.attributes).map_err(Into::into)
112
    }
113

            
114
    /// Update the item attributes.
115
13
    pub fn set_attributes(&mut self, attributes: &impl AsAttributes) {
116
13
        let mut new_attributes = attributes.as_attributes();
117

            
118
        // Preserve MIME type if not explicitly set in new attributes
119
26
        if !new_attributes.contains_key(CONTENT_TYPE_ATTRIBUTE) {
120
26
            if let Some(existing_mime_type) = self.attributes.get(CONTENT_TYPE_ATTRIBUTE) {
121
13
                new_attributes.insert(
122
26
                    CONTENT_TYPE_ATTRIBUTE.to_string(),
123
13
                    existing_mime_type.clone(),
124
                );
125
            } else {
126
                new_attributes.insert(
127
                    CONTENT_TYPE_ATTRIBUTE.to_owned(),
128
                    ContentType::default().as_str().to_string(),
129
                );
130
            }
131
        }
132

            
133
13
        self.attributes = new_attributes;
134
26
        self.modified = std::time::SystemTime::UNIX_EPOCH
135
13
            .elapsed()
136
13
            .unwrap()
137
13
            .as_secs();
138
    }
139

            
140
    /// The item label.
141
23
    pub fn label(&self) -> &str {
142
21
        &self.label
143
    }
144

            
145
    /// Set the item label.
146
12
    pub fn set_label(&mut self, label: impl ToString) {
147
12
        self.modified = std::time::SystemTime::UNIX_EPOCH
148
12
            .elapsed()
149
12
            .unwrap()
150
12
            .as_secs();
151
12
        self.label = label.to_string();
152
    }
153

            
154
    /// Retrieve the currently stored secret.
155
20
    pub fn secret(&self) -> Secret {
156
21
        let content_type = self
157
            .attributes
158
20
            .get(CONTENT_TYPE_ATTRIBUTE)
159
59
            .and_then(|c| ContentType::from_str(c).ok())
160
            .unwrap_or_default();
161

            
162
19
        Secret::with_content_type(content_type, &self.secret)
163
    }
164

            
165
    /// Store a new secret.
166
20
    pub fn set_secret(&mut self, secret: impl Into<Secret>) {
167
53
        self.modified = std::time::SystemTime::UNIX_EPOCH
168
21
            .elapsed()
169
21
            .unwrap()
170
21
            .as_secs();
171
21
        self.secret = secret.into().as_bytes().to_vec();
172
    }
173

            
174
    /// The UNIX time when the item was created.
175
20
    pub const fn created(&self) -> Duration {
176
20
        Duration::from_secs(self.created)
177
    }
178

            
179
    /// The UNIX time when the item was modified.
180
17
    pub const fn modified(&self) -> Duration {
181
17
        Duration::from_secs(self.modified)
182
    }
183

            
184
    /// Lock the item with the given key.
185
8
    pub fn lock(self, key: Option<&Key>) -> Result<LockedItem, Error> {
186
16
        let inner = self.encrypt(key)?;
187
8
        Ok(LockedItem { inner })
188
    }
189

            
190
33
    pub(crate) fn encrypt(&self, key: Option<&Key>) -> Result<EncryptedItem, Error> {
191
32
        match key {
192
27
            Some(key) => {
193
26
                key.check_strength()?;
194
27
                let iv = crypto::generate_iv()?;
195
51
                self.encrypt_encrypted(key, &iv)
196
            }
197
14
            None => self.encrypt_plaintext(),
198
        }
199
    }
200

            
201
14
    fn encrypt_plaintext(&self) -> Result<EncryptedItem, Error> {
202
11
        let blob = zgvariant::to_bytes(*GVARIANT_ENCODING, &self)?.to_vec();
203
11
        Ok(EncryptedItem {
204
13
            hashed_attributes: self
205
                .attributes
206
11
                .iter()
207
37
                .map(|(k, v)| (k.to_owned(), Mac::new(v.as_bytes().to_vec())))
208
11
                .collect(),
209
13
            blob,
210
        })
211
    }
212

            
213
26
    fn encrypt_encrypted(&self, key: &Key, iv: &[u8]) -> Result<EncryptedItem, Error> {
214
28
        let decrypted = Zeroizing::new(zgvariant::to_bytes(*GVARIANT_ENCODING, &self)?.to_vec());
215

            
216
27
        let mut blob = crypto::encrypt(&*decrypted, key, iv)?;
217

            
218
26
        blob.extend_from_slice(iv);
219
25
        let mac = crypto::compute_mac(&blob, key)?;
220
51
        blob.extend_from_slice(mac.as_slice());
221

            
222
28
        let hashed_attributes = self
223
            .attributes
224
            .iter()
225
76
            .filter_map(|(k, v)| Some((k.to_owned(), crypto::compute_mac(v.as_bytes(), key).ok()?)))
226
            .collect();
227

            
228
22
        Ok(EncryptedItem {
229
            hashed_attributes,
230
29
            blob,
231
        })
232
    }
233
}
234

            
235
impl TryFrom<&[u8]> for UnlockedItem {
236
    type Error = Error;
237

            
238
21
    fn try_from(value: &[u8]) -> Result<Self, Error> {
239
44
        let mut item: UnlockedItem = zgvariant::serialized::Data::new(value, *GVARIANT_ENCODING)
240
23
            .deserialize()?
241
23
            .0;
242

            
243
        // Ensure MIME type attribute exists for backward compatibility
244
21
        if !item.attributes.contains_key(CONTENT_TYPE_ATTRIBUTE) {
245
8
            item.attributes.insert(
246
8
                CONTENT_TYPE_ATTRIBUTE.to_owned(),
247
8
                ContentType::default().as_str().to_string(),
248
            );
249
        }
250

            
251
21
        Ok(item)
252
    }
253
}
254

            
255
#[cfg(test)]
256
mod tests {
257
    use super::*;
258

            
259
    #[tokio::test]
260
    async fn set_label() {
261
        let mut item = UnlockedItem::new(
262
            "Original Label",
263
            &[("service", "test-service")],
264
            Secret::text("secret"),
265
        );
266

            
267
        let original_modified = item.modified();
268
        tokio::time::sleep(Duration::from_secs(1)).await;
269

            
270
        item.set_label("New Label");
271

            
272
        assert_eq!(item.label(), "New Label");
273
        assert!(item.modified() > original_modified);
274
        assert_eq!(item.secret().as_bytes(), b"secret");
275
        assert_eq!(item.attributes().get("service").unwrap(), "test-service");
276
    }
277

            
278
    #[tokio::test]
279
    async fn set_secret_text() {
280
        let mut item = UnlockedItem::new(
281
            "Test Item",
282
            &[("service", "test-service")],
283
            Secret::text("original"),
284
        );
285

            
286
        let original_modified = item.modified();
287
        tokio::time::sleep(Duration::from_secs(1)).await;
288

            
289
        item.set_secret(Secret::text("new secret"));
290

            
291
        assert_eq!(item.secret().as_bytes(), b"new secret");
292
        assert!(item.modified() > original_modified);
293
        assert_eq!(item.label(), "Test Item");
294
        assert_eq!(item.attributes().get("service").unwrap(), "test-service");
295
    }
296

            
297
    #[tokio::test]
298
    async fn set_secret_blob() {
299
        let mut item = UnlockedItem::new(
300
            "Binary Item",
301
            &[("type", "binary")],
302
            Secret::blob(b"binary data"),
303
        );
304

            
305
        let original_modified = item.modified();
306
        tokio::time::sleep(Duration::from_secs(1)).await;
307

            
308
        item.set_secret(Secret::blob(b"new binary data"));
309

            
310
        assert_eq!(item.secret().as_bytes(), b"new binary data");
311
        assert!(item.modified() > original_modified);
312
        assert_eq!(item.label(), "Binary Item");
313
    }
314

            
315
    #[tokio::test]
316
    async fn created_timestamp() {
317
        let item = UnlockedItem::new(
318
            "Timestamp Test",
319
            &[("test", "timestamp")],
320
            Secret::text("data"),
321
        );
322

            
323
        let created_time = item.created();
324
        assert!(created_time.as_secs() > 0);
325

            
326
        let modified_time = item.modified();
327
        assert_eq!(created_time, modified_time);
328
    }
329

            
330
    #[tokio::test]
331
    async fn modified_timestamp_updates() {
332
        let mut item = UnlockedItem::new(
333
            "Modification Test",
334
            &[("test", "modification")],
335
            Secret::text("data"),
336
        );
337

            
338
        let original_created = item.created();
339
        let original_modified = item.modified();
340

            
341
        tokio::time::sleep(Duration::from_secs(1)).await;
342

            
343
        item.set_label("Updated Label");
344

            
345
        assert_eq!(item.created(), original_created);
346
        assert!(item.modified() > original_modified);
347

            
348
        let mid_modified = item.modified();
349
        tokio::time::sleep(Duration::from_secs(1)).await;
350

            
351
        item.set_secret(Secret::text("updated secret"));
352

            
353
        assert_eq!(item.created(), original_created);
354
        assert!(item.modified() > mid_modified);
355
    }
356

            
357
    #[test]
358
    fn serialization() {
359
        let key = Key::new(vec![
360
            204, 53, 139, 40, 55, 167, 183, 240, 191, 252, 186, 174, 28, 36, 229, 26,
361
        ]);
362
        let n_mac = crypto::mac_len();
363
        let n_iv = crypto::iv_len();
364

            
365
        let iv = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0];
366
        assert_eq!(iv.len(), n_iv);
367

            
368
        let attribute_value = "5".to_string();
369
        let attribute_value_mac = crypto::compute_mac(attribute_value.as_bytes(), &key).unwrap();
370

            
371
        let mut item = UnlockedItem {
372
            attributes: HashMap::from([("fooness".to_string(), attribute_value)]),
373
            label: "foo".to_string(),
374
            created: 50,
375
            modified: 50,
376
            secret: b"bar".to_vec(),
377
        };
378

            
379
        let encrypted = item.encrypt_encrypted(&key, &iv).unwrap();
380
        assert!(encrypted.has_attribute("fooness", &attribute_value_mac));
381

            
382
        let blob = &encrypted.blob;
383
        let n = blob.len();
384

            
385
        // encrypted.blob should be the concatenation of the encrypted data, the
386
        // iv, and the mac.
387
        let encrypted_item_blob = &encrypted.blob[..n - n_mac - n_iv];
388
        let item_mac = crypto::compute_mac(&encrypted.blob[..n - n_mac], &key).unwrap();
389

            
390
        assert_eq!(&blob[n - n_mac..], item_mac.as_slice());
391
        assert_eq!(&blob[n - n_mac - n_iv..n - n_mac], &iv);
392
        assert_eq!(
393
            encrypted_item_blob,
394
            vec![
395
                196, 246, 127, 53, 194, 30, 176, 37, 128, 145, 195, 96, 211, 161, 60, 150, 160,
396
                126, 85, 125, 85, 238, 5, 93, 153, 128, 176, 205, 31, 87, 48, 82, 121, 230, 143,
397
                152, 153, 193, 182, 114, 59, 157, 85, 41, 50, 1, 142, 112
398
            ]
399
        );
400

            
401
        let decrypted = encrypted.decrypt(Some(&key)).unwrap();
402

            
403
        // The decrypted item matches the original one but with the content-type
404
        // attribute set.
405
        item.attributes.insert(
406
            crate::CONTENT_TYPE_ATTRIBUTE.to_string(),
407
            crate::secret::ContentType::Blob.as_str().to_string(),
408
        );
409
        assert_eq!(decrypted, item);
410
    }
411
}