Skip to main content
← rust.krizaka.comkrizaka.com

krizaka_rust/
secrets.rs

1//! Small secrets of a Mac app (the session token first of all: the bearer the product's API gave at sign in, the same kind
2//! the mobile apps hold), in the macOS Keychain — never a file, never the page's storage. The page sees it as the
3//! `KeyValueStorage` port of `@krizaka/app-client`, so the Mac apps use the same session store and API client as the
4//! mobile ones. This module holds the rules every store follows, and an in-memory store for tests.
5
6use std::collections::HashMap;
7use std::fmt;
8use std::sync::Mutex;
9
10/// Why a secret could not be read, written or removed. A refused key or value is never repeated: the page may have put
11/// a secret in the wrong argument.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub enum SecretError {
14    /// The key breaks [`check_key`].
15    BadKey,
16    /// The value breaks [`check_value`].
17    BadValue,
18    /// A lock of the store was poisoned by a panic elsewhere.
19    Poisoned,
20    /// The store itself failed (the Keychain refused, is locked or is missing). The text is the system's, never the
21    /// caller's.
22    Backend(String),
23}
24
25impl SecretError {
26    /// The stable code the page reads.
27    pub fn code(&self) -> &'static str {
28        match self {
29            SecretError::BadKey => "secret_bad_key",
30            SecretError::BadValue => "secret_bad_value",
31            SecretError::Poisoned | SecretError::Backend(_) => "secret_store_failed",
32        }
33    }
34}
35
36impl fmt::Display for SecretError {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        match self {
39            SecretError::BadKey => f.write_str("not a secret key"),
40            SecretError::BadValue => f.write_str("not a value the Keychain keeps"),
41            SecretError::Poisoned => f.write_str("the secret store is locked by a failure"),
42            SecretError::Backend(detail) => write!(f, "the secret store failed: {detail}"),
43        }
44    }
45}
46
47impl std::error::Error for SecretError {}
48
49/// The largest value stored; a bearer or a piece of the discovery manifest is far shorter.
50// @fixed: the size of a Keychain item, not a setting
51pub const MAX_VALUE: usize = 4096;
52
53/// Where the secrets are kept. One Keychain service per app (its bundle id), one account per key.
54pub trait SecretStore: Send + Sync {
55    fn get(&self, key: &str) -> Result<Option<String>, SecretError>;
56    fn set(&self, key: &str, value: &str) -> Result<(), SecretError>;
57    /// Removing a key that is not there is not an error (signing out twice is signing out).
58    fn remove(&self, key: &str) -> Result<(), SecretError>;
59}
60
61/// The longest key.
62// @fixed: room for `<product>.<name>` of the longest product, not a setting
63pub const MAX_KEY: usize = 64;
64
65/// A key is lowercase letters, digits, `.`, `-`, `_`, at most [`MAX_KEY`] characters (`verikora.session`). A refused key is not
66/// repeated in the error: the page may have put a secret in the wrong argument.
67pub fn check_key(key: &str) -> Result<(), SecretError> {
68    let ok = !key.is_empty()
69        && key.len() <= MAX_KEY
70        && key
71            .chars()
72            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '-' | '_'));
73    if ok {
74        Ok(())
75    } else {
76        Err(SecretError::BadKey)
77    }
78}
79
80/// A value is text of at most [`MAX_VALUE`] bytes, without a NUL.
81pub fn check_value(value: &str) -> Result<(), SecretError> {
82    if value.len() > MAX_VALUE || value.contains('\0') {
83        return Err(SecretError::BadValue);
84    }
85    Ok(())
86}
87
88/// The checked way to every store: what reaches the Keychain has passed [`check_key`] and [`check_value`].
89pub struct Checked<S: SecretStore>(pub S);
90
91impl<S: SecretStore> SecretStore for Checked<S> {
92    fn get(&self, key: &str) -> Result<Option<String>, SecretError> {
93        check_key(key)?;
94        self.0.get(key)
95    }
96
97    fn set(&self, key: &str, value: &str) -> Result<(), SecretError> {
98        check_key(key)?;
99        check_value(value)?;
100        self.0.set(key, value)
101    }
102
103    fn remove(&self, key: &str) -> Result<(), SecretError> {
104        check_key(key)?;
105        self.0.remove(key)
106    }
107}
108
109/// A store in memory, for tests and previews.
110#[derive(Default)]
111pub struct MemorySecrets(Mutex<HashMap<String, String>>);
112
113impl SecretStore for MemorySecrets {
114    fn get(&self, key: &str) -> Result<Option<String>, SecretError> {
115        Ok(self
116            .0
117            .lock()
118            .map_err(|_| SecretError::Poisoned)?
119            .get(key)
120            .cloned())
121    }
122
123    fn set(&self, key: &str, value: &str) -> Result<(), SecretError> {
124        self.0
125            .lock()
126            .map_err(|_| SecretError::Poisoned)?
127            .insert(key.into(), value.into());
128        Ok(())
129    }
130
131    fn remove(&self, key: &str) -> Result<(), SecretError> {
132        self.0
133            .lock()
134            .map_err(|_| SecretError::Poisoned)?
135            .remove(key);
136        Ok(())
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143
144    const TOKEN: &str = "yz_sess_3f9a1c0b7e2d4a5f8c6b";
145
146    #[test]
147    fn a_session_is_stored_read_and_removed_twice_without_error() {
148        let secrets = Checked(MemorySecrets::default());
149        assert_eq!(secrets.get("verikora.session").unwrap(), None);
150        secrets.set("verikora.session", TOKEN).unwrap();
151        assert_eq!(
152            secrets.get("verikora.session").unwrap().as_deref(),
153            Some(TOKEN)
154        );
155        secrets
156            .set("verikora.discovery.0", "{\"v\": 1, \"services\": []}")
157            .unwrap();
158        secrets.remove("verikora.session").unwrap();
159        secrets.remove("verikora.session").unwrap();
160        assert_eq!(secrets.get("verikora.session").unwrap(), None);
161        assert!(secrets.get("verikora.discovery.0").unwrap().is_some());
162    }
163
164    #[test]
165    fn a_bad_key_or_value_never_reaches_the_store() {
166        let secrets = Checked(MemorySecrets::default());
167        for key in [
168            "",
169            "Session",
170            "a/b",
171            "a b",
172            "../x",
173            &"k".repeat(MAX_KEY + 1),
174        ] {
175            assert!(secrets.set(key, TOKEN).is_err(), "{key:?}");
176            assert!(secrets.get(key).is_err(), "{key:?}");
177            assert!(secrets.remove(key).is_err(), "{key:?}");
178        }
179        assert!(secrets.set("s", &"a".repeat(MAX_VALUE + 1)).is_err());
180        assert!(secrets.set("s", "nul\0byte").is_err());
181        assert_eq!(secrets.get("s").unwrap(), None);
182    }
183
184    #[test]
185    fn a_refused_key_or_value_is_not_echoed_in_the_error() -> Result<(), &'static str> {
186        let secrets = Checked(MemorySecrets::default());
187        let key = format!("Bearer {TOKEN}");
188        let refusals = [
189            secrets.set(&key, "x").err(),
190            secrets.get(&key).err(),
191            secrets.remove(&key).err(),
192            secrets.set("s", &format!("{TOKEN}\0")).err(),
193            secrets.set("s", &TOKEN.repeat(MAX_VALUE)).err(),
194        ];
195        for refusal in refusals {
196            let message = refusal
197                .ok_or("a bad key or value was accepted")?
198                .to_string();
199            assert!(!message.contains(TOKEN), "the input is echoed: {message}");
200        }
201        Ok(())
202    }
203}