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    fn capture_selected(
439        &self,
440        declarations: &BTreeMap<String, ConfigDeclareRequest>,
441        selected: Option<&BTreeSet<String>>,
442    ) -> Result<CapturedConfiguration> {
443        let daemon = CapturedFile::open(&self.daemon_path)?;
444        self.capture_layers(daemon, declarations, selected, true, CapturedFile::open)
445    }
446
447    pub(super) fn capture_with_retained_user(
448        &self,
449        declarations: &BTreeMap<String, ConfigDeclareRequest>,
450        selected: Option<&BTreeSet<String>>,
451        mut retained: BTreeMap<PathBuf, CapturedFile>,
452    ) -> Result<CapturedConfiguration> {
453        let daemon = CapturedFile::open(&self.daemon_path)?;
454        self.capture_layers(daemon, declarations, selected, true, |path| {
455            retained
456                .remove(path)
457                .map_or_else(|| CapturedFile::open(path), Ok)
458        })
459    }
460
461    /// Re-evaluate saved raw configuration rather than today's edited files.
462    /// Program capture still opens the files at the restored configured paths.
463    pub(crate) fn capture_retained(
464        &self,
465        target: &GateSnapshot,
466        delivery: &crate::config_store::DeliverySnapshot,
467    ) -> Result<CapturedConfiguration> {
468        self.capture_retained_inner(target, delivery, &delivery.declarations, true)
469    }
470
471    pub(crate) fn capture_retained_declared(
472        &self,
473        target: &GateSnapshot,
474        delivery: &crate::config_store::DeliverySnapshot,
475        declarations: &BTreeMap<String, ConfigDeclareRequest>,
476    ) -> Result<CapturedConfiguration> {
477        self.capture_retained_inner(target, delivery, declarations, false)
478    }
479
480    fn capture_retained_inner(
481        &self,
482        target: &GateSnapshot,
483        delivery: &crate::config_store::DeliverySnapshot,
484        declarations: &BTreeMap<String, ConfigDeclareRequest>,
485        require_identical: bool,
486    ) -> Result<CapturedConfiguration> {
487        let invalid = || {
488            GateError::new(
489                "rollback_snapshot_unavailable",
490                "retained raw configuration is absent or inconsistent",
491            )
492        };
493        let retained_file = |layer: &ConfigLayerSnapshot, key: &InputKey| -> Result<CapturedFile> {
494            let path = layer.path.as_ref().ok_or_else(invalid)?;
495            let input = target.inputs.get(key).ok_or_else(invalid)?;
496            if layer.bytes.as_deref().map(subc_config::raw_digest) != layer.digest {
497                return Err(invalid());
498            }
499            Ok(CapturedFile {
500                path: path.into(),
501                bytes: layer.bytes.clone(),
502                state: input.state.clone(),
503                _file: None,
504            })
505        };
506        let daemon = retained_file(
507            delivery.daemon.as_ref().ok_or_else(invalid)?,
508            &InputKey::Daemon,
509        )?;
510        if daemon.path != self.daemon_path || daemon.bytes.is_none() {
511            return Err(invalid());
512        }
513        let mut files = BTreeMap::new();
514        for (module, view) in &delivery.modules {
515            let [layer] = view.layers.as_slice() else {
516                return Err(invalid());
517            };
518            if layer.layer != ConfigLayer::User
519                || layer.module_id != *module
520                || layer.project_id.is_some()
521                || layer.workspace_id.is_some()
522            {
523                return Err(invalid());
524            }
525            let path = layer.path.as_ref().ok_or_else(invalid)?;
526            let file = retained_file(
527                layer,
528                &InputKey::Layer {
529                    module: module.clone(),
530                    path: path.clone(),
531                },
532            )?;
533            files.insert(file.path.clone(), file);
534        }
535        let captured = self.capture_layers(daemon, declarations, None, true, |path| {
536            files.remove(path).ok_or_else(invalid)
537        })?;
538        if !files.is_empty()
539            || (require_identical
540                && target
541                    .inputs
542                    .iter()
543                    .filter(|(key, _)| !key.is_program() && !key.is_project())
544                    .ne(captured
545                        .diagnostic
546                        .inputs
547                        .iter()
548                        .filter(|(key, _)| !key.is_program())))
549        {
550            return Err(invalid());
551        }
552        Ok(captured)
553    }
554
555    fn capture_layers(
556        &self,
557        daemon: CapturedFile,
558        declarations: &BTreeMap<String, ConfigDeclareRequest>,
559        selected: Option<&BTreeSet<String>>,
560        programs: bool,
561        layer_file: impl FnMut(&Path) -> Result<CapturedFile>,
562    ) -> Result<CapturedConfiguration> {
563        self.capture_layers_observed::<false>(daemon, declarations, selected, programs, layer_file)
564            .map(|captured| captured.configuration)
565    }
566
567    fn capture_layers_observed<const REPORT_MODULE_ERRORS: bool>(
568        &self,
569        daemon: CapturedFile,
570        declarations: &BTreeMap<String, ConfigDeclareRequest>,
571        selected: Option<&BTreeSet<String>>,
572        programs: bool,
573        mut layer_file: impl FnMut(&Path) -> Result<CapturedFile>,
574    ) -> Result<SettingsCapture> {
575        let invalid_daemon =
576            || GateError::new("invalid_daemon_config", "captured subc.jsonc is invalid");
577        let doc = daemon.parse().map_err(|_| invalid_daemon())?;
578        let mut launch_specs = BTreeMap::new();
579        if let Some(bytes) = &daemon.bytes {
580            let (config, _) = crate::daemon_config::parse_with_activity(
581                std::str::from_utf8(bytes).map_err(|_| invalid_daemon())?,
582                &self.daemon_path,
583            )
584            .map_err(|_| invalid_daemon())?;
585            launch_specs.extend(
586                config
587                    .modules
588                    .into_iter()
589                    .map(|module| (module.module_id.clone(), module.module_spec())),
590            );
591            refuse_expansions(&doc, "subc", "")?;
592        }
593        let mut program_handles = Vec::new();
594        // Launch arguments and environment participate in review verbatim;
595        // credential reference objects remain redacted in diagnostic views.
596        let safe_doc = redact_launch_values(&doc)?;
597        let mut diagnostic = GateSnapshot::default();
598        diagnostic.inputs.insert(
599            InputKey::Daemon,
600            CapturedInput {
601                state: daemon.state.clone(),
602                value: RecordedValue::new(safe_doc.clone()),
603            },
604        );
605        if let Some(entries) = safe_doc.get("modules").and_then(Value::as_object) {
606            for (module, entry) in entries {
607                diagnostic.inputs.insert(
608                    InputKey::Entry(module.clone()),
609                    CapturedInput {
610                        state: InputState::Present {
611                            digest: subc_config::raw_digest(
612                                &serde_json::to_vec(entry).map_err(GateError::invalid)?,
613                            ),
614                        },
615                        value: RecordedValue::new(entry.clone()),
616                    },
617                );
618            }
619        }
620        if let Some(entries) = doc
621            .get("modules")
622            .and_then(Value::as_object)
623            .filter(|_| programs)
624        {
625            for (module, entry) in entries {
626                if selected.is_some_and(|modules| !modules.contains(module)) {
627                    continue;
628                }
629                if let Some(spec) = launch_specs.get(module) {
630                    let covered = super::program::program_files(entry)?;
631                    let launch = super::program::capture(spec, &covered).map_err(|error| {
632                        GateError::new(&error.code, format!("{module}: {}", error.detail))
633                    })?;
634                    diagnostic.inputs.extend(launch.inputs);
635                    program_handles.extend(launch.files);
636                }
637            }
638        }
639        let mut modules = BTreeMap::new();
640        let mut file_errors = BTreeMap::new();
641        let mut module_errors = BTreeMap::new();
642        for (module, declaration) in declarations {
643            if selected.is_some_and(|modules| !modules.contains(module)) {
644                continue;
645            }
646            let decl_input = match declaration_input(module, declaration) {
647                Ok(input) => input,
648                Err(error) if REPORT_MODULE_ERRORS => {
649                    module_errors.insert(module.clone(), error);
650                    continue;
651                }
652                Err(error) => return Err(error),
653            };
654            let (captured, input) = match self.capture_module(module, declaration, &mut layer_file)
655            {
656                Ok(captured) => captured,
657                Err(error) if REPORT_MODULE_ERRORS && !error.is_capture_race() => {
658                    if is_settings_file_error(&error) {
659                        file_errors.insert(
660                            module.clone(),
661                            ConfigFileError::new(error.code, error.detail),
662                        );
663                    } else {
664                        module_errors.insert(module.clone(), error);
665                    }
666                    continue;
667                }
668                Err(error) => return Err(error),
669            };
670            diagnostic.inputs.insert(
671                InputKey::Layer {
672                    module: module.clone(),
673                    path: captured.file.path.to_string_lossy().into_owned(),
674                },
675                input,
676            );
677            diagnostic
678                .inputs
679                .insert(InputKey::Declaration(module.clone()), decl_input);
680            modules.insert(module.clone(), captured);
681        }
682        Ok(SettingsCapture {
683            configuration: CapturedConfiguration {
684                diagnostic,
685                daemon,
686                modules,
687                _program_handles: program_handles,
688            },
689            file_errors,
690            module_errors,
691        })
692    }
693
694    pub(super) fn capture_module(
695        &self,
696        module: &str,
697        declaration: &ConfigDeclareRequest,
698        layer_file: impl FnOnce(&Path) -> Result<CapturedFile>,
699    ) -> Result<(CapturedModule, CapturedInput)> {
700        if !declaration.project_dirs.is_empty() {
701            // Workspace/project roots must come from the project registry,
702            // not from directories supplied by the module.
703            return Err(GateError::new(
704                "config_gated",
705                format!("{module}: project-tuple planning and delivery are not supported yet"),
706            ));
707        }
708        if module.is_empty() || module.contains(['/', '\\']) || module == "." || module == ".." {
709            return Err(GateError::new(
710                "path_invalid",
711                "module identity cannot form a layer path",
712            ));
713        }
714        let expected = self
715            .config_home
716            .join("cortexkit")
717            .join(format!("{module}.jsonc"));
718        if Path::new(&declaration.user_file) != expected || !expected.is_absolute() {
719            return Err(GateError::new(
720                "path_invalid",
721                format!("{module}: user layer must use its canonical config-home path"),
722            ));
723        }
724        let schema = Schema::new(declaration.schema.clone()).map_err(|refusal| {
725            GateError::new("schema_invalid", format!("{module}: {}", refusal.path))
726        })?;
727        let file_context = |mut error: GateError| {
728            error.detail = format!("{module}: {}: {}", expected.display(), error.detail);
729            error
730        };
731        let file = layer_file(&expected)?;
732        let value = file.parse_with_canonical_context(file_context)?;
733        refuse_expansions(&value, module, "")?;
734        // Record even invalid literals through the schema projection first;
735        // nothing raw is retained on the refusal path.
736        let recorded = schema.record(&value).map_err(GateError::invalid)?;
737        let layers = if file.bytes.is_some() {
738            vec![LayerValue::new(Layer::User, value)]
739        } else {
740            Vec::new()
741        };
742        let reviewed = schema
743            .review_tuple(&layers, &ValidationContext::new(module, None))
744            .map_err(|refusal| {
745                GateError::new(
746                    refusal_code(refusal.code),
747                    format!("{module}: {}", refusal.path),
748                )
749            })?;
750        let layer = ConfigLayerSnapshot::file(
751            module,
752            ConfigLayer::User,
753            expected.to_string_lossy(),
754            file.bytes.clone(),
755        );
756        let view = ConfigView::new(
757            0,
758            reviewed.effective,
759            reviewed.sources,
760            vec![layer],
761            ConfigStatus::Unstamped,
762        );
763        let input = CapturedInput {
764            state: file.state.clone(),
765            value: RecordedValue::new(recorded),
766        };
767        Ok((
768            CapturedModule {
769                declaration: declaration.clone(),
770                schema,
771                view,
772                file,
773            },
774            input,
775        ))
776    }
777
778    pub(crate) fn settings_file_error(
779        &self,
780        module: &str,
781        declaration: &ConfigDeclareRequest,
782    ) -> Result<Option<ConfigFileError>> {
783        match self.capture_module(module, declaration, CapturedFile::open) {
784            Ok(_) => Ok(None),
785            Err(error) if is_settings_file_error(&error) => {
786                Ok(Some(ConfigFileError::new(error.code, error.detail)))
787            }
788            Err(error) => Err(error),
789        }
790    }
791}
792
793impl CapturedFile {
794    pub(super) fn retained(path: PathBuf, bytes: Option<Vec<u8>>, state: InputState) -> Self {
795        Self {
796            _file: None,
797            path,
798            bytes,
799            state,
800        }
801    }
802}
803
804fn declaration_input(module: &str, declaration: &ConfigDeclareRequest) -> Result<CapturedInput> {
805    let value = serde_json::to_value(declaration).map_err(GateError::invalid)?;
806    let digest =
807        subc_config::digest(subc_config::PURPOSE_DECLARATION, &value).map_err(|error| {
808            let mut error = super::strict_json::canonical_error(error, &value, "");
809            error.detail = format!("{module}: {}", error.detail);
810            error
811        })?;
812    Ok(CapturedInput {
813        state: InputState::Present { digest },
814        value: RecordedValue::new(redact_launch_values(&value)?),
815    })
816}
817
818fn is_settings_file_error(error: &GateError) -> bool {
819    matches!(error.code.as_str(), "value_invalid" | "input_unavailable")
820}
821
822fn redact_launch_values(value: &Value) -> Result<Value> {
823    if subc_config::is_vault_reference(value) {
824        return serde_json::to_value(RecordedValue::redacted(value).map_err(GateError::invalid)?)
825            .map_err(GateError::invalid);
826    }
827    match value {
828        Value::Object(object) => object
829            .iter()
830            .map(|(key, value)| {
831                let value = redact_launch_values(value)?;
832                Ok((key.clone(), value))
833            })
834            .collect::<Result<serde_json::Map<_, _>>>()
835            .map(Value::Object),
836        Value::Array(array) => array
837            .iter()
838            .map(redact_launch_values)
839            .collect::<Result<Vec<_>>>()
840            .map(Value::Array),
841        value => Ok(value.clone()),
842    }
843}
844
845pub(crate) fn capture_program(path: &Path) -> Result<(File, CapturedInput)> {
846    let (file, input, _) = capture_program_classified(path)?;
847    Ok((file, input))
848}
849
850pub(crate) fn capture_program_classified(path: &Path) -> Result<(File, CapturedInput, bool)> {
851    use sha2::{Digest as _, Sha256};
852    if !path.is_absolute() {
853        return Err(GateError::new(
854            "path_invalid",
855            "covered program path must be absolute",
856        ));
857    }
858    let resolved = std::fs::canonicalize(path).map_err(|error| {
859        if error.kind() == io::ErrorKind::NotFound {
860            GateError::new("program_missing", "configured program file is absent")
861        } else {
862            capture_error(error)
863        }
864    })?;
865    let file = subc_os::open_regular_nofollow(&resolved).map_err(capture_error)?;
866    let before = file.metadata().map_err(capture_error)?;
867    if !before.is_file() {
868        return Err(GateError::new(
869            "path_invalid",
870            "covered program must be a regular file",
871        ));
872    }
873    if before.len() > PROGRAM_FILE_LIMIT {
874        return Err(GateError::new(
875            "input_too_large",
876            "covered program exceeds the 512 MiB streamed-hash limit",
877        ));
878    }
879    let id = file_object_id(&file)?;
880    let mut hasher = Sha256::new();
881    let mut length = 0;
882    // Classify the same byte stream that supplies the approved hash, not an
883    // earlier path open that could have seen different content on this inode.
884    let mut prefix = Vec::with_capacity(2);
885    #[cfg(target_os = "macos")]
886    let signatures = subc_os::code_signature::file_signature(&file, |chunk| {
887        prefix.extend_from_slice(&chunk[..chunk.len().min(2 - prefix.len())]);
888        length += chunk.len() as u64;
889        hasher.update(chunk);
890    });
891    #[cfg(not(target_os = "macos"))]
892    {
893        let mut reader = &file;
894        let mut buffer = [0; 64 * 1024];
895        loop {
896            let count = reader.read(&mut buffer).map_err(capture_error)?;
897            if count == 0 {
898                break;
899            }
900            prefix.extend_from_slice(&buffer[..count.min(2 - prefix.len())]);
901            length += count as u64;
902            if length > PROGRAM_FILE_LIMIT {
903                return Err(GateError::new(
904                    "input_too_large",
905                    "covered program exceeds the 512 MiB streamed-hash limit",
906                ));
907            }
908            hasher.update(&buffer[..count]);
909        }
910    }
911    let after = file.metadata().map_err(capture_error)?;
912    let reopened = subc_os::open_regular_nofollow(&resolved).map_err(capture_error)?;
913    #[cfg(target_os = "macos")]
914    let completed = signatures.is_ok();
915    #[cfg(not(target_os = "macos"))]
916    let completed = true;
917    if (completed && length != before.len())
918        || std::fs::canonicalize(path).map_err(capture_error)? != resolved
919        || before.len() != after.len()
920        || before.modified().ok() != after.modified().ok()
921        || file_object_id(&reopened)? != id
922    {
923        return Err(GateError::stale());
924    }
925    #[cfg(target_os = "macos")]
926    let signatures = signatures.map_err(|error| match error {
927        subc_os::code_signature::SignatureError::Parse => GateError::new(
928            "program_invalid",
929            "covered program has an invalid or unsupported Mach-O structure",
930        ),
931        other => capture_error(other),
932    })?;
933    let identity = json!({ "path": resolved, "file": id, "length": length, "raw": format!("sha256:{:x}", hasher.finalize()) });
934    #[cfg(target_os = "macos")]
935    let identity = {
936        let mut identity = identity;
937        match signatures {
938            subc_os::code_signature::FileSignature::Signed(hashes) => {
939                identity["cdhashes"] = json!(hashes
940                    .into_iter()
941                    .map(|hash| hash
942                        .0
943                        .iter()
944                        .map(|byte| format!("{byte:02x}"))
945                        .collect::<String>())
946                    .collect::<Vec<_>>())
947            }
948            subc_os::code_signature::FileSignature::Unsigned => identity["cdhashes"] = json!([]),
949            subc_os::code_signature::FileSignature::Invalid => {
950                identity["cdhashes"] = json!([]);
951                identity["signature_invalid"] = json!(true);
952            }
953            subc_os::code_signature::FileSignature::NotMachO => {}
954        }
955        identity
956    };
957    let state = InputState::Present {
958        digest: subc_config::raw_digest(
959            &serde_json::to_vec(&identity).map_err(GateError::invalid)?,
960        ),
961    };
962    Ok((
963        file,
964        CapturedInput {
965            state,
966            value: RecordedValue::new(identity),
967        },
968        prefix == b"#!",
969    ))
970}
971
972pub(super) fn refusal_code(code: subc_config::RefusalCode) -> &'static str {
973    use subc_config::RefusalCode::*;
974    match code {
975        SchemaInvalid => "schema_invalid",
976        LayerForbidden => "layer_forbidden",
977        BoundViolated => "bound_violated",
978        CredentialShared => "credential_shared",
979        PlanStale => "plan_stale",
980        _ => "value_invalid",
981    }
982}
983
984pub(super) fn refuse_expansions(value: &Value, module: &str, path: &str) -> Result<()> {
985    match value {
986        Value::String(text) if text.contains("{env:") || text.contains("{file:") => {
987            Err(GateError::new("value_invalid", format!("{module}: {path}")))
988        }
989        Value::Object(values) => {
990            for (key, value) in values {
991                refuse_expansions(
992                    value,
993                    module,
994                    &format!("{path}/{}", key.replace('~', "~0").replace('/', "~1")),
995                )?;
996            }
997            Ok(())
998        }
999        Value::Array(values) => {
1000            for (index, value) in values.iter().enumerate() {
1001                refuse_expansions(value, module, &format!("{path}/{index}"))?;
1002            }
1003            Ok(())
1004        }
1005        _ => Ok(()),
1006    }
1007}
1008
1009#[cfg(test)]
1010mod tests {
1011    use super::*;
1012
1013    struct Rig {
1014        root: PathBuf,
1015        _scratch: cortexkit_test_support::ScratchDir,
1016        capturer: ConfigCapturer,
1017        declarations: BTreeMap<String, ConfigDeclareRequest>,
1018    }
1019    impl Rig {
1020        fn new() -> Self {
1021            let scratch = cortexkit_test_support::ScratchDir::new("subc-gate-capture");
1022            std::fs::create_dir_all(scratch.join("cortexkit")).unwrap();
1023            let root = scratch.path().canonicalize().unwrap();
1024            let daemon_path = root.join("cortexkit/subc.jsonc");
1025            std::fs::write(&daemon_path, br#"{"version":1,"modules":{}}"#).unwrap();
1026            let schema = json!({
1027                "$schema":"https://json-schema.org/draft/2020-12/schema", "type":"object", "unevaluatedProperties":false,
1028                "x-ck-layers":["user"], "x-ck-apply":"live",
1029                "properties": {
1030                    "credential": {"type":"object", "description":"Vault credential", "x-ck-kind":"credential_ref", "x-ck-required":true},
1031                    "limit": {"type":"integer", "description":"Request limit", "default":10}
1032                }
1033            });
1034            let declaration = ConfigDeclareRequest::new(
1035                schema,
1036                root.join("cortexkit/a.jsonc").to_string_lossy(),
1037                Vec::new(),
1038            );
1039            Self {
1040                capturer: ConfigCapturer {
1041                    daemon_path,
1042                    config_home: root.clone(),
1043                    projects: Arc::new(OfflineProjectRegistry),
1044                },
1045                declarations: BTreeMap::from([("a".into(), declaration)]),
1046                root,
1047                _scratch: scratch,
1048            }
1049        }
1050        fn write(&self, bytes: &[u8]) {
1051            std::fs::write(self.root.join("cortexkit/a.jsonc"), bytes).unwrap();
1052        }
1053    }
1054
1055    #[test]
1056    fn config_capture_preserves_raw_reference_bytes_and_redacts_diagnostics() {
1057        let rig = Rig::new();
1058        let bytes = b"{ // reference, not its secret\n\"credential\":{\"vault_ref\":\"opaque-credential-id\"}, \"limit\":11,}\n";
1059        rig.write(bytes);
1060        let captured = rig.capturer.capture(&rig.declarations).unwrap();
1061        assert_eq!(
1062            captured.modules["a"].view.layers[0].bytes.as_deref(),
1063            Some(bytes.as_slice())
1064        );
1065        let diagnostic = serde_json::to_string(&captured.diagnostic.to_store().unwrap()).unwrap();
1066        assert!(!diagnostic.contains("opaque-credential-id"));
1067        assert!(diagnostic.contains("redacted"));
1068    }
1069
1070    #[test]
1071    fn config_capture_refuses_literal_and_expansion_at_field_without_retaining_bytes() {
1072        let rig = Rig::new();
1073        for value in [
1074            json!("literal-password-never-retained"),
1075            json!("{env:PRIVATE_TOKEN}"),
1076        ] {
1077            rig.write(&serde_json::to_vec(&json!({"credential":value})).unwrap());
1078            let error = rig.capturer.capture(&rig.declarations).err().unwrap();
1079            assert_eq!(error.code, "value_invalid");
1080            assert_eq!(error.detail, "a: /credential");
1081            assert!(!error.to_string().contains(value.as_str().unwrap()));
1082        }
1083    }
1084
1085    #[test]
1086    fn config_capture_replacement_with_identical_bytes_changes_read_set() {
1087        let rig = Rig::new();
1088        let bytes = br#"{"credential":{"vault_ref":"ref"}}"#;
1089        rig.write(bytes);
1090        let before = rig.capturer.capture(&rig.declarations).unwrap();
1091        let replacement = rig.root.join("replacement");
1092        std::fs::write(&replacement, bytes).unwrap();
1093        std::fs::remove_file(rig.root.join("cortexkit/a.jsonc")).unwrap();
1094        std::fs::rename(replacement, rig.root.join("cortexkit/a.jsonc")).unwrap();
1095        let after = rig.capturer.capture(&rig.declarations).unwrap();
1096        let modules = ["a".into()].into_iter().collect();
1097        assert_ne!(
1098            before.diagnostic.read_set(&modules).unwrap(),
1099            after.diagnostic.read_set(&modules).unwrap()
1100        );
1101    }
1102
1103    #[test]
1104    fn config_capture_refuses_project_directories_without_opening_them() {
1105        let mut rig = Rig::new();
1106        rig.declarations.get_mut("a").unwrap().project_dirs = vec!["/not-a-registry-root".into()];
1107        let error = rig.capturer.capture(&rig.declarations).err().unwrap();
1108        assert_eq!(error.code, "config_gated");
1109        assert!(error.detail.contains("project-tuple planning and delivery"));
1110        assert!(error.detail.contains("a: project-tuple"));
1111    }
1112
1113    #[test]
1114    fn config_capture_distinguishes_absent_empty_and_over_bound_files() {
1115        let rig = Rig::new();
1116        let path = rig.root.join("cortexkit/missing.jsonc");
1117        assert_eq!(CapturedFile::open(&path).unwrap().state, InputState::Absent);
1118        std::fs::write(&path, b"").unwrap();
1119        assert!(matches!(
1120            CapturedFile::open(&path).unwrap().state,
1121            InputState::Present { .. }
1122        ));
1123        File::options()
1124            .write(true)
1125            .open(&path)
1126            .unwrap()
1127            .set_len(CONFIG_FILE_LIMIT + 1)
1128            .unwrap();
1129        assert_eq!(
1130            CapturedFile::open(&path).err().unwrap().code,
1131            "input_too_large"
1132        );
1133    }
1134}