Skip to main content

subc_daemon/config_gate/
capture.rs

1//! Bounded, handle-bound proposal capture. Raw bytes are ephemeral until review.
2
3use std::{
4    collections::{BTreeMap, BTreeSet},
5    fs::File,
6    io::{self, Read},
7    path::{Path, PathBuf},
8    sync::Arc,
9};
10
11use serde::{Deserialize, Serialize};
12use serde_json::{json, Value};
13use subc_config::{
14    Digest, InputState, Layer, LayerValue, RecordedValue, Schema, ValidationContext,
15};
16use subc_control::config::{ConfigFileError, ConfigStatusFileError};
17use subc_protocol::config::{
18    ConfigDeclareRequest, ConfigLayer, ConfigLayerSnapshot, ConfigStatus, ConfigView,
19};
20
21use super::{CapturedInput, GateError, GateSnapshot, InputKey, Result};
22
23// A configuration document is small control-plane input, not an unbounded stream.
24/// Bound untrusted JSONC reads and parsing to 1 MiB per document.
25pub(super) const CONFIG_FILE_LIMIT: u64 = 1024 * 1024;
26/// Bound streamed executable hashing so a proposal cannot demand an endless scan.
27const PROGRAM_FILE_LIMIT: u64 = 512 * 1024 * 1024;
28
29/// A file-object id is distinct from its bytes and from its pathname.
30#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
31#[serde(tag = "platform", rename_all = "snake_case")]
32pub enum FileObjectId {
33    Unix {
34        #[serde(with = "decimal_id")]
35        device: u64,
36        #[serde(with = "decimal_id")]
37        inode: u64,
38    },
39    Windows {
40        #[serde(with = "decimal_id")]
41        volume_serial_number: u64,
42        file_id: [u8; 16],
43    },
44}
45
46pub(super) mod decimal_id {
47    use serde::{Deserialize, Deserializer, Serializer};
48    pub fn serialize<S: Serializer>(
49        value: &u64,
50        serializer: S,
51    ) -> std::result::Result<S::Ok, S::Error> {
52        serializer.serialize_str(&value.to_string())
53    }
54    pub fn deserialize<'de, D: Deserializer<'de>>(
55        deserializer: D,
56    ) -> std::result::Result<u64, D::Error> {
57        String::deserialize(deserializer)?
58            .parse()
59            .map_err(serde::de::Error::custom)
60    }
61}
62
63pub(super) fn file_object_id(file: &File) -> Result<FileObjectId> {
64    let id = subc_os::retained_file_identity(file).map_err(capture_error)?;
65    #[cfg(unix)]
66    return Ok(FileObjectId::Unix {
67        device: id.device,
68        inode: id.inode,
69    });
70    #[cfg(windows)]
71    return Ok(FileObjectId::Windows {
72        volume_serial_number: id.volume_serial_number,
73        file_id: id.file_id,
74    });
75}
76
77/// A bounded change detector: timestamps can coalesce same-size writes, so
78/// unchanged metadata must also have an equal content digest on every platform.
79#[derive(Clone, Debug, PartialEq, Eq)]
80pub(crate) struct UserFileMetadata {
81    identity: FileObjectId,
82    length: u64,
83    modified: Option<std::time::SystemTime>,
84    content_digest: Option<subc_config::Digest>,
85}
86
87impl UserFileMetadata {
88    pub(crate) fn has_content_digest(&self) -> bool {
89        self.content_digest.is_some()
90    }
91
92    pub(super) fn content_digest(&self) -> Option<&Digest> {
93        self.content_digest.as_ref()
94    }
95
96    pub(crate) fn read(path: &Path) -> Result<Option<Self>> {
97        let metadata = match std::fs::symlink_metadata(path) {
98            Ok(metadata) => metadata,
99            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
100            Err(error) => return Err(capture_error(error)),
101        };
102        if !metadata.is_file() || metadata.file_type().is_symlink() {
103            return Err(GateError::new(
104                "path_invalid",
105                "user file must be a regular file",
106            ));
107        }
108        let file = subc_os::open_regular_nofollow(path).map_err(capture_error)?;
109        let metadata = file.metadata().map_err(capture_error)?;
110        let identity = file_object_id(&file)?;
111        // Hash at most 1 MiB, the same bound as configuration capture. One
112        // extra byte detects growth while reading. Larger or unstable files
113        // have no digest and must never be classified as unchanged.
114        let content_digest = if metadata.len() <= CONFIG_FILE_LIMIT {
115            let mut bytes = Vec::with_capacity(metadata.len() as usize);
116            (&file)
117                .take(CONFIG_FILE_LIMIT + 1)
118                .read_to_end(&mut bytes)
119                .map_err(capture_error)?;
120            let after = file.metadata().map_err(capture_error)?;
121            (bytes.len() as u64 == metadata.len()
122                && after.len() == metadata.len()
123                && after.modified().ok() == metadata.modified().ok())
124            .then(|| subc_config::raw_digest(&bytes))
125        } else {
126            None
127        };
128        Ok(Some(Self {
129            identity,
130            length: metadata.len(),
131            modified: metadata.modified().ok(),
132            content_digest,
133        }))
134    }
135}
136
137#[cfg(test)]
138pub(crate) use super::project_registry::OfflineProjectRegistry;
139pub use super::project_registry::{ProjectRegistry, RegistryRevision};
140
141pub struct ConfigCapturer {
142    pub daemon_path: PathBuf,
143    pub config_home: PathBuf,
144    pub projects: Arc<dyn ProjectRegistry>,
145}
146
147/// The handle remains open until capture/validation completes. It is never
148/// serialized: only its file identity, byte digest and redacted values are.
149pub struct CapturedFile {
150    _file: Option<File>,
151    pub path: PathBuf,
152    pub bytes: Option<Vec<u8>>,
153    pub state: InputState,
154}
155
156fn capture_error(_: impl std::fmt::Display) -> GateError {
157    // OS/parser errors can echo submitted text. Do not put it in a retained view.
158    GateError::new(
159        "input_unavailable",
160        "configuration input could not be captured",
161    )
162}
163
164impl CapturedFile {
165    pub fn open(path: &Path) -> Result<Self> {
166        Self::open_with_read_hook(path, || {})
167    }
168
169    pub(crate) fn open_with_read_hook(path: &Path, after_read: impl FnOnce()) -> Result<Self> {
170        if !path.is_absolute() {
171            return Err(GateError::new(
172                "path_invalid",
173                "configuration input must be absolute",
174            ));
175        }
176        let before = match std::fs::symlink_metadata(path) {
177            Ok(metadata) => metadata,
178            Err(error) if error.kind() == io::ErrorKind::NotFound => {
179                return Ok(Self {
180                    _file: None,
181                    path: path.into(),
182                    bytes: None,
183                    state: InputState::Absent,
184                });
185            }
186            Err(error) => return Err(capture_error(error)),
187        };
188        if !before.is_file() || before.file_type().is_symlink() {
189            return Err(GateError::new(
190                "path_invalid",
191                "configuration input must be a regular non-symlink file",
192            ));
193        }
194        let file = subc_os::open_regular_nofollow(path).map_err(capture_error)?;
195        let metadata = file.metadata().map_err(capture_error)?;
196        if !metadata.is_file() || metadata.len() > CONFIG_FILE_LIMIT {
197            return Err(GateError::new(
198                "input_too_large",
199                "configuration document exceeds the 1 MiB JSONC limit",
200            ));
201        }
202        let id = file_object_id(&file)?;
203        let mut bytes = Vec::with_capacity(metadata.len() as usize);
204        (&file)
205            .take(CONFIG_FILE_LIMIT + 1)
206            .read_to_end(&mut bytes)
207            .map_err(capture_error)?;
208        after_read();
209        let after = file.metadata().map_err(capture_error)?;
210        let supplied = std::fs::symlink_metadata(path).map_err(capture_error)?;
211        let reopened = subc_os::open_regular_nofollow(path).map_err(capture_error)?;
212        if bytes.len() as u64 > CONFIG_FILE_LIMIT {
213            return Err(GateError::new(
214                "input_too_large",
215                "configuration document exceeds the 1 MiB JSONC limit",
216            ));
217        }
218        if bytes.len() as u64 != metadata.len()
219            || after.len() != metadata.len()
220            || after.modified().ok() != metadata.modified().ok()
221            || !supplied.is_file()
222            || supplied.file_type().is_symlink()
223            || file_object_id(&reopened)? != id
224        {
225            return Err(GateError::capture_race());
226        }
227        let digest = subc_config::raw_digest(&serde_json::to_vec(&json!({
228            "file": id, "raw": subc_config::raw_digest(&bytes), "length": metadata.len(),
229            "modified": metadata.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| (d.as_secs(), d.subsec_nanos())),
230        })).map_err(GateError::invalid)?);
231        Ok(Self {
232            _file: Some(file),
233            path: path.into(),
234            bytes: Some(bytes),
235            state: InputState::Present { digest },
236        })
237    }
238
239    pub(super) fn parse(&self) -> Result<Value> {
240        self.parse_with_canonical_context(|error| error)
241    }
242
243    fn parse_with_canonical_context(
244        &self,
245        with_context: impl FnOnce(GateError) -> GateError,
246    ) -> Result<Value> {
247        match &self.bytes {
248            Some(bytes) => parse_layer_with_canonical_context(bytes, with_context),
249            None => Ok(json!({})),
250        }
251    }
252
253    pub(super) fn take_handles(&mut self) -> Vec<File> {
254        self._file.take().into_iter().collect()
255    }
256}
257
258pub(super) fn parse_layer(bytes: &[u8]) -> Result<Value> {
259    parse_layer_with_canonical_context(bytes, |error| error)
260}
261
262fn parse_layer_with_canonical_context(
263    bytes: &[u8],
264    with_context: impl FnOnce(GateError) -> GateError,
265) -> Result<Value> {
266    let text = std::str::from_utf8(bytes).map_err(capture_error)?;
267    let normalized = subc_jsonc::jsonc_to_json(text).map_err(capture_error)?;
268    super::strict_json::parse_with_canonical_context(&normalized, with_context)
269}
270
271pub struct CapturedModule {
272    pub declaration: ConfigDeclareRequest,
273    pub schema: Schema,
274    pub view: ConfigView,
275    pub file: CapturedFile,
276}
277
278pub struct CapturedConfiguration {
279    pub diagnostic: GateSnapshot,
280    pub daemon: CapturedFile,
281    pub modules: BTreeMap<String, CapturedModule>,
282    _program_handles: Vec<File>,
283}
284
285pub(crate) struct SettingsCapture {
286    pub configuration: CapturedConfiguration,
287    pub file_errors: BTreeMap<String, ConfigFileError>,
288    pub(super) refused_file_digests: BTreeMap<String, Digest>,
289    pub module_errors: BTreeMap<String, GateError>,
290}
291
292impl SettingsCapture {
293    fn has_error(&self, module: &str) -> bool {
294        self.module_errors.contains_key(module) || self.file_errors.contains_key(module)
295    }
296
297    pub(super) fn proposal_snapshot(&self, approved: &GateSnapshot) -> GateSnapshot {
298        let mut snapshot = self.configuration.proposal_snapshot(approved);
299        // A failed observation is not evidence that the approved inputs vanished.
300        for (key, input) in &approved.inputs {
301            if let InputKey::Declaration(module) | InputKey::Layer { module, .. } = key {
302                if self.has_error(module) {
303                    snapshot.inputs.insert(key.clone(), input.clone());
304                }
305            }
306        }
307        snapshot
308    }
309
310    pub(super) fn report_errors(&self, status: &mut subc_control::config::ConfigStatus) {
311        status
312            .ungated_modules
313            .retain(|module| !self.has_error(module));
314        for (module, error) in &self.module_errors {
315            status.warnings.push(format!("module {module}: {error}"));
316        }
317        for (module, error) in &self.file_errors {
318            status.warnings.push(format!(
319                "module {module}: {}: {}",
320                error.code, error.message
321            ));
322            status
323                .file_errors
324                .push(ConfigStatusFileError::new(module.clone(), error.clone()));
325        }
326    }
327}
328
329impl CapturedConfiguration {
330    /// Edit candidates bind content before the replacement file has an identity.
331    /// For drift reporting, equal written bytes satisfy that approved digest;
332    /// keep the original capture fingerprints for review and compare-and-swap.
333    pub(crate) fn proposal_snapshot(&self, approved: &GateSnapshot) -> GateSnapshot {
334        let mut snapshot = self.diagnostic.clone();
335        for (key, input) in &mut snapshot.inputs {
336            let InputKey::Layer { module, path } = key else {
337                continue;
338            };
339            let Some(previous) = approved.inputs.get(key) else {
340                continue;
341            };
342            let Some(file) = self.modules.get(module).map(|module| &module.file) else {
343                continue;
344            };
345            if file.path.to_string_lossy() == path.as_str()
346                && input.value == previous.value
347                && file.bytes.as_deref().is_some_and(|bytes| {
348                    previous.state
349                        == InputState::Present {
350                            digest: subc_config::raw_digest(bytes),
351                        }
352                })
353            {
354                input.state = previous.state.clone();
355            }
356        }
357        snapshot
358    }
359
360    pub(crate) fn take_handles(&mut self) -> Vec<File> {
361        let mut handles = std::mem::take(&mut self._program_handles);
362        handles.extend(self.daemon._file.take());
363        for module in self.modules.values_mut() {
364            handles.extend(module.file._file.take());
365        }
366        handles
367    }
368
369    /// A rollback may restore a path different from the current configuration's
370    /// path. Bind both programs in the observed read set without restoring any
371    /// historical executable bytes or trusting a historical file identity.
372    pub(crate) fn capture_programs(&mut self, keys: &[InputKey]) -> Result<()> {
373        for key in keys {
374            if self.diagnostic.inputs.contains_key(key) {
375                continue;
376            }
377            let InputKey::Program { path, .. } = key else {
378                unreachable!()
379            };
380            let (file, captured) = capture_program(Path::new(path))?;
381            self.diagnostic.inputs.insert(key.clone(), captured);
382            self._program_handles.push(file);
383        }
384        Ok(())
385    }
386}
387
388impl ConfigCapturer {
389    /// Candidate configuration only: no approved-store access, keychain work or
390    /// executable capture belongs on a polled diagnostic read.
391    pub(crate) fn capture_polled(
392        &self,
393        declarations: &BTreeMap<String, ConfigDeclareRequest>,
394    ) -> Result<GateSnapshot> {
395        self.capture_polled_configuration(declarations)
396            .map(|captured| captured.diagnostic)
397    }
398
399    pub(crate) fn capture_polled_configuration(
400        &self,
401        declarations: &BTreeMap<String, ConfigDeclareRequest>,
402    ) -> Result<CapturedConfiguration> {
403        let daemon = CapturedFile::open(&self.daemon_path)?;
404        self.capture_layers(daemon, declarations, None, false, CapturedFile::open)
405    }
406
407    /// Settings observations report invalid declarations and files per module.
408    /// Planning and delivery still reject invalid inputs they select.
409    pub(crate) fn capture_settings(
410        &self,
411        declarations: &BTreeMap<String, ConfigDeclareRequest>,
412    ) -> Result<SettingsCapture> {
413        self.capture_settings_with(declarations, CapturedFile::open)
414    }
415
416    pub(crate) fn capture_settings_with(
417        &self,
418        declarations: &BTreeMap<String, ConfigDeclareRequest>,
419        layer_file: impl FnMut(&Path) -> Result<CapturedFile>,
420    ) -> Result<SettingsCapture> {
421        let daemon = CapturedFile::open(&self.daemon_path)?;
422        self.capture_layers_observed::<true>(daemon, declarations, None, false, layer_file)
423    }
424
425    pub(super) fn capture_status(
426        &self,
427        declarations: &BTreeMap<String, ConfigDeclareRequest>,
428    ) -> Result<SettingsCapture> {
429        let daemon = CapturedFile::open(&self.daemon_path)?;
430        self.capture_layers_observed::<true>(daemon, declarations, None, true, CapturedFile::open)
431    }
432
433    pub fn capture(
434        &self,
435        declarations: &BTreeMap<String, ConfigDeclareRequest>,
436    ) -> Result<CapturedConfiguration> {
437        self.capture_selected(declarations, None)
438    }
439
440    pub fn capture_modules(
441        &self,
442        declarations: &BTreeMap<String, ConfigDeclareRequest>,
443        modules: &BTreeSet<String>,
444    ) -> Result<CapturedConfiguration> {
445        self.capture_selected(declarations, Some(modules))
446    }
447
448    /// Capture the selected modules' settings files without reading their
449    /// programs. A settings view never uses program identity, and capturing a
450    /// program hashes the whole binary. On an unstamped install (one with no
451    /// approved settings store), the project poll did that for every requested
452    /// project every two seconds, which kept the daemon at about two cores.
453    /// Plans and approvals still use [`Self::capture_modules`].
454    pub fn capture_module_settings(
455        &self,
456        declarations: &BTreeMap<String, ConfigDeclareRequest>,
457        modules: &BTreeSet<String>,
458    ) -> Result<CapturedConfiguration> {
459        let daemon = CapturedFile::open(&self.daemon_path)?;
460        self.capture_layers(
461            daemon,
462            declarations,
463            Some(modules),
464            false,
465            CapturedFile::open,
466        )
467    }
468
469    pub(super) fn project_daemon_digest(&self) -> Result<Option<subc_config::Digest>> {
470        let daemon = CapturedFile::open(&self.daemon_path)?;
471        let captured =
472            self.capture_layers(daemon, &BTreeMap::new(), None, false, CapturedFile::open)?;
473        Ok(captured
474            .daemon
475            .bytes
476            .as_deref()
477            .map(subc_config::raw_digest))
478    }
479
480    pub(super) fn capture_project_user(
481        &self,
482        module: &str,
483        declaration: &ConfigDeclareRequest,
484        file: Result<CapturedFile>,
485    ) -> Result<CapturedModule> {
486        declaration_input(module, declaration)?;
487        self.capture_module(module, declaration, |_| file)
488            .map(|(module, _)| module)
489    }
490
491    fn capture_selected(
492        &self,
493        declarations: &BTreeMap<String, ConfigDeclareRequest>,
494        selected: Option<&BTreeSet<String>>,
495    ) -> Result<CapturedConfiguration> {
496        let daemon = CapturedFile::open(&self.daemon_path)?;
497        self.capture_layers(daemon, declarations, selected, true, CapturedFile::open)
498    }
499
500    pub(super) fn capture_with_retained_user(
501        &self,
502        declarations: &BTreeMap<String, ConfigDeclareRequest>,
503        selected: Option<&BTreeSet<String>>,
504        mut retained: BTreeMap<PathBuf, CapturedFile>,
505    ) -> Result<CapturedConfiguration> {
506        let daemon = CapturedFile::open(&self.daemon_path)?;
507        self.capture_layers(daemon, declarations, selected, true, |path| {
508            retained
509                .remove(path)
510                .map_or_else(|| CapturedFile::open(path), Ok)
511        })
512    }
513
514    /// Re-evaluate saved raw configuration rather than today's edited files.
515    /// Program capture still opens the files at the restored configured paths.
516    pub(crate) fn capture_retained(
517        &self,
518        target: &GateSnapshot,
519        delivery: &crate::config_store::DeliverySnapshot,
520    ) -> Result<CapturedConfiguration> {
521        self.capture_retained_inner(target, delivery, &delivery.declarations, true)
522    }
523
524    pub(crate) fn capture_retained_declared(
525        &self,
526        target: &GateSnapshot,
527        delivery: &crate::config_store::DeliverySnapshot,
528        declarations: &BTreeMap<String, ConfigDeclareRequest>,
529    ) -> Result<CapturedConfiguration> {
530        self.capture_retained_inner(target, delivery, declarations, false)
531    }
532
533    fn capture_retained_inner(
534        &self,
535        target: &GateSnapshot,
536        delivery: &crate::config_store::DeliverySnapshot,
537        declarations: &BTreeMap<String, ConfigDeclareRequest>,
538        require_identical: bool,
539    ) -> Result<CapturedConfiguration> {
540        let invalid = || {
541            GateError::new(
542                "rollback_snapshot_unavailable",
543                "retained raw configuration is absent or inconsistent",
544            )
545        };
546        let retained_file = |layer: &ConfigLayerSnapshot, key: &InputKey| -> Result<CapturedFile> {
547            let path = layer.path.as_ref().ok_or_else(invalid)?;
548            let input = target.inputs.get(key).ok_or_else(invalid)?;
549            if layer.bytes.as_deref().map(subc_config::raw_digest) != layer.digest {
550                return Err(invalid());
551            }
552            Ok(CapturedFile {
553                path: path.into(),
554                bytes: layer.bytes.clone(),
555                state: input.state.clone(),
556                _file: None,
557            })
558        };
559        let daemon = retained_file(
560            delivery.daemon.as_ref().ok_or_else(invalid)?,
561            &InputKey::Daemon,
562        )?;
563        if daemon.path != self.daemon_path || daemon.bytes.is_none() {
564            return Err(invalid());
565        }
566        let mut files = BTreeMap::new();
567        for (module, view) in &delivery.modules {
568            let [layer] = view.layers.as_slice() else {
569                return Err(invalid());
570            };
571            if layer.layer != ConfigLayer::User
572                || layer.module_id != *module
573                || layer.project_id.is_some()
574                || layer.workspace_id.is_some()
575            {
576                return Err(invalid());
577            }
578            let path = layer.path.as_ref().ok_or_else(invalid)?;
579            let file = retained_file(
580                layer,
581                &InputKey::Layer {
582                    module: module.clone(),
583                    path: path.clone(),
584                },
585            )?;
586            files.insert(file.path.clone(), file);
587        }
588        let captured = self.capture_layers(daemon, declarations, None, true, |path| {
589            files.remove(path).ok_or_else(invalid)
590        })?;
591        if !files.is_empty()
592            || (require_identical
593                && target
594                    .inputs
595                    .iter()
596                    .filter(|(key, _)| !key.is_program() && !key.is_project())
597                    .ne(captured
598                        .diagnostic
599                        .inputs
600                        .iter()
601                        .filter(|(key, _)| !key.is_program())))
602        {
603            return Err(invalid());
604        }
605        Ok(captured)
606    }
607
608    fn capture_layers(
609        &self,
610        daemon: CapturedFile,
611        declarations: &BTreeMap<String, ConfigDeclareRequest>,
612        selected: Option<&BTreeSet<String>>,
613        programs: bool,
614        layer_file: impl FnMut(&Path) -> Result<CapturedFile>,
615    ) -> Result<CapturedConfiguration> {
616        self.capture_layers_observed::<false>(daemon, declarations, selected, programs, layer_file)
617            .map(|captured| captured.configuration)
618    }
619
620    fn capture_layers_observed<const REPORT_MODULE_ERRORS: bool>(
621        &self,
622        daemon: CapturedFile,
623        declarations: &BTreeMap<String, ConfigDeclareRequest>,
624        selected: Option<&BTreeSet<String>>,
625        programs: bool,
626        mut layer_file: impl FnMut(&Path) -> Result<CapturedFile>,
627    ) -> Result<SettingsCapture> {
628        let invalid_daemon =
629            || GateError::new("invalid_daemon_config", "captured subc.jsonc is invalid");
630        let doc = daemon.parse().map_err(|_| invalid_daemon())?;
631        let mut launch_specs = BTreeMap::new();
632        if let Some(bytes) = &daemon.bytes {
633            let (config, _) = crate::daemon_config::parse_with_activity(
634                std::str::from_utf8(bytes).map_err(|_| invalid_daemon())?,
635                &self.daemon_path,
636            )
637            .map_err(|_| invalid_daemon())?;
638            launch_specs.extend(
639                config
640                    .modules
641                    .into_iter()
642                    .map(|module| (module.module_id.clone(), module.module_spec())),
643            );
644            refuse_expansions(&doc, "subc", "")?;
645        }
646        let mut program_handles = Vec::new();
647        // Launch arguments and environment participate in review verbatim;
648        // credential reference objects remain redacted in diagnostic views.
649        let safe_doc = redact_launch_values(&doc)?;
650        let mut diagnostic = GateSnapshot::default();
651        diagnostic.inputs.insert(
652            InputKey::Daemon,
653            CapturedInput {
654                state: daemon.state.clone(),
655                value: RecordedValue::new(safe_doc.clone()),
656            },
657        );
658        if let Some(entries) = safe_doc.get("modules").and_then(Value::as_object) {
659            for (module, entry) in entries {
660                diagnostic.inputs.insert(
661                    InputKey::Entry(module.clone()),
662                    CapturedInput {
663                        state: InputState::Present {
664                            digest: subc_config::raw_digest(
665                                &serde_json::to_vec(entry).map_err(GateError::invalid)?,
666                            ),
667                        },
668                        value: RecordedValue::new(entry.clone()),
669                    },
670                );
671            }
672        }
673        if let Some(entries) = doc
674            .get("modules")
675            .and_then(Value::as_object)
676            .filter(|_| programs)
677        {
678            for (module, entry) in entries {
679                if selected.is_some_and(|modules| !modules.contains(module)) {
680                    continue;
681                }
682                if let Some(spec) = launch_specs.get(module) {
683                    let covered = super::program::program_files(entry)?;
684                    let launch = super::program::capture(spec, &covered).map_err(|error| {
685                        GateError::new(&error.code, format!("{module}: {}", error.detail))
686                    })?;
687                    diagnostic.inputs.extend(launch.inputs);
688                    program_handles.extend(launch.files);
689                }
690            }
691        }
692        let mut modules = BTreeMap::new();
693        let mut file_errors = BTreeMap::new();
694        let mut refused_file_digests = BTreeMap::new();
695        let mut module_errors = BTreeMap::new();
696        for (module, declaration) in declarations {
697            if selected.is_some_and(|modules| !modules.contains(module)) {
698                continue;
699            }
700            let decl_input = match declaration_input(module, declaration) {
701                Ok(input) => input,
702                Err(error) if REPORT_MODULE_ERRORS => {
703                    module_errors.insert(module.clone(), error);
704                    continue;
705                }
706                Err(error) => return Err(error),
707            };
708            let (captured, input) = match self.capture_module(module, declaration, &mut layer_file)
709            {
710                Ok(captured) => captured,
711                Err(error) if REPORT_MODULE_ERRORS && !error.is_capture_race() => {
712                    if is_settings_file_error(&error) {
713                        if let Some(digest) = error
714                            .settings_file
715                            .as_ref()
716                            .and_then(|file| file.content_digest.as_ref())
717                        {
718                            refused_file_digests.insert(module.clone(), digest.clone());
719                        }
720                        file_errors.insert(module.clone(), error.into_settings_file_error());
721                    } else {
722                        module_errors.insert(module.clone(), error);
723                    }
724                    continue;
725                }
726                Err(error) => return Err(error),
727            };
728            diagnostic.inputs.insert(
729                InputKey::Layer {
730                    module: module.clone(),
731                    path: captured.file.path.to_string_lossy().into_owned(),
732                },
733                input,
734            );
735            diagnostic
736                .inputs
737                .insert(InputKey::Declaration(module.clone()), decl_input);
738            modules.insert(module.clone(), captured);
739        }
740        Ok(SettingsCapture {
741            configuration: CapturedConfiguration {
742                diagnostic,
743                daemon,
744                modules,
745                _program_handles: program_handles,
746            },
747            file_errors,
748            refused_file_digests,
749            module_errors,
750        })
751    }
752
753    pub(super) fn module_settings_path(
754        &self,
755        module: &str,
756        declaration: &ConfigDeclareRequest,
757    ) -> Result<PathBuf> {
758        if !declaration.project_dirs.is_empty() {
759            // Workspace/project roots must come from the project registry,
760            // not from directories supplied by the module.
761            return Err(GateError::new(
762                "config_gated",
763                format!("{module}: project-tuple planning and delivery are not supported yet"),
764            ));
765        }
766        if module.is_empty() || module.contains(['/', '\\']) || module == "." || module == ".." {
767            return Err(GateError::new(
768                "path_invalid",
769                "module identity cannot form a layer path",
770            ));
771        }
772        let expected = self
773            .config_home
774            .join("cortexkit")
775            .join(format!("{module}.jsonc"));
776        if Path::new(&declaration.user_file) != expected || !expected.is_absolute() {
777            return Err(GateError::new(
778                "path_invalid",
779                format!("{module}: user layer must use its canonical config-home path"),
780            ));
781        }
782        Ok(expected)
783    }
784
785    pub(super) fn capture_module(
786        &self,
787        module: &str,
788        declaration: &ConfigDeclareRequest,
789        layer_file: impl FnOnce(&Path) -> Result<CapturedFile>,
790    ) -> Result<(CapturedModule, CapturedInput)> {
791        let expected = self.module_settings_path(module, declaration)?;
792        let schema = Schema::new(declaration.schema.clone()).map_err(|refusal| {
793            GateError::new("schema_invalid", format!("{module}: {}", refusal.path))
794        })?;
795        let file_context = |mut error: GateError| {
796            error.detail = format!("{module}: {}: {}", expected.display(), error.detail);
797            error
798        };
799        let file = layer_file(&expected).map_err(|error| {
800            if is_settings_file_error(&error) {
801                error.at_user_file(&expected, None)
802            } else {
803                error
804            }
805        })?;
806        let at_user_file = |error: GateError| error.at_user_file(&expected, file.bytes.as_deref());
807        let value = file
808            .parse_with_canonical_context(file_context)
809            .map_err(at_user_file)?;
810        refuse_expansions(&value, module, "").map_err(at_user_file)?;
811        // Record even invalid literals through the schema projection first;
812        // nothing raw is retained on the refusal path.
813        let recorded = schema
814            .record(&value)
815            .map_err(|error| at_user_file(GateError::invalid(error)))?;
816        let layers = if file.bytes.is_some() {
817            vec![LayerValue::new(Layer::User, value)]
818        } else {
819            Vec::new()
820        };
821        let reviewed = schema
822            .review_tuple_attributed(&layers, &ValidationContext::new(module, None))
823            .map_err(|error| {
824                let refusal = GateError::new(
825                    refusal_code(error.refusal.code),
826                    format!("{module}: {}", error.refusal.path),
827                );
828                match error.layer {
829                    Some(Layer::User) => at_user_file(refusal),
830                    _ => refusal,
831                }
832            })?;
833        let layer = ConfigLayerSnapshot::file(
834            module,
835            ConfigLayer::User,
836            expected.to_string_lossy(),
837            file.bytes.clone(),
838        );
839        let view = ConfigView::new(
840            0,
841            reviewed.effective,
842            reviewed.sources,
843            vec![layer],
844            ConfigStatus::Unstamped,
845        );
846        let input = CapturedInput {
847            state: file.state.clone(),
848            value: RecordedValue::new(recorded),
849        };
850        Ok((
851            CapturedModule {
852                declaration: declaration.clone(),
853                schema,
854                view,
855                file,
856            },
857            input,
858        ))
859    }
860
861    pub(crate) fn settings_file_error(
862        &self,
863        module: &str,
864        declaration: &ConfigDeclareRequest,
865    ) -> Result<Option<ConfigFileError>> {
866        match self.capture_module(module, declaration, CapturedFile::open) {
867            Ok(_) => Ok(None),
868            Err(error) if is_settings_file_error(&error) => {
869                Ok(Some(error.into_settings_file_error()))
870            }
871            Err(error) => Err(error),
872        }
873    }
874}
875
876impl CapturedFile {
877    pub(super) fn retained(path: PathBuf, bytes: Option<Vec<u8>>, state: InputState) -> Self {
878        Self {
879            _file: None,
880            path,
881            bytes,
882            state,
883        }
884    }
885}
886
887fn declaration_input(module: &str, declaration: &ConfigDeclareRequest) -> Result<CapturedInput> {
888    let value = serde_json::to_value(declaration).map_err(GateError::invalid)?;
889    let digest =
890        subc_config::digest(subc_config::PURPOSE_DECLARATION, &value).map_err(|error| {
891            let mut error = super::strict_json::canonical_error(error, &value, "");
892            error.detail = format!("{module}: {}", error.detail);
893            error
894        })?;
895    Ok(CapturedInput {
896        state: InputState::Present { digest },
897        value: RecordedValue::new(redact_launch_values(&value)?),
898    })
899}
900
901fn is_settings_file_error(error: &GateError) -> bool {
902    error.settings_file.is_some()
903        || matches!(error.code.as_str(), "value_invalid" | "input_unavailable")
904}
905
906fn redact_launch_values(value: &Value) -> Result<Value> {
907    if subc_config::is_vault_reference(value) {
908        return serde_json::to_value(RecordedValue::redacted(value).map_err(GateError::invalid)?)
909            .map_err(GateError::invalid);
910    }
911    match value {
912        Value::Object(object) => object
913            .iter()
914            .map(|(key, value)| {
915                let value = redact_launch_values(value)?;
916                Ok((key.clone(), value))
917            })
918            .collect::<Result<serde_json::Map<_, _>>>()
919            .map(Value::Object),
920        Value::Array(array) => array
921            .iter()
922            .map(redact_launch_values)
923            .collect::<Result<Vec<_>>>()
924            .map(Value::Array),
925        value => Ok(value.clone()),
926    }
927}
928
929pub(crate) fn capture_program(path: &Path) -> Result<(File, CapturedInput)> {
930    let (file, input, _) = capture_program_classified(path)?;
931    Ok((file, input))
932}
933
934pub(crate) fn capture_program_classified(path: &Path) -> Result<(File, CapturedInput, bool)> {
935    use sha2::{Digest as _, Sha256};
936    if !path.is_absolute() {
937        return Err(GateError::new(
938            "path_invalid",
939            "covered program path must be absolute",
940        ));
941    }
942    let resolved = std::fs::canonicalize(path).map_err(|error| {
943        if error.kind() == io::ErrorKind::NotFound {
944            GateError::new("program_missing", "configured program file is absent")
945        } else {
946            capture_error(error)
947        }
948    })?;
949    let file = subc_os::open_regular_nofollow(&resolved).map_err(capture_error)?;
950    let before = file.metadata().map_err(capture_error)?;
951    if !before.is_file() {
952        return Err(GateError::new(
953            "path_invalid",
954            "covered program must be a regular file",
955        ));
956    }
957    if before.len() > PROGRAM_FILE_LIMIT {
958        return Err(GateError::new(
959            "input_too_large",
960            "covered program exceeds the 512 MiB streamed-hash limit",
961        ));
962    }
963    let id = file_object_id(&file)?;
964    let mut hasher = Sha256::new();
965    let mut length = 0;
966    // Classify the same byte stream that supplies the approved hash, not an
967    // earlier path open that could have seen different content on this inode.
968    let mut prefix = Vec::with_capacity(2);
969    #[cfg(target_os = "macos")]
970    let signatures = subc_os::code_signature::file_signature(&file, |chunk| {
971        prefix.extend_from_slice(&chunk[..chunk.len().min(2 - prefix.len())]);
972        length += chunk.len() as u64;
973        hasher.update(chunk);
974    });
975    #[cfg(not(target_os = "macos"))]
976    {
977        let mut reader = &file;
978        let mut buffer = [0; 64 * 1024];
979        loop {
980            let count = reader.read(&mut buffer).map_err(capture_error)?;
981            if count == 0 {
982                break;
983            }
984            prefix.extend_from_slice(&buffer[..count.min(2 - prefix.len())]);
985            length += count as u64;
986            if length > PROGRAM_FILE_LIMIT {
987                return Err(GateError::new(
988                    "input_too_large",
989                    "covered program exceeds the 512 MiB streamed-hash limit",
990                ));
991            }
992            hasher.update(&buffer[..count]);
993        }
994    }
995    let after = file.metadata().map_err(capture_error)?;
996    let reopened = subc_os::open_regular_nofollow(&resolved).map_err(capture_error)?;
997    #[cfg(target_os = "macos")]
998    let completed = signatures.is_ok();
999    #[cfg(not(target_os = "macos"))]
1000    let completed = true;
1001    if (completed && length != before.len())
1002        || std::fs::canonicalize(path).map_err(capture_error)? != resolved
1003        || before.len() != after.len()
1004        || before.modified().ok() != after.modified().ok()
1005        || file_object_id(&reopened)? != id
1006    {
1007        return Err(GateError::stale());
1008    }
1009    #[cfg(target_os = "macos")]
1010    let signatures = signatures.map_err(|error| match error {
1011        subc_os::code_signature::SignatureError::Parse => GateError::new(
1012            "program_invalid",
1013            "covered program has an invalid or unsupported Mach-O structure",
1014        ),
1015        other => capture_error(other),
1016    })?;
1017    let identity = json!({ "path": resolved, "file": id, "length": length, "raw": format!("sha256:{:x}", hasher.finalize()) });
1018    #[cfg(target_os = "macos")]
1019    let identity = {
1020        let mut identity = identity;
1021        match signatures {
1022            subc_os::code_signature::FileSignature::Signed(hashes) => {
1023                identity["cdhashes"] = json!(hashes
1024                    .into_iter()
1025                    .map(|hash| hash
1026                        .0
1027                        .iter()
1028                        .map(|byte| format!("{byte:02x}"))
1029                        .collect::<String>())
1030                    .collect::<Vec<_>>())
1031            }
1032            subc_os::code_signature::FileSignature::Unsigned => identity["cdhashes"] = json!([]),
1033            subc_os::code_signature::FileSignature::Invalid => {
1034                identity["cdhashes"] = json!([]);
1035                identity["signature_invalid"] = json!(true);
1036            }
1037            subc_os::code_signature::FileSignature::NotMachO => {}
1038        }
1039        identity
1040    };
1041    let state = InputState::Present {
1042        digest: subc_config::raw_digest(
1043            &serde_json::to_vec(&identity).map_err(GateError::invalid)?,
1044        ),
1045    };
1046    Ok((
1047        file,
1048        CapturedInput {
1049            state,
1050            value: RecordedValue::new(identity),
1051        },
1052        prefix == b"#!",
1053    ))
1054}
1055
1056pub(super) fn refusal_code(code: subc_config::RefusalCode) -> &'static str {
1057    use subc_config::RefusalCode::*;
1058    match code {
1059        SchemaInvalid => "schema_invalid",
1060        LayerForbidden => "layer_forbidden",
1061        BoundViolated => "bound_violated",
1062        CredentialShared => "credential_shared",
1063        PlanStale => "plan_stale",
1064        _ => "value_invalid",
1065    }
1066}
1067
1068pub(super) fn refuse_expansions(value: &Value, module: &str, path: &str) -> Result<()> {
1069    match value {
1070        Value::String(text) if text.contains("{env:") || text.contains("{file:") => {
1071            Err(GateError::new("value_invalid", format!("{module}: {path}")))
1072        }
1073        Value::Object(values) => {
1074            for (key, value) in values {
1075                refuse_expansions(
1076                    value,
1077                    module,
1078                    &format!("{path}/{}", key.replace('~', "~0").replace('/', "~1")),
1079                )?;
1080            }
1081            Ok(())
1082        }
1083        Value::Array(values) => {
1084            for (index, value) in values.iter().enumerate() {
1085                refuse_expansions(value, module, &format!("{path}/{index}"))?;
1086            }
1087            Ok(())
1088        }
1089        _ => Ok(()),
1090    }
1091}
1092
1093#[cfg(test)]
1094mod tests {
1095    use super::*;
1096
1097    struct Rig {
1098        root: PathBuf,
1099        _scratch: cortexkit_test_support::ScratchDir,
1100        capturer: ConfigCapturer,
1101        declarations: BTreeMap<String, ConfigDeclareRequest>,
1102    }
1103    impl Rig {
1104        fn new() -> Self {
1105            let scratch = cortexkit_test_support::ScratchDir::new("subc-gate-capture");
1106            std::fs::create_dir_all(scratch.join("cortexkit")).unwrap();
1107            let root = scratch.path().canonicalize().unwrap();
1108            let daemon_path = root.join("cortexkit/subc.jsonc");
1109            std::fs::write(&daemon_path, br#"{"version":1,"modules":{}}"#).unwrap();
1110            let schema = json!({
1111                "$schema":"https://json-schema.org/draft/2020-12/schema", "type":"object", "unevaluatedProperties":false,
1112                "x-ck-layers":["user"], "x-ck-apply":"live",
1113                "properties": {
1114                    "credential": {"type":"object", "description":"Vault credential", "x-ck-kind":"credential_ref", "x-ck-required":true},
1115                    "limit": {"type":"integer", "description":"Request limit", "default":10}
1116                }
1117            });
1118            let declaration = ConfigDeclareRequest::new(
1119                schema,
1120                root.join("cortexkit/a.jsonc").to_string_lossy(),
1121                Vec::new(),
1122            );
1123            Self {
1124                capturer: ConfigCapturer {
1125                    daemon_path,
1126                    config_home: root.clone(),
1127                    projects: Arc::new(OfflineProjectRegistry),
1128                },
1129                declarations: BTreeMap::from([("a".into(), declaration)]),
1130                root,
1131                _scratch: scratch,
1132            }
1133        }
1134        fn write(&self, bytes: &[u8]) {
1135            std::fs::write(self.root.join("cortexkit/a.jsonc"), bytes).unwrap();
1136        }
1137    }
1138
1139    #[test]
1140    fn config_capture_preserves_raw_reference_bytes_and_redacts_diagnostics() {
1141        let rig = Rig::new();
1142        let bytes = b"{ // reference, not its secret\n\"credential\":{\"vault_ref\":\"opaque-credential-id\"}, \"limit\":11,}\n";
1143        rig.write(bytes);
1144        let captured = rig.capturer.capture(&rig.declarations).unwrap();
1145        assert_eq!(
1146            captured.modules["a"].view.layers[0].bytes.as_deref(),
1147            Some(bytes.as_slice())
1148        );
1149        let diagnostic = serde_json::to_string(&captured.diagnostic.to_store().unwrap()).unwrap();
1150        assert!(!diagnostic.contains("opaque-credential-id"));
1151        assert!(diagnostic.contains("redacted"));
1152    }
1153
1154    #[test]
1155    fn config_capture_refuses_literal_and_expansion_at_field_without_retaining_bytes() {
1156        let rig = Rig::new();
1157        for value in [
1158            json!("literal-password-never-retained"),
1159            json!("{env:PRIVATE_TOKEN}"),
1160        ] {
1161            rig.write(&serde_json::to_vec(&json!({"credential":value})).unwrap());
1162            let error = rig.capturer.capture(&rig.declarations).err().unwrap();
1163            assert_eq!(error.code, "value_invalid");
1164            assert_eq!(error.detail, "a: /credential");
1165            assert!(!error.to_string().contains(value.as_str().unwrap()));
1166        }
1167    }
1168
1169    #[test]
1170    fn config_capture_replacement_with_identical_bytes_changes_read_set() {
1171        let rig = Rig::new();
1172        let bytes = br#"{"credential":{"vault_ref":"ref"}}"#;
1173        rig.write(bytes);
1174        let before = rig.capturer.capture(&rig.declarations).unwrap();
1175        let replacement = rig.root.join("replacement");
1176        std::fs::write(&replacement, bytes).unwrap();
1177        std::fs::remove_file(rig.root.join("cortexkit/a.jsonc")).unwrap();
1178        std::fs::rename(replacement, rig.root.join("cortexkit/a.jsonc")).unwrap();
1179        let after = rig.capturer.capture(&rig.declarations).unwrap();
1180        let modules = ["a".into()].into_iter().collect();
1181        assert_ne!(
1182            before.diagnostic.read_set(&modules).unwrap(),
1183            after.diagnostic.read_set(&modules).unwrap()
1184        );
1185    }
1186
1187    #[test]
1188    fn config_capture_refuses_project_directories_without_opening_them() {
1189        let mut rig = Rig::new();
1190        rig.declarations.get_mut("a").unwrap().project_dirs = vec!["/not-a-registry-root".into()];
1191        let error = rig.capturer.capture(&rig.declarations).err().unwrap();
1192        assert_eq!(error.code, "config_gated");
1193        assert!(error.detail.contains("project-tuple planning and delivery"));
1194        assert!(error.detail.contains("a: project-tuple"));
1195    }
1196
1197    #[test]
1198    fn config_capture_distinguishes_absent_empty_and_over_bound_files() {
1199        let rig = Rig::new();
1200        let path = rig.root.join("cortexkit/missing.jsonc");
1201        assert_eq!(CapturedFile::open(&path).unwrap().state, InputState::Absent);
1202        std::fs::write(&path, b"").unwrap();
1203        assert!(matches!(
1204            CapturedFile::open(&path).unwrap().state,
1205            InputState::Present { .. }
1206        ));
1207        File::options()
1208            .write(true)
1209            .open(&path)
1210            .unwrap()
1211            .set_len(CONFIG_FILE_LIMIT + 1)
1212            .unwrap();
1213        assert_eq!(
1214            CapturedFile::open(&path).err().unwrap().code,
1215            "input_too_large"
1216        );
1217    }
1218}