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