1use crate::development::{DevelopmentError, DevelopmentResult};
4use serde::{Deserialize, Serialize};
5use std::fs::{File, OpenOptions};
6use std::io::{Read, Write};
7use std::path::{Path, PathBuf};
8use std::time::{SystemTime, UNIX_EPOCH};
9
10const TRUST_STORE_VERSION: u32 = 1;
11const MAX_TRUST_STORE_BYTES: u64 = 1024 * 1024;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "camelCase")]
16pub enum WorkspaceTrust {
17 Untrusted,
19 TrustedOnce,
21 TrustedProject,
23}
24
25impl WorkspaceTrust {
26 pub fn permits_project_execution(self) -> bool {
27 matches!(self, Self::TrustedOnce | Self::TrustedProject)
28 }
29
30 pub fn label(self) -> &'static str {
32 match self {
33 Self::Untrusted => "untrusted",
34 Self::TrustedOnce => "trusted once",
35 Self::TrustedProject => "trusted project",
36 }
37 }
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum LocalTrustDecision {
43 OpenUntrusted,
44 TrustOnce,
45 TrustProject,
46}
47
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(rename_all = "camelCase")]
51pub struct WorkspaceIdentity {
52 pub canonical_root: PathBuf,
53 pub git_remote: Option<String>,
54 pub created_unix_nanos: Option<u128>,
55 #[cfg(unix)]
56 pub device: u64,
57 #[cfg(unix)]
58 pub inode: u64,
59}
60
61impl WorkspaceIdentity {
62 pub fn inspect(root: impl AsRef<Path>) -> DevelopmentResult<Self> {
63 let canonical_root = std::fs::canonicalize(root)?;
64 let metadata = std::fs::metadata(&canonical_root)?;
65 let created_unix_nanos = metadata
66 .created()
67 .ok()
68 .and_then(|created| created.duration_since(UNIX_EPOCH).ok())
69 .map(|duration| duration.as_nanos());
70 #[cfg(unix)]
71 let (device, inode) = {
72 use std::os::unix::fs::MetadataExt;
73 (metadata.dev(), metadata.ino())
74 };
75 Ok(Self {
76 git_remote: read_git_remote(&canonical_root),
77 canonical_root,
78 created_unix_nanos,
79 #[cfg(unix)]
80 device,
81 #[cfg(unix)]
82 inode,
83 })
84 }
85
86 fn is_persistable(&self) -> bool {
87 #[cfg(unix)]
88 {
89 self.device != 0 && self.inode != 0
90 }
91 #[cfg(not(unix))]
92 {
93 self.created_unix_nanos.is_some()
94 }
95 }
96}
97
98#[derive(Debug, Clone, Serialize, Deserialize)]
99#[serde(rename_all = "camelCase", deny_unknown_fields)]
100struct TrustRecord {
101 identity: WorkspaceIdentity,
102 trusted_at_unix_ms: u128,
103}
104
105#[derive(Debug, Default, Serialize, Deserialize)]
106#[serde(rename_all = "camelCase", deny_unknown_fields)]
107struct TrustStoreDocument {
108 version: u32,
109 records: Vec<TrustRecord>,
110}
111
112#[derive(Debug, Clone)]
114pub struct WorkspaceTrustStore {
115 path: PathBuf,
116}
117
118impl WorkspaceTrustStore {
119 pub fn platform_default() -> DevelopmentResult<Self> {
120 if let Some(path) = std::env::var_os("GLASS_TRUST_STORE_PATH") {
121 return Ok(Self::at(path));
122 }
123 let base = dirs::data_local_dir().ok_or_else(|| {
124 DevelopmentError::Config("platform local-data directory is unavailable".into())
125 })?;
126 Ok(Self::at(base.join("glass/trust/workspaces-v1.json")))
127 }
128
129 pub fn at(path: impl Into<PathBuf>) -> Self {
130 Self { path: path.into() }
131 }
132
133 pub fn path(&self) -> &Path {
134 &self.path
135 }
136
137 pub fn status(&self, identity: &WorkspaceIdentity) -> DevelopmentResult<WorkspaceTrust> {
138 let document = self.load()?;
139 Ok(
140 if document
141 .records
142 .iter()
143 .any(|record| record.identity == *identity)
144 {
145 WorkspaceTrust::TrustedProject
146 } else {
147 WorkspaceTrust::Untrusted
148 },
149 )
150 }
151
152 pub fn trust_project(&self, identity: &WorkspaceIdentity) -> DevelopmentResult<()> {
153 if !identity.is_persistable() {
154 return Err(DevelopmentError::Conflict(
155 "project identity cannot be proven safely on this filesystem; use trust-once"
156 .into(),
157 ));
158 }
159 self.with_exclusive_lock(|| {
160 let mut document = self.load()?;
161 document
162 .records
163 .retain(|record| record.identity.canonical_root != identity.canonical_root);
164 document.records.push(TrustRecord {
165 identity: identity.clone(),
166 trusted_at_unix_ms: SystemTime::now()
167 .duration_since(UNIX_EPOCH)
168 .unwrap_or_default()
169 .as_millis(),
170 });
171 if document.records.len() > 1024 {
172 document
173 .records
174 .sort_by_key(|record| record.trusted_at_unix_ms);
175 document.records.drain(..document.records.len() - 1024);
176 }
177 self.save(&document)
178 })
179 }
180
181 pub fn forget(&self, identity: &WorkspaceIdentity) -> DevelopmentResult<()> {
182 self.with_exclusive_lock(|| {
183 let mut document = self.load()?;
184 document
185 .records
186 .retain(|record| record.identity != *identity);
187 self.save(&document)
188 })
189 }
190
191 fn with_exclusive_lock<T>(
192 &self,
193 operation: impl FnOnce() -> DevelopmentResult<T>,
194 ) -> DevelopmentResult<T> {
195 let parent = self.path.parent().ok_or_else(|| {
196 DevelopmentError::Config("trust-store path has no parent directory".into())
197 })?;
198 std::fs::create_dir_all(parent)?;
199 let lock_path = self.path.with_extension("lock");
200 let lock = OpenOptions::new()
201 .create(true)
202 .truncate(false)
203 .read(true)
204 .write(true)
205 .open(lock_path)?;
206 fs2::FileExt::lock_exclusive(&lock)?;
207 let result = operation();
208 let _ = fs2::FileExt::unlock(&lock);
209 result
210 }
211
212 fn load(&self) -> DevelopmentResult<TrustStoreDocument> {
213 if !self.path.exists() {
214 return Ok(TrustStoreDocument {
215 version: TRUST_STORE_VERSION,
216 records: Vec::new(),
217 });
218 }
219 let metadata = std::fs::metadata(&self.path)?;
220 if !metadata.is_file() || metadata.len() > MAX_TRUST_STORE_BYTES {
221 return Err(DevelopmentError::Config(
222 "workspace trust store is not a bounded regular file".into(),
223 ));
224 }
225 let mut bytes = Vec::with_capacity(metadata.len() as usize);
226 File::open(&self.path)?.read_to_end(&mut bytes)?;
227 let document: TrustStoreDocument = serde_json::from_slice(&bytes)
228 .map_err(|error| DevelopmentError::Config(error.to_string()))?;
229 if document.version != TRUST_STORE_VERSION {
230 return Err(DevelopmentError::Config(format!(
231 "unsupported workspace trust-store version {}",
232 document.version
233 )));
234 }
235 Ok(document)
236 }
237
238 fn save(&self, document: &TrustStoreDocument) -> DevelopmentResult<()> {
239 let parent = self.path.parent().ok_or_else(|| {
240 DevelopmentError::Config("trust-store path has no parent directory".into())
241 })?;
242 std::fs::create_dir_all(parent)?;
243 let bytes = serde_json::to_vec_pretty(document)?;
244 if bytes.len() as u64 > MAX_TRUST_STORE_BYTES {
245 return Err(DevelopmentError::Config(
246 "workspace trust store exceeds its size limit".into(),
247 ));
248 }
249 let temporary = self
250 .path
251 .with_extension(format!("tmp-{}", std::process::id()));
252 let mut file = OpenOptions::new()
253 .create(true)
254 .truncate(true)
255 .write(true)
256 .open(&temporary)?;
257 file.write_all(&bytes)?;
258 file.sync_all()?;
259 std::fs::rename(temporary, &self.path)?;
260 Ok(())
261 }
262}
263
264fn read_git_remote(root: &Path) -> Option<String> {
265 let output = crate::git::git_command(root)
266 .args([
267 "-c",
268 "alias.config=",
269 "config",
270 "--get",
271 "remote.origin.url",
272 ])
273 .stdin(std::process::Stdio::null())
274 .stderr(std::process::Stdio::null())
275 .output()
276 .ok()?;
277 if !output.status.success() || output.stdout.len() > 4096 {
278 return None;
279 }
280 let remote = String::from_utf8(output.stdout).ok()?;
281 let remote = remote.trim();
282 (!remote.is_empty()).then(|| remote.to_string())
283}
284
285#[cfg(test)]
286mod tests {
287 use super::*;
288
289 fn root(label: &str) -> PathBuf {
290 std::env::temp_dir().join(format!(
291 "glass-trust-{label}-{}-{}",
292 std::process::id(),
293 SystemTime::now()
294 .duration_since(UNIX_EPOCH)
295 .unwrap()
296 .as_nanos()
297 ))
298 }
299
300 #[test]
301 fn trusted_project_is_external_and_identity_bound() {
302 let root = root("identity");
303 let store_path = root.with_extension("store.json");
304 std::fs::create_dir_all(&root).unwrap();
305 let store = WorkspaceTrustStore::at(&store_path);
306 let original = WorkspaceIdentity::inspect(&root).unwrap();
307 assert_eq!(store.status(&original).unwrap(), WorkspaceTrust::Untrusted);
308 store.trust_project(&original).unwrap();
309 assert_eq!(
310 store.status(&original).unwrap(),
311 WorkspaceTrust::TrustedProject
312 );
313 assert!(!root.join(".glass-trust").exists());
314
315 std::fs::remove_dir(&root).unwrap();
316 std::fs::create_dir(&root).unwrap();
317 let replacement = WorkspaceIdentity::inspect(&root).unwrap();
318 assert_ne!(replacement, original);
319 assert_eq!(
320 store.status(&replacement).unwrap(),
321 WorkspaceTrust::Untrusted
322 );
323
324 std::fs::remove_dir_all(root).unwrap();
325 std::fs::remove_file(store_path).unwrap();
326 }
327
328 #[test]
329 fn trust_once_is_never_written_to_the_store() {
330 let root = root("once");
331 let store_path = root.with_extension("store.json");
332 std::fs::create_dir_all(&root).unwrap();
333 let identity = WorkspaceIdentity::inspect(&root).unwrap();
334 let store = WorkspaceTrustStore::at(&store_path);
335 assert_eq!(WorkspaceTrust::TrustedOnce, WorkspaceTrust::TrustedOnce);
336 assert_eq!(store.status(&identity).unwrap(), WorkspaceTrust::Untrusted);
337 assert!(!store_path.exists());
338 std::fs::remove_dir_all(root).unwrap();
339 }
340}