Skip to main content

dort_core/
local.rs

1use crate::{
2    Error, Manifest, Result,
3    context::HostContext,
4    error::io_error,
5    state::{PrivateDir, WriterLock},
6};
7use serde::{Deserialize, Serialize};
8use sha2::{Digest, Sha256};
9use std::{
10    collections::BTreeMap,
11    os::unix::ffi::OsStrExt,
12    path::{Path, PathBuf},
13};
14
15fn schema_one() -> u32 {
16    1
17}
18
19/// Bind the file's full identity but only parent identities: unrelated sibling
20/// creation changes a parent clock without making this read unsafe.
21fn same_read(before: &crate::observation::Entry, after: &crate::observation::Entry) -> bool {
22    before.path == after.path
23        && before.kind == after.kind
24        && before.fingerprint == after.fingerprint
25        && before.link_target == after.link_target
26        && before.parents.len() == after.parents.len()
27        && before.parents.iter().zip(&after.parents).all(|(a, b)| {
28            a.path == b.path && crate::adoption::parent_identity(&a.fingerprint, &b.fingerprint)
29        })
30}
31
32#[derive(Debug, Clone, Serialize, Deserialize)]
33#[serde(deny_unknown_fields)]
34pub struct RepositoryRecord {
35    pub root: PathBuf,
36}
37
38#[derive(Clone, Serialize, Deserialize)]
39#[serde(deny_unknown_fields)]
40pub struct LocalConfig {
41    #[serde(default = "schema_one")]
42    pub schema: u32,
43    #[serde(default)]
44    pub active_profiles: Vec<String>,
45    #[serde(default)]
46    pub variables: BTreeMap<String, toml::Value>,
47    pub active_repository: Option<String>,
48    #[serde(default)]
49    pub repositories: BTreeMap<String, RepositoryRecord>,
50}
51
52impl Default for LocalConfig {
53    fn default() -> Self {
54        Self {
55            schema: 1,
56            active_profiles: vec![],
57            variables: BTreeMap::new(),
58            active_repository: None,
59            repositories: BTreeMap::new(),
60        }
61    }
62}
63
64impl LocalConfig {
65    /// No Debug implementation: variable values must not leak through debug logging.
66    pub fn load(host: &HostContext) -> Result<Self> {
67        let Some(directory) = PrivateDir::open(&host.config_dir, false)? else {
68            return Ok(Self::default());
69        };
70        let Some(text) = directory.read("local.toml")? else {
71            return Ok(Self::default());
72        };
73        let config: Self = toml::from_str(&text)
74            .map_err(|_| Error::Invalid("invalid local configuration (values redacted)".into()))?;
75        config.validate()?;
76        Ok(config)
77    }
78
79    /// Bounded, stable private configuration read for source-bound Tools writes.
80    /// Only the fingerprint/hash escapes; variable values remain private.
81    pub(crate) fn load_bound(host: &HostContext) -> Result<(Self, crate::observation::Entry)> {
82        let directory = PrivateDir::open(&host.config_dir, false)?
83            .ok_or_else(|| Error::Invalid("registered local configuration required".into()))?;
84        let before = crate::observation::inspect(&host.local_config_path(), false)?;
85        let bytes = crate::journal::read_bytes(&directory, "local.toml")?;
86        let text = std::str::from_utf8(&bytes)
87            .map_err(|_| Error::Invalid("invalid local configuration (values redacted)".into()))?;
88        let config: Self = toml::from_str(text)
89            .map_err(|_| Error::Invalid("invalid local configuration (values redacted)".into()))?;
90        config.validate()?;
91        let mut after = crate::observation::inspect(&host.local_config_path(), false)?;
92        if !same_read(&before, &after) {
93            return Err(Error::Invalid(
94                "local configuration changed during read".into(),
95            ));
96        }
97        after.sha256 = Some(crate::journal::digest(&bytes));
98        Ok((config, after))
99    }
100
101    fn validate(&self) -> Result<()> {
102        if self.schema != 1 {
103            return Err(Error::Invalid(
104                "unsupported local configuration schema".into(),
105            ));
106        }
107        for (id, record) in &self.repositories {
108            validate_repository_id(id)?;
109            crate::context::validate_absolute(&record.root)?;
110        }
111        if self
112            .active_repository
113            .as_ref()
114            .is_some_and(|id| !self.repositories.contains_key(id))
115        {
116            return Err(Error::Invalid("active repository is not registered".into()));
117        }
118        let roots: std::collections::BTreeSet<_> =
119            self.repositories.values().map(|r| &r.root).collect();
120        if roots.len() != self.repositories.len() {
121            return Err(Error::Invalid(
122                "repository root is registered more than once".into(),
123            ));
124        }
125        Ok(())
126    }
127
128    fn save(&self, host: &HostContext, lock: &WriterLock) -> Result<()> {
129        lock.check_context(host)?;
130        self.validate()?;
131        let text = toml::to_string(self).map_err(|_| {
132            Error::Invalid("could not encode local configuration (values redacted)".into())
133        })?;
134        let directory =
135            PrivateDir::open(&host.config_dir, true)?.expect("created config directory");
136        directory.replace("local.toml", &text)
137    }
138
139    pub fn select_repository(&self, explicit: Option<&Path>) -> Result<PathBuf> {
140        if let Some(path) = explicit {
141            return path
142                .canonicalize()
143                .map_err(|e| io_error("resolve explicit repository", path, e));
144        }
145        self.active_repository
146            .as_ref()
147            .and_then(|id| self.repositories.get(id))
148            .map(|r| r.root.clone())
149            .ok_or(Error::NoRepository)
150    }
151}
152
153/// Foundation APIs only: callers must hold the application lock.
154/// These operations register metadata, never initialise Git or touch live dotfiles.
155pub struct RepositoryRegistry;
156
157impl RepositoryRegistry {
158    pub fn register(host: &HostContext, lock: &WriterLock, root: &Path) -> Result<String> {
159        lock.check_context(host)?;
160        crate::journal::ensure_writable(host)?;
161        let root = inspect_repository(host, root)?;
162        let mut config = LocalConfig::load(host)?;
163        let id = config
164            .repositories
165            .iter()
166            .find(|(_, r)| r.root == root)
167            .map(|(id, _)| id.clone())
168            .unwrap_or_else(|| format!("{:x}", Sha256::digest(root.as_os_str().as_bytes())));
169        config
170            .repositories
171            .insert(id.clone(), RepositoryRecord { root });
172        config.active_repository = Some(id.clone());
173        config.save(host, lock)?;
174        Ok(id)
175    }
176
177    /// Preserve the state ID after a deliberate move. Refuse forks or missing manifests.
178    pub fn relocate(host: &HostContext, lock: &WriterLock, id: &str, root: &Path) -> Result<()> {
179        lock.check_context(host)?;
180        crate::journal::ensure_writable(host)?;
181        let mut config = LocalConfig::load(host)?;
182        let old = config
183            .repositories
184            .get(id)
185            .ok_or_else(|| Error::Invalid("unknown repository ID".into()))?;
186        if old
187            .root
188            .try_exists()
189            .map_err(|e| io_error("inspect previous repository", &old.root, e))?
190        {
191            return Err(Error::Invalid(
192                "old repository still exists; refusing ambiguous relocation".into(),
193            ));
194        }
195        let root = inspect_repository(host, root)?;
196        if config.repositories.values().any(|r| r.root == root) {
197            return Err(Error::Invalid(
198                "new repository root is already registered".into(),
199            ));
200        }
201        config
202            .repositories
203            .insert(id.into(), RepositoryRecord { root });
204        config.save(host, lock)
205    }
206}
207
208pub fn repository_state_path(host: &HostContext, id: &str) -> Result<PathBuf> {
209    validate_repository_id(id)?;
210    Ok(host.state_dir.join("repositories").join(id))
211}
212
213fn validate_repository_id(id: &str) -> Result<()> {
214    if id.len() != 64
215        || !id
216            .bytes()
217            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
218    {
219        return Err(Error::Invalid("invalid local repository ID".into()));
220    }
221    Ok(())
222}
223
224pub(crate) fn registration_text(host: &HostContext, root: &Path) -> Result<(String, String)> {
225    let mut config = LocalConfig::load(host)?;
226    let id = config
227        .repositories
228        .iter()
229        .find(|(_, r)| r.root == root)
230        .map(|(id, _)| id.clone())
231        .unwrap_or_else(|| format!("{:x}", Sha256::digest(root.as_os_str().as_bytes())));
232    config.repositories.insert(
233        id.clone(),
234        RepositoryRecord {
235            root: root.to_owned(),
236        },
237    );
238    config.active_repository = Some(id.clone());
239    config.validate()?;
240    let text = toml::to_string(&config)
241        .map_err(|_| Error::Invalid("cannot encode registration (values redacted)".into()))?;
242    Ok((id, text))
243}
244
245fn inspect_repository(host: &HostContext, root: &Path) -> Result<PathBuf> {
246    let root = root
247        .canonicalize()
248        .map_err(|e| io_error("resolve repository", root, e))?;
249    if root.to_str().is_none() {
250        return Err(Error::Invalid(
251            "non-UTF-8 repository paths cannot be stored in TOML yet".into(),
252        ));
253    }
254    if root == host.home
255        || root.parent().is_none()
256        || root.starts_with(&host.config_dir)
257        || host.config_dir.starts_with(&root)
258        || root.starts_with(&host.state_dir)
259        || host.state_dir.starts_with(&root)
260    {
261        return Err(Error::Invalid(
262            "repository cannot be HOME or filesystem root, or overlap Dort metadata".into(),
263        ));
264    }
265    if !root
266        .join(".git")
267        .try_exists()
268        .map_err(|e| io_error("inspect Git metadata", &root, e))?
269    {
270        return Err(Error::Invalid(
271            "registry requires existing Git metadata; use bootstrap to create a repository".into(),
272        ));
273    }
274    let path = root.join("dort.toml");
275    let text = std::fs::read_to_string(&path)
276        .map_err(|e| io_error("read repository manifest", &path, e))?;
277    Manifest::parse(&text)?;
278    Ok(root)
279}
280
281#[cfg(test)]
282mod tests {
283    use super::same_read;
284    use crate::observation::{Entry, Fingerprint, Kind, Parent};
285
286    fn fingerprint(inode: u64, modified: i64) -> Fingerprint {
287        Fingerprint {
288            device: 1,
289            inode,
290            links: 1,
291            mode: 0o100600,
292            uid: 501,
293            gid: 20,
294            size: 10,
295            modified: (modified, 0),
296            changed: (modified, 0),
297        }
298    }
299
300    fn entry(parent_modified: i64, parent_inode: u64) -> Entry {
301        Entry {
302            path: "/h/.config/dort/local.toml".into(),
303            kind: Kind::Regular,
304            fingerprint: Some(fingerprint(7, 100)),
305            parents: vec![Parent {
306                path: "/h/.config/dort".into(),
307                fingerprint: fingerprint(parent_inode, parent_modified),
308            }],
309            link_target: None,
310            sha256: None,
311            sensitive: true,
312        }
313    }
314
315    #[test]
316    fn unrelated_parent_clock_changes_do_not_invalidate_a_config_read() {
317        assert!(same_read(&entry(100, 3), &entry(999, 3)));
318        assert!(!same_read(&entry(100, 3), &entry(100, 4)));
319        let mut replaced = entry(100, 3);
320        replaced.fingerprint = Some(fingerprint(8, 100));
321        assert!(!same_read(&entry(100, 3), &replaced));
322    }
323}