Skip to main content

glass_dev/
trust.rs

1//! Identity-bound workspace trust stored outside repository control.
2
3use 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/// Effective authority of the currently open workspace.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "camelCase")]
16pub enum WorkspaceTrust {
17    /// Static inspection only; repository-controlled execution is blocked.
18    Untrusted,
19    /// Executable project configuration is enabled for this process lifetime.
20    TrustedOnce,
21    /// Identity was matched in the Glass-owned trust store.
22    TrustedProject,
23}
24
25impl WorkspaceTrust {
26    pub fn permits_project_execution(self) -> bool {
27        matches!(self, Self::TrustedOnce | Self::TrustedProject)
28    }
29
30    /// Human-facing label for TUI surfaces.
31    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/// Explicit local-user decision. This is intentionally absent from MCP/tools.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum LocalTrustDecision {
43    OpenUntrusted,
44    TrustOnce,
45    TrustProject,
46}
47
48/// Stable evidence used to reject a moved or replaced project.
49#[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/// Glass-owned persisted trust database.
113#[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        let parent = self.path.parent().ok_or_else(|| {
160            DevelopmentError::Config("trust-store path has no parent directory".into())
161        })?;
162        std::fs::create_dir_all(parent)?;
163        let lock_path = self.path.with_extension("lock");
164        let lock = OpenOptions::new()
165            .create(true)
166            .truncate(false)
167            .read(true)
168            .write(true)
169            .open(lock_path)?;
170        fs2::FileExt::lock_exclusive(&lock)?;
171        let result = (|| {
172            let mut document = self.load()?;
173            document
174                .records
175                .retain(|record| record.identity.canonical_root != identity.canonical_root);
176            document.records.push(TrustRecord {
177                identity: identity.clone(),
178                trusted_at_unix_ms: SystemTime::now()
179                    .duration_since(UNIX_EPOCH)
180                    .unwrap_or_default()
181                    .as_millis(),
182            });
183            if document.records.len() > 1024 {
184                document
185                    .records
186                    .sort_by_key(|record| record.trusted_at_unix_ms);
187                document.records.drain(..document.records.len() - 1024);
188            }
189            self.save(&document)
190        })();
191        let _ = fs2::FileExt::unlock(&lock);
192        result
193    }
194
195    pub fn forget(&self, identity: &WorkspaceIdentity) -> DevelopmentResult<()> {
196        let mut document = self.load()?;
197        document
198            .records
199            .retain(|record| record.identity != *identity);
200        self.save(&document)
201    }
202
203    fn load(&self) -> DevelopmentResult<TrustStoreDocument> {
204        if !self.path.exists() {
205            return Ok(TrustStoreDocument {
206                version: TRUST_STORE_VERSION,
207                records: Vec::new(),
208            });
209        }
210        let metadata = std::fs::metadata(&self.path)?;
211        if !metadata.is_file() || metadata.len() > MAX_TRUST_STORE_BYTES {
212            return Err(DevelopmentError::Config(
213                "workspace trust store is not a bounded regular file".into(),
214            ));
215        }
216        let mut bytes = Vec::with_capacity(metadata.len() as usize);
217        File::open(&self.path)?.read_to_end(&mut bytes)?;
218        let document: TrustStoreDocument = serde_json::from_slice(&bytes)
219            .map_err(|error| DevelopmentError::Config(error.to_string()))?;
220        if document.version != TRUST_STORE_VERSION {
221            return Err(DevelopmentError::Config(format!(
222                "unsupported workspace trust-store version {}",
223                document.version
224            )));
225        }
226        Ok(document)
227    }
228
229    fn save(&self, document: &TrustStoreDocument) -> DevelopmentResult<()> {
230        let parent = self.path.parent().ok_or_else(|| {
231            DevelopmentError::Config("trust-store path has no parent directory".into())
232        })?;
233        std::fs::create_dir_all(parent)?;
234        let bytes = serde_json::to_vec_pretty(document)?;
235        if bytes.len() as u64 > MAX_TRUST_STORE_BYTES {
236            return Err(DevelopmentError::Config(
237                "workspace trust store exceeds its size limit".into(),
238            ));
239        }
240        let temporary = self
241            .path
242            .with_extension(format!("tmp-{}", std::process::id()));
243        let mut file = OpenOptions::new()
244            .create(true)
245            .truncate(true)
246            .write(true)
247            .open(&temporary)?;
248        file.write_all(&bytes)?;
249        file.sync_all()?;
250        std::fs::rename(temporary, &self.path)?;
251        Ok(())
252    }
253}
254
255fn read_git_remote(root: &Path) -> Option<String> {
256    let output = std::process::Command::new("git")
257        .arg("-C")
258        .arg(root)
259        .args(["config", "--get", "remote.origin.url"])
260        .stdin(std::process::Stdio::null())
261        .stderr(std::process::Stdio::null())
262        .output()
263        .ok()?;
264    if !output.status.success() || output.stdout.len() > 4096 {
265        return None;
266    }
267    let remote = String::from_utf8(output.stdout).ok()?;
268    let remote = remote.trim();
269    (!remote.is_empty()).then(|| remote.to_string())
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275
276    fn root(label: &str) -> PathBuf {
277        std::env::temp_dir().join(format!(
278            "glass-trust-{label}-{}-{}",
279            std::process::id(),
280            SystemTime::now()
281                .duration_since(UNIX_EPOCH)
282                .unwrap()
283                .as_nanos()
284        ))
285    }
286
287    #[test]
288    fn trusted_project_is_external_and_identity_bound() {
289        let root = root("identity");
290        let store_path = root.with_extension("store.json");
291        std::fs::create_dir_all(&root).unwrap();
292        let store = WorkspaceTrustStore::at(&store_path);
293        let original = WorkspaceIdentity::inspect(&root).unwrap();
294        assert_eq!(store.status(&original).unwrap(), WorkspaceTrust::Untrusted);
295        store.trust_project(&original).unwrap();
296        assert_eq!(
297            store.status(&original).unwrap(),
298            WorkspaceTrust::TrustedProject
299        );
300        assert!(!root.join(".glass-trust").exists());
301
302        std::fs::remove_dir(&root).unwrap();
303        std::fs::create_dir(&root).unwrap();
304        let replacement = WorkspaceIdentity::inspect(&root).unwrap();
305        assert_ne!(replacement, original);
306        assert_eq!(
307            store.status(&replacement).unwrap(),
308            WorkspaceTrust::Untrusted
309        );
310
311        std::fs::remove_dir_all(root).unwrap();
312        std::fs::remove_file(store_path).unwrap();
313    }
314
315    #[test]
316    fn trust_once_is_never_written_to_the_store() {
317        let root = root("once");
318        let store_path = root.with_extension("store.json");
319        std::fs::create_dir_all(&root).unwrap();
320        let identity = WorkspaceIdentity::inspect(&root).unwrap();
321        let store = WorkspaceTrustStore::at(&store_path);
322        assert_eq!(WorkspaceTrust::TrustedOnce, WorkspaceTrust::TrustedOnce);
323        assert_eq!(store.status(&identity).unwrap(), WorkspaceTrust::Untrusted);
324        assert!(!store_path.exists());
325        std::fs::remove_dir_all(root).unwrap();
326    }
327}