Repository navigation
Expand file tree
/
Copy pathmod.rs
More file actions
2011 lines (1886 loc) · 72.1 KB
/
Copy pathmod.rs
File metadata and controls
2011 lines (1886 loc) · 72.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
mod application;
mod layer_io;
mod local;
#[cfg(target_os = "macos")]
mod macos;
mod managed_requirements;
mod project_discovery;
#[cfg(test)]
mod tests;
#[cfg(test)]
#[path = "projectless_directory_tests.rs"]
mod projectless_directory_tests;
#[cfg(windows)]
mod windows;
pub use application::LocalApplicationRequirements;
pub use application::load_local_application_requirements;
use self::layer_io::LoadedConfigLayers;
use crate::CONFIG_TOML_FILE;
use crate::CloudConfigBundleLayers;
use crate::ConfigLayerSource;
use crate::ProfileV2Name;
use crate::RequirementsLayerEntry;
use crate::config_requirements::RequirementSource;
use crate::config_requirements::SandboxModeRequirement;
use crate::config_toml::ConfigToml;
use crate::config_toml::ProjectConfig;
use crate::diagnostics::ConfigError;
use crate::diagnostics::config_error_from_toml;
use crate::diagnostics::first_layer_config_error_from_entries as typed_first_layer_config_error_from_entries;
use crate::diagnostics::io_error_from_config_error;
use crate::merge::merge_toml_values;
use crate::overrides::build_cli_overrides_layer;
use crate::project_root_markers::default_project_root_markers;
use crate::project_root_markers::project_root_markers_from_config;
use crate::shell_environment_policy::ShellEnvironmentPolicyFilterConfigToml;
use crate::state::ConfigLayerEntry;
use crate::state::ConfigLayerStack;
use crate::state::ConfigLoadOptions;
use crate::state::LoaderOverrides;
use crate::state::validate_enabled_config_layers;
use crate::strict_config::config_error_from_ignored_toml_value_fields;
use crate::strict_config::ignored_config_warning;
use crate::strict_config::ignored_toml_value_fields;
use crate::strict_config::unknown_feature_toml_value_field;
use crate::thread_config::ThreadConfigContext;
use crate::thread_config::ThreadConfigLoader;
use codex_file_system::ExecutorFileSystem;
use codex_git_utils::resolve_root_git_project_for_trust;
use codex_network_proxy::is_credential_broker_provider_env_key;
use codex_protocol::config_types::ApprovalsReviewer;
use codex_protocol::config_types::SandboxMode;
use codex_protocol::config_types::TrustLevel;
use codex_protocol::protocol::AskForApproval;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_absolute_path::AbsolutePathBufGuard;
use codex_utils_path_uri::PathUri;
use dunce::canonicalize as normalize_path;
use serde::Deserialize;
use std::io;
use std::path::Path;
#[cfg(windows)]
use std::path::PathBuf;
use toml::Value as TomlValue;
pub use local::LocalConfigLayers;
pub use local::LocalTomlLayer;
pub use local::LocalTomlLayerStack;
pub use local::load_local_config_layers;
pub use managed_requirements::load_managed_requirements_state;
#[cfg(windows)]
pub use windows::WindowsSystemConfigNamespaceProbe;
#[cfg(windows)]
pub use windows::probe_windows_system_config_namespace;
#[cfg(unix)]
const SYSTEM_CONFIG_TOML_FILE_UNIX: &str = "/etc/codex/config.toml";
#[cfg(windows)]
const DEFAULT_PROGRAM_DATA_DIR_WINDOWS: &str = r"C:\ProgramData";
// Project-local config comes from repository contents, so it should not get to
// choose where a user's credentials are sent or which local commands are run.
// These settings are still supported from user, system, managed, and runtime
// config layers.
const PROJECT_LOCAL_CONFIG_DENYLIST: &[&str] = &[
"openai_base_url",
"chatgpt_base_url",
"apps_mcp_product_sku",
"responses_api_metadata",
"model_provider",
"model_providers",
"notify",
"profile",
"profiles",
"experimental_realtime_webrtc_call_base_url",
"experimental_realtime_ws_base_url",
"otel",
];
async fn first_layer_config_error_from_entries(layers: &[ConfigLayerEntry]) -> Option<ConfigError> {
typed_first_layer_config_error_from_entries::<ConfigToml>(layers, CONFIG_TOML_FILE).await
}
/// To build up the set of admin-enforced constraints, requirements layers are
/// collected in ascending precedence order, matching config layers, and then
/// composed with config-style TOML merging plus field-specific handling for
/// hooks, rules, deny-read permissions, and remote sandbox config:
///
/// - system `/etc/codex/requirements.toml` (Unix) or
/// `%ProgramData%\OpenAI\Codex\requirements.toml` (Windows)
/// - cloud: enterprise-managed cloud config bundle requirements
/// - legacy: `/etc/codex/managed_config.toml` (Unix) reinterpreted as
/// requirements.toml
/// - admin: managed preferences (*)
///
/// For backwards compatibility, Unix continues to load
/// `/etc/codex/managed_config.toml` and map it to `requirements.toml`.
///
/// Configuration is built up from multiple layers in the following order:
///
/// - package: optional default configuration supplied with the Codex package
/// - admin: managed preferences (*)
/// - system `/etc/codex/config.toml` (Unix) or
/// `%ProgramData%\OpenAI\Codex\config.toml` (Windows)
/// - cloud enterprise-managed cloud config bundle fragments
/// - user `${CODEX_HOME}/config.toml`
/// - profile `${CODEX_HOME}/<name>.config.toml`, when selected
/// - cwd `${PWD}/config.toml` (loaded but disabled when the directory is untrusted)
/// - tree parent directories up to root looking for `./.codex/config.toml` (loaded but disabled when untrusted)
/// - repo `$(git rev-parse --show-toplevel)/.codex/config.toml` (loaded but disabled when untrusted)
/// - runtime e.g., --config flags, model selector in UI
///
/// (*) Only available on macOS via managed device profiles.
///
/// See https://developers.openai.com/codex/security for details.
///
/// When loading the config stack for a thread, there should be a `cwd`
/// associated with it such that `cwd` should be `Some(...)`. Only for
/// thread-agnostic config loading (e.g., for the app server's `/config`
/// endpoint) should `cwd` be `None`.
#[allow(clippy::too_many_arguments)]
pub async fn load_config_layers_state(
fs: &dyn ExecutorFileSystem,
codex_home: &Path,
cwd: Option<AbsolutePathBuf>,
cli_overrides: &[(String, TomlValue)],
options: impl Into<ConfigLoadOptions>,
thread_config_loader: &dyn ThreadConfigLoader,
) -> io::Result<ConfigLayerStack> {
let ConfigLoadOptions {
loader_overrides: overrides,
strict_config,
cloud_config_bundle,
} = options.into();
let packaged_defaults_layer = if let Some(file) = &overrides.packaged_defaults_path {
let config = layer_io::read_config_from_path(
fs,
file,
/*log_missing_as_info*/ false,
strict_config,
)
.await?
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!("packaged defaults config file {} not found", file.display()),
)
})?;
let base_dir = file.as_path().parent().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData,
format!(
"packaged defaults config file {} has no parent directory",
file.display()
),
)
})?;
ConfigLayerEntry::new(
ConfigLayerSource::PackagedDefaults { file: file.clone() },
resolve_relative_paths_in_config_toml(config, base_dir)?,
)
} else {
let file = AbsolutePathBuf::from_absolute_path(std::env::current_exe()?)?;
let raw_toml = include_str!("../../defaults.toml");
let config = toml::from_str(raw_toml).map_err(|error| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("invalid embedded packaged defaults; this is a Codex build error: {error}"),
)
})?;
ConfigLayerEntry::new_with_raw_toml(
ConfigLayerSource::PackagedDefaults { file },
config,
raw_toml.to_owned(),
AbsolutePathBuf::from_absolute_path(codex_home)?,
)
};
let active_user_profile = overrides.user_config_profile.clone();
let ignore_user_config = overrides.ignore_user_config;
let ignore_project_config = overrides.ignore_project_config;
let ignore_user_and_project_exec_policy_rules =
overrides.ignore_user_and_project_exec_policy_rules;
let mut bundle_requirements_layers = Vec::new();
let mut cloud_config_layers = Vec::new();
if !overrides.ignore_managed_requirements
&& let Some(bundle) = cloud_config_bundle.get().await.map_err(io::Error::other)?
{
let cloud_config_base_dir = AbsolutePathBuf::from_absolute_path(codex_home)?;
let bundle_layers = if strict_config {
CloudConfigBundleLayers::from_bundle_strict_config(bundle, &cloud_config_base_dir)?
} else {
CloudConfigBundleLayers::from_bundle(bundle, &cloud_config_base_dir)?
};
let CloudConfigBundleLayers {
enterprise_managed_config,
enterprise_managed_requirements,
} = bundle_layers;
bundle_requirements_layers = enterprise_managed_requirements;
cloud_config_layers = enterprise_managed_config;
}
let (config_requirements_toml, loaded_config_layers, requirements_layers) =
managed_requirements::load_requirements_from_sources(
fs,
codex_home,
&overrides,
strict_config,
bundle_requirements_layers,
)
.await?;
let mut startup_warnings = loaded_config_layers.startup_warnings.clone();
let thread_config_context = ThreadConfigContext {
thread_id: None,
cwd: cwd.clone(),
};
let thread_config_layers = thread_config_loader
.load_config_layers(thread_config_context)
.await
.map_err(io::Error::other)?;
let mut layers = Vec::<ConfigLayerEntry>::new();
layers.push(packaged_defaults_layer);
let cli_overrides_layer = if cli_overrides.is_empty() {
None
} else {
let cli_overrides_layer = build_cli_overrides_layer(cli_overrides);
let base_dir = cwd
.as_ref()
.map(AbsolutePathBuf::as_path)
.unwrap_or(codex_home);
if strict_config {
validate_cli_overrides_strictly(&cli_overrides_layer, base_dir)?;
}
Some(resolve_relative_paths_in_config_toml(
cli_overrides_layer,
base_dir,
)?)
};
// Include an entry for the "system" config folder, loading its config.toml,
// if it exists.
let system_config_toml_file = system_config_toml_file_with_overrides(&overrides)?;
let system_layer = load_config_toml_for_required_layer(
fs,
&system_config_toml_file,
strict_config,
|config_toml| {
ConfigLayerEntry::new(
ConfigLayerSource::System {
file: system_config_toml_file.clone(),
},
config_toml,
)
},
)
.await?;
layers.push(system_layer);
layers.extend(cloud_config_layers);
// Add the base user config layer. When profile-v2 is selected, add the
// profile config as a second user layer on top so the profile only needs to
// contain overrides.
let active_user_file = overrides.user_config_path(codex_home)?;
let base_user_file = AbsolutePathBuf::resolve_path_against_base(CONFIG_TOML_FILE, codex_home);
let base_user_layer = load_user_config_layer(
fs,
&base_user_file,
/*profile*/ None,
ignore_user_config,
strict_config,
)
.await?;
if let Some(active_user_profile) = active_user_profile.as_ref()
&& let Some(base_user_config) = base_user_layer.config.as_table()
{
let legacy_profile_is_selected = base_user_config
.get("profile")
.and_then(TomlValue::as_str)
.is_some_and(|profile| profile == active_user_profile.as_str());
let legacy_profile_table_exists = base_user_config
.get("profiles")
.and_then(TomlValue::as_table)
.is_some_and(|profiles| profiles.contains_key(active_user_profile.as_str()));
if legacy_profile_is_selected || legacy_profile_table_exists {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"--profile `{active_user_profile}` cannot be used while {} contains legacy `profile = \"{active_user_profile}\"` or `[profiles.{active_user_profile}]` config; move those settings into {} and remove the legacy profile selector/table. See https://developers.openai.com/codex/config-advanced#profiles for more information.",
base_user_file.as_path().display(),
active_user_file.as_path().display()
),
));
}
}
layers.push(base_user_layer);
if active_user_file != base_user_file {
layers.push(
load_user_config_layer(
fs,
&active_user_file,
active_user_profile.as_ref(),
ignore_user_config,
strict_config,
)
.await?,
);
}
let mut is_projectless = false;
if !ignore_project_config && let Some(cwd) = cwd {
let mut merged_so_far = TomlValue::Table(toml::map::Map::new());
for layer in &layers {
merge_toml_values(&mut merged_so_far, &layer.config);
}
if let Some(cli_overrides_layer) = cli_overrides_layer.as_ref() {
merge_toml_values(&mut merged_so_far, cli_overrides_layer);
}
let trusted_broker_config = credential_broker_trusted_config(
&merged_so_far,
&thread_config_layers,
&loaded_config_layers,
);
// Managed config wins over CLI config. Apply it before choosing the
// project root and trust, but keep its final layers above project config.
project_discovery::merge_managed_config_for_discovery(
&mut merged_so_far,
&loaded_config_layers,
codex_home,
)?;
let project_root_markers = match project_root_markers_from_config(&merged_so_far) {
Ok(markers) => markers.unwrap_or_else(default_project_root_markers),
Err(err) => {
if let Some(config_error) = first_layer_config_error_from_entries(&layers).await {
return Err(io_error_from_config_error(
io::ErrorKind::InvalidData,
config_error,
/*source*/ None,
));
}
return Err(err);
}
};
let mut project_trust_context = match project_trust_context(
fs,
&merged_so_far,
&trusted_broker_config,
&cwd,
&project_root_markers,
codex_home,
&active_user_file,
)
.await
{
Ok(context) => context,
Err(err) => {
let source = err
.get_ref()
.and_then(|err| err.downcast_ref::<toml::de::Error>())
.cloned();
if let Some(config_error) = first_layer_config_error_from_entries(&layers).await {
return Err(io_error_from_config_error(
io::ErrorKind::InvalidData,
config_error,
source,
));
}
return Err(err);
}
};
apply_credential_broker_requirements(&mut project_trust_context, &config_requirements_toml);
let project_layers = load_project_layers(
fs,
&cwd,
&project_trust_context.project_root,
&project_trust_context,
codex_home,
strict_config,
)
.await?;
is_projectless = !project_trust_context.has_project_root_marker
&& project_trust_context.checkout_root.is_none()
&& project_layers.layers.is_empty();
layers.extend(project_layers.layers);
startup_warnings.extend(project_layers.startup_warnings);
}
// Add a layer for runtime overrides from the CLI or UI, if any exist.
if let Some(cli_overrides_layer) = cli_overrides_layer {
layers.push(ConfigLayerEntry::new(
ConfigLayerSource::SessionFlags,
cli_overrides_layer,
));
}
for thread_config_layer in thread_config_layers {
insert_layer_by_precedence(&mut layers, thread_config_layer);
}
// Make a best-effort to support the legacy `managed_config.toml` as a
// config layer on top of everything else. For fields in
// `managed_config.toml` that do not have an equivalent in
// `ConfigRequirements`, note users can still override these values on a
// per-turn basis in the TUI and VS Code.
let LoadedConfigLayers {
managed_config,
managed_config_from_mdm,
..
} = loaded_config_layers;
if let Some(config) = managed_config {
let managed_parent = config.file.as_path().parent().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData,
format!(
"Managed config file {} has no parent directory",
config.file.as_path().display()
),
)
})?;
let managed_config =
resolve_relative_paths_in_config_toml(config.managed_config, managed_parent)?;
layers.push(ConfigLayerEntry::new(
ConfigLayerSource::LegacyManagedConfigTomlFromFile { file: config.file },
managed_config,
));
}
if let Some(config) = managed_config_from_mdm {
// As a general rule, config from MDM should _not_ include relative
// paths, starting with `./`, but a path starting with `~/` _is_ a
// supported use case. Because resolve_relative_paths_in_config_toml()
// relies on AbsolutePathBufGuard to resolve `~/`, we must supply a
// value for base_dir. Preserve that same base on the layer so later
// raw-TOML diagnostics parse with the same path semantics.
let raw_toml_base_dir = AbsolutePathBuf::from_absolute_path(codex_home)?;
let managed_config = resolve_relative_paths_in_config_toml(
config.managed_config,
raw_toml_base_dir.as_path(),
)?;
layers.push(ConfigLayerEntry::new_with_raw_toml(
ConfigLayerSource::LegacyManagedConfigTomlFromMdm,
managed_config,
config.raw_toml,
raw_toml_base_dir,
));
}
if let Err(err) = validate_enabled_config_layers(&layers) {
if let Some(config_error) = typed_first_layer_config_error_from_entries::<
ShellEnvironmentPolicyFilterConfigToml,
>(&layers, CONFIG_TOML_FILE)
.await
{
return Err(io_error_from_config_error(
io::ErrorKind::InvalidData,
config_error,
/*source*/ None,
));
}
return Err(err);
}
let mut config_layer_stack = ConfigLayerStack::new(
layers,
config_requirements_toml.clone().try_into()?,
config_requirements_toml.into_toml(),
)?
.with_user_and_project_exec_policy_rules_ignored(ignore_user_and_project_exec_policy_rules);
config_layer_stack.is_projectless = is_projectless;
startup_warnings.extend(ignored_config_warning(
&config_layer_stack,
&requirements_layers,
));
Ok(config_layer_stack.with_startup_warnings(startup_warnings))
}
async fn load_user_config_layer(
fs: &dyn ExecutorFileSystem,
user_file: &AbsolutePathBuf,
profile: Option<&ProfileV2Name>,
ignore_user_config: bool,
strict_config: bool,
) -> io::Result<ConfigLayerEntry> {
let profile = profile.map(ToString::to_string);
if ignore_user_config {
return Ok(ConfigLayerEntry::new(
ConfigLayerSource::User {
file: user_file.clone(),
profile,
},
TomlValue::Table(toml::map::Map::new()),
));
}
load_config_toml_for_required_layer(fs, user_file, strict_config, |config_toml| {
ConfigLayerEntry::new(
ConfigLayerSource::User {
file: user_file.clone(),
profile: profile.clone(),
},
config_toml,
)
})
.await
}
fn insert_layer_by_precedence(layers: &mut Vec<ConfigLayerEntry>, layer: ConfigLayerEntry) {
match layers
.iter()
.position(|existing| existing.name.precedence() > layer.name.precedence())
{
Some(index) => layers.insert(index, layer),
None => layers.push(layer),
}
}
/// Attempts to load a config.toml file from `config_toml`.
/// - If the file exists and is valid TOML, passes the parsed `toml::Value` to
/// `create_entry` and returns the resulting layer entry.
/// - If the file does not exist, uses an empty `Table` with `create_entry` and
/// returns the resulting layer entry.
/// - If there is an error reading the file or parsing the TOML, returns an
/// error.
async fn load_config_toml_for_required_layer(
fs: &dyn ExecutorFileSystem,
toml_file: &AbsolutePathBuf,
strict_config: bool,
create_entry: impl FnOnce(TomlValue) -> ConfigLayerEntry,
) -> io::Result<ConfigLayerEntry> {
let loaded = load_config_toml_for_required_layer_raw(fs, toml_file, strict_config).await?;
let toml_value = resolve_relative_paths_in_config_toml(loaded.toml, loaded.base_dir.as_path())?;
Ok(create_entry(toml_value))
}
#[derive(Debug, Clone)]
struct LoadedTomlFile {
toml: TomlValue,
base_dir: AbsolutePathBuf,
}
async fn load_config_toml_for_required_layer_raw(
fs: &dyn ExecutorFileSystem,
toml_file: &AbsolutePathBuf,
strict_config: bool,
) -> io::Result<LoadedTomlFile> {
let config_parent = toml_file.as_path().parent().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData,
format!(
"Config file {} has no parent directory",
toml_file.as_path().display()
),
)
})?;
let base_dir = AbsolutePathBuf::from_absolute_path(config_parent)?;
let toml_file_uri = PathUri::from_abs_path(toml_file);
let toml_value = match fs
.read_file_text(&toml_file_uri, Default::default(), /*sandbox*/ None)
.await
{
Ok(contents) => {
let config: TomlValue = toml::from_str(&contents).map_err(|err| {
let config_error =
config_error_from_toml(toml_file.as_path(), &contents, err.clone());
io_error_from_config_error(io::ErrorKind::InvalidData, config_error, Some(err))
})?;
if strict_config {
validate_config_toml_strictly(
toml_file.as_path(),
&contents,
&config,
config_parent,
)?;
}
Ok(config)
}
Err(e) => {
if e.kind() == io::ErrorKind::NotFound {
Ok(TomlValue::Table(toml::map::Map::new()))
} else {
Err(io::Error::new(
e.kind(),
format!(
"Failed to read config file {}: {e}",
toml_file.as_path().display()
),
))
}
}
}?;
Ok(LoadedTomlFile {
toml: toml_value,
base_dir,
})
}
fn validate_config_toml_strictly(
toml_file: &Path,
contents: &str,
value: &TomlValue,
base_dir: &Path,
) -> io::Result<()> {
let _guard = AbsolutePathBufGuard::new(base_dir);
if let Some(config_error) = config_error_from_ignored_toml_value_fields::<ConfigToml>(
toml_file,
contents,
value.clone(),
) {
Err(io_error_from_config_error(
io::ErrorKind::InvalidData,
config_error,
/*source*/ None,
))
} else {
Ok(())
}
}
fn validate_cli_overrides_strictly(
cli_overrides_layer: &TomlValue,
base_dir: &Path,
) -> io::Result<()> {
let _guard = AbsolutePathBufGuard::new(base_dir);
if let Some(path) = ignored_toml_value_fields::<ConfigToml>(cli_overrides_layer.clone()).first()
{
let ignored_path = path.join(".");
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("unknown configuration field `{ignored_path}` in -c/--config override"),
));
}
if let Some(ignored_path) = unknown_feature_toml_value_field(cli_overrides_layer) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("unknown configuration field `{ignored_path}` in -c/--config override"),
));
}
Ok(())
}
/// If available, load requirements from the platform's system `requirements.toml`
/// location as a requirements layer.
pub async fn load_requirements_toml(
fs: &dyn ExecutorFileSystem,
requirements_toml_file: &AbsolutePathBuf,
) -> io::Result<Option<RequirementsLayerEntry>> {
let requirements_toml_file_uri = PathUri::from_abs_path(requirements_toml_file);
match fs
.read_file_text(
&requirements_toml_file_uri,
Default::default(),
/*sandbox*/ None,
)
.await
{
Ok(contents) => {
let requirements_parent = requirements_toml_file.parent().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData,
format!(
"Requirements file {} has no parent directory",
requirements_toml_file.as_ref().display()
),
)
})?;
let base_dir = AbsolutePathBuf::from_absolute_path(requirements_parent)?;
Ok(Some(
RequirementsLayerEntry::from_toml(
RequirementSource::SystemRequirementsToml {
file: requirements_toml_file.clone(),
},
contents,
)
.with_base_dir(base_dir),
))
}
Err(e) => {
if e.kind() != io::ErrorKind::NotFound {
Err(io::Error::new(
e.kind(),
format!(
"Failed to read requirements file {}: {e}",
requirements_toml_file.as_path().display(),
),
))
} else {
Ok(None)
}
}
}
}
#[cfg(unix)]
fn system_requirements_toml_file() -> io::Result<AbsolutePathBuf> {
AbsolutePathBuf::from_absolute_path(Path::new("/etc/codex/requirements.toml"))
}
#[cfg(windows)]
fn system_requirements_toml_file() -> io::Result<AbsolutePathBuf> {
windows_system_requirements_toml_file()
}
fn system_requirements_toml_file_with_overrides(
overrides: &LoaderOverrides,
) -> io::Result<AbsolutePathBuf> {
match &overrides.system_requirements_path {
Some(path) => AbsolutePathBuf::from_absolute_path(path),
None => system_requirements_toml_file(),
}
}
/// Check local managed configuration sources without loading or parsing configuration.
///
/// Filesystem or managed-preference errors are returned so callers can conservatively avoid
/// assuming that administrator-controlled configuration is absent.
pub fn has_local_managed_configuration(codex_home: &Path) -> io::Result<bool> {
let system_requirements_file = system_requirements_toml_file()?;
has_local_managed_configuration_with_system_requirements_path(
codex_home,
system_requirements_file.as_path(),
)
}
fn has_local_managed_configuration_with_system_requirements_path(
codex_home: &Path,
system_requirements_path: &Path,
) -> io::Result<bool> {
#[cfg(windows)]
let _ = codex_home;
#[cfg(not(windows))]
if layer_io::managed_config_default_path(codex_home).try_exists()? {
return Ok(true);
}
if system_requirements_path.try_exists()? {
return Ok(true);
}
#[cfg(target_os = "macos")]
if macos::has_managed_preferences()? {
return Ok(true);
}
Ok(false)
}
#[cfg(unix)]
pub fn system_config_toml_file() -> io::Result<AbsolutePathBuf> {
AbsolutePathBuf::from_absolute_path(Path::new(SYSTEM_CONFIG_TOML_FILE_UNIX))
}
#[cfg(windows)]
pub fn system_config_toml_file() -> io::Result<AbsolutePathBuf> {
windows_system_config_toml_file()
}
fn system_config_toml_file_with_overrides(
overrides: &LoaderOverrides,
) -> io::Result<AbsolutePathBuf> {
match &overrides.system_config_path {
Some(path) => AbsolutePathBuf::from_absolute_path(path),
None => system_config_toml_file(),
}
}
#[cfg(windows)]
fn windows_codex_system_dir() -> PathBuf {
let program_data = windows_program_data_dir_from_known_folder().unwrap_or_else(|err| {
tracing::warn!(
error = %err,
"Failed to resolve ProgramData known folder; using default path"
);
PathBuf::from(DEFAULT_PROGRAM_DATA_DIR_WINDOWS)
});
program_data.join("OpenAI").join("Codex")
}
#[cfg(windows)]
fn windows_system_requirements_toml_file() -> io::Result<AbsolutePathBuf> {
let requirements_toml_file = windows_codex_system_dir().join("requirements.toml");
AbsolutePathBuf::try_from(requirements_toml_file)
}
#[cfg(windows)]
fn windows_system_config_toml_file() -> io::Result<AbsolutePathBuf> {
let config_toml_file = windows_codex_system_dir().join("config.toml");
AbsolutePathBuf::try_from(config_toml_file)
}
#[cfg(windows)]
fn windows_program_data_dir_from_known_folder() -> io::Result<PathBuf> {
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use windows_sys::Win32::System::Com::CoTaskMemFree;
use windows_sys::Win32::UI::Shell::FOLDERID_ProgramData;
use windows_sys::Win32::UI::Shell::KF_FLAG_DEFAULT;
use windows_sys::Win32::UI::Shell::SHGetKnownFolderPath;
let mut path_ptr = std::ptr::null_mut::<u16>();
let known_folder_flags = u32::try_from(KF_FLAG_DEFAULT).map_err(|_| {
io::Error::other(format!(
"KF_FLAG_DEFAULT did not fit in u32: {KF_FLAG_DEFAULT}"
))
})?;
// Known folder IDs reference:
// https://learn.microsoft.com/en-us/windows/win32/shell/knownfolderid
// SAFETY: SHGetKnownFolderPath initializes path_ptr with a CoTaskMem-allocated,
// null-terminated UTF-16 string on success.
let hr = unsafe {
SHGetKnownFolderPath(&FOLDERID_ProgramData, known_folder_flags, 0, &mut path_ptr)
};
if hr != 0 {
return Err(io::Error::other(format!(
"SHGetKnownFolderPath(FOLDERID_ProgramData) failed with HRESULT {hr:#010x}"
)));
}
if path_ptr.is_null() {
return Err(io::Error::other(
"SHGetKnownFolderPath(FOLDERID_ProgramData) returned a null pointer",
));
}
// SAFETY: path_ptr is a valid null-terminated UTF-16 string allocated by
// SHGetKnownFolderPath and must be freed with CoTaskMemFree.
let path = unsafe {
let mut len = 0usize;
while *path_ptr.add(len) != 0 {
len += 1;
}
let wide = std::slice::from_raw_parts(path_ptr, len);
let path = PathBuf::from(OsString::from_wide(wide));
CoTaskMemFree(path_ptr.cast());
path
};
Ok(path)
}
fn requirements_layers_from_legacy_scheme(
loaded_config_layers: LoadedConfigLayers,
codex_home: &Path,
) -> io::Result<Vec<RequirementsLayerEntry>> {
// List the file-backed legacy layer first because requirements layers are
// composed lowest-precedence to highest-precedence, and MDM has higher
// precedence than the legacy managed_config.toml file.
let LoadedConfigLayers {
managed_config,
managed_config_from_mdm,
..
} = loaded_config_layers;
let layer_count =
usize::from(managed_config.is_some()) + usize::from(managed_config_from_mdm.is_some());
let mut layers = Vec::with_capacity(layer_count);
let codex_home = AbsolutePathBuf::from_absolute_path(codex_home)?;
for (source, config, base_dir) in managed_config
.map(|c| {
let base_dir = c.file.parent().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData,
format!(
"Managed config file {} has no parent directory",
c.file.as_path().display()
),
)
})?;
Ok::<_, io::Error>((
RequirementSource::LegacyManagedConfigTomlFromFile { file: c.file },
c.managed_config,
base_dir,
))
})
.transpose()?
.into_iter()
.chain(managed_config_from_mdm.map(|config| {
(
RequirementSource::LegacyManagedConfigTomlFromMdm,
config.managed_config,
codex_home.clone(),
)
}))
{
let legacy_config: LegacyManagedConfigToml =
config.try_into().map_err(|err: toml::de::Error| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("Failed to parse config requirements as TOML: {err}"),
)
})?;
layers.push(
RequirementsLayerEntry::from_toml_value(
source,
legacy_requirements_to_toml_value(legacy_config)?,
)
.with_base_dir(base_dir),
);
}
Ok(layers)
}
fn legacy_requirements_to_toml_value(legacy: LegacyManagedConfigToml) -> io::Result<TomlValue> {
let LegacyManagedConfigToml {
approval_policy,
approvals_reviewer,
sandbox_mode,
} = legacy;
let mut table = toml::map::Map::new();
if let Some(approval_policy) = approval_policy {
table.insert(
"allowed_approval_policies".to_string(),
toml_value_from_serializable(vec![approval_policy])?,
);
}
if let Some(approvals_reviewer) = approvals_reviewer {
let mut allowed_reviewers = vec![approvals_reviewer];
if approvals_reviewer == ApprovalsReviewer::AutoReview {
allowed_reviewers.push(ApprovalsReviewer::User);
}
table.insert(
"allowed_approvals_reviewers".to_string(),
toml_value_from_serializable(allowed_reviewers)?,
);
}
if let Some(sandbox_mode) = sandbox_mode {
let required_mode: SandboxModeRequirement = sandbox_mode.into();
// Allowing read-only is a requirement for Codex to function correctly.
// So in this backfill path, we append read-only if it's not already specified.
let mut allowed_modes = vec![SandboxModeRequirement::ReadOnly];
if required_mode != SandboxModeRequirement::ReadOnly {
allowed_modes.push(required_mode);
}
table.insert(
"allowed_sandbox_modes".to_string(),
toml_value_from_serializable(allowed_modes)?,
);
}
Ok(TomlValue::Table(table))
}
fn toml_value_from_serializable<T: serde::Serialize>(value: T) -> io::Result<TomlValue> {
TomlValue::try_from(value).map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum CredentialBrokerProjectState {
Unconfigured,
Disabled,
Enabled,
}
fn apply_credential_broker_requirements(
context: &mut ProjectTrustContext,
requirements: &crate::ConfigRequirementsWithSources,
) {
if context.credential_broker == CredentialBrokerProjectState::Unconfigured {
return;
}
let enabled = requirements
.feature_requirements
.as_ref()
.and_then(|requirements| requirements.entries.get("network_proxy"))
.copied()
.unwrap_or(context.credential_broker == CredentialBrokerProjectState::Enabled);
context.credential_broker = if enabled
&& requirements
.network
.as_ref()