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        match &self.bytes {
235            Some(bytes) => parse_layer(bytes),
236            None => Ok(json!({})),
237        }
238    }
239
240    pub(super) fn take_handles(&mut self) -> Vec<File> {
241        self._file.take().into_iter().collect()
242    }
243}
244
245pub(super) fn parse_layer(bytes: &[u8]) -> Result<Value> {
246    let text = std::str::from_utf8(bytes).map_err(capture_error)?;
247    let normalized = subc_jsonc::jsonc_to_json(text).map_err(capture_error)?;
248    super::strict_json::parse(&normalized)
249}
250
251pub struct CapturedModule {
252    pub declaration: ConfigDeclareRequest,
253    pub schema: Schema,
254    pub view: ConfigView,
255    pub file: CapturedFile,
256}
257
258pub struct CapturedConfiguration {
259    pub diagnostic: GateSnapshot,
260    pub daemon: CapturedFile,
261    pub modules: BTreeMap<String, CapturedModule>,
262    _program_handles: Vec<File>,
263}
264
265pub(crate) struct SettingsCapture {
266    pub configuration: CapturedConfiguration,
267    pub file_errors: BTreeMap<String, ConfigFileError>,
268}
269
270impl CapturedConfiguration {
271    /// Edit candidates bind content before the replacement file has an identity.
272    /// For drift reporting, equal written bytes satisfy that approved digest;
273    /// keep the original capture fingerprints for review and compare-and-swap.
274    pub(crate) fn proposal_snapshot(&self, approved: &GateSnapshot) -> GateSnapshot {
275        let mut snapshot = self.diagnostic.clone();
276        for (key, input) in &mut snapshot.inputs {
277            let InputKey::Layer { module, path } = key else {
278                continue;
279            };
280            let Some(previous) = approved.inputs.get(key) else {
281                continue;
282            };
283            let Some(file) = self.modules.get(module).map(|module| &module.file) else {
284                continue;
285            };
286            if file.path.to_string_lossy() == path.as_str()
287                && input.value == previous.value
288                && file.bytes.as_deref().is_some_and(|bytes| {
289                    previous.state
290                        == InputState::Present {
291                            digest: subc_config::raw_digest(bytes),
292                        }
293                })
294            {
295                input.state = previous.state.clone();
296            }
297        }
298        snapshot
299    }
300
301    pub(crate) fn take_handles(&mut self) -> Vec<File> {
302        let mut handles = std::mem::take(&mut self._program_handles);
303        handles.extend(self.daemon._file.take());
304        for module in self.modules.values_mut() {
305            handles.extend(module.file._file.take());
306        }
307        handles
308    }
309
310    /// A rollback may restore a path different from the current configuration's
311    /// path. Bind both programs in the observed read set without restoring any
312    /// historical executable bytes or trusting a historical file identity.
313    pub(crate) fn capture_programs(&mut self, keys: &[InputKey]) -> Result<()> {
314        for key in keys {
315            if self.diagnostic.inputs.contains_key(key) {
316                continue;
317            }
318            let InputKey::Program { path, .. } = key else {
319                unreachable!()
320            };
321            let (file, captured) = capture_program(Path::new(path))?;
322            self.diagnostic.inputs.insert(key.clone(), captured);
323            self._program_handles.push(file);
324        }
325        Ok(())
326    }
327}
328
329impl ConfigCapturer {
330    /// Candidate configuration only: no approved-store access, keychain work or
331    /// executable capture belongs on a polled diagnostic read.
332    pub(crate) fn capture_polled(
333        &self,
334        declarations: &BTreeMap<String, ConfigDeclareRequest>,
335    ) -> Result<GateSnapshot> {
336        self.capture_polled_configuration(declarations)
337            .map(|captured| captured.diagnostic)
338    }
339
340    pub(crate) fn capture_polled_configuration(
341        &self,
342        declarations: &BTreeMap<String, ConfigDeclareRequest>,
343    ) -> Result<CapturedConfiguration> {
344        let daemon = CapturedFile::open(&self.daemon_path)?;
345        self.capture_layers(daemon, declarations, None, false, CapturedFile::open)
346    }
347
348    /// Settings observations report invalid user files per module. Planning and
349    /// delivery still use the rejecting capture path and cannot adopt them.
350    pub(crate) fn capture_settings(
351        &self,
352        declarations: &BTreeMap<String, ConfigDeclareRequest>,
353    ) -> Result<SettingsCapture> {
354        let daemon = CapturedFile::open(&self.daemon_path)?;
355        self.capture_layers_observed::<true>(daemon, declarations, None, false, CapturedFile::open)
356    }
357
358    pub fn capture(
359        &self,
360        declarations: &BTreeMap<String, ConfigDeclareRequest>,
361    ) -> Result<CapturedConfiguration> {
362        self.capture_selected(declarations, None)
363    }
364
365    pub fn capture_modules(
366        &self,
367        declarations: &BTreeMap<String, ConfigDeclareRequest>,
368        modules: &BTreeSet<String>,
369    ) -> Result<CapturedConfiguration> {
370        self.capture_selected(declarations, Some(modules))
371    }
372
373    fn capture_selected(
374        &self,
375        declarations: &BTreeMap<String, ConfigDeclareRequest>,
376        selected: Option<&BTreeSet<String>>,
377    ) -> Result<CapturedConfiguration> {
378        let daemon = CapturedFile::open(&self.daemon_path)?;
379        self.capture_layers(daemon, declarations, selected, true, CapturedFile::open)
380    }
381
382    /// Re-evaluate saved raw configuration rather than today's edited files.
383    /// Program capture still opens the files at the restored configured paths.
384    pub(crate) fn capture_retained(
385        &self,
386        target: &GateSnapshot,
387        delivery: &crate::config_store::DeliverySnapshot,
388    ) -> Result<CapturedConfiguration> {
389        self.capture_retained_inner(target, delivery, &delivery.declarations, true)
390    }
391
392    pub(crate) fn capture_retained_declared(
393        &self,
394        target: &GateSnapshot,
395        delivery: &crate::config_store::DeliverySnapshot,
396        declarations: &BTreeMap<String, ConfigDeclareRequest>,
397    ) -> Result<CapturedConfiguration> {
398        self.capture_retained_inner(target, delivery, declarations, false)
399    }
400
401    fn capture_retained_inner(
402        &self,
403        target: &GateSnapshot,
404        delivery: &crate::config_store::DeliverySnapshot,
405        declarations: &BTreeMap<String, ConfigDeclareRequest>,
406        require_identical: bool,
407    ) -> Result<CapturedConfiguration> {
408        let invalid = || {
409            GateError::new(
410                "rollback_snapshot_unavailable",
411                "retained raw configuration is absent or inconsistent",
412            )
413        };
414        let retained_file = |layer: &ConfigLayerSnapshot, key: &InputKey| -> Result<CapturedFile> {
415            let path = layer.path.as_ref().ok_or_else(invalid)?;
416            let input = target.inputs.get(key).ok_or_else(invalid)?;
417            if layer.bytes.as_deref().map(subc_config::raw_digest) != layer.digest {
418                return Err(invalid());
419            }
420            Ok(CapturedFile {
421                path: path.into(),
422                bytes: layer.bytes.clone(),
423                state: input.state.clone(),
424                _file: None,
425            })
426        };
427        let daemon = retained_file(
428            delivery.daemon.as_ref().ok_or_else(invalid)?,
429            &InputKey::Daemon,
430        )?;
431        if daemon.path != self.daemon_path || daemon.bytes.is_none() {
432            return Err(invalid());
433        }
434        let mut files = BTreeMap::new();
435        for (module, view) in &delivery.modules {
436            let [layer] = view.layers.as_slice() else {
437                return Err(invalid());
438            };
439            if layer.layer != ConfigLayer::User
440                || layer.module_id != *module
441                || layer.project_id.is_some()
442                || layer.workspace_id.is_some()
443            {
444                return Err(invalid());
445            }
446            let path = layer.path.as_ref().ok_or_else(invalid)?;
447            let file = retained_file(
448                layer,
449                &InputKey::Layer {
450                    module: module.clone(),
451                    path: path.clone(),
452                },
453            )?;
454            files.insert(file.path.clone(), file);
455        }
456        let captured = self.capture_layers(daemon, declarations, None, true, |path| {
457            files.remove(path).ok_or_else(invalid)
458        })?;
459        if !files.is_empty()
460            || (require_identical
461                && target
462                    .inputs
463                    .iter()
464                    .filter(|(key, _)| !key.is_program())
465                    .ne(captured
466                        .diagnostic
467                        .inputs
468                        .iter()
469                        .filter(|(key, _)| !key.is_program())))
470        {
471            return Err(invalid());
472        }
473        Ok(captured)
474    }
475
476    fn capture_layers(
477        &self,
478        daemon: CapturedFile,
479        declarations: &BTreeMap<String, ConfigDeclareRequest>,
480        selected: Option<&BTreeSet<String>>,
481        programs: bool,
482        layer_file: impl FnMut(&Path) -> Result<CapturedFile>,
483    ) -> Result<CapturedConfiguration> {
484        self.capture_layers_observed::<false>(daemon, declarations, selected, programs, layer_file)
485            .map(|captured| captured.configuration)
486    }
487
488    fn capture_layers_observed<const REPORT_FILE_ERRORS: bool>(
489        &self,
490        daemon: CapturedFile,
491        declarations: &BTreeMap<String, ConfigDeclareRequest>,
492        selected: Option<&BTreeSet<String>>,
493        programs: bool,
494        mut layer_file: impl FnMut(&Path) -> Result<CapturedFile>,
495    ) -> Result<SettingsCapture> {
496        let invalid_daemon =
497            || GateError::new("invalid_daemon_config", "captured subc.jsonc is invalid");
498        let doc = daemon.parse().map_err(|_| invalid_daemon())?;
499        let mut launch_specs = BTreeMap::new();
500        if let Some(bytes) = &daemon.bytes {
501            let (config, _) = crate::daemon_config::parse_with_activity(
502                std::str::from_utf8(bytes).map_err(|_| invalid_daemon())?,
503                &self.daemon_path,
504            )
505            .map_err(|_| invalid_daemon())?;
506            launch_specs.extend(
507                config
508                    .modules
509                    .into_iter()
510                    .map(|module| (module.module_id.clone(), module.module_spec())),
511            );
512            refuse_expansions(&doc, "subc", "")?;
513        }
514        let mut program_handles = Vec::new();
515        // Launch arguments and environment participate in review verbatim;
516        // credential reference objects remain redacted in diagnostic views.
517        let safe_doc = redact_launch_values(&doc)?;
518        let mut diagnostic = GateSnapshot::default();
519        diagnostic.inputs.insert(
520            InputKey::Daemon,
521            CapturedInput {
522                state: daemon.state.clone(),
523                value: RecordedValue::new(safe_doc.clone()),
524            },
525        );
526        if let Some(entries) = safe_doc.get("modules").and_then(Value::as_object) {
527            for (module, entry) in entries {
528                diagnostic.inputs.insert(
529                    InputKey::Entry(module.clone()),
530                    CapturedInput {
531                        state: InputState::Present {
532                            digest: subc_config::raw_digest(
533                                &serde_json::to_vec(entry).map_err(GateError::invalid)?,
534                            ),
535                        },
536                        value: RecordedValue::new(entry.clone()),
537                    },
538                );
539            }
540        }
541        if let Some(entries) = doc
542            .get("modules")
543            .and_then(Value::as_object)
544            .filter(|_| programs)
545        {
546            for (module, entry) in entries {
547                if selected.is_some_and(|modules| !modules.contains(module)) {
548                    continue;
549                }
550                if let Some(spec) = launch_specs.get(module) {
551                    let covered = super::program::program_files(entry)?;
552                    let launch = super::program::capture(spec, &covered).map_err(|error| {
553                        GateError::new(&error.code, format!("{module}: {}", error.detail))
554                    })?;
555                    diagnostic.inputs.extend(launch.inputs);
556                    program_handles.extend(launch.files);
557                }
558            }
559        }
560        let mut modules = BTreeMap::new();
561        let mut file_errors = BTreeMap::new();
562        for (module, declaration) in declarations {
563            if selected.is_some_and(|modules| !modules.contains(module)) {
564                continue;
565            }
566            let (captured, input) = match self.capture_module(module, declaration, &mut layer_file)
567            {
568                Ok(captured) => captured,
569                Err(error) if REPORT_FILE_ERRORS && is_settings_file_error(&error) => {
570                    file_errors.insert(
571                        module.clone(),
572                        ConfigFileError::new(error.code, error.detail),
573                    );
574                    continue;
575                }
576                Err(error) => return Err(error),
577            };
578            diagnostic.inputs.insert(
579                InputKey::Layer {
580                    module: module.clone(),
581                    path: captured.file.path.to_string_lossy().into_owned(),
582                },
583                input,
584            );
585            let decl = serde_json::to_value(declaration).map_err(GateError::invalid)?;
586            diagnostic.inputs.insert(
587                InputKey::Declaration(module.clone()),
588                CapturedInput {
589                    state: InputState::Present {
590                        digest: subc_config::digest(subc_config::PURPOSE_DECLARATION, &decl)
591                            .map_err(GateError::invalid)?,
592                    },
593                    value: RecordedValue::new(redact_launch_values(&decl)?),
594                },
595            );
596            modules.insert(module.clone(), captured);
597        }
598        Ok(SettingsCapture {
599            configuration: CapturedConfiguration {
600                diagnostic,
601                daemon,
602                modules,
603                _program_handles: program_handles,
604            },
605            file_errors,
606        })
607    }
608
609    fn capture_module(
610        &self,
611        module: &str,
612        declaration: &ConfigDeclareRequest,
613        layer_file: impl FnOnce(&Path) -> Result<CapturedFile>,
614    ) -> Result<(CapturedModule, CapturedInput)> {
615        if !declaration.project_dirs.is_empty() {
616            // Workspace/project roots must come from the project registry,
617            // not from directories supplied by the module.
618            return Err(GateError::new(
619                "config_gated",
620                format!("{module}: project-tuple planning and delivery are not supported yet"),
621            ));
622        }
623        if module.is_empty() || module.contains(['/', '\\']) || module == "." || module == ".." {
624            return Err(GateError::new(
625                "path_invalid",
626                "module identity cannot form a layer path",
627            ));
628        }
629        let expected = self
630            .config_home
631            .join("cortexkit")
632            .join(format!("{module}.jsonc"));
633        if Path::new(&declaration.user_file) != expected || !expected.is_absolute() {
634            return Err(GateError::new(
635                "path_invalid",
636                format!("{module}: user layer must use its canonical config-home path"),
637            ));
638        }
639        let schema = Schema::new(declaration.schema.clone()).map_err(|refusal| {
640            GateError::new("schema_invalid", format!("{module}: {}", refusal.path))
641        })?;
642        let file = layer_file(&expected)?;
643        let value = file.parse()?;
644        refuse_expansions(&value, module, "")?;
645        // Record even invalid literals through the schema projection first;
646        // nothing raw is retained on the refusal path.
647        let recorded = schema.record(&value).map_err(GateError::invalid)?;
648        let layers = if file.bytes.is_some() {
649            vec![LayerValue::new(Layer::User, value)]
650        } else {
651            Vec::new()
652        };
653        let reviewed = schema
654            .review_tuple(&layers, &ValidationContext::new(module, None))
655            .map_err(|refusal| {
656                GateError::new(
657                    refusal_code(refusal.code),
658                    format!("{module}: {}", refusal.path),
659                )
660            })?;
661        let layer = ConfigLayerSnapshot::file(
662            module,
663            ConfigLayer::User,
664            expected.to_string_lossy(),
665            file.bytes.clone(),
666        );
667        let view = ConfigView::new(
668            0,
669            reviewed.effective,
670            reviewed.sources,
671            vec![layer],
672            ConfigStatus::Unstamped,
673        );
674        let input = CapturedInput {
675            state: file.state.clone(),
676            value: RecordedValue::new(recorded),
677        };
678        Ok((
679            CapturedModule {
680                declaration: declaration.clone(),
681                schema,
682                view,
683                file,
684            },
685            input,
686        ))
687    }
688
689    pub(crate) fn settings_file_error(
690        &self,
691        module: &str,
692        declaration: &ConfigDeclareRequest,
693    ) -> Result<Option<ConfigFileError>> {
694        match self.capture_module(module, declaration, CapturedFile::open) {
695            Ok(_) => Ok(None),
696            Err(error) if is_settings_file_error(&error) => {
697                Ok(Some(ConfigFileError::new(error.code, error.detail)))
698            }
699            Err(error) => Err(error),
700        }
701    }
702}
703
704fn is_settings_file_error(error: &GateError) -> bool {
705    matches!(error.code.as_str(), "value_invalid" | "input_unavailable")
706}
707
708fn redact_launch_values(value: &Value) -> Result<Value> {
709    if subc_config::is_vault_reference(value) {
710        return serde_json::to_value(RecordedValue::redacted(value).map_err(GateError::invalid)?)
711            .map_err(GateError::invalid);
712    }
713    match value {
714        Value::Object(object) => object
715            .iter()
716            .map(|(key, value)| {
717                let value = redact_launch_values(value)?;
718                Ok((key.clone(), value))
719            })
720            .collect::<Result<serde_json::Map<_, _>>>()
721            .map(Value::Object),
722        Value::Array(array) => array
723            .iter()
724            .map(redact_launch_values)
725            .collect::<Result<Vec<_>>>()
726            .map(Value::Array),
727        value => Ok(value.clone()),
728    }
729}
730
731pub(crate) fn capture_program(path: &Path) -> Result<(File, CapturedInput)> {
732    let (file, input, _) = capture_program_classified(path)?;
733    Ok((file, input))
734}
735
736pub(crate) fn capture_program_classified(path: &Path) -> Result<(File, CapturedInput, bool)> {
737    use sha2::{Digest as _, Sha256};
738    if !path.is_absolute() {
739        return Err(GateError::new(
740            "path_invalid",
741            "covered program path must be absolute",
742        ));
743    }
744    let resolved = std::fs::canonicalize(path).map_err(|error| {
745        if error.kind() == io::ErrorKind::NotFound {
746            GateError::new("program_missing", "configured program file is absent")
747        } else {
748            capture_error(error)
749        }
750    })?;
751    let file = subc_os::open_regular_nofollow(&resolved).map_err(capture_error)?;
752    let before = file.metadata().map_err(capture_error)?;
753    if !before.is_file() {
754        return Err(GateError::new(
755            "path_invalid",
756            "covered program must be a regular file",
757        ));
758    }
759    if before.len() > PROGRAM_FILE_LIMIT {
760        return Err(GateError::new(
761            "input_too_large",
762            "covered program exceeds the 512 MiB streamed-hash limit",
763        ));
764    }
765    let id = file_object_id(&file)?;
766    let mut hasher = Sha256::new();
767    let mut length = 0;
768    // Classify the same byte stream that supplies the approved hash, not an
769    // earlier path open that could have seen different content on this inode.
770    let mut prefix = Vec::with_capacity(2);
771    #[cfg(target_os = "macos")]
772    let signatures = subc_os::code_signature::file_signature(&file, |chunk| {
773        prefix.extend_from_slice(&chunk[..chunk.len().min(2 - prefix.len())]);
774        length += chunk.len() as u64;
775        hasher.update(chunk);
776    });
777    #[cfg(not(target_os = "macos"))]
778    {
779        let mut reader = &file;
780        let mut buffer = [0; 64 * 1024];
781        loop {
782            let count = reader.read(&mut buffer).map_err(capture_error)?;
783            if count == 0 {
784                break;
785            }
786            prefix.extend_from_slice(&buffer[..count.min(2 - prefix.len())]);
787            length += count as u64;
788            if length > PROGRAM_FILE_LIMIT {
789                return Err(GateError::new(
790                    "input_too_large",
791                    "covered program exceeds the 512 MiB streamed-hash limit",
792                ));
793            }
794            hasher.update(&buffer[..count]);
795        }
796    }
797    let after = file.metadata().map_err(capture_error)?;
798    let reopened = subc_os::open_regular_nofollow(&resolved).map_err(capture_error)?;
799    #[cfg(target_os = "macos")]
800    let completed = signatures.is_ok();
801    #[cfg(not(target_os = "macos"))]
802    let completed = true;
803    if (completed && length != before.len())
804        || std::fs::canonicalize(path).map_err(capture_error)? != resolved
805        || before.len() != after.len()
806        || before.modified().ok() != after.modified().ok()
807        || file_object_id(&reopened)? != id
808    {
809        return Err(GateError::stale());
810    }
811    #[cfg(target_os = "macos")]
812    let signatures = signatures.map_err(|error| match error {
813        subc_os::code_signature::SignatureError::Parse => GateError::new(
814            "program_invalid",
815            "covered program has an invalid or unsupported Mach-O structure",
816        ),
817        other => capture_error(other),
818    })?;
819    let identity = json!({ "path": resolved, "file": id, "length": length, "raw": format!("sha256:{:x}", hasher.finalize()) });
820    #[cfg(target_os = "macos")]
821    let identity = {
822        let mut identity = identity;
823        match signatures {
824            subc_os::code_signature::FileSignature::Signed(hashes) => {
825                identity["cdhashes"] = json!(hashes
826                    .into_iter()
827                    .map(|hash| hash
828                        .0
829                        .iter()
830                        .map(|byte| format!("{byte:02x}"))
831                        .collect::<String>())
832                    .collect::<Vec<_>>())
833            }
834            subc_os::code_signature::FileSignature::Unsigned => identity["cdhashes"] = json!([]),
835            subc_os::code_signature::FileSignature::Invalid => {
836                identity["cdhashes"] = json!([]);
837                identity["signature_invalid"] = json!(true);
838            }
839            subc_os::code_signature::FileSignature::NotMachO => {}
840        }
841        identity
842    };
843    let state = InputState::Present {
844        digest: subc_config::raw_digest(
845            &serde_json::to_vec(&identity).map_err(GateError::invalid)?,
846        ),
847    };
848    Ok((
849        file,
850        CapturedInput {
851            state,
852            value: RecordedValue::new(identity),
853        },
854        prefix == b"#!",
855    ))
856}
857
858pub(super) fn refusal_code(code: subc_config::RefusalCode) -> &'static str {
859    use subc_config::RefusalCode::*;
860    match code {
861        SchemaInvalid => "schema_invalid",
862        LayerForbidden => "layer_forbidden",
863        BoundViolated => "bound_violated",
864        CredentialShared => "credential_shared",
865        PlanStale => "plan_stale",
866        _ => "value_invalid",
867    }
868}
869
870pub(super) fn refuse_expansions(value: &Value, module: &str, path: &str) -> Result<()> {
871    match value {
872        Value::String(text) if text.contains("{env:") || text.contains("{file:") => {
873            Err(GateError::new("value_invalid", format!("{module}: {path}")))
874        }
875        Value::Object(values) => {
876            for (key, value) in values {
877                refuse_expansions(
878                    value,
879                    module,
880                    &format!("{path}/{}", key.replace('~', "~0").replace('/', "~1")),
881                )?;
882            }
883            Ok(())
884        }
885        Value::Array(values) => {
886            for (index, value) in values.iter().enumerate() {
887                refuse_expansions(value, module, &format!("{path}/{index}"))?;
888            }
889            Ok(())
890        }
891        _ => Ok(()),
892    }
893}
894
895#[cfg(test)]
896mod tests {
897    use super::*;
898
899    struct Rig {
900        root: PathBuf,
901        _scratch: cortexkit_test_support::ScratchDir,
902        capturer: ConfigCapturer,
903        declarations: BTreeMap<String, ConfigDeclareRequest>,
904    }
905    impl Rig {
906        fn new() -> Self {
907            let scratch = cortexkit_test_support::ScratchDir::new("subc-gate-capture");
908            std::fs::create_dir_all(scratch.join("cortexkit")).unwrap();
909            let root = scratch.path().canonicalize().unwrap();
910            let daemon_path = root.join("cortexkit/subc.jsonc");
911            std::fs::write(&daemon_path, br#"{"version":1,"modules":{}}"#).unwrap();
912            let schema = json!({
913                "$schema":"https://json-schema.org/draft/2020-12/schema", "type":"object", "unevaluatedProperties":false,
914                "x-ck-layers":["user"], "x-ck-apply":"live",
915                "properties": {
916                    "credential": {"type":"object", "description":"Vault credential", "x-ck-kind":"credential_ref", "x-ck-required":true},
917                    "limit": {"type":"integer", "description":"Request limit", "default":10}
918                }
919            });
920            let declaration = ConfigDeclareRequest::new(
921                schema,
922                root.join("cortexkit/a.jsonc").to_string_lossy(),
923                Vec::new(),
924            );
925            Self {
926                capturer: ConfigCapturer {
927                    daemon_path,
928                    config_home: root.clone(),
929                    projects: Arc::new(OfflineProjectRegistry),
930                },
931                declarations: BTreeMap::from([("a".into(), declaration)]),
932                root,
933                _scratch: scratch,
934            }
935        }
936        fn write(&self, bytes: &[u8]) {
937            std::fs::write(self.root.join("cortexkit/a.jsonc"), bytes).unwrap();
938        }
939    }
940
941    #[test]
942    fn config_capture_preserves_raw_reference_bytes_and_redacts_diagnostics() {
943        let rig = Rig::new();
944        let bytes = b"{ // reference, not its secret\n\"credential\":{\"vault_ref\":\"opaque-credential-id\"}, \"limit\":11,}\n";
945        rig.write(bytes);
946        let captured = rig.capturer.capture(&rig.declarations).unwrap();
947        assert_eq!(
948            captured.modules["a"].view.layers[0].bytes.as_deref(),
949            Some(bytes.as_slice())
950        );
951        let diagnostic = serde_json::to_string(&captured.diagnostic.to_store().unwrap()).unwrap();
952        assert!(!diagnostic.contains("opaque-credential-id"));
953        assert!(diagnostic.contains("redacted"));
954    }
955
956    #[test]
957    fn config_capture_refuses_literal_and_expansion_at_field_without_retaining_bytes() {
958        let rig = Rig::new();
959        for value in [
960            json!("literal-password-never-retained"),
961            json!("{env:PRIVATE_TOKEN}"),
962        ] {
963            rig.write(&serde_json::to_vec(&json!({"credential":value})).unwrap());
964            let error = rig.capturer.capture(&rig.declarations).err().unwrap();
965            assert_eq!(error.code, "value_invalid");
966            assert_eq!(error.detail, "a: /credential");
967            assert!(!error.to_string().contains(value.as_str().unwrap()));
968        }
969    }
970
971    #[test]
972    fn config_capture_replacement_with_identical_bytes_changes_read_set() {
973        let rig = Rig::new();
974        let bytes = br#"{"credential":{"vault_ref":"ref"}}"#;
975        rig.write(bytes);
976        let before = rig.capturer.capture(&rig.declarations).unwrap();
977        let replacement = rig.root.join("replacement");
978        std::fs::write(&replacement, bytes).unwrap();
979        std::fs::remove_file(rig.root.join("cortexkit/a.jsonc")).unwrap();
980        std::fs::rename(replacement, rig.root.join("cortexkit/a.jsonc")).unwrap();
981        let after = rig.capturer.capture(&rig.declarations).unwrap();
982        let modules = ["a".into()].into_iter().collect();
983        assert_ne!(
984            before.diagnostic.read_set(&modules).unwrap(),
985            after.diagnostic.read_set(&modules).unwrap()
986        );
987    }
988
989    #[test]
990    fn config_capture_refuses_project_directories_without_opening_them() {
991        let mut rig = Rig::new();
992        rig.declarations.get_mut("a").unwrap().project_dirs = vec!["/not-a-registry-root".into()];
993        let error = rig.capturer.capture(&rig.declarations).err().unwrap();
994        assert_eq!(error.code, "config_gated");
995        assert!(error.detail.contains("project-tuple planning and delivery"));
996        assert!(error.detail.contains("a: project-tuple"));
997    }
998
999    #[test]
1000    fn config_capture_distinguishes_absent_empty_and_over_bound_files() {
1001        let rig = Rig::new();
1002        let path = rig.root.join("cortexkit/missing.jsonc");
1003        assert_eq!(CapturedFile::open(&path).unwrap().state, InputState::Absent);
1004        std::fs::write(&path, b"").unwrap();
1005        assert!(matches!(
1006            CapturedFile::open(&path).unwrap().state,
1007            InputState::Present { .. }
1008        ));
1009        File::options()
1010            .write(true)
1011            .open(&path)
1012            .unwrap()
1013            .set_len(CONFIG_FILE_LIMIT + 1)
1014            .unwrap();
1015        assert_eq!(
1016            CapturedFile::open(&path).err().unwrap().code,
1017            "input_too_large"
1018        );
1019    }
1020}