quickgui_system/
secure_storage.rs1use crate::{Result, invalid, platform, validate_text};
2
3pub const MAX_SECURE_STORAGE_NAME_BYTES: usize = 4 * 1024;
4pub const MAX_SECURE_STORAGE_SECRET_BYTES: usize = 1024 * 1024;
5
6pub struct SecureStorage;
8
9impl SecureStorage {
10 pub const fn is_supported() -> bool {
11 cfg!(any(unix, windows))
12 }
13
14 pub fn set(service: &str, account: &str, secret: &[u8]) -> Result<()> {
15 validate_entry(service, account)?;
16 if secret.len() > MAX_SECURE_STORAGE_SECRET_BYTES {
17 return Err(invalid("secure-storage values cannot exceed 1 MiB"));
18 }
19 keyring::Entry::new(service, account)
20 .and_then(|entry| entry.set_secret(secret))
21 .map_err(platform)
22 }
23
24 pub fn get(service: &str, account: &str) -> Result<Option<Vec<u8>>> {
25 validate_entry(service, account)?;
26 let entry = keyring::Entry::new(service, account).map_err(platform)?;
27 match entry.get_secret() {
28 Ok(secret) if secret.len() <= MAX_SECURE_STORAGE_SECRET_BYTES => Ok(Some(secret)),
29 Ok(_) => Err(invalid(
30 "the native credential exceeds QuickGUI's 1 MiB result limit",
31 )),
32 Err(keyring::Error::NoEntry) => Ok(None),
33 Err(error) => Err(platform(error)),
34 }
35 }
36
37 pub fn delete(service: &str, account: &str) -> Result<bool> {
38 validate_entry(service, account)?;
39 let entry = keyring::Entry::new(service, account).map_err(platform)?;
40 match entry.delete_credential() {
41 Ok(()) => Ok(true),
42 Err(keyring::Error::NoEntry) => Ok(false),
43 Err(error) => Err(platform(error)),
44 }
45 }
46}
47
48fn validate_entry(service: &str, account: &str) -> Result<()> {
49 validate_text(
50 service,
51 "the secure-storage service",
52 MAX_SECURE_STORAGE_NAME_BYTES,
53 )?;
54 validate_text(
55 account,
56 "the secure-storage account",
57 MAX_SECURE_STORAGE_NAME_BYTES,
58 )
59}
60
61#[cfg(test)]
62mod tests {
63 use super::*;
64
65 #[test]
66 fn validates_names_and_value_bounds_without_touching_the_keyring() {
67 assert!(validate_entry("com.example.app", "token").is_ok());
68 assert!(validate_entry("", "token").is_err());
69 assert!(validate_entry("app", "bad\0account").is_err());
70 }
71}