1
use std::str::FromStr;
2

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

            
7
#[derive(Default, PartialEq, Eq, Copy, Clone, Debug, wire::Type)]
8
#[zbus(signature = "s")]
9
pub enum ContentType {
10
    Text,
11
    #[default]
12
    Blob,
13
}
14

            
15
impl Serialize for ContentType {
16
14
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
17
    where
18
        S: serde::Serializer,
19
    {
20
14
        self.as_str().serialize(serializer)
21
    }
22
}
23

            
24
impl<'de> Deserialize<'de> for ContentType {
25
20
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
26
    where
27
        D: serde::Deserializer<'de>,
28
    {
29
19
        let s = String::deserialize(deserializer)?;
30
        // Like gnome-keyring, accept any content type, applications such as
31
        // gnome-abrt use their own (application/libreport).
32
40
        Ok(Self::from_str(&s).unwrap_or_default())
33
    }
34
}
35

            
36
impl FromStr for ContentType {
37
    type Err = String;
38

            
39
21
    fn from_str(s: &str) -> Result<Self, Self::Err> {
40
        // MIME types may include parameters, which are irrelevant to
41
        // ContentType.
42
42
        let media_type = s
43
            .split_once(';')
44
23
            .map_or(s, |(media_type, _)| media_type)
45
            .trim();
46

            
47
41
        if media_type.eq_ignore_ascii_case("text/plain")
48
13
            || media_type.eq_ignore_ascii_case("text/utf8")
49
13
            || media_type.eq_ignore_ascii_case("application/json")
50
        {
51
20
            Ok(Self::Text)
52
26
        } else if media_type.eq_ignore_ascii_case("application/octet-stream")
53
2
            || media_type.eq_ignore_ascii_case("application/binary")
54
        {
55
13
            Ok(Self::Blob)
56
        } else {
57
2
            Err(format!("Invalid content type: {s}"))
58
        }
59
    }
60
}
61

            
62
impl ContentType {
63
29
    pub const fn as_str(&self) -> &'static str {
64
33
        match self {
65
31
            Self::Text => "text/plain",
66
14
            Self::Blob => "application/octet-stream",
67
        }
68
    }
69
}
70

            
71
/// A wrapper around a combination of (secret, content-type).
72
#[derive(Clone, PartialEq, Eq, Zeroize, ZeroizeOnDrop)]
73
pub enum Secret {
74
    /// Corresponds to [`ContentType::Text`]
75
    Text(String),
76
    /// Corresponds to [`ContentType::Blob`]
77
    Blob(Vec<u8>),
78
}
79

            
80
impl std::fmt::Debug for Secret {
81
2
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82
2
        match self {
83
2
            Self::Text(_) => write!(f, "Secret::Text([REDACTED])"),
84
2
            Self::Blob(_) => write!(f, "Secret::Blob([REDACTED])"),
85
        }
86
    }
87
}
88

            
89
impl Secret {
90
    /// Generate a random secret, used when creating a session collection.
91
37
    pub fn random() -> Result<Self, getrandom::Error> {
92
37
        let mut secret = [0; 64];
93
        // Equivalent of `ring::rand::SecureRandom`
94
40
        getrandom::fill(&mut secret)?;
95

            
96
37
        Ok(Self::blob(secret))
97
    }
98

            
99
    /// Get the sandboxed app secret if the app is sandboxed using
100
    /// org.freedesktop.portal.Secret portal.
101
    pub async fn sandboxed() -> Result<Self, crate::file::Error> {
102
        Ok(Self::blob(
103
            ashpd::desktop::secret::retrieve()
104
                .await
105
                .map_err(crate::file::Error::from)?,
106
        ))
107
    }
108

            
109
    /// Create a text secret, stored with `text/plain` content type.
110
80
    pub fn text(value: impl AsRef<str>) -> Self {
111
102
        Self::Text(value.as_ref().to_owned())
112
    }
113

            
114
    /// Create a blob secret, stored with `application/octet-stream` content
115
    /// type.
116
130
    pub fn blob(value: impl AsRef<[u8]>) -> Self {
117
165
        Self::Blob(value.as_ref().to_owned())
118
    }
119

            
120
30
    pub const fn content_type(&self) -> ContentType {
121
28
        match self {
122
31
            Self::Text(_) => ContentType::Text,
123
13
            Self::Blob(_) => ContentType::Blob,
124
        }
125
    }
126

            
127
    /// Returns the secret as a string slice, or `None` if it is not valid
128
    /// UTF-8.
129
    pub fn as_str(&self) -> Option<&str> {
130
        match self {
131
            Self::Text(text) => Some(text.as_str()),
132
            Self::Blob(bytes) => std::str::from_utf8(bytes).ok(),
133
        }
134
    }
135

            
136
48
    pub fn as_bytes(&self) -> &[u8] {
137
102
        match self {
138
46
            Self::Text(text) => text.as_bytes(),
139
30
            Self::Blob(bytes) => bytes.as_ref(),
140
        }
141
    }
142

            
143
21
    pub fn with_content_type(content_type: ContentType, secret: impl AsRef<[u8]>) -> Self {
144
23
        match content_type {
145
23
            ContentType::Text => match String::from_utf8(secret.as_ref().to_owned()) {
146
23
                Ok(text) => Secret::text(text),
147
2
                Err(_e) => {
148
                    #[cfg(feature = "tracing")]
149
                    tracing::warn!(
150
                        "Failed to decode secret as UTF-8: {}, falling back to blob",
151
                        _e
152
                    );
153

            
154
2
                    Secret::blob(secret)
155
                }
156
            },
157
26
            _ => Secret::blob(secret),
158
        }
159
    }
160
}
161

            
162
impl From<&[u8]> for Secret {
163
8
    fn from(value: &[u8]) -> Self {
164
8
        Self::blob(value)
165
    }
166
}
167

            
168
impl From<Zeroizing<Vec<u8>>> for Secret {
169
18
    fn from(value: Zeroizing<Vec<u8>>) -> Self {
170
20
        Self::blob(value)
171
    }
172
}
173

            
174
impl From<Vec<u8>> for Secret {
175
12
    fn from(value: Vec<u8>) -> Self {
176
16
        Self::blob(value)
177
    }
178
}
179

            
180
impl From<&Vec<u8>> for Secret {
181
6
    fn from(value: &Vec<u8>) -> Self {
182
6
        Self::blob(value)
183
    }
184
}
185

            
186
impl<const N: usize> From<&[u8; N]> for Secret {
187
    fn from(value: &[u8; N]) -> Self {
188
        Self::blob(value)
189
    }
190
}
191

            
192
impl From<String> for Secret {
193
6
    fn from(value: String) -> Self {
194
6
        Self::text(value)
195
    }
196
}
197

            
198
impl From<&str> for Secret {
199
43
    fn from(value: &str) -> Self {
200
45
        Self::text(value)
201
    }
202
}
203

            
204
impl std::ops::Deref for Secret {
205
    type Target = [u8];
206

            
207
38
    fn deref(&self) -> &Self::Target {
208
41
        self.as_bytes()
209
    }
210
}
211

            
212
impl AsRef<[u8]> for Secret {
213
12
    fn as_ref(&self) -> &[u8] {
214
12
        self.as_bytes()
215
    }
216
}
217

            
218
#[cfg(test)]
219
mod tests {
220
    use zbus::wire::{Endian, serialized::Context, to_bytes};
221

            
222
    use super::*;
223

            
224
    #[test]
225
    fn secret_debug_is_redacted() {
226
        let text_secret = Secret::text("password");
227
        let blob_secret = Secret::blob([1, 2, 3]);
228

            
229
        assert_eq!(format!("{:?}", text_secret), "Secret::Text([REDACTED])");
230
        assert_eq!(format!("{:?}", blob_secret), "Secret::Blob([REDACTED])");
231
    }
232

            
233
    #[test]
234
    fn content_type_serialization() {
235
        let ctxt = Context::new(Endian::Little, 0);
236

            
237
        // Test Text serialization
238
        let encoded = to_bytes(ctxt, &ContentType::Text).unwrap();
239
        let value: String = encoded.deserialize().unwrap().0;
240
        assert_eq!(value, "text/plain");
241

            
242
        // Test Blob serialization
243
        let encoded = to_bytes(ctxt, &ContentType::Blob).unwrap();
244
        let value: String = encoded.deserialize().unwrap().0;
245
        assert_eq!(value, "application/octet-stream");
246

            
247
        // Test Text deserialization
248
        let encoded = to_bytes(ctxt, &"text/plain").unwrap();
249
        let content_type: ContentType = encoded.deserialize().unwrap().0;
250
        assert_eq!(content_type, ContentType::Text);
251

            
252
        // Test Text deserialization with MIME parameters
253
        let encoded = to_bytes(ctxt, &"text/plain; charset=utf8").unwrap();
254
        let content_type: ContentType = encoded.deserialize().unwrap().0;
255
        assert_eq!(content_type, ContentType::Text);
256

            
257
        // Test Blob deserialization
258
        let encoded = to_bytes(ctxt, &"application/octet-stream").unwrap();
259
        let content_type: ContentType = encoded.deserialize().unwrap().0;
260
        assert_eq!(content_type, ContentType::Blob);
261

            
262
        // application/json deserializes as Text
263
        let encoded = to_bytes(ctxt, &"application/json").unwrap();
264
        let content_type: ContentType = encoded.deserialize().unwrap().0;
265
        assert_eq!(content_type, ContentType::Text);
266

            
267
        // Unknown content types deserialize as Blob
268
        let encoded = to_bytes(ctxt, &"application/libreport").unwrap();
269
        let content_type: ContentType = encoded.deserialize().unwrap().0;
270
        assert_eq!(content_type, ContentType::Blob);
271
    }
272

            
273
    #[test]
274
    fn content_type_from_str() {
275
        for content_type in [
276
            "text/plain",
277
            "text/plain; charset=utf8",
278
            "TEXT/PLAIN; CHARSET=UTF-8",
279
            "application/json",
280
            "application/json; charset=utf8",
281
        ] {
282
            assert_eq!(
283
                ContentType::from_str(content_type).unwrap(),
284
                ContentType::Text
285
            );
286
        }
287

            
288
        for content_type in [
289
            "application/octet-stream",
290
            "application/octet-stream; version=1",
291
        ] {
292
            assert_eq!(
293
                ContentType::from_str(content_type).unwrap(),
294
                ContentType::Blob
295
            );
296
        }
297

            
298
        // Test error case
299
        let result = ContentType::from_str("text/html; charset=utf8");
300
        assert!(result.is_err());
301
        let error = result.unwrap_err();
302
        assert!(error.contains("Invalid content type"));
303
        assert!(error.contains("text/html; charset=utf8"));
304
    }
305

            
306
    #[test]
307
    fn invalid_utf8() {
308
        // Test with invalid UTF-8 bytes
309
        let invalid_utf8 = vec![0xFF, 0xFE, 0xFD];
310

            
311
        // Should fall back to blob when UTF-8 decoding fails
312
        let secret = Secret::with_content_type(ContentType::Text, &invalid_utf8);
313
        assert_eq!(secret.content_type(), ContentType::Blob);
314
        assert_eq!(&*secret, &[0xFF, 0xFE, 0xFD]);
315

            
316
        // Test with valid UTF-8
317
        let valid_utf8 = "Hello, World!";
318
        let secret = Secret::with_content_type(ContentType::Text, valid_utf8.as_bytes());
319
        assert_eq!(secret.content_type(), ContentType::Text);
320
        assert_eq!(&*secret, valid_utf8.as_bytes());
321

            
322
        // Test with blob content type
323
        let data = vec![1, 2, 3, 4];
324
        let secret = Secret::with_content_type(ContentType::Blob, &data);
325
        assert_eq!(secret.content_type(), ContentType::Blob);
326
        assert_eq!(&*secret, &[1, 2, 3, 4]);
327
    }
328

            
329
    #[test]
330
    fn random() {
331
        let secret1 = Secret::random().unwrap();
332
        let secret2 = Secret::random().unwrap();
333

            
334
        // Random secrets should be blobs
335
        assert_eq!(secret1.content_type(), ContentType::Blob);
336
        assert_eq!(secret2.content_type(), ContentType::Blob);
337

            
338
        // Should be 64 bytes
339
        assert_eq!(secret1.as_bytes().len(), 64);
340
        assert_eq!(secret2.as_bytes().len(), 64);
341

            
342
        // Should be different
343
        assert_ne!(secret1.as_bytes(), secret2.as_bytes());
344
    }
345
}