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