Skip to main content

tea_coding/
trust.rs

1use std::collections::BTreeMap;
2use std::fs::{self, OpenOptions};
3use std::io::Write;
4use std::path::{Path, PathBuf};
5
6use serde::{Deserialize, Serialize};
7
8use crate::{CodingError, CodingErrorCode};
9
10const TRUST_SCHEMA_VERSION: u32 = 1;
11const MAX_TRUST_FILE_BYTES: usize = 256 * 1024;
12
13/// Persisted project trust decision.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "snake_case")]
16pub enum PersistedTrustDecision {
17    /// Project-local settings and resources may be loaded.
18    Trusted,
19    /// Project-local settings and resources are explicitly rejected.
20    Rejected,
21    /// Project-local settings and resources are silently ignored.
22    Ignored,
23}
24
25/// One invocation's effective trust request.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum TrustRequest {
28    /// Use persisted policy; interactive caller may prompt if undecided.
29    Default,
30    /// Trust only for this process invocation.
31    TrustOnce,
32    /// Trust and persist the decision.
33    TrustPersisted,
34    /// Reject and optionally persist through [`ProjectTrustStore::set`].
35    Reject,
36    /// Ignore project-local input.
37    Ignore,
38}
39
40/// Whether the current mode can display a trust prompt.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum InteractionMode {
43    /// A user prompt can be shown.
44    Interactive,
45    /// No prompt can be shown; undecided defaults fail closed.
46    NonInteractive,
47}
48
49/// Effective project-local resource access.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum ProjectAccess {
52    /// Project-local configuration/resources may be loaded.
53    Trusted,
54    /// Project-local configuration/resources must be ignored.
55    Ignored,
56    /// Interactive caller must ask before loading project-local data.
57    Ask,
58}
59
60#[derive(Debug, Serialize, Deserialize)]
61#[serde(rename_all = "camelCase", deny_unknown_fields)]
62struct TrustFile {
63    schema_version: u32,
64    decisions: BTreeMap<String, PersistedTrustDecision>,
65}
66
67/// Atomic persistent project-trust repository keyed by canonical workspace.
68#[derive(Debug, Clone)]
69pub struct ProjectTrustStore {
70    path: PathBuf,
71}
72
73impl ProjectTrustStore {
74    /// Creates a repository at an injected path without touching a real home.
75    #[must_use]
76    pub fn new(path: impl Into<PathBuf>) -> Self {
77        Self { path: path.into() }
78    }
79
80    /// Returns a saved decision for the canonical workspace.
81    ///
82    /// # Errors
83    ///
84    /// Rejects non-canonical workspaces and invalid/oversized trust files.
85    pub fn get(&self, workspace: &Path) -> Result<Option<PersistedTrustDecision>, CodingError> {
86        let workspace = canonical_workspace(workspace)?;
87        Ok(self.load()?.decisions.get(&workspace).copied())
88    }
89
90    /// Atomically persists one decision with owner-only Unix permissions.
91    ///
92    /// # Errors
93    ///
94    /// Returns a bounded persistence error if the state cannot be committed.
95    pub fn set(
96        &self,
97        workspace: &Path,
98        decision: PersistedTrustDecision,
99    ) -> Result<(), CodingError> {
100        let workspace = canonical_workspace(workspace)?;
101        let mut file = self.load()?;
102        file.decisions.insert(workspace, decision);
103        let bytes = serde_json::to_vec_pretty(&file).map_err(|_| persistence())?;
104        if bytes.len() > MAX_TRUST_FILE_BYTES {
105            return Err(persistence());
106        }
107        let parent = self.path.parent().ok_or_else(persistence)?;
108        fs::create_dir_all(parent).map_err(|_| persistence())?;
109        let temporary = self.path.with_extension("json.tmp");
110        let mut options = OpenOptions::new();
111        options.write(true).create(true).truncate(true);
112        #[cfg(unix)]
113        {
114            use std::os::unix::fs::OpenOptionsExt;
115            options.mode(0o600);
116        }
117        let mut output = options.open(&temporary).map_err(|_| persistence())?;
118        output.write_all(&bytes).map_err(|_| persistence())?;
119        output.sync_all().map_err(|_| persistence())?;
120        fs::rename(&temporary, &self.path).map_err(|_| persistence())?;
121        #[cfg(unix)]
122        {
123            use std::os::unix::fs::PermissionsExt;
124            fs::set_permissions(&self.path, fs::Permissions::from_mode(0o600))
125                .map_err(|_| persistence())?;
126        }
127        Ok(())
128    }
129
130    /// Resolves a request without reading project-local content.
131    ///
132    /// # Errors
133    ///
134    /// Non-interactive undecided/rejected projects fail closed.
135    pub fn resolve(
136        &self,
137        workspace: &Path,
138        request: TrustRequest,
139        mode: InteractionMode,
140    ) -> Result<ProjectAccess, CodingError> {
141        match request {
142            TrustRequest::TrustOnce => return Ok(ProjectAccess::Trusted),
143            TrustRequest::TrustPersisted => {
144                self.set(workspace, PersistedTrustDecision::Trusted)?;
145                return Ok(ProjectAccess::Trusted);
146            }
147            TrustRequest::Reject => return Err(not_trusted()),
148            TrustRequest::Ignore => return Ok(ProjectAccess::Ignored),
149            TrustRequest::Default => {}
150        }
151        match self.get(workspace)? {
152            Some(PersistedTrustDecision::Trusted) => Ok(ProjectAccess::Trusted),
153            Some(PersistedTrustDecision::Ignored) => Ok(ProjectAccess::Ignored),
154            None if mode == InteractionMode::Interactive => Ok(ProjectAccess::Ask),
155            None | Some(PersistedTrustDecision::Rejected) => Err(not_trusted()),
156        }
157    }
158
159    fn load(&self) -> Result<TrustFile, CodingError> {
160        let bytes = match fs::read(&self.path) {
161            Ok(bytes) => bytes,
162            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
163                return Ok(TrustFile {
164                    schema_version: TRUST_SCHEMA_VERSION,
165                    decisions: BTreeMap::new(),
166                });
167            }
168            Err(_) => return Err(persistence()),
169        };
170        if bytes.len() > MAX_TRUST_FILE_BYTES {
171            return Err(persistence());
172        }
173        let file = serde_json::from_slice::<TrustFile>(&bytes).map_err(|_| persistence())?;
174        if file.schema_version != TRUST_SCHEMA_VERSION || file.decisions.len() > 4096 {
175            return Err(persistence());
176        }
177        Ok(file)
178    }
179}
180
181fn canonical_workspace(workspace: &Path) -> Result<String, CodingError> {
182    let canonical = fs::canonicalize(workspace).map_err(|_| {
183        CodingError::new(
184            CodingErrorCode::NotFound,
185            "workspace directory does not exist",
186        )
187    })?;
188    if !canonical.is_dir() {
189        return Err(CodingError::new(
190            CodingErrorCode::InvalidInput,
191            "workspace is not a directory",
192        ));
193    }
194    canonical
195        .to_str()
196        .filter(|value| value.len() <= 4096 && !value.chars().any(char::is_control))
197        .map(str::to_owned)
198        .ok_or_else(|| {
199            CodingError::new(
200                CodingErrorCode::InvalidInput,
201                "workspace identity is invalid",
202            )
203        })
204}
205
206fn persistence() -> CodingError {
207    CodingError::new(CodingErrorCode::Persistence, "project trust state failed")
208}
209
210fn not_trusted() -> CodingError {
211    CodingError::new(
212        CodingErrorCode::ProjectNotTrusted,
213        "project-local configuration is not trusted",
214    )
215}