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