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