Skip to main content

subc_daemon/config_gate/
capture.rs

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