greentic-setup-dev 1.2.31297906750

End-to-end bundle setup engine for the Greentic platform — pack discovery, QA-driven configuration, secrets persistence, and bundle lifecycle management
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
//! Dev secrets store management for bundle setup.
//!
//! Provides helpers for locating the dev secrets file and
//! [`SecretsSetup`] for ensuring pack secrets are seeded.

use std::collections::BTreeMap;
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use anyhow::{Result, anyhow};
use greentic_secrets_lib::core::Error as SecretError;
use greentic_secrets_lib::{
    ApplyOptions, DevStore, SecretFormat, SecretsStore, SeedDoc, SeedEntry, SeedValue, apply_seed,
};
use serde_cbor::Value as CborValue;
use tracing::{debug, info};

use crate::canonical_secret_uri;

// ── Dev store path helpers ──────────────────────────────────────────────────

const STORE_RELATIVE: &str = ".greentic/dev/.dev.secrets.env";
const STORE_STATE_RELATIVE: &str = ".greentic/state/dev/.dev.secrets.env";
const OVERRIDE_ENV: &str = "GREENTIC_DEV_SECRETS_PATH";

/// Returns a path explicitly configured via `$GREENTIC_DEV_SECRETS_PATH`.
pub fn override_path() -> Option<PathBuf> {
    assert_store_access_is_guarded();
    std::env::var(OVERRIDE_ENV).ok().map(PathBuf::from)
}

/// In test builds, refuse to resolve the dev-store path outside a
/// `secrets::test_support` guard.
///
/// The override is process-global, so an unguarded test reads whatever a
/// concurrent guarded test installed and can write into — or through — a temp
/// dir that is about to be deleted. That surfaced as `failed to persist N
/// secret(s): … No such file or directory` in tests that never touched the
/// store deliberately. Asserting here converts that flake into a deterministic
/// failure that names the offending test.
#[cfg(test)]
fn assert_store_access_is_guarded() {
    assert!(
        test_support::store_access_is_guarded(),
        "dev secrets store resolved without a `secrets::test_support` guard — \
         start this test with `let _store = crate::secrets::test_support::isolated_store();` \
         (or `lock_env()` when it only reads path resolution)"
    );
}

#[cfg(not(test))]
#[inline]
fn assert_store_access_is_guarded() {}

/// Dev-store path inside the shared environment store:
///   `~/.greentic/environments/<env>/.greentic/dev/.dev.secrets.env`
///
/// This is the *same* file that `gtc op secrets` / `provider add` and the
/// running env use, so bundle-path `setup`/`start` rendezvous with the env-path
/// secrets across invocations regardless of any ephemeral extraction dir (it
/// closes the bundle-vs-env split documented in `env-runtime-bundle-ops.md` §6).
/// Returns `None` when the environment-store root can't be resolved (no
/// `HOME`/`USERPROFILE`), letting callers fall back to a bundle-local path.
pub fn env_store_dev_secrets_path(env: &str) -> Option<PathBuf> {
    greentic_deployer::environment::LocalFsStore::default_root()
        .map(|root| root.join(env).join(STORE_RELATIVE))
}

/// The explicitly-selected environment, or `None` when `$GREENTIC_ENV` is unset.
///
/// Bare callers (`ensure_path`/`find_existing`/`default_path`) only route to the
/// shared env store when an env is *explicitly selected* via `$GREENTIC_ENV`.
/// `gtc setup` and `gtc start` always set it before resolving secrets, so
/// production lands on `~/.greentic/environments/<env>/…`; when it is unset
/// (unit tests, ad-hoc library use) resolution stays on the legacy bundle-local
/// store, which keeps those paths hermetic and non-polluting.
fn selected_env() -> Option<String> {
    std::env::var("GREENTIC_ENV")
        .ok()
        .filter(|value| !value.trim().is_empty())
        .map(|raw| crate::resolve_env(Some(&raw)))
}

/// The path a *write* should target for an explicit env: the shared env store
/// when resolvable, otherwise the legacy bundle-local path.
fn write_path_for_env(bundle_root: &Path, env: &str) -> PathBuf {
    env_store_dev_secrets_path(env).unwrap_or_else(|| bundle_root.join(STORE_RELATIVE))
}

/// The write path for a bare caller: the shared env store when an env is
/// selected via `$GREENTIC_ENV`, else the legacy bundle-local path.
fn bare_write_path(bundle_root: &Path) -> PathBuf {
    selected_env()
        .and_then(|env| env_store_dev_secrets_path(&env))
        .unwrap_or_else(|| bundle_root.join(STORE_RELATIVE))
}

/// Read-preference order: the shared env store (when an env is selected), then
/// legacy bundle-local candidates (for already-configured bundle directories).
fn read_candidate_paths(bundle_root: &Path) -> Vec<PathBuf> {
    let mut out = Vec::new();
    if let Some(env_store) = selected_env().and_then(|env| env_store_dev_secrets_path(&env)) {
        out.push(env_store);
    }
    out.push(bundle_root.join(STORE_RELATIVE));
    out.push(bundle_root.join(STORE_STATE_RELATIVE));
    out
}

/// Checks for an existing dev store: override, then env store, then bundle-local.
pub fn find_existing(bundle_root: &Path) -> Option<PathBuf> {
    find_existing_with_override(bundle_root, override_path().as_deref())
}

/// Looks for an existing dev store using an override path before consulting the
/// shared env store and then legacy bundle-local candidates.
pub fn find_existing_with_override(
    bundle_root: &Path,
    override_path: Option<&Path>,
) -> Option<PathBuf> {
    if let Some(path) = override_path
        && path.exists()
    {
        return Some(path.to_path_buf());
    }
    read_candidate_paths(bundle_root)
        .into_iter()
        .find(|candidate| candidate.exists())
}

/// Ensures the default dev store path exists (creating parent directories) before
/// returning it. Routes to the shared env store when `$GREENTIC_ENV` is set.
pub fn ensure_path(bundle_root: &Path) -> Result<PathBuf> {
    if let Some(path) = override_path() {
        ensure_parent(&path)?;
        return Ok(path);
    }
    let path = bare_write_path(bundle_root);
    ensure_parent(&path)?;
    Ok(path)
}

/// Like [`ensure_path`], but with an explicit environment — always the shared
/// env store (when resolvable). The correct key when the caller already resolved
/// `<env>` (e.g. [`SecretsSetup`]), independent of `$GREENTIC_ENV`.
pub fn ensure_path_for_env(bundle_root: &Path, env: &str) -> Result<PathBuf> {
    if let Some(path) = override_path() {
        ensure_parent(&path)?;
        return Ok(path);
    }
    let path = write_path_for_env(bundle_root, env);
    ensure_parent(&path)?;
    Ok(path)
}

/// Returns the default dev store path without creating anything.
pub fn default_path(bundle_root: &Path) -> PathBuf {
    override_path().unwrap_or_else(|| bare_write_path(bundle_root))
}

fn ensure_parent(path: &Path) -> Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    Ok(())
}

// ── SecretsSetup ────────────────────────────────────────────────────────────

/// Single entry-point for secrets initialization and resolution.
///
/// Opens exactly one dev store per instance and ensures every required secret
/// discovered from packs is canonicalized and registered.
pub struct SecretsSetup {
    store: DevStore,
    store_path: PathBuf,
    env: String,
    tenant: String,
    team: Option<String>,
    seeds: HashMap<String, SeedEntry>,
}

impl SecretsSetup {
    pub fn new(bundle_root: &Path, env: &str, tenant: &str, team: Option<&str>) -> Result<Self> {
        // Env-explicit, NOT `$GREENTIC_ENV`-gated. This is a write path: gating on
        // the ambient env meant setup persisted into the bundle-local store while
        // the runtime read the env store, so provisioned secrets went "missing" at
        // runtime (the whole point of the env-store seam fix). `env` is already a
        // parameter here — use it.
        let store_path = ensure_path_for_env(bundle_root, env)?;
        info!(path = %store_path.display(), "secrets: using dev store backend");
        let store = DevStore::with_path(&store_path).map_err(|err| {
            anyhow!(
                "failed to open dev secrets store {}: {err}",
                store_path.display()
            )
        })?;
        let seeds = load_seed_entries(bundle_root)?;
        Ok(Self {
            store,
            store_path,
            env: env.to_string(),
            tenant: tenant.to_string(),
            team: team.map(|v| v.to_string()),
            seeds,
        })
    }

    /// Path to the dev store file on disk.
    pub fn store_path(&self) -> &Path {
        &self.store_path
    }

    /// Reference to the underlying `DevStore`.
    pub fn store(&self) -> &DevStore {
        &self.store
    }

    /// Ensure all required secrets for a pack exist in the dev store.
    ///
    /// Reads `assets/secret-requirements.json` from the pack and seeds any
    /// missing keys from `seeds.yaml` or with a placeholder.
    pub async fn ensure_pack_secrets(&self, pack_path: &Path, provider_id: &str) -> Result<()> {
        let keys = load_secret_keys_from_pack(pack_path)?;
        if keys.is_empty() {
            return Ok(());
        }

        let mut missing = Vec::new();
        for key in keys {
            let uri = canonical_secret_uri(
                &self.env,
                &self.tenant,
                self.team.as_deref(),
                provider_id,
                &key,
            );
            debug!(uri = %uri, provider = %provider_id, key = %key, "canonicalized secret requirement");
            match self.store.get(&uri).await {
                Ok(_) => continue,
                Err(SecretError::NotFound { .. }) => {
                    let source = if self.seeds.contains_key(&uri) {
                        "seeds.yaml"
                    } else {
                        "placeholder"
                    };
                    debug!(uri = %uri, source, "seeding missing secret");
                    missing.push(
                        self.seeds
                            .get(&uri)
                            .cloned()
                            .unwrap_or_else(|| placeholder_entry(uri)),
                    );
                }
                Err(err) => {
                    return Err(anyhow!("failed to read secret {uri}: {err}"));
                }
            }
        }

        if missing.is_empty() {
            return Ok(());
        }
        let report = apply_seed(
            &self.store,
            &SeedDoc { entries: missing },
            ApplyOptions::default(),
        )
        .await;
        if !report.failed.is_empty() {
            return Err(anyhow!("failed to seed secrets: {:?}", report.failed));
        }
        Ok(())
    }
}

// ── Helpers ─────────────────────────────────────────────────────────────────

fn load_seed_entries(bundle_root: &Path) -> Result<HashMap<String, SeedEntry>> {
    for candidate in seed_paths(bundle_root) {
        if candidate.exists() {
            let contents = std::fs::read_to_string(&candidate)?;
            let doc: SeedDoc = serde_yaml_bw::from_str(&contents)?;
            return Ok(doc
                .entries
                .into_iter()
                .map(|entry| (entry.uri.clone(), entry))
                .collect());
        }
    }
    Ok(HashMap::new())
}

fn seed_paths(bundle_root: &Path) -> [PathBuf; 2] {
    [
        bundle_root.join("seeds.yaml"),
        bundle_root.join("state").join("seeds.yaml"),
    ]
}

fn placeholder_entry(uri: String) -> SeedEntry {
    SeedEntry {
        uri: uri.clone(),
        format: SecretFormat::Text,
        value: SeedValue::Text {
            text: format!("placeholder for {uri}"),
        },
        description: Some("auto-applied placeholder".to_string()),
    }
}

/// Load secret requirement keys from a `.gtpack` archive.
///
/// Tries `assets/secret-requirements.json` first, then falls back to
/// CBOR manifest extraction.
pub fn load_secret_keys_from_pack(pack_path: &Path) -> Result<Vec<String>> {
    Ok(load_secret_requirements_from_pack(pack_path)?
        .into_iter()
        .map(|req| req.key)
        .collect())
}

/// Rich secret requirements extracted from a `.gtpack` archive.
pub fn load_secret_requirements_from_pack(pack_path: &Path) -> Result<Vec<PackSecretRequirement>> {
    let file = std::fs::File::open(pack_path)?;
    let mut archive = zip::ZipArchive::new(file)?;

    for entry_name in &[
        "assets/secret-requirements.json",
        "assets/secret_requirements.json",
        "secret-requirements.json",
        "secret_requirements.json",
    ] {
        match archive.by_name(entry_name) {
            Ok(reader) => {
                let reqs: Vec<PackSecretRequirement> = serde_json::from_reader(reader)?;
                return Ok(dedup_requirements(reqs));
            }
            Err(zip::result::ZipError::FileNotFound) => continue,
            Err(err) => return Err(err.into()),
        }
    }

    let mut reqs = Vec::new();
    for index in 0..archive.len() {
        let name = {
            let entry = archive.by_index(index)?;
            entry.name().to_string()
        };
        if name != "manifest.cbor" && !name.ends_with(".manifest.cbor") {
            continue;
        }
        let mut entry = archive.by_name(&name)?;
        let mut bytes = Vec::new();
        std::io::Read::read_to_end(&mut entry, &mut bytes)?;
        let value: CborValue = serde_cbor::from_slice(&bytes)?;
        collect_secret_requirements_from_cbor(&value, &mut reqs);
    }

    Ok(dedup_requirements(reqs))
}

#[derive(Clone, Debug, serde::Deserialize)]
pub struct PackSecretRequirement {
    pub key: String,
    #[serde(default = "default_required")]
    pub required: bool,
    #[serde(default)]
    pub description: Option<String>,
}

fn default_required() -> bool {
    true
}

fn dedup_requirements(reqs: Vec<PackSecretRequirement>) -> Vec<PackSecretRequirement> {
    let mut by_key = BTreeMap::new();
    for req in reqs {
        by_key.entry(req.key.clone()).or_insert(req);
    }
    by_key.into_values().collect()
}

fn collect_secret_requirements_from_cbor(value: &CborValue, out: &mut Vec<PackSecretRequirement>) {
    match value {
        CborValue::Array(values) => {
            for value in values {
                collect_secret_requirements_from_cbor(value, out);
            }
        }
        CborValue::Map(map) => {
            if let Some(req) = parse_secret_requirement_map(map) {
                out.push(req);
            }
            for value in map.values() {
                collect_secret_requirements_from_cbor(value, out);
            }
        }
        _ => {}
    }
}

fn parse_secret_requirement_map(
    map: &BTreeMap<CborValue, CborValue>,
) -> Option<PackSecretRequirement> {
    let key = map_get_text(map, "key")?;
    let has_secret_shape = map.contains_key(&CborValue::Text("required".to_string()))
        || map.contains_key(&CborValue::Text("scope".to_string()))
        || map.contains_key(&CborValue::Text("format".to_string()))
        || map.contains_key(&CborValue::Text("description".to_string()));
    if !has_secret_shape {
        return None;
    }
    Some(PackSecretRequirement {
        key,
        required: map_get_bool(map, "required").unwrap_or(true),
        description: map_get_text(map, "description"),
    })
}

fn map_get_text(map: &BTreeMap<CborValue, CborValue>, key: &str) -> Option<String> {
    map.get(&CborValue::Text(key.to_string()))
        .and_then(|value| match value {
            CborValue::Text(text) => Some(text.clone()),
            _ => None,
        })
}

fn map_get_bool(map: &BTreeMap<CborValue, CborValue>, key: &str) -> Option<bool> {
    map.get(&CborValue::Text(key.to_string()))
        .and_then(|value| match value {
            CborValue::Bool(flag) => Some(*flag),
            _ => None,
        })
}

/// Open a `DevStore` keyed to an explicit `env` — ALWAYS the shared env store,
/// the exact file the greentic-start serve path reads. Use this on WRITE paths
/// that already know the env, so a setup-provisioned secret lands where the
/// runtime looks, never in the `$GREENTIC_ENV`-gated bundle-local store.
pub fn open_dev_store_for_env(bundle_root: &Path, env: &str) -> Result<DevStore> {
    let store_path = ensure_path_for_env(bundle_root, env)?;
    DevStore::with_path(&store_path).map_err(|err| {
        anyhow!(
            "failed to open dev secrets store {}: {err}",
            store_path.display()
        )
    })
}

/// Open a `DevStore` from a bundle root path (convenience). Prefer
/// [`open_dev_store_for_env`] on write paths — this bare form gates on
/// `$GREENTIC_ENV` and can diverge from the serve reader.
pub fn open_dev_store(bundle_root: &Path) -> Result<DevStore> {
    let store_path = ensure_path(bundle_root)?;
    DevStore::with_path(&store_path).map_err(|err| {
        anyhow!(
            "failed to open dev secrets store {}: {err}",
            store_path.display()
        )
    })
}

/// Test-only isolation for the dev secrets store.
///
/// Needed because the write path deliberately resolves to the SHARED env store
/// (`~/.greentic/environments/<env>/…` via `LocalFsStore::default_root()`), which
/// is the whole point of the env-store seam — setup and the runtime must meet in
/// one file. In tests that means store writes escape the temp dir and land in the
/// developer's real `~/.greentic`, so tests pollute real state and race each
/// other over one file.
///
/// `GREENTIC_DEV_SECRETS_PATH` is consulted before any other resolution, so
/// pointing it at a temp path isolates a test completely. It is process-global,
/// so acquiring it also serialises the tests that use it.
#[cfg(test)]
pub(crate) mod test_support {
    use std::path::Path;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::{Mutex, MutexGuard, OnceLock};

    /// Set while a guard from this module is alive.
    ///
    /// Read by [`super::assert_store_access_is_guarded`]: an unguarded test that
    /// resolves the store path reads whatever override a *concurrent* guarded
    /// test installed, and that test's temp dir can be removed mid-write — the
    /// store call then fails with `No such file or directory`. Failing loudly on
    /// the unguarded access turns that flake into a deterministic error naming
    /// the test that has to be fixed.
    static GUARDED: AtomicBool = AtomicBool::new(false);

    pub(crate) fn store_access_is_guarded() -> bool {
        GUARDED.load(Ordering::SeqCst)
    }

    /// Marks the guarded window. Held by every guard below for its lifetime.
    struct GuardFlag;

    impl GuardFlag {
        fn set() -> Self {
            GUARDED.store(true, Ordering::SeqCst);
            Self
        }
    }

    impl Drop for GuardFlag {
        fn drop(&mut self) {
            GUARDED.store(false, Ordering::SeqCst);
        }
    }

    /// THE process-wide env lock for this crate's tests.
    ///
    /// Must be the ONLY such lock: `lib.rs` previously kept its own `ENV_LOCK`
    /// for `GREENTIC_ENV`/`GREENTIC_DISABLE_DEV_ALIAS`, so its tests mutated
    /// those vars under one mutex while secrets tests read them under another —
    /// two locks give no mutual exclusion, which is exactly how the store tests
    /// raced. Everything that touches process-global env in tests takes this.
    pub(crate) fn env_lock() -> MutexGuard<'static, ()> {
        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
        LOCK.get_or_init(|| Mutex::new(()))
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    /// Points the dev-store override at a path for as long as it is held, then
    /// restores whatever was there before. Hold it for the whole test body.
    pub(crate) struct StoreOverride {
        // Declaration order is drop order, and it runs after `Drop::drop` below:
        // clear the flag and release the lock only once the env is restored.
        _flag: GuardFlag,
        _guard: MutexGuard<'static, ()>,
        previous: Option<String>,
    }

    impl StoreOverride {
        pub(crate) fn at(path: &Path) -> Self {
            let guard = env_lock();
            let previous = std::env::var(super::OVERRIDE_ENV).ok();
            // SAFETY: the process-global env is mutated only while holding
            // `env_lock`, so no other test observes a torn value, and Drop
            // restores the prior state.
            unsafe { std::env::set_var(super::OVERRIDE_ENV, path) };
            Self {
                _flag: GuardFlag::set(),
                _guard: guard,
                previous,
            }
        }

        /// Isolate inside `dir`, using the conventional store filename.
        pub(crate) fn in_dir(dir: &Path) -> Self {
            Self::at(&dir.join(".dev.secrets.env"))
        }
    }

    /// A [`StoreOverride`] that owns the temp dir it points at.
    ///
    /// This is what a test that *writes* secrets wants: `let _store =
    /// isolated_store();` as the first statement of the test body keeps the
    /// override installed — and the directory alive — for the whole test.
    pub(crate) struct IsolatedStore {
        // Drop the override (restoring the env and releasing the lock) before the
        // directory it points at is removed, so no other test can ever observe an
        // override aimed at a deleted path.
        _override: StoreOverride,
        _dir: tempfile::TempDir,
    }

    /// Points the dev store at a fresh temp dir for the rest of the test.
    pub(crate) fn isolated_store() -> IsolatedStore {
        let dir = tempfile::tempdir().expect("dev store isolation dir");
        let guard = StoreOverride::in_dir(dir.path());
        IsolatedStore {
            _override: guard,
            _dir: dir,
        }
    }

    /// Serialises against [`StoreOverride`] WITHOUT changing anything.
    ///
    /// Needed by tests that assert path resolution in its natural state: they
    /// read the same process-global var others set, so they must hold the lock or
    /// they observe another test's override. Because `StoreOverride` restores the
    /// previous value in `Drop` before releasing the lock, holding it here
    /// guarantees the var is back to its pre-test state.
    pub(crate) struct EnvLock(
        #[allow(dead_code)] GuardFlag,
        #[allow(dead_code)] MutexGuard<'static, ()>,
    );

    pub(crate) fn lock_env() -> EnvLock {
        let guard = env_lock();
        EnvLock(GuardFlag::set(), guard)
    }

    impl Drop for StoreOverride {
        fn drop(&mut self) {
            // SAFETY: still holding `env_lock` (dropped after this).
            match self.previous.take() {
                Some(value) => unsafe { std::env::set_var(super::OVERRIDE_ENV, value) },
                None => unsafe { std::env::remove_var(super::OVERRIDE_ENV) },
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use zip::write::SimpleFileOptions;

    fn write_pack_with_secret_requirements(path: &Path, req_json: &str) -> anyhow::Result<()> {
        let file = std::fs::File::create(path)?;
        let mut zip = zip::ZipWriter::new(file);
        zip.start_file(
            "assets/secret-requirements.json",
            SimpleFileOptions::default(),
        )?;
        zip.write_all(req_json.as_bytes())?;
        zip.finish()?;
        Ok(())
    }

    // NOTE on hermeticity: the dev-store resolvers read process-global env
    // (`$GREENTIC_ENV`, `$GREENTIC_DEV_SECRETS_PATH`) and the home dir, which
    // other tests in this crate also mutate. To stay race-free these unit tests
    // avoid asserting on that global state; the shared-env-store *activation*
    // path is covered end-to-end by the real-binary round-trip instead.

    #[test]
    fn env_store_path_has_expected_shape() {
        // `env_store_dev_secrets_path(env)` lays out
        // <home>/.greentic/environments/<env>/.greentic/dev/.dev.secrets.env.
        // Assert the suffix, which is independent of the home value (race-free).
        if let Some(path) = env_store_dev_secrets_path("some-env") {
            assert!(
                path.ends_with("environments/some-env/.greentic/dev/.dev.secrets.env"),
                "unexpected env-store path: {}",
                path.display()
            );
        }
    }

    /// Creates `<bundle>/.greentic/dev/.dev.secrets.env` and returns its path.
    fn write_bundle_local_store(bundle: &Path) -> PathBuf {
        let path = bundle.join(STORE_RELATIVE);
        std::fs::create_dir_all(path.parent().expect("store parent")).expect("store dir");
        std::fs::write(&path, "KEY=value\n").expect("write store");
        path
    }

    #[test]
    fn write_path_for_env_and_default_path_target_the_dev_store() {
        let _env_lock = crate::secrets::test_support::lock_env();
        // Both resolvers land on a `.dev.secrets.env` dev store, whether they
        // route to the shared env store (home resolvable) or fall back to the
        // bundle-local path. Assert the shared suffix — it holds either way and
        // is independent of process-global `$GREENTIC_ENV` (race-free).
        let temp = tempfile::tempdir().expect("tempdir");
        let bundle = temp.path().join("bundle");

        let write = write_path_for_env(&bundle, "some-env");
        assert!(
            write.ends_with(STORE_RELATIVE),
            "unexpected write path: {}",
            write.display()
        );

        let default = default_path(&bundle);
        assert!(
            default.ends_with(STORE_RELATIVE),
            "unexpected default path: {}",
            default.display()
        );
    }

    /// Guards the webex_bot_token seam: setup once wrote the bundle-local store
    /// while the runtime read the env store, so the secret went "missing". An
    /// env-explicit WRITE must target the shared env store and never the
    /// bundle-local one — independent of `$GREENTIC_ENV` (race-free: env is
    /// passed explicitly). Do NOT weaken without a new secrets plan.
    #[test]
    fn write_path_for_env_targets_the_env_store_not_bundle_local() {
        let temp = tempfile::tempdir().expect("tempdir");
        let bundle = temp.path().join("bundle");
        let Some(env_store) = env_store_dev_secrets_path("guard-env") else {
            return; // no HOME → covered by the real-binary round-trip instead
        };
        assert_eq!(
            write_path_for_env(&bundle, "guard-env"),
            env_store,
            "env-explicit write must target the env store",
        );
        assert!(
            !write_path_for_env(&bundle, "guard-env").starts_with(&bundle),
            "env-explicit write must never land in the bundle-local store",
        );
    }

    #[test]
    fn find_existing_locates_a_bundle_local_dev_store() {
        // Serialise: these assert path resolution in its natural state and
        // read the same process-global override other tests set.
        let _env_lock = test_support::lock_env();
        // With no `$GREENTIC_DEV_SECRETS_PATH` override, `find_existing` walks
        // the candidate list and returns an existing dev store. Hermetic: the
        // store lives in a tempdir, so the result exists and carries the dev
        // store suffix regardless of `$GREENTIC_ENV`.
        let temp = tempfile::tempdir().expect("tempdir");
        let bundle = temp.path().join("bundle");
        let store = bundle.join(STORE_RELATIVE);
        std::fs::create_dir_all(store.parent().expect("store parent")).expect("dev dir");
        std::fs::write(&store, "KEY=value\n").expect("write store");

        let found = find_existing(&bundle).expect("find dev store");
        assert!(
            found.exists(),
            "found path should exist: {}",
            found.display()
        );
        assert!(
            found.ends_with(STORE_RELATIVE),
            "unexpected found path: {}",
            found.display()
        );
    }

    #[test]
    fn find_existing_with_override_prefers_override() {
        // Serialise: these assert path resolution in its natural state and
        // read the same process-global override other tests set.
        let _env_lock = test_support::lock_env();
        let temp = tempfile::tempdir().expect("tempdir");
        let bundle = temp.path().join("bundle");
        std::fs::create_dir_all(&bundle).expect("bundle dir");
        let override_file = temp.path().join("custom.env");
        std::fs::write(&override_file, "KEY=value\n").expect("write override");

        let found = find_existing_with_override(&bundle, Some(&override_file));
        assert_eq!(found.as_deref(), Some(override_file.as_path()));
    }

    #[test]
    fn find_existing_with_override_falls_back_when_override_is_absent() {
        // Serialise: these assert path resolution in its natural state and
        // read the same process-global override other tests set.
        let _env_lock = test_support::lock_env();
        let temp = tempfile::tempdir().expect("tempdir");
        let bundle = temp.path().join("bundle");
        std::fs::create_dir_all(&bundle).expect("bundle dir");
        write_bundle_local_store(&bundle);
        let missing_override = temp.path().join("does-not-exist.env");

        // A non-existent override must not short-circuit the candidate walk.
        // The concrete winner depends on `$GREENTIC_ENV`/home (process-global,
        // mutated by other tests), so assert only what holds for every
        // candidate: it resolves to an existing dev-store file.
        for override_arg in [None, Some(missing_override.as_path())] {
            let found = find_existing_with_override(&bundle, override_arg)
                .expect("existing store must be discovered");
            assert!(found.exists(), "resolved store does not exist: {found:?}");
            assert!(
                found.ends_with(".dev.secrets.env"),
                "unexpected store file: {found:?}"
            );
        }
    }

    #[test]
    fn find_existing_discovers_the_bundle_local_store() {
        // Serialise: these assert path resolution in its natural state and
        // read the same process-global override other tests set.
        let _env_lock = test_support::lock_env();
        let temp = tempfile::tempdir().expect("tempdir");
        let bundle = temp.path().join("bundle");
        std::fs::create_dir_all(&bundle).expect("bundle dir");
        write_bundle_local_store(&bundle);

        let found = find_existing(&bundle).expect("existing store must be discovered");
        assert!(found.exists(), "resolved store does not exist: {found:?}");
    }

    #[test]
    fn read_candidate_paths_ends_with_bundle_local_candidates() {
        // Serialise: these assert path resolution in its natural state and
        // read the same process-global override other tests set.
        let _env_lock = test_support::lock_env();
        let temp = tempfile::tempdir().expect("tempdir");
        let bundle = temp.path().join("bundle");

        let candidates = read_candidate_paths(&bundle);
        // The optional leading entry is the shared env store, which only
        // appears when `$GREENTIC_ENV` is set; the bundle-local pair is always
        // present, in order, at the end.
        assert!(
            candidates.len() == 2 || candidates.len() == 3,
            "unexpected candidates: {candidates:?}"
        );
        assert_eq!(
            &candidates[candidates.len() - 2..],
            &[
                bundle.join(STORE_RELATIVE),
                bundle.join(STORE_STATE_RELATIVE)
            ]
        );
    }

    #[test]
    fn write_path_for_env_always_targets_a_dev_store_file() {
        // Serialise: these assert path resolution in its natural state and
        // read the same process-global override other tests set.
        let _env_lock = test_support::lock_env();
        let temp = tempfile::tempdir().expect("tempdir");
        let bundle = temp.path().join("bundle");

        // Both branches (shared env store / bundle-local fallback) end in the
        // same relative store path, so the suffix is home-independent.
        let path = write_path_for_env(&bundle, "some-env");
        assert!(
            path.ends_with(STORE_RELATIVE),
            "unexpected write path: {}",
            path.display()
        );
    }

    #[test]
    fn default_path_creates_nothing() {
        // Serialise: these assert path resolution in its natural state and
        // read the same process-global override other tests set.
        let _env_lock = test_support::lock_env();
        let temp = tempfile::tempdir().expect("tempdir");
        let bundle = temp.path().join("bundle");

        let path = default_path(&bundle);
        assert!(
            path.ends_with(".dev.secrets.env"),
            "unexpected default path: {}",
            path.display()
        );
        assert!(
            !bundle.exists(),
            "default_path must not touch the filesystem"
        );
    }

    #[test]
    fn load_secret_keys_from_pack_reads_requirements() {
        let temp = tempfile::tempdir().expect("tempdir");
        let pack = temp.path().join("provider.gtpack");
        write_pack_with_secret_requirements(&pack, r#"[{"key":"BOT_TOKEN"},{"key":"API_SECRET"}]"#)
            .expect("write pack");

        let keys = load_secret_keys_from_pack(&pack).expect("load keys");
        assert_eq!(
            keys,
            vec!["API_SECRET".to_string(), "BOT_TOKEN".to_string()]
        );
    }

    #[test]
    fn load_secret_keys_from_pack_reads_cbor_manifest_requirements() {
        let temp = tempfile::tempdir().expect("tempdir");
        let pack = temp.path().join("provider.gtpack");
        let file = std::fs::File::create(&pack).expect("create pack");
        let mut zip = zip::ZipWriter::new(file);
        zip.start_file("manifest.cbor", SimpleFileOptions::default())
            .expect("start entry");
        let manifest = serde_json::json!({
            "components": [
                {
                    "host": {
                        "secrets": {
                            "required": [
                                {
                                    "key": "auth.param.get_weather.key",
                                    "required": true,
                                    "description": "Weather key",
                                    "scope": {"env": "runtime", "tenant": "runtime"},
                                    "format": "text"
                                }
                            ]
                        }
                    }
                }
            ]
        });
        let bytes = serde_cbor::to_vec(&manifest).expect("serialize cbor");
        zip.write_all(&bytes).expect("write manifest");
        zip.finish().expect("finish zip");

        let keys = load_secret_keys_from_pack(&pack).expect("load keys");
        assert_eq!(keys, vec!["auth.param.get_weather.key".to_string()]);

        let reqs = load_secret_requirements_from_pack(&pack).expect("load reqs");
        assert_eq!(reqs.len(), 1);
        assert_eq!(reqs[0].description.as_deref(), Some("Weather key"));
    }

    #[test]
    fn load_secret_keys_from_pack_returns_empty_without_requirements() {
        let temp = tempfile::tempdir().expect("tempdir");
        let pack = temp.path().join("provider.gtpack");
        let file = std::fs::File::create(&pack).expect("create pack");
        let mut zip = zip::ZipWriter::new(file);
        zip.start_file("assets/setup.yaml", SimpleFileOptions::default())
            .expect("start entry");
        zip.write_all(b"questions: []\n").expect("write setup");
        zip.finish().expect("finish zip");

        let keys = load_secret_keys_from_pack(&pack).expect("load keys");
        assert!(keys.is_empty());
    }

    #[test]
    fn cbor_manifest_scan_skips_maps_that_are_not_secret_requirements() {
        let temp = tempfile::tempdir().expect("tempdir");
        let pack = temp.path().join("provider.gtpack");
        let file = std::fs::File::create(&pack).expect("create pack");
        let mut zip = zip::ZipWriter::new(file);
        zip.start_file("manifest.cbor", SimpleFileOptions::default())
            .expect("start entry");
        let manifest = serde_json::json!({
            // Has a textual `key` but none of the secret-shaped companion
            // fields — must not be mistaken for a secret requirement.
            "routes": [{"key": "not-a-secret", "target": "node-a"}],
            // `key` is not text, so the map is rejected outright.
            "indexed": [{"key": 7, "required": true}],
            // Secret-shaped, but `required` is not a bool: defaults to true.
            "secrets": [{"key": "loose.secret", "required": "yes"}],
        });
        let bytes = serde_cbor::to_vec(&manifest).expect("serialize cbor");
        zip.write_all(&bytes).expect("write manifest");
        zip.finish().expect("finish zip");

        let reqs = load_secret_requirements_from_pack(&pack).expect("load reqs");
        assert_eq!(reqs.len(), 1, "unexpected requirements: {reqs:?}");
        assert_eq!(reqs[0].key, "loose.secret");
        assert!(reqs[0].required, "non-bool `required` must default to true");
        assert!(reqs[0].description.is_none());
    }

    #[tokio::test]
    async fn ensure_pack_secrets_is_a_no_op_without_requirements() {
        let _store_iso_dir = tempfile::tempdir().expect("store isolation dir");
        let _store_iso = crate::secrets::test_support::StoreOverride::in_dir(_store_iso_dir.path());
        let temp = tempfile::tempdir().expect("tempdir");
        let bundle = temp.path().join("bundle");
        std::fs::create_dir_all(&bundle).expect("bundle dir");
        let pack = temp.path().join("provider.gtpack");
        write_pack_with_secret_requirements(&pack, "[]").expect("pack");

        let setup = SecretsSetup::new(&bundle, "dev", "tenant-a", Some("core")).expect("setup");
        setup
            .ensure_pack_secrets(&pack, "messaging-telegram")
            .await
            .expect("ensure secrets");

        assert!(
            setup
                .store_path()
                .parent()
                .is_some_and(|parent| parent.is_dir()),
            "store parent must be created: {}",
            setup.store_path().display()
        );
        assert!(
            setup.store_path().ends_with(".dev.secrets.env"),
            "unexpected store path: {}",
            setup.store_path().display()
        );
    }

    #[tokio::test]
    async fn ensure_pack_secrets_is_a_noop_without_requirements() {
        let _store_iso_dir = tempfile::tempdir().expect("store isolation dir");
        let _store_iso = crate::secrets::test_support::StoreOverride::in_dir(_store_iso_dir.path());
        let temp = tempfile::tempdir().expect("tempdir");
        let bundle = temp.path().join("bundle");
        std::fs::create_dir_all(&bundle).expect("bundle dir");

        // A pack with no secret-requirements → `ensure_pack_secrets` short-circuits.
        let pack = temp.path().join("provider.gtpack");
        let file = std::fs::File::create(&pack).expect("create pack");
        let mut zip = zip::ZipWriter::new(file);
        zip.start_file("assets/setup.yaml", SimpleFileOptions::default())
            .expect("start entry");
        zip.write_all(b"questions: []\n").expect("write setup");
        zip.finish().expect("finish zip");

        let setup = SecretsSetup::new(&bundle, "dev", "tenant-a", None).expect("setup");
        // The accessor resolves to the opened dev store file.
        assert!(setup.store_path().ends_with(".dev.secrets.env"));

        setup
            .ensure_pack_secrets(&pack, "messaging-telegram")
            .await
            .expect("noop for empty requirements");
    }

    #[tokio::test]
    async fn ensure_pack_secrets_seeds_placeholders_for_missing_keys() {
        let _store_iso_dir = tempfile::tempdir().expect("store isolation dir");
        let _store_iso = crate::secrets::test_support::StoreOverride::in_dir(_store_iso_dir.path());
        let temp = tempfile::tempdir().expect("tempdir");
        let bundle = temp.path().join("bundle");
        std::fs::create_dir_all(&bundle).expect("bundle dir");
        let pack = temp.path().join("provider.gtpack");
        write_pack_with_secret_requirements(&pack, r#"[{"key":"BOT_TOKEN"}]"#).expect("pack");

        let setup = SecretsSetup::new(&bundle, "dev", "tenant-a", Some("core")).expect("setup");
        setup
            .ensure_pack_secrets(&pack, "messaging-telegram")
            .await
            .expect("ensure secrets");

        let uri = canonical_secret_uri(
            "dev",
            "tenant-a",
            Some("core"),
            "messaging-telegram",
            "BOT_TOKEN",
        );
        let value = setup.store().get(&uri).await.expect("seeded value");
        let value = String::from_utf8(value).expect("utf8");
        assert!(
            value.contains("placeholder for secrets://"),
            "unexpected placeholder value: {value}"
        );
    }

    #[tokio::test]
    async fn ensure_pack_secrets_uses_seed_values_when_available() {
        let _store_iso_dir = tempfile::tempdir().expect("store isolation dir");
        let _store_iso = crate::secrets::test_support::StoreOverride::in_dir(_store_iso_dir.path());
        let temp = tempfile::tempdir().expect("tempdir");
        let bundle = temp.path().join("bundle");
        std::fs::create_dir_all(&bundle).expect("bundle dir");
        let seed_uri = canonical_secret_uri(
            "dev",
            "tenant-a",
            Some("core"),
            "messaging-telegram",
            "BOT_TOKEN",
        );
        let seeds_yaml = serde_yaml_bw::to_string(&SeedDoc {
            entries: vec![SeedEntry {
                uri: seed_uri.clone(),
                format: SecretFormat::Text,
                value: SeedValue::Text {
                    text: "seeded-secret".to_string(),
                },
                description: Some("test seed".to_string()),
            }],
        })
        .expect("serialize seeds");
        std::fs::write(bundle.join("seeds.yaml"), seeds_yaml).expect("write seeds");

        let pack = temp.path().join("provider.gtpack");
        write_pack_with_secret_requirements(&pack, r#"[{"key":"BOT_TOKEN"}]"#).expect("pack");

        let setup = SecretsSetup::new(&bundle, "dev", "tenant-a", Some("core")).expect("setup");
        setup
            .ensure_pack_secrets(&pack, "messaging-telegram")
            .await
            .expect("ensure secrets");

        let value = setup.store().get(&seed_uri).await.expect("seeded value");
        let value = String::from_utf8(value).expect("utf8");
        assert_eq!(value, "seeded-secret");
    }
}