Skip to main content

ashwit_license/
storage.rs

1use std::{
2    fs,
3    io::{Read, Write},
4    path::{Path, PathBuf},
5};
6
7use serde::{Deserialize, Serialize};
8
9use crate::{Error, Result, SignedGrant};
10
11pub trait LicenseStore: Send + Sync {
12    fn load_grant(&self) -> Result<Option<SignedGrant>>;
13    fn save_grant(&self, grant: &SignedGrant) -> Result<()>;
14    fn clear_grant(&self) -> Result<()>;
15    fn load_device_secret(&self) -> Result<Option<String>>;
16    fn save_device_secret(&self, secret: &str) -> Result<()>;
17    fn load_security_state(&self) -> Result<Option<SecurityState>>;
18    fn save_security_state(&self, state: &SecurityState) -> Result<()>;
19}
20
21#[derive(Clone, Debug, Deserialize, Serialize)]
22#[serde(rename_all = "camelCase", deny_unknown_fields)]
23pub struct SecurityState {
24    pub version: u8,
25    pub grant_id: String,
26    pub activation_id: String,
27    pub trusted_time: i64,
28    pub wall_time: i64,
29    pub denial: Option<String>,
30}
31
32#[derive(Debug)]
33pub struct FileStore {
34    path: PathBuf,
35}
36
37#[derive(Default, Deserialize, Serialize)]
38#[serde(rename_all = "camelCase")]
39struct StoredLicense {
40    grant: Option<SignedGrant>,
41    device_secret: Option<String>,
42    security_state: Option<SecurityState>,
43}
44
45impl FileStore {
46    pub fn new(path: impl Into<PathBuf>) -> Self {
47        Self { path: path.into() }
48    }
49    fn read(&self) -> Result<StoredLicense> {
50        if !self.path.exists() {
51            return Ok(StoredLicense::default());
52        }
53        let mut bytes = Vec::new();
54        fs::File::open(&self.path)
55            .map_err(|e| storage_error(&e))?
56            .take(65_537)
57            .read_to_end(&mut bytes)
58            .map_err(|e| storage_error(&e))?;
59        if bytes.len() > 65_536 {
60            return Err(Error::Storage("license cache is too large".into()));
61        }
62        serde_json::from_slice(&bytes).map_err(Into::into)
63    }
64    fn update(&self, operation: impl FnOnce(&mut StoredLicense)) -> Result<()> {
65        let mut state = self.read()?;
66        operation(&mut state);
67        write_atomic(&self.path, &serde_json::to_vec_pretty(&state)?)
68    }
69}
70
71impl LicenseStore for FileStore {
72    fn load_grant(&self) -> Result<Option<SignedGrant>> {
73        Ok(self.read()?.grant)
74    }
75    fn save_grant(&self, grant: &SignedGrant) -> Result<()> {
76        self.update(|state| state.grant = Some(grant.clone()))
77    }
78    fn clear_grant(&self) -> Result<()> {
79        self.update(|state| state.grant = None)
80    }
81    fn load_device_secret(&self) -> Result<Option<String>> {
82        Ok(self.read()?.device_secret)
83    }
84    fn save_device_secret(&self, secret: &str) -> Result<()> {
85        self.update(|state| state.device_secret = Some(secret.to_owned()))
86    }
87    fn load_security_state(&self) -> Result<Option<SecurityState>> {
88        Ok(self.read()?.security_state)
89    }
90    fn save_security_state(&self, value: &SecurityState) -> Result<()> {
91        self.update(|state| state.security_state = Some(value.clone()))
92    }
93}
94
95fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> {
96    let parent = path
97        .parent()
98        .filter(|parent| !parent.as_os_str().is_empty())
99        .unwrap_or_else(|| Path::new("."));
100    fs::create_dir_all(parent).map_err(|error| storage_error(&error))?;
101    let mut temporary =
102        tempfile::NamedTempFile::new_in(parent).map_err(|error| storage_error(&error))?;
103    temporary
104        .write_all(bytes)
105        .map_err(|error| storage_error(&error))?;
106    temporary
107        .as_file()
108        .sync_all()
109        .map_err(|error| storage_error(&error))?;
110    temporary
111        .persist(path)
112        .map_err(|error| storage_error(&error.error))?;
113    Ok(())
114}
115fn storage_error(error: &std::io::Error) -> Error {
116    Error::Storage(error.to_string())
117}
118
119#[cfg(feature = "keyring-store")]
120pub struct KeyringStore {
121    file: FileStore,
122    entry: keyring::Entry,
123    security: keyring::Entry,
124}
125
126#[cfg(feature = "keyring-store")]
127impl KeyringStore {
128    pub fn new(path: impl Into<PathBuf>, service: &str, account: &str) -> Result<Self> {
129        let entry = keyring::Entry::new(service, account)
130            .map_err(|error| Error::DeviceKey(error.to_string()))?;
131        Ok(Self {
132            file: FileStore::new(path),
133            entry,
134            security: keyring::Entry::new(&format!("{service}.state"), account)
135                .map_err(|error| Error::Storage(error.to_string()))?,
136        })
137    }
138}
139
140#[cfg(feature = "keyring-store")]
141impl LicenseStore for KeyringStore {
142    fn load_grant(&self) -> Result<Option<SignedGrant>> {
143        self.file.load_grant()
144    }
145    fn save_grant(&self, grant: &SignedGrant) -> Result<()> {
146        write_atomic(
147            &self.file.path,
148            &serde_json::to_vec(&StoredLicense {
149                grant: Some(grant.clone()),
150                ..StoredLicense::default()
151            })?,
152        )
153    }
154    fn clear_grant(&self) -> Result<()> {
155        write_atomic(
156            &self.file.path,
157            &serde_json::to_vec(&StoredLicense::default())?,
158        )
159    }
160    fn load_device_secret(&self) -> Result<Option<String>> {
161        match self.entry.get_password() {
162            Ok(value) => Ok(Some(value)),
163            Err(keyring::Error::NoEntry) => Ok(None),
164            Err(error) => Err(Error::DeviceKey(error.to_string())),
165        }
166    }
167    fn save_device_secret(&self, secret: &str) -> Result<()> {
168        self.entry
169            .set_password(secret)
170            .map_err(|error| Error::DeviceKey(error.to_string()))
171    }
172    fn load_security_state(&self) -> Result<Option<SecurityState>> {
173        match self.security.get_password() {
174            Ok(value) if value.len() <= 4096 => Ok(Some(serde_json::from_str(&value)?)),
175            Ok(_) => Err(Error::Storage("security state is too large".into())),
176            Err(keyring::Error::NoEntry) => Ok(None),
177            Err(error) => Err(Error::Storage(error.to_string())),
178        }
179    }
180    fn save_security_state(&self, state: &SecurityState) -> Result<()> {
181        self.security
182            .set_password(&serde_json::to_string(state)?)
183            .map_err(|error| Error::Storage(error.to_string()))
184    }
185}