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