Skip to main content

aft_base/subc_config/
prepared.rs

1//! Trusted-local config observations retained across a bind's configure attempts.
2
3use super::{bind_cache::ObservedFile, *};
4use crate::config_resolve::resolve_parsed_config_for_harness;
5use std::cell::RefCell;
6use std::io::Read;
7use std::sync::atomic::{AtomicU64, Ordering};
8use std::sync::Arc;
9
10static NEXT_SNAPSHOT_ID: AtomicU64 = AtomicU64::new(1);
11
12pub(super) const CONFIG_FILE_LIMIT: usize = 1024 * 1024;
13
14#[derive(Debug)]
15pub struct ConfigObservationError {
16    pub code: &'static str,
17    detail: String,
18}
19
20impl std::fmt::Display for ConfigObservationError {
21    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22        f.write_str(&self.detail)
23    }
24}
25
26#[derive(Clone, Debug)]
27pub struct PreparedBindConfig {
28    snapshot_id: u64,
29    root: PathBuf,
30    harness: Harness,
31    user_path: Option<PathBuf>,
32    approved_user: Option<ApprovedUser>,
33    project_path: PathBuf,
34    tiers: Vec<ConfigTier>,
35    migration: Option<UserConfigMigration>,
36    resolved: crate::config::Config,
37}
38
39impl PreparedBindConfig {
40    #[cfg(any(test, feature = "test-support"))]
41    pub fn read(
42        user_path: Option<&Path>,
43        root: &Path,
44        harness: &Harness,
45    ) -> Result<Arc<Self>, ConfigObservationError> {
46        Self::read_with_approved(user_path, None, root, harness)
47    }
48
49    pub fn read_with_approved(
50        user_path: Option<&Path>,
51        approved_user: Option<&ApprovedUser>,
52        root: &Path,
53        harness: &Harness,
54    ) -> Result<Arc<Self>, ConfigObservationError> {
55        Self::read_cached(
56            &mut BindConfigCache::default(),
57            user_path,
58            approved_user,
59            root,
60            root,
61            harness,
62        )
63    }
64
65    pub fn read_cached(
66        cache: &mut BindConfigCache,
67        user_path: Option<&Path>,
68        approved_user: Option<&ApprovedUser>,
69        root: &Path,
70        root_key: &Path,
71        harness: &Harness,
72    ) -> Result<Arc<Self>, ConfigObservationError> {
73        let (user, migration) = if let Some(user) = approved_user {
74            (Some(ObservedFile::approved(user.snapshot())), None)
75        } else if let Some(path) = user_path {
76            cache.observe(path, None)?
77        } else {
78            (None, None)
79        };
80        let mut project_path = cortexkit_project_config_path(root);
81        let mut project = None;
82        for candidate in super::project_config_candidates(root, Some(harness)) {
83            if let (Some(file), _) = cache.observe(&candidate, Some(root_key))? {
84                project_path = candidate;
85                project = Some(file);
86                break;
87            }
88        }
89        let files = user.iter().chain(&project).map(|file| &file.parsed);
90        let resolution = resolve_parsed_config_for_harness(
91            files.clone().map(|file| (&file.tier, &file.document)),
92            Some(harness),
93        );
94        if !resolution.errors.is_empty() {
95            return Err(ConfigObservationError {
96                code: "config_rejected",
97                detail: format!("configuration rejected: {}", resolution.errors.join(", ")),
98            });
99        }
100        let tiers = files.map(|file| file.tier.clone()).collect();
101        if let Some(user) = user {
102            cache.remember(user, None);
103        }
104        if let Some(project) = project {
105            cache.remember(project, Some(root_key));
106        }
107        Ok(Arc::new(Self {
108            snapshot_id: NEXT_SNAPSHOT_ID.fetch_add(1, Ordering::Relaxed),
109            root: root.into(),
110            harness: harness.clone(),
111            user_path: user_path.map(Path::to_path_buf),
112            approved_user: approved_user.cloned(),
113            project_path,
114            tiers,
115            migration,
116            resolved: resolution.config,
117        }))
118    }
119
120    pub fn matches(&self, root: &Path, harness: &Harness) -> bool {
121        self.root == root && &self.harness == harness
122    }
123    pub fn id(&self) -> u64 {
124        self.snapshot_id
125    }
126
127    pub fn tiers(&self) -> &[ConfigTier] {
128        &self.tiers
129    }
130    pub fn migration(&self) -> Option<UserConfigMigration> {
131        self.migration.clone()
132    }
133    pub fn resolved(&self) -> &crate::config::Config {
134        &self.resolved
135    }
136    pub fn sources(&self, config: &crate::config::Config) -> crate::config_sources::ConfigSources {
137        let mut sources = crate::config_sources::ConfigSources::from_observed_paths(
138            self.user_path.clone(),
139            self.project_path.clone(),
140            &self.tiers,
141            config,
142        );
143        sources.prepared_bind_snapshot_id = Some(self.snapshot_id);
144        if let Some(user) = &self.approved_user {
145            sources.approved_user = Some(user.clone());
146            sources.owns_user_watch = false;
147            sources.user.path = None;
148            sources.user.from_file = false;
149        }
150        sources
151    }
152    pub fn legacy_notice(&self) -> Option<String> {
153        self.tiers
154            .iter()
155            .any(|tier| tier.tier == "project")
156            .then(|| legacy_project_config_location_notice(&self.root, &self.project_path))
157            .flatten()
158    }
159}
160
161pub(super) fn unknown(path: &Path, error: &std::io::Error) -> ConfigObservationError {
162    ConfigObservationError {
163        code: "config_unknown",
164        detail: format!(
165            "could not observe configuration {}: {}",
166            path.display(),
167            error
168        ),
169    }
170}
171
172/// Bound I/O itself, including migration's locked reread, rather than reading
173/// the entire file and checking its size after allocation.
174pub fn read_bounded_config(reader: impl Read, limit: usize) -> std::io::Result<String> {
175    let detection_limit = limit
176        .checked_add(1)
177        .ok_or_else(|| std::io::Error::other("invalid config byte limit"))?;
178    let mut bytes = Vec::new();
179    reader
180        .take(detection_limit as u64)
181        .read_to_end(&mut bytes)?;
182    if bytes.len() > limit {
183        return Err(std::io::Error::other("configuration exceeds byte limit"));
184    }
185    String::from_utf8(bytes)
186        .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
187}
188
189thread_local! {
190    static PREPARED: RefCell<Option<Arc<PreparedBindConfig>>> = const { RefCell::new(None) };
191}
192
193pub fn current_prepared_bind_config() -> Option<Arc<PreparedBindConfig>> {
194    PREPARED.with(|slot| slot.borrow().clone())
195}
196
197pub fn with_prepared_bind_config<T>(
198    prepared: Arc<PreparedBindConfig>,
199    run: impl FnOnce() -> T,
200) -> T {
201    struct Restore(Option<Arc<PreparedBindConfig>>);
202    impl Drop for Restore {
203        fn drop(&mut self) {
204            PREPARED.with(|slot| *slot.borrow_mut() = self.0.take());
205        }
206    }
207    let _restore = Restore(PREPARED.with(|slot| slot.replace(Some(prepared))));
208    run()
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214
215    fn put(path: &Path, text: &str) {
216        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
217        std::fs::write(path, text).unwrap();
218    }
219
220    #[test]
221    fn prepared_read_never_requests_bytes_beyond_limit_plus_one() {
222        struct ReadFence {
223            bytes: usize,
224        }
225        impl Read for &mut ReadFence {
226            fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
227                if out.is_empty() {
228                    return Ok(0);
229                }
230                assert!(self.bytes < 17, "read beyond config limit+1");
231                let count = out.len().min(17 - self.bytes);
232                out[..count].fill(b' ');
233                self.bytes += count;
234                Ok(count)
235            }
236        }
237        let mut reader = ReadFence { bytes: 0 };
238        assert!(read_bounded_config(&mut reader, 16).is_err());
239        assert_eq!(reader.bytes, 17);
240    }
241
242    #[test]
243    fn prepared_migration_rereads_use_the_same_read_time_bound() {
244        let source = include_str!("../config_fix.rs");
245        let body = source
246            .split_once("pub(crate) fn migrate_user_config_to(")
247            .unwrap()
248            .1
249            .split_once("fn auto_migrate_user_config_with_reader(")
250            .unwrap()
251            .0;
252        assert!(body.contains("read_bounded_config(file, limit)"));
253        assert!(!body.contains("read_to_string"));
254        assert!(!body.contains("read_to_end"));
255    }
256
257    #[test]
258    fn prepared_config_uses_active_harness_and_stops_on_unknown_candidate() {
259        let dir = tempfile::tempdir().unwrap();
260        put(
261            &dir.path().join(".pi/aft.jsonc"),
262            r#"{"idle": {"checkout_hours": 7}}"#,
263        );
264        put(
265            &dir.path().join(".opencode/aft.jsonc"),
266            r#"{"idle": {"checkout_hours": 8}}"#,
267        );
268        assert_eq!(
269            PreparedBindConfig::read(None, dir.path(), &Harness::Pi)
270                .unwrap()
271                .resolved()
272                .idle
273                .checkout_hours,
274            7
275        );
276        assert_eq!(
277            PreparedBindConfig::read(None, dir.path(), &Harness::Opencode)
278                .unwrap()
279                .resolved()
280                .idle
281                .checkout_hours,
282            8
283        );
284        std::fs::create_dir_all(dir.path().join(".cortexkit/aft.jsonc")).unwrap();
285        let error = PreparedBindConfig::read(None, dir.path(), &Harness::Pi).unwrap_err();
286        assert_eq!(
287            error.code, "config_unknown",
288            "an unreadable canonical candidate must not select legacy config"
289        );
290    }
291
292    #[test]
293    fn prepared_config_bounds_reads_and_distinguishes_missing_from_invalid() {
294        let dir = tempfile::tempdir().unwrap();
295        assert!(PreparedBindConfig::read(None, dir.path(), &Harness::Pi)
296            .unwrap()
297            .tiers()
298            .is_empty());
299        let path = dir.path().join(".cortexkit/aft.jsonc");
300        put(&path, &" ".repeat(CONFIG_FILE_LIMIT + 1));
301        assert_eq!(
302            PreparedBindConfig::read(None, dir.path(), &Harness::Pi)
303                .unwrap_err()
304                .code,
305            "config_unknown"
306        );
307        put(&path, "{ invalid config");
308        assert_eq!(
309            PreparedBindConfig::read(None, dir.path(), &Harness::Pi)
310                .unwrap_err()
311                .code,
312            "config_rejected"
313        );
314    }
315
316    #[test]
317    fn prepared_config_scope_restores_on_unwind() {
318        let dir = tempfile::tempdir().unwrap();
319        let snapshot = PreparedBindConfig::read(None, dir.path(), &Harness::Pi).unwrap();
320        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
321            with_prepared_bind_config(snapshot, || panic!("scope unwind"))
322        }));
323        assert!(current_prepared_bind_config().is_none());
324    }
325
326    #[test]
327    fn prepared_nested_scope_restores_the_previous_snapshot_after_unwind() {
328        let dir = tempfile::tempdir().unwrap();
329        let outer = PreparedBindConfig::read(None, dir.path(), &Harness::Pi).unwrap();
330        let inner = PreparedBindConfig::read(None, dir.path(), &Harness::Opencode).unwrap();
331        let expected = outer.id();
332        with_prepared_bind_config(outer, || {
333            let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
334                with_prepared_bind_config(inner, || panic!("nested scope unwind"))
335            }));
336            assert_eq!(current_prepared_bind_config().unwrap().id(), expected);
337        });
338        assert!(current_prepared_bind_config().is_none());
339    }
340}