Skip to main content

lean_ctx/core/config/
intelligence.rs

1// SPDX-License-Identifier: Apache-2.0
2//! User-global opt-in and independent trust pins for the optional local runtime.
3
4use serde::{Deserialize, Serialize};
5use std::path::{Path, PathBuf};
6
7/// The file next to `config.toml` that records `setup runtime deactivate`
8/// (see [`IntelligenceRuntimeConfig::declined`]).
9pub const DECLINED_MARKER: &str = "runtime-declined";
10
11/// Where the decline of this configuration is recorded.
12#[must_use]
13pub fn declined_marker() -> Option<PathBuf> {
14    super::Config::path().and_then(|config| config.parent().map(|dir| dir.join(DECLINED_MARKER)))
15}
16
17/// Whether `marker` records a decline. A symlink counts as recorded (fail
18/// closed: the runtime stays off) and is never followed.
19#[must_use]
20pub fn decline_recorded_at(marker: &Path) -> bool {
21    marker.symlink_metadata().is_ok()
22}
23
24/// Records (`true`) or clears (`false`) the decline at `marker`. Clearing
25/// a missing marker succeeds.
26pub fn record_decline_at(marker: &Path, declined: bool) -> std::io::Result<()> {
27    if !declined {
28        return match std::fs::remove_file(marker) {
29            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
30            other => other,
31        };
32    }
33    if decline_recorded_at(marker) {
34        return Ok(());
35    }
36    if let Some(dir) = marker.parent() {
37        std::fs::create_dir_all(dir)?;
38    }
39    let mut options = std::fs::OpenOptions::new();
40    options.write(true).create_new(true);
41    #[cfg(unix)]
42    std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
43    match options.open(marker) {
44        Ok(mut file) => std::io::Write::write_all(
45            &mut file,
46            b"lean-ctx setup runtime deactivate; cleared by lean-ctx setup runtime install\n",
47        ),
48        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
49        Err(error) => Err(error),
50    }
51}
52
53/// [`record_decline_at`] for this configuration.
54pub fn record_decline(declined: bool) -> std::io::Result<()> {
55    let marker = declined_marker().ok_or_else(|| {
56        std::io::Error::new(std::io::ErrorKind::NotFound, "no configuration directory")
57    })?;
58    record_decline_at(&marker, declined)
59}
60
61/// Never merged from a project file, including trusted workspaces.
62/// A public signing key is not a credential; the package cannot provide its pin.
63#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
64#[serde(default, deny_unknown_fields)]
65pub struct IntelligenceRuntimeConfig {
66    pub enabled: bool,
67    /// Switched off with `setup runtime deactivate`, also before anything
68    /// was installed: setup, onboard, repair, bootstrap, harden and connect
69    /// never install or enable the runtime on their own. Only an explicit
70    /// `setup runtime install` (an activation) clears it.
71    ///
72    /// Never written to `config.toml`: this section is `deny_unknown_fields`,
73    /// and 3.12.7 (a running daemon, a rollback) would refuse the whole file
74    /// and fall back to the defaults. The decline is the file
75    /// [`DECLINED_MARKER`] next to `config.toml`, which older versions
76    /// neither read nor rewrite; [`Self::with_recorded_decline`] merges it.
77    /// Still read from `config.toml`, so a configuration written by an early
78    /// 3.12.8 build keeps loading.
79    #[serde(skip_serializing)]
80    pub declined: bool,
81    pub accept_proprietary: bool,
82    pub staging: bool,
83    pub root: String,
84    pub manifest_sha256: String,
85    pub trust_key_hex: String,
86    pub channel_url: String,
87    pub channel_signature_url: String,
88    pub channel_root_key_hex: String,
89    /// Explicit user-global handoff to the private verifier, never project input.
90    pub license_configuration: String,
91    /// No effect: read-strategy policies are no longer learned by a runtime.
92    /// Kept so an existing config (`deny_unknown_fields`) still loads.
93    pub context_policy_apply: bool,
94    /// The projects of this user that read shared team artifacts, each with
95    /// its team identity. Empty by default: a project without an entry uses
96    /// no artifact. Global-only like the rest of this section, so a
97    /// repository cannot name itself. It carries no clearance: none is
98    /// configurable here.
99    pub team_artifact_projects: Vec<TeamArtifactProject>,
100}
101
102impl IntelligenceRuntimeConfig {
103    /// Switched off with `setup runtime deactivate`, before or after an
104    /// install (an install accepted once and no longer enabled counts too).
105    /// Read from the configuration alone: whether the installed package
106    /// still verifies does not change the person's choice.
107    #[must_use]
108    pub fn deactivated(&self) -> bool {
109        self.declined || (self.accept_proprietary && !self.enabled)
110    }
111
112    /// This configuration with the decline recorded next to `config.toml`.
113    #[must_use]
114    pub fn with_recorded_decline(mut self) -> Self {
115        self.declined |= declined_marker().is_some_and(|marker| decline_recorded_at(&marker));
116        self
117    }
118
119    /// Nothing configured, apart from a switch-off.
120    #[must_use]
121    pub fn is_unset(&self) -> bool {
122        Self {
123            declined: false,
124            ..self.clone()
125        } == Self::default()
126    }
127
128    /// `setup runtime deactivate`: off, and kept off by setup.
129    pub fn switch_off(&mut self) {
130        self.enabled = false;
131        self.declined = true;
132    }
133
134    /// The configuration after an activation of `selected` (an explicit
135    /// install or activate): enabled, accepted and no longer switched off.
136    #[must_use]
137    pub fn activated(
138        previous: Self,
139        staging: bool,
140        root: String,
141        selected: &str,
142        trust_key_hex: &str,
143    ) -> Self {
144        Self {
145            enabled: true,
146            declined: false,
147            accept_proprietary: true,
148            staging,
149            root,
150            manifest_sha256: selected.to_owned(),
151            trust_key_hex: trust_key_hex.to_owned(),
152            ..previous
153        }
154    }
155}
156
157/// One `[[intelligence_runtime.team_artifact_projects]]` entry.
158#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
159#[serde(default, deny_unknown_fields)]
160pub struct TeamArtifactProject {
161    /// Absolute path of the project root.
162    pub root: String,
163    pub organization_id: String,
164    pub project_id: String,
165    /// The project's opaque repository identity — not a URL or a path.
166    pub repository_id: String,
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172
173    /// `[intelligence_runtime]` as 3.12.7 parses it (MR !569 review): the
174    /// same fields, `deny_unknown_fields`. A field it does not know makes
175    /// 3.12.7 refuse the whole `config.toml` and run on the defaults.
176    #[allow(dead_code)]
177    #[derive(Deserialize)]
178    #[serde(default, deny_unknown_fields)]
179    #[derive(Default)]
180    struct Shape3127 {
181        enabled: bool,
182        accept_proprietary: bool,
183        staging: bool,
184        root: String,
185        manifest_sha256: String,
186        trust_key_hex: String,
187        channel_url: String,
188        channel_signature_url: String,
189        channel_root_key_hex: String,
190        license_configuration: String,
191        context_policy_apply: bool,
192        team_artifact_projects: Vec<toml::Value>,
193    }
194
195    #[test]
196    fn a_switched_off_runtime_stays_readable_by_3_12_7() {
197        let installed = IntelligenceRuntimeConfig::activated(
198            IntelligenceRuntimeConfig::default(),
199            false,
200            "/r".into(),
201            &"b".repeat(64),
202            "k",
203        );
204        for mut config in [IntelligenceRuntimeConfig::default(), installed] {
205            config.switch_off();
206            assert!(config.deactivated());
207            let written = toml::to_string(&config).unwrap();
208            assert!(!written.contains("declined"), "{written}");
209            let old: Shape3127 = toml::from_str(&written).unwrap();
210            assert!(!old.enabled, "3.12.7 sees the runtime off");
211        }
212        // A configuration from an early 3.12.8 build still loads here.
213        let early: IntelligenceRuntimeConfig = toml::from_str("declined = true\n").unwrap();
214        assert!(early.deactivated());
215    }
216
217    #[test]
218    fn the_decline_marker_records_and_clears() {
219        let dir = tempfile::tempdir().unwrap();
220        let marker = dir.path().join("config").join(DECLINED_MARKER);
221        assert!(!decline_recorded_at(&marker));
222        record_decline_at(&marker, false).unwrap();
223        record_decline_at(&marker, true).unwrap();
224        record_decline_at(&marker, true).unwrap();
225        assert!(decline_recorded_at(&marker));
226        #[cfg(unix)]
227        {
228            use std::os::unix::fs::PermissionsExt;
229            let mode = std::fs::metadata(&marker).unwrap().permissions().mode();
230            assert_eq!(mode & 0o777, 0o600);
231        }
232        record_decline_at(&marker, false).unwrap();
233        assert!(!decline_recorded_at(&marker));
234        // A dangling symlink counts as a decline (fail closed), unfollowed.
235        #[cfg(unix)]
236        {
237            std::os::unix::fs::symlink(dir.path().join("nowhere"), &marker).unwrap();
238            assert!(decline_recorded_at(&marker));
239        }
240    }
241}