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