1mod cache;
2mod inspect;
3mod migrate;
4mod persistence;
5mod repository;
6
7use cache::{
8 RepositoryProviderSecurityViolation, canonicalize_workspace_root, push_unique_layer_source,
9 should_skip_optional_global_error,
10};
11#[cfg(not(test))]
12use cache::{cache_get, cache_insert, cache_remove, with_cache_mut};
13use migrate::migrate_custom_api_keys_if_needed;
14
15use std::collections::HashMap;
16use std::fmt;
17use std::fs;
18use std::path::{Path, PathBuf};
19use std::sync::{Arc, Mutex};
20
21use anyhow::{Context, Result, bail};
22
23use crate::api_keys::{api_key_env_var, credential_metadata_key, store_credential_with_mode};
24use crate::defaults::{self};
25use crate::hooks::{HooksConfig, LifecycleHooksConfig, WorkspaceHookCommand, WorkspaceLifecycleHooks};
26use crate::loader::config::VTCodeConfig;
27use crate::loader::layers::{
28 ConfigLayerEntry, ConfigLayerMetadata, ConfigLayerSource, ConfigLayerStack, LayerDisabledReason,
29};
30use crate::loader::session_override;
31use vtcode_commons::VtCodePaths;
32use vtcode_commons::canonicalize;
33
34#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
36pub struct ConfigPhaseTiming {
37 pub path_resolution_us: u64,
39 pub layer_loading_us: u64,
41 pub merge_and_parse_us: u64,
43 pub validation_us: u64,
45}
46
47#[derive(Clone)]
49pub struct ConfigManager {
50 pub(crate) config: VTCodeConfig,
51 pub(super) config_path: Option<PathBuf>,
52 pub(super) canonical_user_config_path: Option<PathBuf>,
53 pub(super) tracked_user_config_paths: Vec<PathBuf>,
54 write_global_config_to_canonical: bool,
55 pub(super) explicit_config_is_trusted: bool,
60 pub(super) workspace_root: Option<PathBuf>,
61 pub(super) config_file_name: String,
62 pub(crate) layer_stack: ConfigLayerStack,
63 pub(super) phase_timing: Option<ConfigPhaseTiming>,
64}
65
66impl ConfigManager {
67 pub fn load() -> Result<Self> {
69 if let Some(override_path) = session_override::explicit_config_path() {
70 return Self::load_for_session(std::env::current_dir()?, &override_path).with_context(|| {
71 format!("Failed to load configuration from explicit path {}", override_path.display())
72 });
73 }
74
75 Self::load_from_workspace_with_repository_repair(std::env::current_dir()?)
76 }
77
78 pub fn load_for_session(workspace: impl AsRef<Path>, explicit_path: impl AsRef<Path>) -> Result<Self> {
88 let workspace = workspace.as_ref();
89 let explicit_path = explicit_path.as_ref();
90 #[cfg(not(test))]
91 let canonical_workspace = canonicalize_workspace_root(workspace);
92
93 #[cfg(not(test))]
94 if let Some(cached) = cache_get(&canonical_workspace) {
95 return Ok(cached.as_ref().clone());
96 }
97
98 let mut manager = Self::load_from_file_impl(explicit_path, false).with_context(|| {
99 format!(
100 "Failed to load explicit session config file {} (from --config / VTCODE_CONFIG_PATH)",
101 explicit_path.display()
102 )
103 })?;
104 manager.workspace_root = Some(canonicalize_workspace_root(workspace));
107
108 #[cfg(not(test))]
109 cache_insert(canonical_workspace, Arc::new(manager.clone()));
110
111 Ok(manager)
112 }
113
114 pub fn load_global() -> Result<Self> {
120 let defaults_provider = defaults::current_config_defaults();
121 let config_file_name = defaults_provider.config_file_name().to_string();
122 let canonical_user_config_path = defaults_provider.canonical_user_config_path(&config_file_name)?;
123 let mut tracked_user_config_paths = defaults_provider.home_config_paths(&config_file_name);
124 if let Some(path) = &canonical_user_config_path
125 && !tracked_user_config_paths.iter().any(|existing| existing == path)
126 {
127 tracked_user_config_paths.push(path.clone());
128 }
129
130 let mut layer_sources = Vec::new();
131 for system_config_path in defaults_provider.system_config_paths(&config_file_name)? {
132 push_unique_layer_source(&mut layer_sources, ConfigLayerSource::System { file: system_config_path });
133 }
134 for home_config_path in &tracked_user_config_paths {
135 push_unique_layer_source(&mut layer_sources, ConfigLayerSource::User { file: home_config_path.clone() });
136 }
137
138 let mut layer_stack = ConfigLayerStack::default();
139 for source in layer_sources {
140 if let Some(layer) = Self::load_optional_layer(source) {
141 layer_stack.push(layer);
142 }
143 }
144
145 if let Some((layer, error)) = layer_stack.first_layer_error() {
146 bail!("Configuration layer '{}' failed to load: {}", layer.source.label(), error.message);
147 }
148
149 let (config, config_path) = if layer_stack.layers().is_empty() {
150 let config = VTCodeConfig::default();
151 config.validate().context("Default configuration failed validation")?;
152 (config, None)
153 } else {
154 let (effective_toml, origins) = layer_stack.effective_config_with_origins();
155 let mut config: VTCodeConfig = effective_toml
156 .try_into()
157 .context("Failed to deserialize effective global configuration")?;
158 Self::validate_restricted_agent_fields(&layer_stack, &origins)?;
159 Self::validate_provider_security_fields(&layer_stack, &origins, &config, false)?;
160 Self::validate_sandbox_security_fields(&layer_stack, &origins, false)?;
161 config.validate().context("Global configuration failed validation")?;
162 config.workspace_lifecycle_hooks =
163 Some(Self::collect_workspace_lifecycle_hooks(&layer_stack, &config.hooks));
164 let config_path = layer_stack
165 .layers()
166 .iter()
167 .rev()
168 .find(|layer| layer.is_enabled())
169 .and_then(|layer| match &layer.source {
170 ConfigLayerSource::System { file } | ConfigLayerSource::User { file } => Some(file.clone()),
171 _ => None,
172 });
173 (config, config_path)
174 };
175
176 Ok(Self {
177 config,
178 config_path,
179 canonical_user_config_path,
180 tracked_user_config_paths,
181 write_global_config_to_canonical: false,
182 explicit_config_is_trusted: false,
183 workspace_root: None,
184 config_file_name,
185 layer_stack,
186 phase_timing: None,
187 })
188 }
189
190 pub fn invalidate_workspace_cache(workspace: impl AsRef<Path>) {
196 let workspace = workspace.as_ref();
197 #[cfg(not(test))]
198 {
199 let canonical_workspace = canonicalize_workspace_root(workspace);
200 cache_remove(&canonical_workspace);
201 }
202 #[cfg(test)]
203 let _ = workspace;
204 }
205
206 pub fn invalidate_all_workspace_cache() {
213 #[cfg(not(test))]
214 with_cache_mut(|map| map.clear());
215 }
216
217 pub fn load_from_workspace(workspace: impl AsRef<Path>) -> Result<Self> {
224 if let Some(override_path) = session_override::explicit_config_path() {
225 return Self::load_for_session(workspace, override_path);
226 }
227
228 let workspace = workspace.as_ref();
229 #[cfg(not(test))]
230 let canonical_workspace = canonicalize_workspace_root(workspace);
231
232 #[cfg(not(test))]
233 if let Some(cached) = cache_get(&canonical_workspace) {
234 return Ok(cached.as_ref().clone());
235 }
236
237 let manager = Self::load_from_workspace_impl(workspace)?;
238
239 #[cfg(not(test))]
240 cache_insert(canonical_workspace, Arc::new(manager.clone()));
241
242 Ok(manager)
243 }
244
245 pub fn load_from_workspace_with_repository_repair(workspace: impl AsRef<Path>) -> Result<Self> {
256 let workspace = workspace.as_ref();
257 let mut error = match Self::load_from_workspace(workspace) {
258 Ok(manager) => return Ok(manager),
259 Err(error) => error,
260 };
261
262 let repository_paths = Self::repository_config_paths(workspace);
266 for _ in 0..=repository_paths.len() {
267 let Some(violation) = error.downcast_ref::<RepositoryProviderSecurityViolation>() else {
268 return Err(error);
269 };
270
271 let source = violation.source.clone();
272 let Some(path) = repository_paths
273 .iter()
274 .find(|candidate| Self::repository_source_matches_path(&source, candidate))
275 else {
276 return Err(error);
277 };
278
279 if !Self::repair_repository_config_file(path)? {
280 return Err(error);
281 }
282
283 tracing::warn!(
284 path = %path.display(),
285 "Removed prohibited provider settings left by an older repository configuration write"
286 );
287
288 Self::invalidate_workspace_cache(workspace);
289 match Self::load_from_workspace(workspace) {
290 Ok(manager) => return Ok(manager),
291 Err(next_error) => error = next_error,
292 }
293 }
294
295 Err(error).context("Failed to load workspace configuration after repairing prohibited provider settings")
296 }
297
298 fn load_from_workspace_impl(workspace: impl AsRef<Path>) -> Result<Self> {
299 let t0 = std::time::Instant::now();
300 let workspace = workspace.as_ref();
301 let defaults_provider = defaults::current_config_defaults();
302 let workspace_paths = defaults_provider.workspace_paths_for(workspace);
303 let workspace_root = canonicalize_workspace_root(workspace_paths.workspace_root());
304 let config_dir = workspace_paths.config_dir();
305 let config_file_name = defaults_provider.config_file_name().to_string();
306 let canonical_user_config_path = defaults_provider.canonical_user_config_path(&config_file_name)?;
307 let mut tracked_user_config_paths = defaults_provider.home_config_paths(&config_file_name);
308 if let Some(path) = &canonical_user_config_path
309 && !tracked_user_config_paths.iter().any(|existing| existing == path)
310 {
311 tracked_user_config_paths.push(path.clone());
312 }
313 let path_res_duration = t0.elapsed();
314
315 let t1 = std::time::Instant::now();
316
317 let mut layer_sources: Vec<ConfigLayerSource> = Vec::with_capacity(8);
320
321 for system_config_path in defaults_provider.system_config_paths(&config_file_name)? {
324 push_unique_layer_source(&mut layer_sources, ConfigLayerSource::System { file: system_config_path });
325 }
326
327 for home_config_path in &tracked_user_config_paths {
329 push_unique_layer_source(&mut layer_sources, ConfigLayerSource::User { file: home_config_path.clone() });
330 }
331
332 if let Some(project_config_path) = Self::project_config_path(&config_dir, &workspace_root, &config_file_name) {
334 push_unique_layer_source(&mut layer_sources, ConfigLayerSource::Project { file: project_config_path });
335 }
336
337 let fallback_path = config_dir.join(&config_file_name);
339 let workspace_config_path = workspace_root.join(&config_file_name);
340 if fallback_path != workspace_config_path {
341 push_unique_layer_source(&mut layer_sources, ConfigLayerSource::Workspace { file: fallback_path });
342 }
343
344 push_unique_layer_source(
346 &mut layer_sources,
347 ConfigLayerSource::Workspace { file: workspace_config_path.clone() },
348 );
349
350 let raw_layers: Vec<Option<ConfigLayerEntry>> = std::thread::scope(|s| {
355 let handles = layer_sources
356 .into_iter()
357 .map(|source| s.spawn(move || Self::load_optional_layer(source)))
358 .collect::<Vec<_>>();
359 let joined = handles.into_iter().map(|h| h.join()).collect::<Vec<_>>();
361 joined
362 .into_iter()
363 .map(|r| r.map_err(|_payload| anyhow::anyhow!("config layer loader thread panicked")))
364 .collect::<Result<Vec<_>>>()
365 })?;
366
367 let mut layer_stack = ConfigLayerStack::default();
368 for layer in raw_layers.into_iter().flatten() {
369 layer_stack.push(layer);
370 }
371
372 let layer_load_duration = t1.elapsed();
373
374 if layer_stack.layers().is_empty() {
376 let t_val = std::time::Instant::now();
377 let config = VTCodeConfig::default();
378 config.validate().context("Default configuration failed validation")?;
379 let val_duration = t_val.elapsed();
380
381 let phase_timing = ConfigPhaseTiming {
382 path_resolution_us: path_res_duration.as_micros() as u64,
383 layer_loading_us: layer_load_duration.as_micros() as u64,
384 merge_and_parse_us: 0,
385 validation_us: val_duration.as_micros() as u64,
386 };
387 tracing::debug!(target: "vtcode_config", ?phase_timing, "Default configuration loaded");
388
389 return Ok(Self {
390 config,
391 config_path: None,
392 canonical_user_config_path,
393 tracked_user_config_paths,
394 write_global_config_to_canonical: false,
395 explicit_config_is_trusted: false,
396 workspace_root: Some(workspace_root),
397 config_file_name,
398 layer_stack,
399 phase_timing: Some(phase_timing),
400 });
401 }
402
403 let use_root_config = layer_stack
407 .layers()
408 .iter()
409 .find(|l| {
410 matches!(
411 &l.source,
412 ConfigLayerSource::Workspace { file }
413 if *file == workspace_config_path
414 )
415 })
416 .map(|l| Self::workspace_root_wants_root_config_only(&l.config))
417 .unwrap_or(false);
418 if use_root_config {
419 layer_stack.retain(|layer| {
420 matches!(
421 &layer.source,
422 ConfigLayerSource::Workspace { file }
423 if *file == workspace_config_path
424 ) || matches!(&layer.source, ConfigLayerSource::Runtime)
425 });
426 if layer_stack.layers().is_empty() {
427 bail!(
428 "workspace.use_root_config is true but no workspace root config was found at {}",
429 workspace_config_path.display()
430 );
431 }
432 }
433
434 if let Some((layer, error)) = layer_stack.first_layer_error() {
435 bail!("Configuration layer '{}' failed to load: {}", layer.source.label(), error.message);
436 }
437
438 let t2 = std::time::Instant::now();
439 let (effective_toml, origins) = layer_stack.effective_config_with_origins();
440 let mut config: VTCodeConfig = effective_toml
441 .try_into()
442 .context("Failed to deserialize effective configuration")?;
443 let merge_duration = t2.elapsed();
444
445 let t3 = std::time::Instant::now();
446 Self::validate_restricted_agent_fields(&layer_stack, &origins)?;
447 Self::validate_provider_security_fields(&layer_stack, &origins, &config, false)?;
448 Self::validate_sandbox_security_fields(&layer_stack, &origins, false)?;
449
450 config.validate().context("Configuration failed validation")?;
451 config.workspace_lifecycle_hooks = Some(Self::collect_workspace_lifecycle_hooks(&layer_stack, &config.hooks));
452
453 migrate_custom_api_keys_if_needed(&mut config)?;
455 let val_duration = t3.elapsed();
456
457 let phase_timing = ConfigPhaseTiming {
458 path_resolution_us: path_res_duration.as_micros() as u64,
459 layer_loading_us: layer_load_duration.as_micros() as u64,
460 merge_and_parse_us: merge_duration.as_micros() as u64,
461 validation_us: val_duration.as_micros() as u64,
462 };
463 tracing::debug!(target: "vtcode_config", ?phase_timing, "Workspace configuration loaded");
464
465 let config_path = layer_stack
466 .layers()
467 .iter()
468 .rev()
469 .find(|layer| layer.is_enabled())
470 .and_then(|l| match &l.source {
471 ConfigLayerSource::User { file } => Some(file.clone()),
472 ConfigLayerSource::Project { file } => Some(file.clone()),
473 ConfigLayerSource::Workspace { file } => Some(file.clone()),
474 ConfigLayerSource::System { file } => Some(file.clone()),
475 ConfigLayerSource::Runtime => None,
476 });
477
478 Ok(Self {
479 config,
480 config_path,
481 canonical_user_config_path,
482 tracked_user_config_paths,
483 write_global_config_to_canonical: false,
484 explicit_config_is_trusted: false,
485 workspace_root: Some(workspace_root),
486 config_file_name,
487 layer_stack,
488 phase_timing: Some(phase_timing),
489 })
490 }
491
492 fn load_toml_from_file(path: &Path) -> Result<toml::Value> {
493 let content =
494 fs::read_to_string(path).with_context(|| format!("Failed to read config file: {}", path.display()))?;
495 Self::parse_layer_value(&content, path)
496 }
497
498 fn parse_layer_value(content: &str, path: &Path) -> Result<toml::Value> {
503 let mut value: toml::Value =
504 toml::from_str(content).with_context(|| format!("Failed to parse config file: {}", path.display()))?;
505 crate::loader::merge::normalize_legacy_top_level_provider_aliases(&mut value);
506 Self::warn_removed_config_keys(&value, path);
507 Ok(value)
508 }
509
510 fn warn_removed_config_keys(value: &toml::Value, path: &Path) {
515 for key_path in removed_config_key_paths_present(value) {
516 let joined = key_path.join(".");
517 tracing::warn!(
518 config = %path.display(),
519 "Configuration key `{joined}` was removed and is ignored; it will be pruned on the next config save."
520 );
521 }
522 }
523
524 fn load_optional_layer(source: ConfigLayerSource) -> Option<ConfigLayerEntry> {
525 let file = match &source {
526 ConfigLayerSource::System { file }
527 | ConfigLayerSource::User { file }
528 | ConfigLayerSource::Project { file }
529 | ConfigLayerSource::Workspace { file } => file,
530 ConfigLayerSource::Runtime => {
531 return Some(ConfigLayerEntry::new(source, toml::Value::Table(toml::Table::new())));
532 }
533 };
534
535 let content = match fs::read_to_string(file) {
537 Ok(content) => content,
538 Err(err) if err.kind() == std::io::ErrorKind::NotFound => return None,
539 Err(err) if should_skip_optional_global_error(&source, &err) => {
540 tracing::debug!(path = %file.display(), "skipping inaccessible optional configuration layer");
541 return None;
542 }
543 Err(err) => {
544 let resolved_file = canonicalize_workspace_root(file);
545 let resolved_source = source.with_file(resolved_file);
546 return Some(Self::disabled_layer_from_error(resolved_source, err.into()));
547 }
548 };
549
550 let resolved_file = canonicalize_workspace_root(file);
551 let parsed = Self::parse_layer_value(&content, &resolved_file);
552 let resolved_source = source.with_file(resolved_file);
553
554 match parsed {
555 Ok(toml) => Some(ConfigLayerEntry::new(resolved_source, toml)),
556 Err(error) => Some(Self::disabled_layer_from_error(resolved_source, error)),
557 }
558 }
559
560 fn disabled_layer_from_error(source: ConfigLayerSource, error: anyhow::Error) -> ConfigLayerEntry {
561 let reason = if error.is::<toml::de::Error>() {
562 LayerDisabledReason::ParseError
563 } else {
564 LayerDisabledReason::LoadError
565 };
566 ConfigLayerEntry::disabled(source, reason, format!("{error:#}"))
567 }
568
569 fn workspace_root_wants_root_config_only(config: &toml::Value) -> bool {
574 config
575 .get("workspace")
576 .and_then(|v| v.get("use_root_config"))
577 .and_then(|v| v.as_bool())
578 .unwrap_or(false)
579 }
580
581 pub fn load_from_file(path: impl AsRef<Path>) -> Result<Self> {
583 Self::load_from_file_impl(path, false)
584 }
585
586 fn load_from_file_impl(path: impl AsRef<Path>, write_global_config_to_canonical: bool) -> Result<Self> {
587 let path = path.as_ref();
588 let defaults_provider = defaults::current_config_defaults();
589 let config_file_name = defaults_provider.config_file_name().to_string();
596 let canonical_user_config_path = defaults_provider.canonical_user_config_path(&config_file_name)?;
597 let mut tracked_user_config_paths = defaults_provider.home_config_paths(&config_file_name);
598 if let Some(path) = &canonical_user_config_path
599 && !tracked_user_config_paths.iter().any(|existing| existing == path)
600 {
601 tracked_user_config_paths.push(path.clone());
602 }
603
604 let mut layer_stack = ConfigLayerStack::default();
605 let mut global_sources = Vec::new();
606
607 for system_config in defaults_provider.system_config_paths(&config_file_name)? {
608 push_unique_layer_source(&mut global_sources, ConfigLayerSource::System { file: system_config });
609 }
610 for home_config_path in &tracked_user_config_paths {
611 push_unique_layer_source(&mut global_sources, ConfigLayerSource::User { file: home_config_path.clone() });
612 }
613 for source in global_sources {
614 if let Some(layer) = Self::load_optional_layer(source) {
615 layer_stack.push(layer);
616 }
617 }
618
619 let file = path.to_path_buf();
621 match Self::load_toml_from_file(path) {
622 Ok(toml) => layer_stack.push(ConfigLayerEntry::new(ConfigLayerSource::Workspace { file }, toml)),
623 Err(error) => {
624 layer_stack.push(Self::disabled_layer_from_error(ConfigLayerSource::Workspace { file }, error))
625 }
626 }
627
628 let use_root_config = layer_stack
631 .layers()
632 .iter()
633 .find(|l| {
634 matches!(
635 &l.source,
636 ConfigLayerSource::Workspace { file }
637 if *file == path
638 )
639 })
640 .map(|l| Self::workspace_root_wants_root_config_only(&l.config))
641 .unwrap_or(false);
642 if use_root_config {
643 layer_stack.retain(|layer| {
644 matches!(
645 &layer.source,
646 ConfigLayerSource::Workspace { file }
647 if *file == path
648 ) || matches!(&layer.source, ConfigLayerSource::Runtime)
649 });
650 }
651
652 if let Some((layer, error)) = layer_stack.first_layer_error() {
653 bail!("Configuration layer '{}' failed to load: {}", layer.source.label(), error.message);
654 }
655
656 let (effective_toml, origins) = layer_stack.effective_config_with_origins();
657 let mut config: VTCodeConfig = effective_toml
658 .try_into()
659 .with_context(|| format!("Failed to parse effective config with file: {}", path.display()))?;
660 Self::validate_restricted_agent_fields(&layer_stack, &origins)?;
661 Self::validate_provider_security_fields(&layer_stack, &origins, &config, true)?;
665 Self::validate_sandbox_security_fields(&layer_stack, &origins, true)?;
666
667 config
668 .validate()
669 .with_context(|| format!("Failed to validate effective config with file: {}", path.display()))?;
670 config.workspace_lifecycle_hooks = Some(Self::collect_workspace_lifecycle_hooks(&layer_stack, &config.hooks));
671
672 Ok(Self {
673 config,
674 config_path: Some(canonicalize_workspace_root(path)),
675 canonical_user_config_path,
676 tracked_user_config_paths,
677 write_global_config_to_canonical,
678 explicit_config_is_trusted: true,
679 workspace_root: path.parent().map(canonicalize_workspace_root),
680 config_file_name,
681 layer_stack,
682 phase_timing: None,
683 })
684 }
685
686 pub fn current_project_name(workspace_root: &Path) -> Option<String> {
688 Self::identify_current_project(workspace_root)
689 }
690
691 fn validate_restricted_agent_fields(
692 layer_stack: &ConfigLayerStack,
693 origins: &hashbrown::HashMap<String, ConfigLayerMetadata>,
694 ) -> Result<()> {
695 if let Some(origin) = origins.get("agent.persistent_memory.directory_override")
696 && let Some(layer) = layer_stack.layers().iter().find(|layer| layer.metadata == *origin)
697 {
698 match layer.source {
699 ConfigLayerSource::System { .. }
700 | ConfigLayerSource::User { .. }
701 | ConfigLayerSource::Project { .. } => {}
702 ConfigLayerSource::Workspace { .. } | ConfigLayerSource::Runtime => {
703 bail!(
704 "agent.persistent_memory.directory_override may only be set in system, user, or project-profile configuration layers"
705 );
706 }
707 }
708 }
709
710 Ok(())
711 }
712
713 fn validate_provider_security_fields(
722 layer_stack: &ConfigLayerStack,
723 origins: &hashbrown::HashMap<String, ConfigLayerMetadata>,
724 config: &VTCodeConfig,
725 explicit_config_is_trusted: bool,
726 ) -> Result<()> {
727 if explicit_config_is_trusted {
728 return Ok(());
729 }
730
731 if !config.custom_providers.is_empty()
732 && let Some(origin) = origins.get("custom_providers")
733 && let Some(layer) = Self::enabled_layer_for_origin(layer_stack, origin)
734 && Self::is_repository_controlled_source(&layer.source)
735 {
736 return Err(RepositoryProviderSecurityViolation {
737 source: layer.source.clone(),
738 message: format!(
739 "repository-controlled configuration cannot define `custom_providers` (including `auth.command`); move custom provider settings to system, user, or an explicitly selected config file (source: {})",
740 layer.source.label()
741 ),
742 }
743 .into());
744 }
745
746 for (path, origin) in origins {
747 if path == "auth.copilot.command"
748 && config
749 .auth
750 .copilot
751 .command
752 .as_deref()
753 .is_some_and(|command| !command.trim().is_empty())
754 && let Some(layer) = Self::enabled_layer_for_origin(layer_stack, origin)
755 && Self::is_repository_controlled_source(&layer.source)
756 {
757 bail!(
758 "repository-controlled configuration cannot set `auth.copilot.command`; configure it in system, user, or an explicitly selected config file (source: {})",
759 layer.source.label()
760 );
761 }
762 if !Self::is_provider_endpoint_or_credential_path(path) {
763 continue;
764 }
765
766 let Some(layer) = Self::enabled_layer_for_origin(layer_stack, origin) else {
767 continue;
768 };
769 if Self::is_repository_controlled_source(&layer.source) {
770 return Err(RepositoryProviderSecurityViolation {
771 source: layer.source.clone(),
772 message: format!(
773 "repository-controlled configuration cannot set `{path}`; provider endpoints and credential environment variables must be configured in system, user, or an explicitly selected config file (source: {})",
774 layer.source.label()
775 ),
776 }
777 .into());
778 }
779 }
780
781 Ok(())
782 }
783
784 fn validate_sandbox_security_fields(
793 layer_stack: &ConfigLayerStack,
794 origins: &hashbrown::HashMap<String, ConfigLayerMetadata>,
795 explicit_config_is_trusted: bool,
796 ) -> Result<()> {
797 if explicit_config_is_trusted {
798 return Ok(());
799 }
800
801 let trusted_enabled = layer_stack.layers().iter().any(|layer| {
802 layer.is_enabled()
803 && matches!(layer.source, ConfigLayerSource::System { .. } | ConfigLayerSource::User { .. })
804 && Self::toml_bool_at(&layer.config, "sandbox.enabled") == Some(true)
805 });
806
807 for (path, origin) in origins {
808 let Some(layer) = Self::enabled_layer_for_origin(layer_stack, origin) else {
809 continue;
810 };
811 if !Self::is_repository_controlled_source(&layer.source) {
812 continue;
813 }
814 let value = Self::toml_value_at(&layer.config, path);
815 let relaxing = match path.as_str() {
816 "sandbox.enabled" => trusted_enabled && value.and_then(toml::Value::as_bool) == Some(false),
817 "sandbox.default_policy" => value
818 .and_then(toml::Value::as_str)
819 .is_some_and(|policy| matches!(policy, "danger_full_access" | "external")),
820 "sandbox.network.policy" => value.and_then(toml::Value::as_str) == Some("allow_all"),
821 "sandbox.network.allow_all" => value.and_then(toml::Value::as_bool) == Some(true),
822 "sandbox.sensitive_paths.use_defaults" => value.and_then(toml::Value::as_bool) == Some(false),
823 "sandbox.sensitive_paths.exceptions" => {
824 value.and_then(toml::Value::as_array).is_some_and(|paths| !paths.is_empty())
825 }
826 "sandbox.resource_limits.preset" => value
827 .and_then(toml::Value::as_str)
828 .is_some_and(|preset| matches!(preset, "unlimited" | "generous")),
829 "sandbox.seccomp.enabled" => value.and_then(toml::Value::as_bool) == Some(false),
830 "sandbox.seccomp.profile" => value
831 .and_then(toml::Value::as_str)
832 .is_some_and(|profile| matches!(profile, "permissive" | "disabled")),
833 "sandbox.seccomp.log_only" => value.and_then(toml::Value::as_bool) == Some(true),
834 _ => false,
835 };
836 if relaxing {
837 bail!(
838 "repository-controlled configuration cannot relax `{path}`; the sandbox boundary must come from system, user, or an explicitly selected config file (source: {})",
839 layer.source.label()
840 );
841 }
842 }
843
844 Ok(())
845 }
846
847 fn toml_value_at<'a>(root: &'a toml::Value, path: &str) -> Option<&'a toml::Value> {
848 path.split('.').try_fold(root, |value, part| value.get(part))
849 }
850
851 fn toml_bool_at(root: &toml::Value, path: &str) -> Option<bool> {
852 Self::toml_value_at(root, path).and_then(toml::Value::as_bool)
853 }
854
855 fn enabled_layer_for_origin<'a>(
856 layer_stack: &'a ConfigLayerStack,
857 origin: &ConfigLayerMetadata,
858 ) -> Option<&'a ConfigLayerEntry> {
859 layer_stack
860 .layers()
861 .iter()
862 .find(|layer| layer.is_enabled() && layer.metadata == *origin)
863 }
864
865 fn is_repository_controlled_source(source: &ConfigLayerSource) -> bool {
866 matches!(source, ConfigLayerSource::Project { .. } | ConfigLayerSource::Workspace { .. })
867 }
868
869 fn is_provider_endpoint_or_credential_path(path: &str) -> bool {
870 let mut segments = path.split('.');
871 matches!(segments.next(), Some("provider_overrides"))
872 && segments.next().is_some()
873 && matches!(segments.next(), Some("base_url" | "api_key_env"))
874 && segments.next().is_none()
875 }
876
877 pub(crate) fn collect_workspace_lifecycle_hooks(
883 layer_stack: &ConfigLayerStack,
884 hooks: &HooksConfig,
885 ) -> WorkspaceLifecycleHooks {
886 let (_, origins) = layer_stack.effective_config_with_origins();
887 let mut commands = Vec::new();
888
889 for event in crate::hooks::LIFECYCLE_HOOK_EVENTS {
890 let origin_key = format!("hooks.lifecycle.{event}");
891 let Some(origin) = origins.get(&origin_key) else {
892 continue;
893 };
894 let workspace_controlled = layer_stack.layers().iter().any(|layer| {
895 layer.is_enabled()
896 && layer.metadata == *origin
897 && matches!(layer.source, ConfigLayerSource::Workspace { .. } | ConfigLayerSource::Project { .. })
898 });
899 if !workspace_controlled {
900 continue;
901 }
902
903 let tag = match *event {
905 "task_completion" | "task_completed" => "stop",
906 other => other,
907 };
908 for group in hooks.lifecycle.groups_for_event(event) {
909 for command in &group.hooks {
910 commands.push(WorkspaceHookCommand {
911 event: tag.to_string(),
912 matcher: group.matcher.clone(),
913 command: command.command.clone(),
914 timeout_seconds: command.timeout_seconds,
915 });
916 }
917 }
918 }
919
920 WorkspaceLifecycleHooks { commands }
921 }
922}
923
924mod removed_keys;
925pub(super) use removed_keys::{REMOVED_CONFIG_KEY_PATHS, removed_config_key_paths_present};
926
927#[cfg(test)]
928mod sparse_config_tests;
929#[cfg(test)]
930mod workspace_lifecycle_hooks_tests;