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_protocol::config::{
15    ConfigDeclareRequest, ConfigLayer, ConfigLayerSnapshot, ConfigStatus, ConfigView,
16};
17
18use super::{CapturedInput, GateError, GateSnapshot, InputKey, Result};
19
20// A configuration document is small control-plane input, not an unbounded stream.
21/// Bound untrusted JSONC reads and parsing to 1 MiB per document.
22const CONFIG_FILE_LIMIT: u64 = 1024 * 1024;
23/// Bound streamed executable hashing so a proposal cannot demand an endless scan.
24const PROGRAM_FILE_LIMIT: u64 = 512 * 1024 * 1024;
25
26/// A file-object id is distinct from its bytes and from its pathname.
27#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(tag = "platform", rename_all = "snake_case")]
29pub enum FileObjectId {
30    Unix {
31        #[serde(with = "decimal_id")]
32        device: u64,
33        #[serde(with = "decimal_id")]
34        inode: u64,
35    },
36    Windows {
37        #[serde(with = "decimal_id")]
38        volume_serial_number: u64,
39        file_id: [u8; 16],
40    },
41}
42
43pub(super) mod decimal_id {
44    use serde::{Deserialize, Deserializer, Serializer};
45    pub fn serialize<S: Serializer>(
46        value: &u64,
47        serializer: S,
48    ) -> std::result::Result<S::Ok, S::Error> {
49        serializer.serialize_str(&value.to_string())
50    }
51    pub fn deserialize<'de, D: Deserializer<'de>>(
52        deserializer: D,
53    ) -> std::result::Result<u64, D::Error> {
54        String::deserialize(deserializer)?
55            .parse()
56            .map_err(serde::de::Error::custom)
57    }
58}
59
60fn file_object_id(file: &File) -> Result<FileObjectId> {
61    let id = subc_os::retained_file_identity(file).map_err(capture_error)?;
62    #[cfg(unix)]
63    return Ok(FileObjectId::Unix {
64        device: id.device,
65        inode: id.inode,
66    });
67    #[cfg(windows)]
68    return Ok(FileObjectId::Windows {
69        volume_serial_number: id.volume_serial_number,
70        file_id: id.file_id,
71    });
72}
73
74/// A cheap change detector; bytes are compared only after this metadata changes.
75#[derive(Clone, Debug, PartialEq, Eq)]
76pub(crate) struct UserFileMetadata {
77    identity: FileObjectId,
78    length: u64,
79    modified: Option<std::time::SystemTime>,
80}
81
82impl UserFileMetadata {
83    pub(crate) fn read(path: &Path) -> Result<Option<Self>> {
84        let metadata = match std::fs::symlink_metadata(path) {
85            Ok(metadata) => metadata,
86            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
87            Err(error) => return Err(capture_error(error)),
88        };
89        if !metadata.is_file() || metadata.file_type().is_symlink() {
90            return Err(GateError::new(
91                "path_invalid",
92                "user file must be a regular file",
93            ));
94        }
95        #[cfg(unix)]
96        let identity = {
97            use std::os::unix::fs::MetadataExt;
98            FileObjectId::Unix {
99                device: metadata.dev(),
100                inode: metadata.ino(),
101            }
102        };
103        #[cfg(windows)]
104        let identity =
105            file_object_id(&subc_os::open_regular_nofollow(path).map_err(capture_error)?)?;
106        Ok(Some(Self {
107            identity,
108            length: metadata.len(),
109            modified: metadata.modified().ok(),
110        }))
111    }
112}
113
114#[cfg(test)]
115pub(crate) use super::project_registry::OfflineProjectRegistry;
116pub use super::project_registry::{ProjectRegistry, RegistryRevision};
117
118pub struct ConfigCapturer {
119    pub daemon_path: PathBuf,
120    pub config_home: PathBuf,
121    pub projects: Arc<dyn ProjectRegistry>,
122}
123
124/// The handle remains open until capture/validation completes. It is never
125/// serialized: only its file identity, byte digest and redacted values are.
126pub struct CapturedFile {
127    _file: Option<File>,
128    pub path: PathBuf,
129    pub bytes: Option<Vec<u8>>,
130    pub state: InputState,
131}
132
133fn capture_error(_: impl std::fmt::Display) -> GateError {
134    // OS/parser errors can echo submitted text. Do not put it in a retained view.
135    GateError::new(
136        "input_unavailable",
137        "configuration input could not be captured",
138    )
139}
140
141impl CapturedFile {
142    pub fn open(path: &Path) -> Result<Self> {
143        if !path.is_absolute() {
144            return Err(GateError::new(
145                "path_invalid",
146                "configuration input must be absolute",
147            ));
148        }
149        let before = match std::fs::symlink_metadata(path) {
150            Ok(metadata) => metadata,
151            Err(error) if error.kind() == io::ErrorKind::NotFound => {
152                return Ok(Self {
153                    _file: None,
154                    path: path.into(),
155                    bytes: None,
156                    state: InputState::Absent,
157                });
158            }
159            Err(error) => return Err(capture_error(error)),
160        };
161        if !before.is_file() || before.file_type().is_symlink() {
162            return Err(GateError::new(
163                "path_invalid",
164                "configuration input must be a regular non-symlink file",
165            ));
166        }
167        let file = subc_os::open_regular_nofollow(path).map_err(capture_error)?;
168        let metadata = file.metadata().map_err(capture_error)?;
169        if !metadata.is_file() || metadata.len() > CONFIG_FILE_LIMIT {
170            return Err(GateError::new(
171                "input_too_large",
172                "configuration document exceeds the 1 MiB JSONC limit",
173            ));
174        }
175        let id = file_object_id(&file)?;
176        let mut bytes = Vec::with_capacity(metadata.len() as usize);
177        (&file)
178            .take(CONFIG_FILE_LIMIT + 1)
179            .read_to_end(&mut bytes)
180            .map_err(capture_error)?;
181        let after = file.metadata().map_err(capture_error)?;
182        let supplied = std::fs::symlink_metadata(path).map_err(capture_error)?;
183        let reopened = subc_os::open_regular_nofollow(path).map_err(capture_error)?;
184        if bytes.len() as u64 > CONFIG_FILE_LIMIT {
185            return Err(GateError::new(
186                "input_too_large",
187                "configuration document exceeds the 1 MiB JSONC limit",
188            ));
189        }
190        if bytes.len() as u64 != metadata.len()
191            || after.len() != metadata.len()
192            || after.modified().ok() != metadata.modified().ok()
193            || !supplied.is_file()
194            || supplied.file_type().is_symlink()
195            || file_object_id(&reopened)? != id
196        {
197            return Err(GateError::stale());
198        }
199        let digest = subc_config::raw_digest(&serde_json::to_vec(&json!({
200            "file": id, "raw": subc_config::raw_digest(&bytes), "length": metadata.len(),
201            "modified": metadata.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| (d.as_secs(), d.subsec_nanos())),
202        })).map_err(GateError::invalid)?);
203        Ok(Self {
204            _file: Some(file),
205            path: path.into(),
206            bytes: Some(bytes),
207            state: InputState::Present { digest },
208        })
209    }
210
211    fn parse(&self) -> Result<Value> {
212        match &self.bytes {
213            Some(bytes) => {
214                let text = std::str::from_utf8(bytes).map_err(capture_error)?;
215                let normalized = subc_jsonc::jsonc_to_json(text).map_err(capture_error)?;
216                super::strict_json::parse(&normalized)
217            }
218            None => Ok(json!({})),
219        }
220    }
221}
222
223pub struct CapturedModule {
224    pub declaration: ConfigDeclareRequest,
225    pub schema: Schema,
226    pub view: ConfigView,
227    pub file: CapturedFile,
228}
229
230pub struct CapturedConfiguration {
231    pub diagnostic: GateSnapshot,
232    pub daemon: CapturedFile,
233    pub modules: BTreeMap<String, CapturedModule>,
234    _program_handles: Vec<File>,
235}
236
237impl CapturedConfiguration {
238    pub(crate) fn take_handles(&mut self) -> Vec<File> {
239        let mut handles = std::mem::take(&mut self._program_handles);
240        handles.extend(self.daemon._file.take());
241        for module in self.modules.values_mut() {
242            handles.extend(module.file._file.take());
243        }
244        handles
245    }
246
247    /// A rollback may restore a path different from the current configuration's
248    /// path. Bind both programs in the observed read set without restoring any
249    /// historical executable bytes or trusting a historical file identity.
250    pub(crate) fn capture_programs(&mut self, keys: &[InputKey]) -> Result<()> {
251        for key in keys {
252            if self.diagnostic.inputs.contains_key(key) {
253                continue;
254            }
255            let InputKey::Program { path, .. } = key else {
256                unreachable!()
257            };
258            let (file, captured) = capture_program(Path::new(path))?;
259            self.diagnostic.inputs.insert(key.clone(), captured);
260            self._program_handles.push(file);
261        }
262        Ok(())
263    }
264}
265
266impl ConfigCapturer {
267    /// Candidate configuration only: no approved-store access, keychain work or
268    /// executable capture belongs on a polled diagnostic read.
269    pub(crate) fn capture_polled(
270        &self,
271        declarations: &BTreeMap<String, ConfigDeclareRequest>,
272    ) -> Result<GateSnapshot> {
273        let daemon = CapturedFile::open(&self.daemon_path)?;
274        self.capture_layers(daemon, declarations, None, false, CapturedFile::open)
275            .map(|captured| captured.diagnostic)
276    }
277
278    pub fn capture(
279        &self,
280        declarations: &BTreeMap<String, ConfigDeclareRequest>,
281    ) -> Result<CapturedConfiguration> {
282        self.capture_selected(declarations, None)
283    }
284
285    pub fn capture_modules(
286        &self,
287        declarations: &BTreeMap<String, ConfigDeclareRequest>,
288        modules: &BTreeSet<String>,
289    ) -> Result<CapturedConfiguration> {
290        self.capture_selected(declarations, Some(modules))
291    }
292
293    fn capture_selected(
294        &self,
295        declarations: &BTreeMap<String, ConfigDeclareRequest>,
296        selected: Option<&BTreeSet<String>>,
297    ) -> Result<CapturedConfiguration> {
298        let daemon = CapturedFile::open(&self.daemon_path)?;
299        self.capture_layers(daemon, declarations, selected, true, CapturedFile::open)
300    }
301
302    /// Re-evaluate saved raw configuration rather than today's edited files.
303    /// Program capture still opens the files at the restored configured paths.
304    pub(crate) fn capture_retained(
305        &self,
306        target: &GateSnapshot,
307        delivery: &crate::config_store::DeliverySnapshot,
308    ) -> Result<CapturedConfiguration> {
309        let invalid = || {
310            GateError::new(
311                "rollback_snapshot_unavailable",
312                "retained raw configuration is absent or inconsistent",
313            )
314        };
315        let retained_file = |layer: &ConfigLayerSnapshot, key: &InputKey| -> Result<CapturedFile> {
316            let path = layer.path.as_ref().ok_or_else(invalid)?;
317            let input = target.inputs.get(key).ok_or_else(invalid)?;
318            if layer.bytes.as_deref().map(subc_config::raw_digest) != layer.digest {
319                return Err(invalid());
320            }
321            Ok(CapturedFile {
322                path: path.into(),
323                bytes: layer.bytes.clone(),
324                state: input.state.clone(),
325                _file: None,
326            })
327        };
328        let daemon = retained_file(
329            delivery.daemon.as_ref().ok_or_else(invalid)?,
330            &InputKey::Daemon,
331        )?;
332        if daemon.path != self.daemon_path || daemon.bytes.is_none() {
333            return Err(invalid());
334        }
335        let mut files = BTreeMap::new();
336        for (module, view) in &delivery.modules {
337            let [layer] = view.layers.as_slice() else {
338                return Err(invalid());
339            };
340            if layer.layer != ConfigLayer::User
341                || layer.module_id != *module
342                || layer.project_id.is_some()
343                || layer.workspace_id.is_some()
344            {
345                return Err(invalid());
346            }
347            let path = layer.path.as_ref().ok_or_else(invalid)?;
348            let file = retained_file(
349                layer,
350                &InputKey::Layer {
351                    module: module.clone(),
352                    path: path.clone(),
353                },
354            )?;
355            files.insert(file.path.clone(), file);
356        }
357        let captured = self.capture_layers(daemon, &delivery.declarations, None, true, |path| {
358            files.remove(path).ok_or_else(invalid)
359        })?;
360        if !files.is_empty()
361            || target
362                .inputs
363                .iter()
364                .filter(|(key, _)| !key.is_program())
365                .ne(captured
366                    .diagnostic
367                    .inputs
368                    .iter()
369                    .filter(|(key, _)| !key.is_program()))
370        {
371            return Err(invalid());
372        }
373        Ok(captured)
374    }
375
376    fn capture_layers(
377        &self,
378        daemon: CapturedFile,
379        declarations: &BTreeMap<String, ConfigDeclareRequest>,
380        selected: Option<&BTreeSet<String>>,
381        programs: bool,
382        mut layer_file: impl FnMut(&Path) -> Result<CapturedFile>,
383    ) -> Result<CapturedConfiguration> {
384        let invalid_daemon =
385            || GateError::new("invalid_daemon_config", "captured subc.jsonc is invalid");
386        let doc = daemon.parse().map_err(|_| invalid_daemon())?;
387        let mut launch_specs = BTreeMap::new();
388        if let Some(bytes) = &daemon.bytes {
389            let (config, _) = crate::daemon_config::parse_with_activity(
390                std::str::from_utf8(bytes).map_err(|_| invalid_daemon())?,
391                &self.daemon_path,
392            )
393            .map_err(|_| invalid_daemon())?;
394            launch_specs.extend(
395                config
396                    .modules
397                    .into_iter()
398                    .map(|module| (module.module_id.clone(), module.module_spec())),
399            );
400            refuse_expansions(&doc, "subc", "")?;
401        }
402        let mut program_handles = Vec::new();
403        // Launch arguments and environment participate in review verbatim;
404        // credential reference objects remain redacted in diagnostic views.
405        let safe_doc = redact_launch_values(&doc)?;
406        let mut diagnostic = GateSnapshot::default();
407        diagnostic.inputs.insert(
408            InputKey::Daemon,
409            CapturedInput {
410                state: daemon.state.clone(),
411                value: RecordedValue::new(safe_doc.clone()),
412            },
413        );
414        if let Some(entries) = safe_doc.get("modules").and_then(Value::as_object) {
415            for (module, entry) in entries {
416                diagnostic.inputs.insert(
417                    InputKey::Entry(module.clone()),
418                    CapturedInput {
419                        state: InputState::Present {
420                            digest: subc_config::raw_digest(
421                                &serde_json::to_vec(entry).map_err(GateError::invalid)?,
422                            ),
423                        },
424                        value: RecordedValue::new(entry.clone()),
425                    },
426                );
427            }
428        }
429        if let Some(entries) = doc
430            .get("modules")
431            .and_then(Value::as_object)
432            .filter(|_| programs)
433        {
434            for (module, entry) in entries {
435                if selected.is_some_and(|modules| !modules.contains(module)) {
436                    continue;
437                }
438                if let Some(spec) = launch_specs.get(module) {
439                    let covered = super::program::program_files(entry)?;
440                    let launch = super::program::capture(spec, &covered).map_err(|error| {
441                        GateError::new(&error.code, format!("{module}: {}", error.detail))
442                    })?;
443                    diagnostic.inputs.extend(launch.inputs);
444                    program_handles.extend(launch.files);
445                }
446            }
447        }
448        let mut modules = BTreeMap::new();
449        for (module, declaration) in declarations {
450            if selected.is_some_and(|modules| !modules.contains(module)) {
451                continue;
452            }
453            if !declaration.project_dirs.is_empty() {
454                // Module-authored directories never become registry roots.
455                return Err(GateError::new(
456                    "config_gated",
457                    format!("{module}: project-tuple planning and delivery are not supported yet"),
458                ));
459            }
460            if module.is_empty() || module.contains(['/', '\\']) || module == "." || module == ".."
461            {
462                return Err(GateError::new(
463                    "path_invalid",
464                    "module identity cannot form a layer path",
465                ));
466            }
467            let expected = self
468                .config_home
469                .join("cortexkit")
470                .join(format!("{module}.jsonc"));
471            if Path::new(&declaration.user_file) != expected || !expected.is_absolute() {
472                return Err(GateError::new(
473                    "path_invalid",
474                    format!("{module}: user layer must use its canonical config-home path"),
475                ));
476            }
477            let schema = Schema::new(declaration.schema.clone()).map_err(|refusal| {
478                GateError::new("schema_invalid", format!("{module}: {}", refusal.path))
479            })?;
480            let file = layer_file(&expected)?;
481            let value = file.parse()?;
482            refuse_expansions(&value, module, "")?;
483            // Record even invalid literals through the schema projection first;
484            // nothing raw is retained on the refusal path.
485            let recorded = schema.record(&value).map_err(GateError::invalid)?;
486            let layers = if file.bytes.is_some() {
487                vec![LayerValue::new(Layer::User, value)]
488            } else {
489                Vec::new()
490            };
491            let reviewed = schema
492                .review_tuple(&layers, &ValidationContext::new(module, None))
493                .map_err(|refusal| {
494                    GateError::new(
495                        refusal_code(refusal.code),
496                        format!("{module}: {}", refusal.path),
497                    )
498                })?;
499            let layer = ConfigLayerSnapshot::file(
500                module,
501                ConfigLayer::User,
502                expected.to_string_lossy(),
503                file.bytes.clone(),
504            );
505            let view = ConfigView::new(
506                0,
507                reviewed.effective,
508                reviewed.sources,
509                vec![layer],
510                ConfigStatus::Unstamped,
511            );
512            diagnostic.inputs.insert(
513                InputKey::Layer {
514                    module: module.clone(),
515                    path: expected.to_string_lossy().into_owned(),
516                },
517                CapturedInput {
518                    state: file.state.clone(),
519                    value: RecordedValue::new(recorded),
520                },
521            );
522            let decl = serde_json::to_value(declaration).map_err(GateError::invalid)?;
523            diagnostic.inputs.insert(
524                InputKey::Declaration(module.clone()),
525                CapturedInput {
526                    state: InputState::Present {
527                        digest: subc_config::digest(subc_config::PURPOSE_DECLARATION, &decl)
528                            .map_err(GateError::invalid)?,
529                    },
530                    value: RecordedValue::new(redact_launch_values(&decl)?),
531                },
532            );
533            modules.insert(
534                module.clone(),
535                CapturedModule {
536                    declaration: declaration.clone(),
537                    schema,
538                    view,
539                    file,
540                },
541            );
542        }
543        Ok(CapturedConfiguration {
544            diagnostic,
545            daemon,
546            modules,
547            _program_handles: program_handles,
548        })
549    }
550}
551
552fn redact_launch_values(value: &Value) -> Result<Value> {
553    if subc_config::is_vault_reference(value) {
554        return serde_json::to_value(RecordedValue::redacted(value).map_err(GateError::invalid)?)
555            .map_err(GateError::invalid);
556    }
557    match value {
558        Value::Object(object) => object
559            .iter()
560            .map(|(key, value)| {
561                let value = redact_launch_values(value)?;
562                Ok((key.clone(), value))
563            })
564            .collect::<Result<serde_json::Map<_, _>>>()
565            .map(Value::Object),
566        Value::Array(array) => array
567            .iter()
568            .map(redact_launch_values)
569            .collect::<Result<Vec<_>>>()
570            .map(Value::Array),
571        value => Ok(value.clone()),
572    }
573}
574
575pub(crate) fn capture_program(path: &Path) -> Result<(File, CapturedInput)> {
576    let (file, input, _) = capture_program_classified(path)?;
577    Ok((file, input))
578}
579
580pub(crate) fn capture_program_classified(path: &Path) -> Result<(File, CapturedInput, bool)> {
581    use sha2::{Digest as _, Sha256};
582    if !path.is_absolute() {
583        return Err(GateError::new(
584            "path_invalid",
585            "covered program path must be absolute",
586        ));
587    }
588    let resolved = std::fs::canonicalize(path).map_err(|error| {
589        if error.kind() == io::ErrorKind::NotFound {
590            GateError::new("program_missing", "configured program file is absent")
591        } else {
592            capture_error(error)
593        }
594    })?;
595    let file = subc_os::open_regular_nofollow(&resolved).map_err(capture_error)?;
596    let before = file.metadata().map_err(capture_error)?;
597    if !before.is_file() {
598        return Err(GateError::new(
599            "path_invalid",
600            "covered program must be a regular file",
601        ));
602    }
603    if before.len() > PROGRAM_FILE_LIMIT {
604        return Err(GateError::new(
605            "input_too_large",
606            "covered program exceeds the 512 MiB streamed-hash limit",
607        ));
608    }
609    let id = file_object_id(&file)?;
610    let mut hasher = Sha256::new();
611    let mut length = 0;
612    // Classify the same byte stream that supplies the approved hash, not an
613    // earlier path open that could have seen different content on this inode.
614    let mut prefix = Vec::with_capacity(2);
615    #[cfg(target_os = "macos")]
616    let signatures = subc_os::code_signature::file_signature(&file, |chunk| {
617        prefix.extend_from_slice(&chunk[..chunk.len().min(2 - prefix.len())]);
618        length += chunk.len() as u64;
619        hasher.update(chunk);
620    });
621    #[cfg(not(target_os = "macos"))]
622    {
623        let mut reader = &file;
624        let mut buffer = [0; 64 * 1024];
625        loop {
626            let count = reader.read(&mut buffer).map_err(capture_error)?;
627            if count == 0 {
628                break;
629            }
630            prefix.extend_from_slice(&buffer[..count.min(2 - prefix.len())]);
631            length += count as u64;
632            if length > PROGRAM_FILE_LIMIT {
633                return Err(GateError::new(
634                    "input_too_large",
635                    "covered program exceeds the 512 MiB streamed-hash limit",
636                ));
637            }
638            hasher.update(&buffer[..count]);
639        }
640    }
641    let after = file.metadata().map_err(capture_error)?;
642    let reopened = subc_os::open_regular_nofollow(&resolved).map_err(capture_error)?;
643    #[cfg(target_os = "macos")]
644    let completed = signatures.is_ok();
645    #[cfg(not(target_os = "macos"))]
646    let completed = true;
647    if (completed && length != before.len())
648        || std::fs::canonicalize(path).map_err(capture_error)? != resolved
649        || before.len() != after.len()
650        || before.modified().ok() != after.modified().ok()
651        || file_object_id(&reopened)? != id
652    {
653        return Err(GateError::stale());
654    }
655    #[cfg(target_os = "macos")]
656    let signatures = signatures.map_err(|error| match error {
657        subc_os::code_signature::SignatureError::Parse => GateError::new(
658            "program_invalid",
659            "covered program has an invalid or unsupported Mach-O structure",
660        ),
661        other => capture_error(other),
662    })?;
663    let identity = json!({ "path": resolved, "file": id, "length": length, "raw": format!("sha256:{:x}", hasher.finalize()) });
664    #[cfg(target_os = "macos")]
665    let identity = {
666        let mut identity = identity;
667        match signatures {
668            subc_os::code_signature::FileSignature::Signed(hashes) => {
669                identity["cdhashes"] = json!(hashes
670                    .into_iter()
671                    .map(|hash| hash
672                        .0
673                        .iter()
674                        .map(|byte| format!("{byte:02x}"))
675                        .collect::<String>())
676                    .collect::<Vec<_>>())
677            }
678            subc_os::code_signature::FileSignature::Unsigned => identity["cdhashes"] = json!([]),
679            subc_os::code_signature::FileSignature::Invalid => {
680                identity["cdhashes"] = json!([]);
681                identity["signature_invalid"] = json!(true);
682            }
683            subc_os::code_signature::FileSignature::NotMachO => {}
684        }
685        identity
686    };
687    let state = InputState::Present {
688        digest: subc_config::raw_digest(
689            &serde_json::to_vec(&identity).map_err(GateError::invalid)?,
690        ),
691    };
692    Ok((
693        file,
694        CapturedInput {
695            state,
696            value: RecordedValue::new(identity),
697        },
698        prefix == b"#!",
699    ))
700}
701
702fn refusal_code(code: subc_config::RefusalCode) -> &'static str {
703    use subc_config::RefusalCode::*;
704    match code {
705        SchemaInvalid => "schema_invalid",
706        LayerForbidden => "layer_forbidden",
707        BoundViolated => "bound_violated",
708        CredentialShared => "credential_shared",
709        PlanStale => "plan_stale",
710        _ => "value_invalid",
711    }
712}
713
714fn refuse_expansions(value: &Value, module: &str, path: &str) -> Result<()> {
715    match value {
716        Value::String(text) if text.contains("{env:") || text.contains("{file:") => {
717            Err(GateError::new("value_invalid", format!("{module}: {path}")))
718        }
719        Value::Object(values) => {
720            for (key, value) in values {
721                refuse_expansions(
722                    value,
723                    module,
724                    &format!("{path}/{}", key.replace('~', "~0").replace('/', "~1")),
725                )?;
726            }
727            Ok(())
728        }
729        Value::Array(values) => {
730            for (index, value) in values.iter().enumerate() {
731                refuse_expansions(value, module, &format!("{path}/{index}"))?;
732            }
733            Ok(())
734        }
735        _ => Ok(()),
736    }
737}
738
739#[cfg(test)]
740mod tests {
741    use super::*;
742
743    struct Rig {
744        root: PathBuf,
745        _scratch: cortexkit_test_support::ScratchDir,
746        capturer: ConfigCapturer,
747        declarations: BTreeMap<String, ConfigDeclareRequest>,
748    }
749    impl Rig {
750        fn new() -> Self {
751            let scratch = cortexkit_test_support::ScratchDir::new("subc-gate-capture");
752            std::fs::create_dir_all(scratch.join("cortexkit")).unwrap();
753            let root = scratch.path().canonicalize().unwrap();
754            let daemon_path = root.join("cortexkit/subc.jsonc");
755            std::fs::write(&daemon_path, br#"{"version":1,"modules":{}}"#).unwrap();
756            let schema = json!({
757                "$schema":"https://json-schema.org/draft/2020-12/schema", "type":"object", "unevaluatedProperties":false,
758                "x-ck-layers":["user"], "x-ck-apply":"live",
759                "properties": {
760                    "credential": {"type":"object", "description":"Vault credential", "x-ck-kind":"credential_ref", "x-ck-required":true},
761                    "limit": {"type":"integer", "description":"Request limit", "default":10}
762                }
763            });
764            let declaration = ConfigDeclareRequest::new(
765                schema,
766                root.join("cortexkit/a.jsonc").to_string_lossy(),
767                Vec::new(),
768            );
769            Self {
770                capturer: ConfigCapturer {
771                    daemon_path,
772                    config_home: root.clone(),
773                    projects: Arc::new(OfflineProjectRegistry),
774                },
775                declarations: BTreeMap::from([("a".into(), declaration)]),
776                root,
777                _scratch: scratch,
778            }
779        }
780        fn write(&self, bytes: &[u8]) {
781            std::fs::write(self.root.join("cortexkit/a.jsonc"), bytes).unwrap();
782        }
783    }
784
785    #[test]
786    fn config_capture_preserves_raw_reference_bytes_and_redacts_diagnostics() {
787        let rig = Rig::new();
788        let bytes = b"{ // reference, not its secret\n\"credential\":{\"vault_ref\":\"opaque-credential-id\"}, \"limit\":11,}\n";
789        rig.write(bytes);
790        let captured = rig.capturer.capture(&rig.declarations).unwrap();
791        assert_eq!(
792            captured.modules["a"].view.layers[0].bytes.as_deref(),
793            Some(bytes.as_slice())
794        );
795        let diagnostic = serde_json::to_string(&captured.diagnostic.to_store().unwrap()).unwrap();
796        assert!(!diagnostic.contains("opaque-credential-id"));
797        assert!(diagnostic.contains("redacted"));
798    }
799
800    #[test]
801    fn config_capture_refuses_literal_and_expansion_at_field_without_retaining_bytes() {
802        let rig = Rig::new();
803        for value in [
804            json!("literal-password-never-retained"),
805            json!("{env:PRIVATE_TOKEN}"),
806        ] {
807            rig.write(&serde_json::to_vec(&json!({"credential":value})).unwrap());
808            let error = rig.capturer.capture(&rig.declarations).err().unwrap();
809            assert_eq!(error.code, "value_invalid");
810            assert_eq!(error.detail, "a: /credential");
811            assert!(!error.to_string().contains(value.as_str().unwrap()));
812        }
813    }
814
815    #[test]
816    fn config_capture_replacement_with_identical_bytes_changes_read_set() {
817        let rig = Rig::new();
818        let bytes = br#"{"credential":{"vault_ref":"ref"}}"#;
819        rig.write(bytes);
820        let before = rig.capturer.capture(&rig.declarations).unwrap();
821        let replacement = rig.root.join("replacement");
822        std::fs::write(&replacement, bytes).unwrap();
823        std::fs::remove_file(rig.root.join("cortexkit/a.jsonc")).unwrap();
824        std::fs::rename(replacement, rig.root.join("cortexkit/a.jsonc")).unwrap();
825        let after = rig.capturer.capture(&rig.declarations).unwrap();
826        let modules = ["a".into()].into_iter().collect();
827        assert_ne!(
828            before.diagnostic.read_set(&modules).unwrap(),
829            after.diagnostic.read_set(&modules).unwrap()
830        );
831    }
832
833    #[test]
834    fn config_capture_refuses_project_directories_without_opening_them() {
835        let mut rig = Rig::new();
836        rig.declarations.get_mut("a").unwrap().project_dirs = vec!["/not-a-registry-root".into()];
837        let error = rig.capturer.capture(&rig.declarations).err().unwrap();
838        assert_eq!(error.code, "config_gated");
839        assert!(error.detail.contains("project-tuple planning and delivery"));
840        assert!(error.detail.contains("a: project-tuple"));
841    }
842
843    #[test]
844    fn config_capture_distinguishes_absent_empty_and_over_bound_files() {
845        let rig = Rig::new();
846        let path = rig.root.join("cortexkit/missing.jsonc");
847        assert_eq!(CapturedFile::open(&path).unwrap().state, InputState::Absent);
848        std::fs::write(&path, b"").unwrap();
849        assert!(matches!(
850            CapturedFile::open(&path).unwrap().state,
851            InputState::Present { .. }
852        ));
853        File::options()
854            .write(true)
855            .open(&path)
856            .unwrap()
857            .set_len(CONFIG_FILE_LIMIT + 1)
858            .unwrap();
859        assert_eq!(
860            CapturedFile::open(&path).err().unwrap().code,
861            "input_too_large"
862        );
863    }
864}