harn-vm 0.10.165

Async bytecode virtual machine for the Harn programming language
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
//! The child-process environment allowlist and the single policy-aware env
//! resolver.
//!
//! # Why an allowlist, not a scrub
//!
//! `isolated` and `granted` start empty and admit only names from
//! [`ENV_ALLOWLIST`] plus explicit grant targets. This is safer and simpler
//! than inheriting everything and trying to maintain a secret denylist.
//!
//! # One resolver
//!
//! [`resolve_env`] materializes the environment snapshot for subprocesses.
//! [`lookup_env`] answers the same policy question for in-process consumers
//! such as `harness.env` and model providers:
//!
//! ```text
//! inherited = launcher_snapshot - provider_credentials
//! isolated  = allowlist(launcher_snapshot)
//! granted   = allowlist(launcher_snapshot) + grants
//! ```
//!
//! Under `inherited`, [`lookup_env`] still reads the provider credentials, so
//! Harn's own model calls authenticate; only children lose them. A spawn that
//! genuinely needs one names it in its own explicit `env`, which layers on top.
//!
//! Every spawn seam routes through [`crate::stdlib::process::session_env`].
//!
//! # Single owner
//!
//! [`ENV_ALLOWLIST`] is the one place the admitted names live. Nothing else in
//! the codebase should hand-maintain a parallel "safe env" list; the drift test
//! in this module pins the invariants (unique, no obviously-secret
//! names, base essentials present) so an accidental scatter or a secret-shaped
//! addition fails `cargo test`.

use std::collections::BTreeMap;
use std::ffi::{OsStr, OsString};

use super::session_environment::{
    EnvironmentPolicyError, EnvironmentPolicyKind, SessionEnvironment,
};

/// A payload may configure its loader after confinement. A trusted setup
/// executable must reach its confinement code before loader controls fire.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ProcessEnvironmentBoundary {
    Payload,
    TrustedSetup,
}

// The ELF loader namespace and GNU libc's tunable frontends. Glibc reads
// GLIBC_TUNABLES and the legacy MALLOC_* aliases in elf/dl-tunables.c during
// loader initialization, before a trusted executable reaches its entry point.
const TRUSTED_SETUP_CONTROL_PREFIXES: &[&[u8]] = &[b"LD_", b"MALLOC_"];
const TRUSTED_SETUP_CONTROL_NAMES: &[&[u8]] = &[b"GLIBC_TUNABLES"];

/// glibc allocator tuning that only sizes arenas, thresholds, and padding.
///
/// Like every `MALLOC_*` name these are read during loader initialization, so a
/// trusted setup executable still never sees them. Unlike the rest, they can't
/// change what is loaded or how it runs, and production environments commonly
/// set them (Heroku and many container images export `MALLOC_ARENA_MAX`). A
/// launcher that can configure its payload's environment after setup therefore
/// keeps them out of setup and re-applies them to the payload instead of
/// refusing the launch. `MALLOC_CHECK_` and `MALLOC_PERTURB_` stay refused: they
/// change allocator behavior, not just its sizing.
pub const REAPPLIED_ALLOCATOR_TUNING: &[&str] = &[
    "MALLOC_ARENA_MAX",
    "MALLOC_ARENA_TEST",
    "MALLOC_MMAP_MAX_",
    "MALLOC_MMAP_THRESHOLD_",
    "MALLOC_TOP_PAD_",
    "MALLOC_TRIM_THRESHOLD_",
];

/// Whether `name` is allocator tuning a launcher may re-apply after setup.
pub fn is_reapplied_allocator_tuning(name: &OsStr) -> bool {
    REAPPLIED_ALLOCATOR_TUNING
        .iter()
        .any(|tuning| tuning.as_bytes() == name.as_encoded_bytes())
}

/// Loader and runtime-library controls that precede trusted setup.
pub fn is_trusted_setup_control(name: &OsStr) -> bool {
    let name = name.as_encoded_bytes();
    TRUSTED_SETUP_CONTROL_PREFIXES
        .iter()
        .any(|prefix| name.starts_with(prefix))
        || TRUSTED_SETUP_CONTROL_NAMES.contains(&name)
}

/// Validate the effective launch environment without changing payload grants.
/// The caller supplies no inherited entries after `env_clear`; explicit
/// removals and replacements are composed last, exactly as at exec.
pub fn validate_process_environment(
    boundary: ProcessEnvironmentBoundary,
    inherited: impl IntoIterator<Item = (OsString, OsString)>,
    explicit: impl IntoIterator<Item = (OsString, Option<OsString>)>,
) -> Result<(), EnvironmentPolicyError> {
    if boundary == ProcessEnvironmentBoundary::Payload {
        return Ok(());
    }
    // Only loader controls need inspection; ordinary grant values are never
    // retained by this validator or included in a diagnostic.
    let mut controls: BTreeMap<_, _> = inherited
        .into_iter()
        .filter(|(name, _)| is_trusted_setup_control(name))
        .collect();
    for (name, value) in explicit {
        if !is_trusted_setup_control(&name) {
            continue;
        }
        if let Some(value) = value {
            controls.insert(name, value);
        } else {
            controls.remove(&name);
        }
    }
    for (name, value) in controls {
        if !value.is_empty() {
            return Err(EnvironmentPolicyError::UnsafeTrustedSetupVariable {
                variable: name.to_string_lossy().into_owned(),
            });
        }
    }
    Ok(())
}

/// POSIX/shell/locale essentials any build or test process needs to run at all.
/// These are workspace/user facts, never credentials.
const BASE_ENV_ALLOWLIST: &[&str] = &[
    "PATH",
    "HOME",
    "USER",
    "LOGNAME",
    "SHELL",
    "PWD",
    "TERM",
    "TZ",
    "HOSTNAME",
    "COLUMNS",
    "LINES",
    // Temp dirs — honored by compiler/linker toolchains for intermediates.
    "TMPDIR",
    "TMP",
    "TEMP",
    // Locale — pins message/encoding behavior; not secret-bearing.
    "LANG",
    "LANGUAGE",
    "LC_ALL",
    "LC_CTYPE",
    "LC_MESSAGES",
    // XDG base dirs — toolchain caches/config live under these.
    "XDG_CACHE_HOME",
    "XDG_CONFIG_HOME",
    "XDG_DATA_HOME",
    // TLS trust roots — needed for any HTTPS a build performs (crate/pkg
    // fetches). These name CA-bundle *paths*, not credentials.
    "SSL_CERT_FILE",
    "SSL_CERT_DIR",
    "CURL_CA_BUNDLE",
];

/// Toolchain variables, grouped by ecosystem. Each is a build/tooling fact
/// (install root, cache dir, module path) — never a credential. Add here, with
/// a receipt, when a toolchain fails an isolated run for want of one; never
/// regress to a denylist. Grouped by ecosystem (not globally sorted) so a
/// reviewer reads a toolchain's vars as a unit.
const TOOLCHAIN_ENV_ALLOWLIST: &[&str] = &[
    // Rust / Cargo: install roots + target/backtrace controls.
    "CARGO_HOME",
    "CARGO_TARGET_DIR",
    "RUSTUP_HOME",
    "RUST_BACKTRACE",
    "RUST_LOG",
    // SwiftPM manifest compiler modules are a relocatable build cache.
    "SWIFTPM_MODULECACHE_OVERRIDE",
    // clang and swift-frontend's module cache, relocated the same way.
    "CLANG_MODULE_CACHE_PATH",
    // Node / npm / pnpm: module path + cache/home roots.
    "NODE_PATH",
    "NPM_CONFIG_CACHE",
    "NPM_CONFIG_STORE_DIR",
    "NVM_DIR",
    "PNPM_HOME",
    "YARN_CACHE_FOLDER",
    // Python / uv / pyenv: path, install roots, active venv.
    "PIP_CACHE_DIR",
    "PYENV_ROOT",
    "PYTHONPATH",
    "PYTHONUSERBASE",
    "UV_CACHE_DIR",
    "VIRTUAL_ENV",
    // Go: workspace, install root, build/module caches.
    "GOCACHE",
    "GOMODCACHE",
    "GOPATH",
    "GOROOT",
    // JVM: install root.
    "JAVA_HOME",
    // C/C++ compiler selection (values are program names/paths, not secrets).
    "AR",
    "CC",
    "CXX",
    "LD",
    // ccache: the object cache and its scratch dir. CCACHE_TEMPDIR is the one
    // that breaks builds when unset, because it defaults to XDG_RUNTIME_DIR
    // (`/run/user/<uid>`), which no workspace write root covers.
    "CCACHE_DIR",
    "CCACHE_TEMPDIR",
];

/// Windows shell and system essentials.
///
/// A child on Windows needs these the way a POSIX child needs `PATH` and
/// `HOME`. `cmd.exe` resolves its own intrinsics through `SystemRoot` and
/// decides what counts as an executable from `PATHEXT`; without them it
/// starts and then cannot find any program, which reads as a missing tool
/// rather than a missing environment. They name install and profile
/// directories, never credentials.
const WINDOWS_ENV_ALLOWLIST: &[&str] = &[
    "SystemRoot",
    "SystemDrive",
    "windir",
    "COMSPEC",
    "PATHEXT",
    "USERPROFILE",
    "APPDATA",
    "LOCALAPPDATA",
    "ProgramData",
    "ProgramFiles",
    "ProgramW6432",
    "NUMBER_OF_PROCESSORS",
    "PROCESSOR_ARCHITECTURE",
    "OS",
];

/// The filesystem-path-valued subset of [`TOOLCHAIN_ENV_ALLOWLIST`]: toolchain
/// install roots, module paths, and cache dirs (never the flag/program-name
/// vars like `RUST_BACKTRACE`, `CC`, or `LD`). Consumers that need to reason
/// about *where a toolchain lives* — e.g. enriching a sandbox environment-denial
/// diagnostic with the roots a relocated toolchain points at — read this list so
/// there is no second per-language path table to drift from the allowlist.
pub const TOOLCHAIN_PATH_ENV_VARS: &[&str] = &[
    "SWIFTPM_MODULECACHE_OVERRIDE",
    "CLANG_MODULE_CACHE_PATH",
    // Rust / Cargo
    "CARGO_HOME",
    "CARGO_TARGET_DIR",
    "RUSTUP_HOME",
    // Node / npm / pnpm
    "NODE_PATH",
    "NPM_CONFIG_CACHE",
    "NPM_CONFIG_STORE_DIR",
    "NVM_DIR",
    "PNPM_HOME",
    "YARN_CACHE_FOLDER",
    // Python / uv / pyenv
    "PIP_CACHE_DIR",
    "PYENV_ROOT",
    "PYTHONPATH",
    "PYTHONUSERBASE",
    "UV_CACHE_DIR",
    "VIRTUAL_ENV",
    // Go
    "GOCACHE",
    "GOMODCACHE",
    "GOPATH",
    "GOROOT",
    // C/C++ compiler cache. ccache defaults its tempdir to XDG_RUNTIME_DIR
    // (`/run/user/<uid>`), which is outside every workspace write root, so a
    // cgo or C build fails "Permission denied" before it compiles anything.
    "CCACHE_DIR",
    "CCACHE_TEMPDIR",
    // JVM
    "JAVA_HOME",
];

/// The write-cache subset of [`TOOLCHAIN_PATH_ENV_VARS`]: dirs a toolchain
/// *writes* while building (build caches, module/download caches, install
/// homes that hold mutable registry caches). Deliberately excludes read-only
/// install/lib roots like `GOROOT`, `JAVA_HOME`, and `PYTHONPATH`, which usually
/// live under a system-preset prefix and so must not be flagged as an
/// out-of-jail gap. A denial while one of these points *outside* the sandbox
/// jail is a provable environment/config gap, not the workload's code defect.
pub const TOOLCHAIN_CACHE_ENV_VARS: &[&str] = &[
    "SWIFTPM_MODULECACHE_OVERRIDE",
    "CLANG_MODULE_CACHE_PATH",
    "CARGO_HOME",
    "CARGO_TARGET_DIR",
    "CCACHE_DIR",
    "CCACHE_TEMPDIR",
    "GOCACHE",
    "GOMODCACHE",
    "GOPATH",
    "NPM_CONFIG_CACHE",
    "NPM_CONFIG_STORE_DIR",
    "PIP_CACHE_DIR",
    "PNPM_HOME",
    "RUSTUP_HOME",
    "UV_CACHE_DIR",
    "YARN_CACHE_FOLDER",
];

/// The complete set of environment variable names admitted into a
/// policy-governed child process. The single owner; see the module docs.
pub const ENV_ALLOWLIST: &[&str] = &const_concat();

const ALLOWLIST_LEN: usize =
    BASE_ENV_ALLOWLIST.len() + TOOLCHAIN_ENV_ALLOWLIST.len() + WINDOWS_ENV_ALLOWLIST.len();

/// Whether `name` is admitted by [`ENV_ALLOWLIST`], matched the way the host
/// platform matches environment names.
///
/// Windows environment names are case-insensitive, and the case a parent
/// reports is not the case the allowlist is written in: the variable this
/// codebase calls `PATH` arrives from a Windows parent spelled `Path`. An
/// exact-match `contains` therefore misses it on Windows while every name in
/// the allowlist still looks admitted, so any admission check driven by a
/// launcher-reported name must go through this function rather than
/// `ENV_ALLOWLIST.contains` directly. POSIX names are case-sensitive, so the
/// exact match stays exact there. `SessionEnvironment::launch_from_snapshot`
/// uses this to decide whether a launcher-reported name survives into the
/// snapshot; `SessionEnvironment::launcher_value` folds case again on the
/// snapshot itself so a later exact-cased lookup (e.g. `"PATH"`) still finds
/// a value stored under the launcher's own casing (e.g. `"Path"`).
pub(crate) fn allowlist_admits(name: &str) -> bool {
    ENV_ALLOWLIST
        .iter()
        .any(|allowed| environment_names_equal(allowed, name))
}

/// Environment names follow the host platform's matching semantics.
pub(crate) fn environment_names_equal(left: &str, right: &str) -> bool {
    environment_names_equal_for_platform(left, right, cfg!(windows))
}

pub(crate) fn environment_names_equal_for_platform(left: &str, right: &str, windows: bool) -> bool {
    left == right || windows && left.eq_ignore_ascii_case(right)
}

/// Concatenate the base, toolchain, and Windows lists at compile time so
/// [`ENV_ALLOWLIST`] stays one flat, single-owned array without a runtime
/// allocation.
///
/// The Windows names are admitted on every platform rather than behind a
/// `cfg`. Admitting a name only says "pass this through if the parent has
/// it", and no POSIX parent has these, so a `cfg` would buy nothing and
/// would leave the list reading differently depending on who compiled it.
const fn const_concat() -> [&'static str; ALLOWLIST_LEN] {
    let mut out: [&'static str; ALLOWLIST_LEN] = [""; ALLOWLIST_LEN];
    let mut n = 0;
    let mut i = 0;
    while i < BASE_ENV_ALLOWLIST.len() {
        out[n] = BASE_ENV_ALLOWLIST[i];
        n += 1;
        i += 1;
    }
    let mut j = 0;
    while j < TOOLCHAIN_ENV_ALLOWLIST.len() {
        out[n] = TOOLCHAIN_ENV_ALLOWLIST[j];
        n += 1;
        j += 1;
    }
    let mut k = 0;
    while k < WINDOWS_ENV_ALLOWLIST.len() {
        out[n] = WINDOWS_ENV_ALLOWLIST[k];
        n += 1;
        k += 1;
    }
    out
}

/// Every variable name a catalogued provider declares as its credential.
///
/// The catalog, including user overlays, is the single owner of that mapping,
/// so a provider added with a novel key name is covered without a list here.
pub fn provider_credential_env_names() -> std::collections::BTreeSet<String> {
    let mut names = std::collections::BTreeSet::new();
    for provider in crate::llm_config::provider_names() {
        if let Some(definition) = crate::llm_config::provider_config(&provider) {
            names.extend(crate::llm_config::auth_env_names(&definition.auth_env));
            names.extend(definition.credential_env.iter().cloned());
        }
    }
    names
}

/// What an inherited policy hands a child: the launcher snapshot without any
/// provider credential. The key exists for Harn's own provider calls, which
/// read it in-process through [`lookup_env`]; a command the agent runs, an MCP
/// server, or an ACP child has no claim on it merely by being spawned.
fn inherited_child_env(environment: &SessionEnvironment) -> BTreeMap<String, String> {
    let withheld = provider_credential_env_names();
    environment
        .launcher_snapshot()
        .iter()
        .filter(|(name, _)| {
            !withheld
                .iter()
                .any(|credential| environment_names_equal(credential, name))
        })
        .map(|(name, value)| (name.clone(), value.clone()))
        .collect()
}

/// Build the environment for a policy-governed child process, closed by
/// construction: the allowlisted subset of the parent environment plus the
/// environment's granted exposure. The one resolver both policies flow through —
/// an isolated policy contributes an empty exposure and so yields the allowlist
/// alone.
///
/// `env_lookup` reads the launcher/parent environment (production passes
/// `|name| std::env::var(name).ok()`); `resolve_secret` materializes a
/// `secret_store` grant on exposure (production passes the crate's secret chain).
pub fn resolve_env(
    environment: &SessionEnvironment,
    _env_lookup: &dyn Fn(&str) -> Option<String>,
    resolve_secret: &dyn Fn(&str, &str) -> Option<String>,
) -> Result<BTreeMap<String, String>, EnvironmentPolicyError> {
    if matches!(environment.kind(), EnvironmentPolicyKind::Inherited) {
        return Ok(inherited_child_env(environment));
    }
    let mut env = BTreeMap::new();
    for name in ENV_ALLOWLIST {
        if let Some(value) = environment.launcher_value(name) {
            env.insert((*name).to_string(), value.to_string());
        }
    }
    // Session-scoped grants overlay the allowlist. An isolated policy has
    // none, so this is a no-op there; the empty-grants case IS the isolated
    // environment. Command-bound grants are added only by
    // [`resolve_env_for_command`].
    for (var, value) in environment.env_exposure(resolve_secret)? {
        env.insert(var, value);
    }
    Ok(env)
}

/// Build the environment for one spawn of `program` under a policy-governed
/// session: the allowlisted subset plus session-scoped grants and any
/// command-bound grants whose `for_command` matches the executable basename.
pub fn resolve_env_for_command(
    environment: &SessionEnvironment,
    program: &str,
    _env_lookup: &dyn Fn(&str) -> Option<String>,
    resolve_secret: &dyn Fn(&str, &str) -> Option<String>,
) -> Result<BTreeMap<String, String>, EnvironmentPolicyError> {
    if matches!(environment.kind(), EnvironmentPolicyKind::Inherited) {
        return Ok(inherited_child_env(environment));
    }
    let mut env = BTreeMap::new();
    for name in ENV_ALLOWLIST {
        if let Some(value) = environment.launcher_value(name) {
            env.insert((*name).to_string(), value.to_string());
        }
    }
    for (var, value) in environment.env_exposure_for_command(program, resolve_secret)? {
        env.insert(var, value);
    }
    Ok(env)
}

/// The policy-governed value of a single environment variable as Harn's own
/// process reads it — the same answer [`resolve_env`] would put in the map
/// under `name`, without building the map, except for an `in_process` grant,
/// which this reader sees and no child environment ever contains.
///
/// Grants win over the allowlist (matching `resolve_env`'s overlay order), so a
/// granted policy that grants `FIREWORKS_API_KEY` sees the granted value here even though
/// the allowlist would never admit a credential. A name that is neither granted
/// nor allowlisted resolves to `None` — which is exactly what makes an isolated
/// session credential-free *in-process*, not merely for its children.
///
/// This exists so the in-process credential path (`llm_call`'s provider key
/// resolution) reads the session's environment rather than the launcher's raw
/// `std::env`. The equivalence with `resolve_env` is pinned by a test in this
/// module rather than left to the reader.
pub fn lookup_env(
    environment: &SessionEnvironment,
    name: &str,
    _env_lookup: &dyn Fn(&str) -> Option<String>,
    resolve_secret: &dyn Fn(&str, &str) -> Option<String>,
) -> Result<Option<String>, EnvironmentPolicyError> {
    // Only the grant targeting `name` is resolved: probing an unrelated
    // variable must not reach the secret store, and one unresolvable grant must
    // not mask an unrelated credential.
    if let Some(value) = environment.env_exposure_for(name, resolve_secret)? {
        return Ok(Some(value));
    }
    if matches!(environment.kind(), EnvironmentPolicyKind::Inherited)
        || ENV_ALLOWLIST.contains(&name)
    {
        return Ok(environment.launcher_value(name).map(str::to_string));
    }
    Ok(None)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn trusted_setup_validates_inherited_and_explicit_loader_controls() {
        for name in [
            "LD_BIND_NOW",
            "LD_TRACE_LOADED_OBJECTS",
            "GLIBC_TUNABLES",
            "MALLOC_CHECK_",
            "MALLOC_TOP_PAD_",
            "MALLOC_PERTURB_",
            "MALLOC_MMAP_THRESHOLD_",
            "MALLOC_TRIM_THRESHOLD_",
            "MALLOC_MMAP_MAX_",
            "MALLOC_ARENA_MAX",
            "MALLOC_ARENA_TEST",
        ] {
            let inherited = vec![(OsString::from(name), OsString::from("1"))];
            let explicit = vec![(OsString::from(name), Some(OsString::from("1")))];
            for (parent, overlay) in [(inherited.clone(), vec![]), (vec![], explicit.clone())] {
                assert_eq!(
                    validate_process_environment(
                        ProcessEnvironmentBoundary::TrustedSetup,
                        parent,
                        overlay
                    ),
                    Err(EnvironmentPolicyError::UnsafeTrustedSetupVariable {
                        variable: name.into()
                    })
                );
            }
            // Payload grants retain their meaning when confinement precedes exec.
            assert_eq!(
                validate_process_environment(
                    ProcessEnvironmentBoundary::Payload,
                    inherited,
                    explicit
                ),
                Ok(())
            );
        }
    }

    #[test]
    fn trusted_setup_honors_clear_removal_and_empty_override() {
        for name in ["LD_BIND_NOW", "GLIBC_TUNABLES", "MALLOC_TRIM_THRESHOLD_"] {
            let inherited = vec![(OsString::from(name), OsString::from("1"))];
            for replacement in [None, Some(OsString::new())] {
                assert_eq!(
                    validate_process_environment(
                        ProcessEnvironmentBoundary::TrustedSetup,
                        inherited.clone(),
                        [(OsString::from(name), replacement)]
                    ),
                    Ok(())
                );
            }
        }
        // env_clear supplies no inherited entries. Ordinary grants survive.
        assert_eq!(
            validate_process_environment(
                ProcessEnvironmentBoundary::TrustedSetup,
                [],
                [
                    (
                        OsString::from("ORDINARY_PROBE"),
                        Some(OsString::from("admitted"))
                    ),
                    (OsString::from("LD"), Some(OsString::from("ld"))),
                    (
                        OsString::from("GLIBC_TUNABLES_ORDINARY"),
                        Some(OsString::from("admitted"))
                    )
                ]
            ),
            Ok(())
        );
    }

    #[test]
    fn allowlist_admits_the_windows_names_a_child_cannot_start_a_program_without() {
        // A Windows child with no `Path` finds no program at all, and one with
        // no `SystemRoot` or `PATHEXT` cannot resolve even the shell's own
        // notion of an executable. The allowlist was POSIX-only, so every
        // policy-governed Windows child ran with none of them.
        for required in [
            "SystemRoot",
            "SystemDrive",
            "COMSPEC",
            "PATHEXT",
            "USERPROFILE",
            "LOCALAPPDATA",
        ] {
            assert!(
                ENV_ALLOWLIST.contains(&required),
                "{required} is a Windows start-up essential and must be admitted",
            );
        }
    }

    #[test]
    fn allowlist_admits_no_windows_name_that_carries_a_credential() {
        // The control on the test above: growing the list must not become a
        // way to widen what a child can read. These are the names a Windows
        // parent commonly holds secrets under, and none may be admitted.
        for forbidden in [
            "GITHUB_TOKEN",
            "AZURE_CLIENT_SECRET",
            "USERDOMAIN_ROAMINGPROFILE",
        ] {
            assert!(
                !ENV_ALLOWLIST.contains(&forbidden),
                "{forbidden} must never be admitted by the allowlist",
            );
        }
    }

    #[test]
    fn windows_launcher_value_folds_case_so_the_parents_path_is_found() {
        // Windows reports the search path as `Path`. Matched exactly against
        // the allowlist's `PATH`, it missed, and the child inherited no search
        // path while the allowlist still read as though it admitted one. This
        // lookup uses the same platform matcher on every test host.
        let parent = env_from(&[]);
        let environment = SessionEnvironment::launch_from_snapshot(
            EnvironmentPolicyKind::Inherited,
            Vec::new(),
            BTreeMap::from([("Path".to_string(), "C:\\Windows\\System32".to_string())]),
            &parent,
        )
        .unwrap();
        assert_eq!(
            environment.launcher_value_for_platform("PATH", true),
            Some("C:\\Windows\\System32")
        );
        assert_eq!(environment.launcher_value_for_platform("PATH", false), None);
        // The control: folding case must not invent a value for a name the
        // parent never set.
        assert_eq!(
            environment.launcher_value_for_platform("ABSENT_NAME", true),
            None
        );
        #[cfg(windows)]
        {
            let isolated = SessionEnvironment::launch_from_snapshot(
                EnvironmentPolicyKind::Isolated,
                Vec::new(),
                BTreeMap::from([("Path".to_string(), "C:\\Windows\\System32".to_string())]),
                &parent,
            )
            .unwrap();
            let never_secret = |_: &str, _: &str| None;
            let env = resolve_env(&isolated, &parent, &never_secret).unwrap();
            assert_eq!(
                env.get("PATH").map(String::as_str),
                Some("C:\\Windows\\System32")
            );
        }
    }

    use crate::security::session_environment::{EnvironmentPolicyKind, GrantSourceSpec, GrantSpec};

    #[test]
    fn toolchain_path_env_vars_are_a_subset_of_the_allowlist() {
        // The path-valued view must never name a var the child env would not
        // even carry; keep it a strict subset of the single-owner toolchain
        // allowlist so a diagnostic never references an inaccessible var.
        for name in TOOLCHAIN_PATH_ENV_VARS {
            assert!(
                TOOLCHAIN_ENV_ALLOWLIST.contains(name),
                "{name} is in TOOLCHAIN_PATH_ENV_VARS but not TOOLCHAIN_ENV_ALLOWLIST"
            );
        }
        // The cache subset must in turn be path-valued (and so allowlisted).
        for name in TOOLCHAIN_CACHE_ENV_VARS {
            assert!(
                TOOLCHAIN_PATH_ENV_VARS.contains(name),
                "{name} is in TOOLCHAIN_CACHE_ENV_VARS but not TOOLCHAIN_PATH_ENV_VARS"
            );
        }
    }

    /// A local re-derivation of the "looks like a secret" shape. It cannot call
    /// `harn-hostlib::is_sensitive_env_name` (that crate depends on this one), so
    /// the drift test carries its own copy of the suffix/prefix rules; if those
    /// rules ever diverge the allowlist is still independently pinned here.
    ///
    /// This is a heuristic backstop for names no catalog declares (a vendor
    /// token a toolchain wants, say). The catalog-derived check in
    /// `allowlist_is_single_owned_and_secret_free` is the authoritative half.
    fn looks_like_secret(name: &str) -> bool {
        let upper = name.to_ascii_uppercase();
        const SECRET_PREFIXES: &[&str] = &[
            "ANTHROPIC_",
            "OPENAI_",
            "OPENROUTER_",
            "FIREWORKS_",
            "TOGETHER_",
            "XAI_",
            "GROQ_",
            "AWS_",
        ];
        const SECRET_SUFFIXES: &[&str] = &[
            "_API_KEY",
            "_TOKEN",
            "_SECRET",
            "_KEY",
            "_PASSWORD",
            "_PASSWD",
            "_CREDENTIALS",
        ];
        SECRET_PREFIXES.iter().any(|p| upper.starts_with(p))
            || SECRET_SUFFIXES.iter().any(|s| upper.ends_with(s))
    }

    /// The allowlist is the single owned artifact — unique, free of any
    /// secret-shaped name, and carrying the base essentials a build cannot run
    /// without. A scattered or secret-shaped addition fails here.
    #[test]
    fn allowlist_is_single_owned_and_secret_free() {
        // Unique.
        let mut seen = std::collections::BTreeSet::new();
        for name in ENV_ALLOWLIST {
            assert!(seen.insert(*name), "duplicate allowlist entry: {name}");
        }
        // No secret-shaped name may ever be admitted — that would defeat the
        // closed-by-construction property. This is the load-bearing guard.
        for name in ENV_ALLOWLIST {
            assert!(
                !looks_like_secret(name),
                "allowlist admits a secret-shaped variable '{name}' — a credential must \
                 cross via a grant, never the allowlist"
            );
        }
        // Stronger than the shape heuristic, and self-maintaining: no variable
        // any catalogued provider declares as its credential may be admitted.
        // The catalog is the single owner of that mapping, so adding a provider
        // with a novel key name — one the prefix list above would not
        // recognize — cannot silently open the door.
        for credential in provider_credential_env_names() {
            assert!(
                !ENV_ALLOWLIST.contains(&credential.as_str()),
                "allowlist admits '{credential}', a credential variable the provider \
                 catalog declares — a credential must cross via a grant"
            );
        }
        // Base essentials present: without these a child cannot resolve tools or
        // its home/temp, so an isolated build would fail for a trivial reason.
        for required in ["PATH", "HOME", "TMPDIR", "LANG"] {
            assert!(
                ENV_ALLOWLIST.contains(&required),
                "base allowlist missing essential '{required}'"
            );
        }
        // No global-sort assertion: the arrays are deliberately grouped by
        // ecosystem (with a receipt comment per group) rather than alphabetized,
        // because a reviewer reasons about "the Rust toolchain vars" as a unit.
        // The load-bearing guards above (uniqueness, no secret-shaped name, base
        // essentials present) are what actually protect the closed-by-construction
        // property; ordering within the source is cosmetic.
    }

    fn env_from(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<String> {
        move |var: &str| {
            pairs
                .iter()
                .find(|(name, _)| *name == var)
                .map(|(_, value)| value.to_string())
        }
    }

    #[test]
    fn isolated_environment_is_the_allowlist_alone() {
        // A parent env carrying both allowlisted vars and a secret. The isolated
        // child sees the allowlisted vars and NOT the secret — and no grant path
        // exists to add one (isolated forbids grants at launch).
        let parent = env_from(&[
            ("PATH", "/usr/bin"),
            ("HOME", "/home/agent"),
            ("ANTHROPIC_API_KEY", "sk-secret"),
            ("SOME_UNLISTED_VAR", "whatever"),
        ]);
        let never_secret = |_: &str, _: &str| None;
        let environment = SessionEnvironment::launch_from_snapshot(
            EnvironmentPolicyKind::Isolated,
            Vec::new(),
            BTreeMap::from([
                ("PATH".to_string(), "/usr/bin".to_string()),
                ("HOME".to_string(), "/home/agent".to_string()),
                ("ANTHROPIC_API_KEY".to_string(), "sk-secret".to_string()),
                ("SOME_UNLISTED_VAR".to_string(), "whatever".to_string()),
            ]),
            &parent,
        )
        .unwrap();
        let env = resolve_env(&environment, &parent, &never_secret).unwrap();

        assert_eq!(env.get("PATH").map(String::as_str), Some("/usr/bin"));
        assert_eq!(env.get("HOME").map(String::as_str), Some("/home/agent"));
        assert!(
            !env.contains_key("ANTHROPIC_API_KEY"),
            "isolated env must not inherit a secret from the parent"
        );
        assert!(
            !env.contains_key("SOME_UNLISTED_VAR"),
            "isolated env must not inherit an unlisted var"
        );
    }

    #[test]
    fn granted_env_is_allowlist_plus_grants_via_the_same_resolver() {
        // The granted env is the isolated env (allowlist) plus exactly the granted
        // pairs. Same resolver, non-empty grant set.
        let parent = env_from(&[("PATH", "/usr/bin"), ("FIREWORKS_API_KEY", "fw-secret")]);
        let specs = vec![
            GrantSpec {
                name: "fireworks".to_string(),
                source: GrantSourceSpec::Env {
                    var: "FIREWORKS_API_KEY".to_string(),
                },
                expose_as_env: Some("FIREWORKS_API_KEY".to_string()),
                for_command: None,
                expose_to: Default::default(),
            },
            GrantSpec {
                name: "gh".to_string(),
                source: GrantSourceSpec::SecretStore {
                    account: "gh".to_string(),
                    key: "token".to_string(),
                },
                expose_as_env: Some("GH_TOKEN".to_string()),
                for_command: None,
                expose_to: Default::default(),
            },
        ];
        let environment =
            SessionEnvironment::launch(EnvironmentPolicyKind::Granted, specs, &parent).unwrap();
        let resolve_secret = |account: &str, key: &str| {
            (account == "gh" && key == "token").then(|| "ghp".to_string())
        };
        let env = resolve_env(&environment, &parent, &resolve_secret).unwrap();

        // Allowlist base still present.
        assert_eq!(env.get("PATH").map(String::as_str), Some("/usr/bin"));
        // The env-snapshot grant is exposed under its target var...
        assert_eq!(
            env.get("FIREWORKS_API_KEY").map(String::as_str),
            Some("fw-secret")
        );
        // ...and the secret_store grant resolved through the closure.
        assert_eq!(env.get("GH_TOKEN").map(String::as_str), Some("ghp"));
    }

    #[test]
    fn single_name_lookup_agrees_with_the_full_resolver() {
        // `lookup_env` is the in-process credential path and `resolve_env` is
        // the subprocess path; if they ever disagree, an isolated session leaks
        // in-process or a granted policy's own llm_call cannot see its granted key. Pin
        // the equivalence over every interesting class of name at once: an
        // allowlisted var, a granted var, a granted var that shadows an
        // allowlisted one, and an unlisted/ungranted var.
        let parent = env_from(&[
            ("PATH", "/usr/bin"),
            ("RUST_LOG", "from_parent"),
            ("FIREWORKS_API_KEY", "fw-secret"),
            ("ANTHROPIC_API_KEY", "sk-launcher"),
            ("SOME_UNLISTED_VAR", "whatever"),
        ]);
        let specs = vec![
            GrantSpec {
                name: "fireworks".to_string(),
                source: GrantSourceSpec::Env {
                    var: "FIREWORKS_API_KEY".to_string(),
                },
                expose_as_env: Some("FIREWORKS_API_KEY".to_string()),
                for_command: None,
                expose_to: Default::default(),
            },
            GrantSpec {
                name: "log".to_string(),
                source: GrantSourceSpec::Env {
                    var: "RUST_LOG".to_string(),
                },
                expose_as_env: Some("RUST_LOG".to_string()),
                for_command: None,
                expose_to: Default::default(),
            },
            GrantSpec {
                name: "gh".to_string(),
                source: GrantSourceSpec::SecretStore {
                    account: "gh".to_string(),
                    key: "token".to_string(),
                },
                expose_as_env: Some("GH_TOKEN".to_string()),
                for_command: None,
                expose_to: Default::default(),
            },
        ];
        let resolve_secret = |account: &str, key: &str| {
            (account == "gh" && key == "token").then(|| "ghp".to_string())
        };
        let probes = [
            "PATH",
            "RUST_LOG",
            "FIREWORKS_API_KEY",
            "ANTHROPIC_API_KEY",
            "GH_TOKEN",
            "SOME_UNLISTED_VAR",
            "HOME",
        ];

        for environment in [
            SessionEnvironment::isolated(),
            SessionEnvironment::launch(EnvironmentPolicyKind::Granted, specs, &parent).unwrap(),
        ] {
            let map = resolve_env(&environment, &parent, &resolve_secret).unwrap();
            for name in probes {
                assert_eq!(
                    lookup_env(&environment, name, &parent, &resolve_secret).unwrap(),
                    map.get(name).cloned(),
                    "lookup_env disagreed with resolve_env for {name} under {:?}",
                    environment.kind()
                );
            }
        }
    }

    #[test]
    fn an_in_process_grant_is_the_one_name_the_two_readers_disagree_on() {
        // The equivalence above holds for every grant a child may see. An
        // in-process grant is the deliberate exception: Harn's own reader
        // resolves it and the child resolvers leave it out, both the one that
        // knows the program and the one that does not.
        let parent = env_from(&[("PATH", "/usr/bin"), ("LAUNCHER_KEY", "provider-value")]);
        let environment = SessionEnvironment::launch(
            EnvironmentPolicyKind::Granted,
            vec![GrantSpec {
                name: "provider".to_string(),
                source: GrantSourceSpec::Env {
                    var: "LAUNCHER_KEY".to_string(),
                },
                expose_as_env: Some("PROVIDER_API_KEY".to_string()),
                for_command: None,
                expose_to: crate::security::GrantAudience::InProcess,
            }],
            &parent,
        )
        .unwrap();
        let never_secret = |_: &str, _: &str| None;
        assert_eq!(
            lookup_env(&environment, "PROVIDER_API_KEY", &parent, &never_secret).unwrap(),
            Some("provider-value".to_string())
        );
        let spawn = resolve_env(&environment, &parent, &never_secret).unwrap();
        let for_program =
            resolve_env_for_command(&environment, "/usr/bin/env", &parent, &never_secret).unwrap();
        for child in [&spawn, &for_program] {
            assert!(!child.contains_key("PROVIDER_API_KEY"));
            // Direction control: the child environment is not simply empty.
            assert_eq!(child.get("PATH").map(String::as_str), Some("/usr/bin"));
        }
    }

    #[test]
    fn a_single_name_lookup_touches_only_its_own_grant() {
        // Resolving one variable must not drag every other secret_store grant
        // through the secret store: probing an unrelated name would otherwise
        // cost N store round-trips, and a single unresolvable grant would mask
        // an unrelated credential that resolves perfectly well.
        let parent = env_from(&[("FIREWORKS_API_KEY", "fw-secret")]);
        let specs = vec![
            GrantSpec {
                name: "fireworks".to_string(),
                source: GrantSourceSpec::Env {
                    var: "FIREWORKS_API_KEY".to_string(),
                },
                expose_as_env: Some("FIREWORKS_API_KEY".to_string()),
                for_command: None,
                expose_to: Default::default(),
            },
            GrantSpec {
                name: "broken".to_string(),
                source: GrantSourceSpec::SecretStore {
                    account: "vault".to_string(),
                    key: "absent".to_string(),
                },
                expose_as_env: Some("OTHER_TOKEN".to_string()),
                for_command: None,
                expose_to: Default::default(),
            },
        ];
        let environment =
            SessionEnvironment::launch(EnvironmentPolicyKind::Granted, specs, &parent).unwrap();
        let explode = |_: &str, _: &str| -> Option<String> {
            panic!("an unrelated grant's secret must not be resolved")
        };

        // The env-snapshot grant resolves without consulting the store at all.
        assert_eq!(
            lookup_env(&environment, "FIREWORKS_API_KEY", &parent, &explode).unwrap(),
            Some("fw-secret".to_string())
        );
        // ...as does an ungranted, unlisted name.
        assert_eq!(
            lookup_env(&environment, "UNRELATED_VAR", &parent, &explode).unwrap(),
            None
        );

        // The broken grant still fails loudly when it is the one being asked
        // for — the failure is scoped to it, not spread across the environment.
        let missing = |_: &str, _: &str| -> Option<String> { None };
        assert_eq!(
            lookup_env(&environment, "OTHER_TOKEN", &parent, &missing),
            Err(EnvironmentPolicyError::MissingSecret {
                name: "broken".to_string()
            })
        );
        assert_eq!(
            lookup_env(&environment, "FIREWORKS_API_KEY", &parent, &missing).unwrap(),
            Some("fw-secret".to_string()),
            "one unresolvable grant must not mask a healthy one"
        );
    }

    #[test]
    fn isolated_hides_a_launcher_credential_from_the_in_process_reader() {
        // The load-bearing property for evals: under an isolated policy, harn's
        // OWN credential read sees nothing, even though the launcher env has a
        // key sitting right there.
        let parent = env_from(&[("PATH", "/usr/bin"), ("ANTHROPIC_API_KEY", "sk-launcher")]);
        let never_secret = |_: &str, _: &str| None;
        let isolated = SessionEnvironment::launch_from_snapshot(
            EnvironmentPolicyKind::Isolated,
            Vec::new(),
            BTreeMap::from([
                ("PATH".to_string(), "/usr/bin".to_string()),
                ("ANTHROPIC_API_KEY".to_string(), "sk-launcher".to_string()),
            ]),
            &parent,
        )
        .unwrap();
        assert_eq!(
            lookup_env(&isolated, "ANTHROPIC_API_KEY", &parent, &never_secret).unwrap(),
            None
        );
        // ...while an ordinary allowlisted var still resolves, so an isolated run
        // is credential-free rather than environment-free.
        assert_eq!(
            lookup_env(&isolated, "PATH", &parent, &never_secret).unwrap(),
            Some("/usr/bin".to_string())
        );
    }

    #[test]
    fn a_grant_may_re_expose_an_allowlisted_name_and_wins() {
        // If a grant targets a name that is also on the allowlist, the grant
        // value wins (the resolver overlays grants last). This lets a granted policy
        // deliberately override an inherited toolchain var.
        let parent = env_from(&[("RUST_LOG", "from_parent")]);
        let specs = vec![GrantSpec {
            name: "log".to_string(),
            source: GrantSourceSpec::Env {
                var: "RUST_LOG".to_string(),
            },
            expose_as_env: Some("RUST_LOG".to_string()),
            for_command: None,
            expose_to: Default::default(),
        }];
        let environment =
            SessionEnvironment::launch(EnvironmentPolicyKind::Granted, specs, &parent).unwrap();
        let never_secret = |_: &str, _: &str| None;
        let env = resolve_env(&environment, &parent, &never_secret).unwrap();
        // Same value here, but it flows through the grant, not the allowlist
        // pull — proving the overlay order without a second source of truth.
        assert_eq!(env.get("RUST_LOG").map(String::as_str), Some("from_parent"));
    }

    /// An inherited child keeps the launcher's environment except a catalogued
    /// provider credential, which Harn's own process still reads.
    #[test]
    fn inherited_children_never_receive_a_provider_credential() {
        let withheld = provider_credential_env_names();
        for name in [
            "OPENAI_API_KEY",
            "ANTHROPIC_API_KEY",
            "GOOGLE_APPLICATION_CREDENTIALS",
        ] {
            assert!(withheld.contains(name), "catalog no longer declares {name}");
        }
        let snapshot = BTreeMap::from([
            ("OPENAI_API_KEY".to_string(), "sk-dummy-canary".to_string()),
            (
                "ANTHROPIC_API_KEY".to_string(),
                "harn-secret://probe/anthropic".to_string(),
            ),
            ("UNRELATED_VAR".to_string(), "kept".to_string()),
        ]);
        let lookup = |name: &str| snapshot.get(name).cloned();
        let environment = SessionEnvironment::launch_from_snapshot(
            EnvironmentPolicyKind::Inherited,
            Vec::new(),
            snapshot.clone(),
            &lookup,
        )
        .unwrap();
        let never_secret = |_: &str, _: &str| None;
        for child in [
            resolve_env(&environment, &lookup, &never_secret).unwrap(),
            resolve_env_for_command(&environment, "sh", &lookup, &never_secret).unwrap(),
        ] {
            assert_eq!(child.get("UNRELATED_VAR").map(String::as_str), Some("kept"));
            assert!(!child.contains_key("OPENAI_API_KEY"), "{child:?}");
            assert!(!child.contains_key("ANTHROPIC_API_KEY"), "{child:?}");
        }
        assert_eq!(
            lookup_env(&environment, "OPENAI_API_KEY", &lookup, &never_secret).unwrap(),
            Some("sk-dummy-canary".to_string())
        );
    }
}