greentic-deployer-dev 1.2.28461464450

Greentic deployer runtime for plan construction and deployment-pack dispatch
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
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
//! `gtc op secrets {list,put,get,rotate}` (`A3`).
//!
//! Operates on the env's bound `Secrets` env-pack. The actual backend
//! dispatch (AWS Secrets Manager, Azure Key Vault, dev-store, Vault, etc.)
//! lives in `greentic-secrets-lib`; the env-pack registry (A9) is what binds
//! a `PackDescriptor` to a concrete backend at runtime. A3 ships the
//! command surface, enforces the env-must-have-secrets-pack precondition,
//! and reports the resolved kind in every envelope.
//!
//! `put` is live for the `greentic.secrets.dev-store` kind (the default
//! binding `op env init` creates): it writes the value into the env's local
//! dev store at the same path the runtime reader (greentic-start
//! `SecretsClient::open(<env_dir>)`) resolves, so a put is immediately
//! visible to served revisions. All other kinds — and get/rotate against any
//! live backend — return `NotYetImplemented` and point at the gating PR
//! (A9 — env-pack registry + handler dispatch).
//! `list` returns the *namespace* keys the env owns (always `secret://<env>/...`)
//! — no actual material is fetched.

use std::path::{Path, PathBuf};

use chrono::Utc;
use greentic_deploy_spec::{CapabilitySlot, EnvId, EnvPackBinding, Environment, SecretRef};
use greentic_secrets_lib::{DevStore, SecretFormat, SecretsStore, canonical_secret_store_key};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use crate::environment::{EnvFlock, EnvironmentStore, LocalFsStore};

use super::{
    AuditCtx, AuditGens, OpError, OpFlags, OpOutcome, audit_and_record, resolve_idempotency_key,
};

const NOUN: &str = "secrets";

/// `PackDescriptor::path()` of the local dev-store secrets backend — the
/// default binding `op env init` creates and the only kind `put` dispatches
/// to in Phase A. Shared with `env apply` (PR-2), which pre-checks the bound
/// backend at validation time so a non-dev-store env fails before any
/// mutation instead of mid-run.
pub(super) const DEV_STORE_KIND_PATH: &str = "greentic.secrets.dev-store";

/// Same override the runtime reader honors (`greentic-start
/// `dev_store_path::override_path`): when set, both writer and reader use
/// this path instead of the env-dir defaults below.
pub(super) const DEV_SECRETS_PATH_ENV: &str = "GREENTIC_DEV_SECRETS_PATH";

/// Dev-store candidates relative to the env dir. MUST mirror greentic-start's
/// `dev_store_path.rs` (`STORE_RELATIVE` / `STORE_STATE_RELATIVE`) — the
/// runtime's `SecretsClient::open(<env_dir>)` resolves the same chain, so a
/// put here is what a served revision reads back.
pub(super) const DEV_STORE_RELATIVE: &str = ".greentic/dev/.dev.secrets.env";
const DEV_STORE_STATE_RELATIVE: &str = ".greentic/state/dev/.dev.secrets.env";

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecretsListPayload {
    pub environment_id: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecretsPutPayload {
    pub environment_id: String,
    /// Path relative to the env's secret namespace. The full SecretRef is
    /// rendered as `secret://<env>/<path>`.
    pub path: String,
    /// The value is intentionally typed as a plain JSON string so payload
    /// transport stays uniform; the live backend handler (A9) is what reads
    /// this and converts to the backend-native shape.
    pub value: String,
    /// Caller-supplied A8 §2 idempotency key. Optional on the CLI
    /// surface; when absent, the verb mints one per invocation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub idempotency_key: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecretsGetPayload {
    pub environment_id: String,
    pub path: String,
    /// When true, the decrypted value is included in the outcome envelope.
    /// Default false — only presence + metadata is returned, so a `get` does
    /// not leak the value into CI logs / audit trails.
    #[serde(default)]
    pub reveal: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecretsRotatePayload {
    pub environment_id: String,
    pub path: String,
}

/// `op secrets list`. Returns the env's secret-ref namespace plus the kind
/// of the bound secrets env-pack. Phase A does not yet enumerate live
/// backend-side keys (no handler dispatch); the operator gets the namespace
/// plus backend identity, which is what wizards need to know to write into
/// the right place.
pub fn list(
    store: &LocalFsStore,
    flags: &OpFlags,
    payload: Option<SecretsListPayload>,
) -> Result<OpOutcome, OpError> {
    if flags.schema_only {
        return Ok(OpOutcome::new(NOUN, "list", list_schema()));
    }
    let payload = resolve_payload::<SecretsListPayload>(flags, payload)?;
    let env_id = parse_env_id(&payload.environment_id)?;
    let env = store.load(&env_id)?;
    let secrets = require_secrets_pack(&env, &env_id)?;
    // Walk every SecretRef known in the env so the operator can audit what
    // the env *expects* to be present. This is purely structural — the
    // backend itself may have more or fewer keys.
    let mut known_refs: Vec<String> = env
        .credentials_ref
        .as_ref()
        .map(|c| c.as_str().to_string())
        .into_iter()
        .collect();
    if let Some(bs) = env
        .bundles
        .iter()
        .map(|b| b.authorization_ref.to_string_lossy().into_owned())
        .next()
    {
        // authorization_ref is a path, not a secret://, but include it for
        // visibility into where bundle auth resolves.
        known_refs.push(format!("auth://{bs}"));
    }
    Ok(OpOutcome::new(
        NOUN,
        "list",
        json!({
            "environment_id": env_id.as_str(),
            "secrets_kind": secrets.kind.to_string(),
            "namespace": format!("secret://{}/", env_id.as_str()),
            "known_refs": known_refs,
            "snapshot_at": Utc::now(),
            "note": "Phase A: namespace + known-refs only; live backend enumeration lands in A9.",
        }),
    ))
}

pub fn put(
    store: &LocalFsStore,
    flags: &OpFlags,
    payload: Option<SecretsPutPayload>,
) -> Result<OpOutcome, OpError> {
    if flags.schema_only {
        return Ok(OpOutcome::new(NOUN, "put", put_schema()));
    }
    let payload = resolve_payload::<SecretsPutPayload>(flags, payload)?;
    let env_id = parse_env_id(&payload.environment_id)?;
    let idempotency_key = resolve_idempotency_key(payload.idempotency_key.clone())?;
    let ctx = AuditCtx {
        env_id: env_id.clone(),
        noun: NOUN,
        verb: "put",
        target: json!({"path": payload.path}),
        idempotency_key: Some(idempotency_key.as_str().to_string()),
    };
    audit_and_record(store, ctx, |_committed| {
        let env = store.load(&env_id)?;
        let secrets = require_secrets_pack(&env, &env_id)?;
        let rel_path = payload.path.trim_start_matches('/');
        // Build the resolved SecretRef so we can validate the env-scoping.
        let secret_uri = format!("secret://{}/{rel_path}", env_id.as_str());
        SecretRef::try_new(secret_uri.clone())
            .map_err(|e| OpError::InvalidArgument(format!("secret path: {e}")))?;
        // Make sure the value is non-empty — writing empty strings to a real
        // backend is almost always a bug.
        if payload.value.is_empty() {
            return Err(OpError::InvalidArgument(
                "value must not be empty".to_string(),
            ));
        }
        let kind_path = secrets.kind.path();
        if kind_path == DEV_STORE_KIND_PATH {
            validate_dev_store_secret_path(rel_path)?;
            let store_uri = format!("secrets://{}/{rel_path}", env_id.as_str());
            let dev_path = resolve_dev_store_path(
                &store.env_dir(&env_id)?,
                std::env::var_os(DEV_SECRETS_PATH_ENV).map(PathBuf::from),
            );
            dev_store_put(&dev_path, &store_uri, &payload.value)?;
            Ok((
                OpOutcome::new(
                    NOUN,
                    "put",
                    json!({
                        "environment_id": env_id.as_str(),
                        "secret_ref": secret_uri,
                        "store_uri": store_uri,
                        "secrets_kind": secrets.kind.to_string(),
                        "store_path": dev_path.display().to_string(),
                        "written": true,
                    }),
                ),
                AuditGens::NONE,
            ))
        } else if kind_path == crate::defaults::VAULT_SECRETS_PATH {
            // Same ref shape as the dev store; the difference is the backend.
            validate_dev_store_secret_path(rel_path)?;
            let store_uri = format!("secrets://{}/{rel_path}", env_id.as_str());
            let vault_addr = vault_seed_put(store, &env, &store_uri, &payload.value)?;
            Ok((
                OpOutcome::new(
                    NOUN,
                    "put",
                    json!({
                        "environment_id": env_id.as_str(),
                        "secret_ref": secret_uri,
                        "store_uri": store_uri,
                        "secrets_kind": secrets.kind.to_string(),
                        "vault_addr": vault_addr,
                        "written": true,
                    }),
                ),
                AuditGens::NONE,
            ))
        } else {
            Err(OpError::NotYetImplemented(
                "secrets backend dispatch beyond the dev-store and Vault lands in A9 \
                 (env-pack registry)"
                    .to_string(),
            ))
        }
    })
}

/// `op secrets get`. Reads a secret back for the dev-store and Vault backends
/// (symmetric to [`put`]); other kinds return `NotYetImplemented` (A9). Reads
/// are not audited (matching [`list`]). By default only presence + metadata is
/// returned; `reveal: true` includes the decrypted value.
pub fn get(
    store: &LocalFsStore,
    flags: &OpFlags,
    payload: Option<SecretsGetPayload>,
) -> Result<OpOutcome, OpError> {
    if flags.schema_only {
        return Ok(OpOutcome::new(NOUN, "get", get_schema()));
    }
    let payload = resolve_payload::<SecretsGetPayload>(flags, payload)?;
    let env_id = parse_env_id(&payload.environment_id)?;
    let env = store.load(&env_id)?;
    let secrets = require_secrets_pack(&env, &env_id)?;
    let rel_path = payload.path.trim_start_matches('/');
    let secret_uri = format!("secret://{}/{rel_path}", env_id.as_str());
    SecretRef::try_new(secret_uri.clone())
        .map_err(|e| OpError::InvalidArgument(format!("secret path: {e}")))?;

    let kind = secrets.kind.to_string();
    let kind_path = secrets.kind.path();
    if kind_path == DEV_STORE_KIND_PATH {
        validate_dev_store_secret_path(rel_path)?;
        let store_uri = format!("secrets://{}/{rel_path}", env_id.as_str());
        let dev_path = resolve_dev_store_path(
            &store.env_dir(&env_id)?,
            std::env::var_os(DEV_SECRETS_PATH_ENV).map(PathBuf::from),
        );
        // A missing store file means nothing was ever written for this env —
        // absence, not an error (mirrors `dev_store_has`'s existence guard).
        let value = if dev_path.exists() {
            dev_store_get_value(&dev_path, &store_uri)?
        } else {
            None
        };
        Ok(OpOutcome::new(
            NOUN,
            "get",
            get_result_json(
                env_id.as_str(),
                &secret_uri,
                &store_uri,
                &kind,
                json!({"store_path": dev_path.display().to_string()}),
                value,
                payload.reveal,
            ),
        ))
    } else if kind_path == crate::defaults::VAULT_SECRETS_PATH {
        validate_dev_store_secret_path(rel_path)?;
        let store_uri = format!("secrets://{}/{rel_path}", env_id.as_str());
        let (value, vault_addr) = vault_seed_get(store, &env, &store_uri)?;
        Ok(OpOutcome::new(
            NOUN,
            "get",
            get_result_json(
                env_id.as_str(),
                &secret_uri,
                &store_uri,
                &kind,
                json!({"vault_addr": vault_addr}),
                value,
                payload.reveal,
            ),
        ))
    } else {
        Err(OpError::NotYetImplemented(
            "secrets backend dispatch beyond the dev-store and Vault lands in A9 \
             (env-pack registry)"
                .to_string(),
        ))
    }
}

pub fn rotate(
    store: &LocalFsStore,
    flags: &OpFlags,
    payload: Option<SecretsRotatePayload>,
) -> Result<OpOutcome, OpError> {
    if flags.schema_only {
        return Ok(OpOutcome::new(NOUN, "rotate", rotate_schema()));
    }
    let payload = resolve_payload::<SecretsRotatePayload>(flags, payload)?;
    let env_id = parse_env_id(&payload.environment_id)?;
    let ctx = AuditCtx {
        env_id: env_id.clone(),
        noun: NOUN,
        verb: "rotate",
        target: json!({"path": payload.path}),
        idempotency_key: None,
    };
    audit_and_record(store, ctx, |_committed| {
        let env = store.load(&env_id)?;
        let _secrets = require_secrets_pack(&env, &env_id)?;
        SecretRef::try_new(format!(
            "secret://{}/{}",
            env_id.as_str(),
            payload.path.trim_start_matches('/')
        ))
        .map_err(|e| OpError::InvalidArgument(format!("secret path: {e}")))?;
        Err(OpError::NotYetImplemented(
            "secret rotation depends on backend-specific rotate hooks; lands in A9".to_string(),
        ))
    })
}

// --- internals -----------------------------------------------------------

/// Build the `get` outcome body: identity fields + a `present` flag, plus the
/// decrypted value only when `reveal` is set (so a non-revealing `get` never
/// puts material into logs/audit). `extra` carries the backend-specific field
/// (`store_path` for dev-store, `vault_addr` for Vault).
fn get_result_json(
    env_id: &str,
    secret_ref: &str,
    store_uri: &str,
    secrets_kind: &str,
    extra: Value,
    value: Option<String>,
    reveal: bool,
) -> Value {
    let mut body = json!({
        "environment_id": env_id,
        "secret_ref": secret_ref,
        "store_uri": store_uri,
        "secrets_kind": secrets_kind,
        "present": value.is_some(),
    });
    if let Value::Object(extra_map) = extra
        && let Value::Object(map) = &mut body
    {
        map.extend(extra_map);
    }
    if reveal && let Some(v) = value {
        body["value"] = Value::String(v);
    }
    body
}

/// Seed a Vault-backed secret through the embedded [`SecretsCore`]: the value is
/// envelope-encrypted via `transit/encrypt` and written to the KV record the
/// worker reads back (a raw `vault kv put` would not produce that envelope, so
/// the runtime could not decrypt it).
///
/// The Vault *connection* is assembled from two sources. The env's Vault binding
/// supplies the non-secret mounts/prefix/transit, so the seeded path matches
/// exactly what the worker reads. The operator's ambient environment supplies the
/// admin credential (`VAULT_TOKEN`, which must hold `transit/encrypt` + KV write)
/// and a reachable `VAULT_ADDR` — seeding runs from the operator host, not the
/// pod, so it authenticates with a token rather than the pod's Kubernetes-role
/// identity. The provider exposes only an env-driven `build_backend()` and this
/// crate is `#![forbid(unsafe_code)]`, so the deployer cannot inject the binding's
/// mounts into the process env; it instead fails closed when the ambient env would
/// not resolve to the binding's values. Returns the Vault address used.
fn vault_seed_put(
    store: &LocalFsStore,
    env: &Environment,
    store_uri: &str,
    value: &str,
) -> Result<String, OpError> {
    use crate::env_packs::k8s::manifests::SecretsBackend;
    use greentic_secrets_lib::core::{CoreBuilder, rt};

    // A Vault-backed env is single-tenant at the runtime (greentic-start scopes
    // one SecretsCore to the env owner and fails closed otherwise), so seeding
    // requires an owner and writes under it.
    let tenant = env
        .host_config
        .tenant_org_id
        .clone()
        .filter(|t| !t.trim().is_empty())
        .ok_or_else(|| {
            OpError::InvalidArgument(
                "a Vault-backed env must be tenant-owned before seeding; set the owner with \
                 `op env update <env> --tenant-org <tenant>`"
                    .to_string(),
            )
        })?;

    // Non-secret connection config (mounts/prefix/transit) from the env binding.
    let SecretsBackend::Vault(vault) = super::env::resolve_secrets_backend(store, env)? else {
        return Err(OpError::Conflict(
            "env secrets binding is not Vault-backed".to_string(),
        ));
    };

    // Admin credential + reachable address come from the operator's environment.
    // The address is intentionally NOT matched against the binding's `addr`: the
    // binding holds the in-cluster service DNS the worker pod dials, which the
    // operator host generally cannot reach — it seeds via a port-forward or
    // ingress. The seeded address is returned in the outcome for visibility, and
    // a wrong target surfaces loudly as a missing-secret read at runtime.
    if std::env::var("VAULT_TOKEN")
        .map(|t| t.trim().is_empty())
        .unwrap_or(true)
    {
        return Err(OpError::InvalidArgument(
            "seeding a Vault-backed secret needs an admin `VAULT_TOKEN` (with `transit/encrypt` \
             and KV write) exported in the environment"
                .to_string(),
        ));
    }
    let addr = match std::env::var("VAULT_ADDR") {
        Ok(a) if !a.trim().is_empty() => a,
        _ => {
            return Err(OpError::InvalidArgument(
                "seeding a Vault-backed secret needs `VAULT_ADDR` exported (a Vault address \
                 reachable from here, e.g. a port-forward to the in-cluster Vault)"
                    .to_string(),
            ));
        }
    };

    // The seed must land where the worker reads: `build_backend()` takes the
    // mounts/prefix/transit/namespace from ambient env (or provider defaults), and
    // this crate cannot set them, so fail closed when the operator's ambient env
    // would not resolve to the binding's path-determining values.
    vault_seed_path_consistency(&vault, |var| {
        std::env::var(var).ok().and_then(|v| {
            let trimmed = v.trim();
            (!trimmed.is_empty()).then(|| trimmed.to_string())
        })
    })?;

    // Construct the embedded core over the env-driven Vault backend and write the
    // value verbatim (the broker envelope-encrypts). Driven through the secrets
    // runtime so the async backend runs from this synchronous verb.
    rt::sync_await(async {
        let components = greentic_secrets_lib::vault::build_backend()
            .await
            .map_err(|e| OpError::Conflict(format!("vault backend init failed: {e}")))?;
        let core = CoreBuilder::default()
            .tenant(tenant.as_str())
            .backend(components.backend, components.key_provider)
            .build()
            .await
            .map_err(|e| OpError::Conflict(format!("vault secrets core build failed: {e}")))?;
        core.put_text(store_uri, value)
            .await
            .map_err(|e| OpError::Conflict(format!("vault put failed: {e}")))?;
        Ok::<(), OpError>(())
    })?;

    Ok(addr)
}

/// Read a Vault-backed secret back through the embedded [`SecretsCore`] — the
/// counterpart to [`vault_seed_put`]. Assembles the same connection (binding
/// mounts + ambient `VAULT_TOKEN`/`VAULT_ADDR`, with the same path-consistency
/// guard) and `get_text`s the store URI; the broker `transit/decrypt`s the
/// envelope. Returns `(Some(plaintext), addr)` when present, `(None, addr)`
/// when the key is absent. The admin `VAULT_TOKEN` must hold `transit/decrypt`
/// + KV read.
fn vault_seed_get(
    store: &LocalFsStore,
    env: &Environment,
    store_uri: &str,
) -> Result<(Option<String>, String), OpError> {
    use crate::env_packs::k8s::manifests::SecretsBackend;
    use greentic_secrets_lib::core::{CoreBuilder, Error as CoreError, SecretsError, rt};

    let tenant = env
        .host_config
        .tenant_org_id
        .clone()
        .filter(|t| !t.trim().is_empty())
        .ok_or_else(|| {
            OpError::InvalidArgument(
                "a Vault-backed env must be tenant-owned before reading; set the owner with \
                 `op env update <env> --tenant-org <tenant>`"
                    .to_string(),
            )
        })?;

    let SecretsBackend::Vault(vault) = super::env::resolve_secrets_backend(store, env)? else {
        return Err(OpError::Conflict(
            "env secrets binding is not Vault-backed".to_string(),
        ));
    };

    if std::env::var("VAULT_TOKEN")
        .map(|t| t.trim().is_empty())
        .unwrap_or(true)
    {
        return Err(OpError::InvalidArgument(
            "reading a Vault-backed secret needs an admin `VAULT_TOKEN` (with `transit/decrypt` \
             and KV read) exported in the environment"
                .to_string(),
        ));
    }
    let addr = match std::env::var("VAULT_ADDR") {
        Ok(a) if !a.trim().is_empty() => a,
        _ => {
            return Err(OpError::InvalidArgument(
                "reading a Vault-backed secret needs `VAULT_ADDR` exported (a Vault address \
                 reachable from here, e.g. a port-forward to the in-cluster Vault)"
                    .to_string(),
            ));
        }
    };

    vault_seed_path_consistency(&vault, |var| {
        std::env::var(var).ok().and_then(|v| {
            let trimmed = v.trim();
            (!trimmed.is_empty()).then(|| trimmed.to_string())
        })
    })?;

    let value: Option<String> = rt::sync_await(async {
        let components = greentic_secrets_lib::vault::build_backend()
            .await
            .map_err(|e| OpError::Conflict(format!("vault backend init failed: {e}")))?;
        let core = CoreBuilder::default()
            .tenant(tenant.as_str())
            .backend(components.backend, components.key_provider)
            .build()
            .await
            .map_err(|e| OpError::Conflict(format!("vault secrets core build failed: {e}")))?;
        match core.get_text(store_uri).await {
            Ok(text) => Ok(Some(text)),
            Err(SecretsError::Core(CoreError::NotFound { .. })) => Ok(None),
            Err(e) => Err(OpError::Conflict(format!("vault get failed: {e}"))),
        }
    })?;

    Ok((value, addr))
}

/// Fail closed when the operator's ambient Vault environment would not resolve
/// to the binding's path-determining values, so a seed cannot silently land
/// somewhere the worker will never read. `ambient(var)` returns the trimmed,
/// non-empty value of a `VAULT_*` variable, else `None`.
///
/// Each tuple is `(env var, the binding's value, the provider default applied
/// when the var is unset)`. The KV mount/prefix and transit mount/key choose the
/// record location and envelope; the Enterprise **namespace** prefixes *every*
/// path, so an absent binding namespace (default `""`) requires the ambient var
/// to be absent too — a stray `VAULT_NAMESPACE` would otherwise seed a different
/// namespace than the (namespace-less) worker reads. The k8s auth mount is
/// deliberately excluded: it governs login, not where the record lands, and is
/// unused here because seeding authenticates with a static `VAULT_TOKEN`.
fn vault_seed_path_consistency(
    vault: &crate::env_packs::k8s::manifests::VaultBackend,
    ambient: impl Fn(&str) -> Option<String>,
) -> Result<(), OpError> {
    use crate::env_packs::k8s::manifests::{
        VAULT_DEFAULT_KV_MOUNT, VAULT_DEFAULT_KV_PREFIX, VAULT_DEFAULT_TRANSIT_KEY,
        VAULT_DEFAULT_TRANSIT_MOUNT,
    };
    let checks = [
        (
            "VAULT_KV_MOUNT",
            vault.kv_mount.as_str(),
            VAULT_DEFAULT_KV_MOUNT,
        ),
        (
            "VAULT_KV_PREFIX",
            vault.kv_prefix.as_str(),
            VAULT_DEFAULT_KV_PREFIX,
        ),
        (
            "VAULT_TRANSIT_MOUNT",
            vault.transit_mount.as_str(),
            VAULT_DEFAULT_TRANSIT_MOUNT,
        ),
        (
            "VAULT_TRANSIT_KEY",
            vault.transit_key.as_str(),
            VAULT_DEFAULT_TRANSIT_KEY,
        ),
        (
            "VAULT_NAMESPACE",
            vault.namespace.as_deref().unwrap_or(""),
            "",
        ),
    ];
    for (var, binding_value, default) in checks {
        let ambient_value = ambient(var);
        let effective = ambient_value.as_deref().unwrap_or(default);
        if effective != binding_value {
            return Err(OpError::InvalidArgument(format!(
                "the env's Vault binding requires {var}=`{binding_value}` but the seed would use \
                 `{effective}`; export {var}=`{binding_value}` so the seeded record matches what \
                 the worker reads"
            )));
        }
    }
    Ok(())
}

/// Where the env's dev store lives, mirroring the runtime reader's chain
/// (greentic-start `dev_store_path`): explicit override env var, else the
/// first *existing* default candidate under the env dir, else the primary
/// default (created on first write).
pub(super) fn resolve_dev_store_path(env_dir: &Path, override_path: Option<PathBuf>) -> PathBuf {
    if let Some(path) = override_path {
        return path;
    }
    let primary = env_dir.join(DEV_STORE_RELATIVE);
    if primary.exists() {
        return primary;
    }
    let fallback = env_dir.join(DEV_STORE_STATE_RELATIVE);
    if fallback.exists() {
        return fallback;
    }
    primary
}

/// Validate that `rel_path` (leading `/` already trimmed) is a writable
/// dev-store secret path: exactly `<tenant>/<team>/<pack>/<name>` with
/// store-canonical team and name segments.
///
/// The dev store's native key shape is the runtime's `secrets://` (plural)
/// URI: `secrets://<env>/<tenant>/<team>/<pack>/<name>`; the backend handler
/// converts the logical `secret://` ref 1:1. `DevStore::put` itself rejects
/// any other depth, so enforce the shape upfront with a teachable error
/// instead of surfacing the backend's "uri is missing category" — exactly
/// four non-empty segments.
///
/// Shared between `put` (pre-write) and `env apply`'s pre-mutation manifest
/// validation (PR-2) so the two surfaces cannot drift.
pub(super) fn validate_dev_store_secret_path(rel_path: &str) -> Result<(), OpError> {
    let shape_err = || {
        OpError::InvalidArgument(format!(
            "dev-store secret path must be `<tenant>/<team>/<pack>/<name>` \
             (e.g. `default/_/messaging-telegram/telegram_bot_token`); \
             got `{rel_path}`"
        ))
    };
    let segs: Vec<&str> = rel_path.split('/').collect();
    let [_tenant, team, _pack, name] = segs[..] else {
        return Err(shape_err());
    };
    if segs.iter().any(|s| s.is_empty()) {
        return Err(shape_err());
    }
    // The runtime reader canonicalizes the team segment before lookup
    // (greentic-start `secrets_manager::canonical_team` maps `default`/
    // empty — trimmed, case-insensitive — to `_`), so a literal
    // `default` team would be written under a key no lookup ever uses.
    // Same policy as the name segment: reject instead of silently
    // transforming.
    if !is_canonical_team(team) {
        return Err(OpError::InvalidArgument(format!(
            "team segment `{team}` is not store-canonical: the runtime \
             reads the default team as `_` — pass `_` (or a real team \
             name without surrounding whitespace)"
        )));
    }
    // The runtime reader canonicalizes the name segment before lookup
    // (greentic-start `secret_name::canonical_secret_name`), so a
    // non-canonical name would be written but never found. Reject
    // instead of silently transforming — producer and consumer must
    // share one derivation, and we share it by only accepting
    // already-canonical input.
    if !is_canonical_secret_name(name) {
        return Err(OpError::InvalidArgument(format!(
            "secret name `{name}` is not store-canonical: use lowercase \
             a-z, 0-9 and single `_` separators (no leading/trailing `_`)"
        )));
    }
    Ok(())
}

/// A segment is writable iff the runtime reader's canonicalization maps it to
/// itself — anything else is written under a key no lookup will ever use. Both
/// checks call the shared `greentic-secrets` definitions (`normalize_team` /
/// `canonical_secret_name`) — the same functions the runtime reader and the
/// deployer's resolver use — so the predicate can't drift from the
/// transformation it guards.
fn is_canonical_team(team: &str) -> bool {
    // `normalize_team` returns `None` for the team-less cases (`default`,
    // empty, whitespace, AND the `_` placeholder itself). The canonical
    // string form of a team-less segment is `TEAM_PLACEHOLDER` (`_`), so a
    // segment is store-canonical iff it equals its normalization rendered
    // back through that placeholder — this accepts `_` (and real team names)
    // while still rejecting `default`/empty.
    greentic_secrets_lib::normalize_team(Some(team))
        .as_deref()
        .unwrap_or(greentic_secrets_lib::TEAM_PLACEHOLDER)
        == team
}

fn is_canonical_secret_name(name: &str) -> bool {
    greentic_secrets_lib::canonical_secret_name(name) == name
}

/// Write one value into the dev store from this sync context.
///
/// `DevStore::put` is async; same constraint as
/// `runtime_secrets::block_on_async_resolution` — the caller may sit on a
/// current-thread runtime (where `block_in_place` panics) or no runtime at
/// all, so hop to a dedicated OS thread that owns its own current-thread
/// runtime.
///
/// The backend is load-snapshot-at-open / persist-full-snapshot-on-write
/// (its internal flock covers each step, NOT the open→put window), so two
/// concurrent writers silently lose the slower one's update. Serialize the
/// whole cycle with a blocking sidecar flock (`<store>.lock`) held from
/// before `DevStore::with_path` (the snapshot load) until after `put` (the
/// persist). The sidecar — not the store file itself — because the
/// backend's own flock on the store file would deadlock against ours.
/// This serializes `op secrets put` writers; other tools writing the same
/// store (`greentic-secrets apply`, the runtime's QA persist) don't take
/// this lock — closing that belongs in the backend (A9 follow-up).
///
/// Failures map to `OpError::Io` keyed on the store path — the dev store is
/// a local file, and adding a dedicated `OpError` variant would break
/// Map a deploy-spec [`SecretRef`] (`secret://`) to its runtime dev-store URI
/// (`secrets://`), delegating to the one authoritative converter in
/// `greentic-secrets` ([`SecretRef::to_store_uri`]) instead of a local
/// `replacen`. It additionally re-canonicalizes the team segment (`default` →
/// `_`), and errors when the ref is not a store-aligned 5-segment URI (a scheme
/// flip alone has no canonical store location for other shapes).
pub(super) fn secret_ref_to_store_uri(secret_ref: &SecretRef) -> Result<String, OpError> {
    secret_ref
        .to_store_uri()
        .map(|uri| uri.to_string())
        .map_err(|e| {
            OpError::InvalidArgument(format!(
                "secret ref `{}` is not a store-aligned URI: {e}",
                secret_ref.as_str()
            ))
        })
}

/// downstream exhaustive matches (greentic-operator's HTTP status mapping).
/// Error messages carry the backend's text only — never secret material.
pub(super) fn dev_store_put(path: &Path, uri: &str, value: &str) -> Result<(), OpError> {
    let io_err = |message: String| OpError::Io {
        path: path.to_path_buf(),
        source: std::io::Error::other(message),
    };
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|source| OpError::Io {
            path: parent.to_path_buf(),
            source,
        })?;
    }
    let _write_lock = EnvFlock::acquire(&dev_store_lock_path(path))
        .map_err(|source| OpError::Store(source.into()))?;
    let store = DevStore::with_path(path.to_path_buf())
        .map_err(|e| io_err(format!("open dev store: {e}")))?;
    std::thread::scope(|scope| {
        scope
            .spawn(|| {
                tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .map_err(|e| io_err(format!("build runtime: {e}")))?
                    .block_on(store.put(uri, SecretFormat::Text, value.as_bytes()))
                    .map_err(|e| io_err(format!("dev store write: {e}")))
            })
            .join()
            .expect("dev-store write thread panicked")
    })
}

/// Persist a bound credential's material into the env dev store at the
/// location [`resolve_credentials_token`] reads it back from — the
/// secret-backend write the credentials-bootstrap runner drives through its
/// secret sink. Mirrors `op secrets put`'s dev-store write exactly so a
/// bound token resolves identically on later live verbs (reconcile /
/// apply-revision / requirements).
pub(super) fn put_credential_material(
    env_dir: &Path,
    secret_ref: &SecretRef,
    value: &str,
) -> Result<(), OpError> {
    let store_uri = secret_ref_to_store_uri(secret_ref)?;
    let dev_path = resolve_dev_store_path(
        env_dir,
        std::env::var_os(DEV_SECRETS_PATH_ENV).map(PathBuf::from),
    );
    dev_store_put(&dev_path, &store_uri, value)
}

/// Whether the env's dev store already holds a non-empty value at `rel_path`
/// (`<tenant>/<team>/<pack>/<name>`). `env apply` uses this so a paste-sourced
/// secret (`from_env` absent) that is already stored is treated as satisfied —
/// no re-prompt, no missing input — making the store the source of truth for
/// pasted values across re-applies. A missing store file (fresh env) reads as
/// `false`.
pub(super) fn dev_store_has(
    env_dir: &Path,
    env_id: &EnvId,
    rel_path: &str,
) -> Result<bool, OpError> {
    let dev_path = resolve_dev_store_path(
        env_dir,
        std::env::var_os(DEV_SECRETS_PATH_ENV).map(PathBuf::from),
    );
    if !dev_path.exists() {
        return Ok(false);
    }
    let uri = format!(
        "secrets://{}/{}",
        env_id.as_str(),
        rel_path.trim_start_matches('/')
    );
    dev_store_contains(&dev_path, &uri)
}

/// Read one key from a dev store, reporting only presence. Delegates to
/// [`dev_store_get_value`] — a `get` error (missing key / unreadable) maps to
/// `false` (absence), so apply re-collects the value rather than aborting.
fn dev_store_contains(path: &Path, uri: &str) -> Result<bool, OpError> {
    Ok(dev_store_get_value(path, uri)?.is_some())
}

/// Read one key's value from a dev store, returning `None` when the key is
/// absent / empty / not valid UTF-8 (a missing secret is absence, not a hard
/// error — the only hard failure is being unable to open the store file). Same
/// dedicated-thread runtime hop as [`dev_store_put`] (the caller may sit on a
/// current-thread runtime where `block_in_place` panics).
fn dev_store_get_value(path: &Path, uri: &str) -> Result<Option<String>, OpError> {
    let io_err = |message: String| OpError::Io {
        path: path.to_path_buf(),
        source: std::io::Error::other(message),
    };
    let store = DevStore::with_path(path.to_path_buf())
        .map_err(|e| io_err(format!("open dev store: {e}")))?;
    std::thread::scope(|scope| {
        scope
            .spawn(|| {
                let rt = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .map_err(|e| io_err(format!("build runtime: {e}")))?;
                Ok(rt.block_on(async {
                    match store.get(uri).await {
                        Ok(bytes) if !bytes.is_empty() => String::from_utf8(bytes).ok(),
                        _ => None,
                    }
                }))
            })
            .join()
            .expect("dev-store read thread panicked")
    })
}

/// Resolve an environment's bound `credentials_ref` to the deployer's bearer
/// token for live cluster verbs (`op env reconcile` / `apply-revision` /
/// `credentials requirements`).
///
/// Mirrors `runtime_secrets::resolve_runtime_secrets` precedence so an operator
/// supplies the deployer's ServiceAccount token exactly the way every other
/// secret is supplied — environment variable first (keyed by the canonical
/// store key), then the env's dev store (the same file [`put`] writes):
///
/// - `Ok(None)` — no `credentials_ref` is bound. The caller connects with the
///   ambient kubeconfig / in-cluster identity (the pre-closure behaviour).
/// - `Ok(Some(token))` — the ref resolves to a non-empty value; the caller
///   binds it onto the kube config (overriding the ambient identity).
/// - `Err(Conflict)` — a ref IS bound but no material is found. Fail closed:
///   silently falling back to the ambient (often broader-privileged) identity
///   when an env explicitly declares a bound credential would be a
///   privilege-escalation surprise.
pub(crate) fn resolve_credentials_token(
    store: &LocalFsStore,
    env: &Environment,
    env_id: &EnvId,
) -> Result<Option<String>, OpError> {
    let Some(secret_ref) = env.credentials_ref.as_ref() else {
        return Ok(None);
    };
    let store_uri = secret_ref_to_store_uri(secret_ref)?;
    let mut checked: Vec<String> = Vec::new();

    if let Some(env_key) = canonical_secret_store_key(&store_uri) {
        checked.push(format!("env {env_key}"));
        if let Ok(value) = std::env::var(&env_key)
            && !value.is_empty()
        {
            return Ok(Some(value));
        }
    }

    let dev_path = resolve_dev_store_path(
        &store.env_dir(env_id)?,
        std::env::var_os(DEV_SECRETS_PATH_ENV).map(PathBuf::from),
    );
    checked.push(dev_path.display().to_string());
    if dev_path.exists()
        && let Some(value) = dev_store_get_value(&dev_path, &store_uri)?
    {
        return Ok(Some(value));
    }

    Err(OpError::Conflict(format!(
        "environment `{}` declares credentials_ref `{}` but no secret material was \
         found (looked in: {}); supply it via `op secrets put` or the corresponding \
         environment variable before running live cluster verbs",
        env_id.as_str(),
        secret_ref.as_str(),
        checked.join(", "),
    )))
}

/// Sidecar lock path for a dev store file: the full path with `.lock`
/// appended (`.dev.secrets.env` → `.dev.secrets.env.lock`). Appending to the
/// whole path (not just the file name) keeps the directory component intact
/// without the extract-fallback-reassemble dance.
fn dev_store_lock_path(store_path: &Path) -> PathBuf {
    let mut lock = store_path.as_os_str().to_os_string();
    lock.push(".lock");
    PathBuf::from(lock)
}

fn resolve_payload<T: serde::de::DeserializeOwned>(
    flags: &OpFlags,
    payload: Option<T>,
) -> Result<T, OpError> {
    if let Some(p) = payload {
        return Ok(p);
    }
    if let Some(path) = &flags.answers {
        return super::load_answers::<T>(path);
    }
    Err(OpError::InvalidArgument(
        "no payload provided: pass --answers <path> or supply the payload directly".to_string(),
    ))
}

fn parse_env_id(raw: &str) -> Result<EnvId, OpError> {
    EnvId::try_from(raw).map_err(|e| OpError::InvalidArgument(format!("environment_id: {e}")))
}

/// The env-must-have-secrets-pack precondition every secrets verb enforces.
/// Shared with `env apply`'s validation (PR-2).
pub(super) fn require_secrets_pack<'a>(
    env: &'a greentic_deploy_spec::Environment,
    env_id: &EnvId,
) -> Result<&'a EnvPackBinding, OpError> {
    env.pack_for_slot(CapabilitySlot::Secrets).ok_or_else(|| {
        OpError::Conflict(format!(
            "env `{env_id}` has no secrets env-pack bound; bind one with `op env-packs add` first"
        ))
    })
}

fn list_schema() -> Value {
    json!({
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "title": "SecretsListPayload",
        "type": "object",
        "required": ["environment_id"],
        "additionalProperties": false,
        "properties": {"environment_id": {"type": "string"}}
    })
}

fn put_schema() -> Value {
    json!({
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "title": "SecretsPutPayload",
        "type": "object",
        "required": ["environment_id", "path", "value"],
        "additionalProperties": false,
        "properties": {
            "environment_id": {"type": "string"},
            "path": {"type": "string", "description": "Relative path under secret://<env>/. For the dev-store backend: <tenant>/<team>/<pack>/<name> (e.g. default/_/messaging-telegram/telegram_bot_token). Use `_` for the default team — a literal `default` team is rejected (the runtime reads the default team as `_`)."},
            "value": {"type": "string"},
            "idempotency_key": {"type": ["string", "null"], "description": "Caller-supplied idempotency key; minted per invocation when absent."}
        }
    })
}

fn get_schema() -> Value {
    json!({
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "title": "SecretsGetPayload",
        "type": "object",
        "required": ["environment_id", "path"],
        "additionalProperties": false,
        "properties": {
            "environment_id": {"type": "string"},
            "path": {"type": "string"},
            "reveal": {"type": "boolean", "default": false, "description": "Include the decrypted value in the outcome. Default false — presence + metadata only."}
        }
    })
}

fn rotate_schema() -> Value {
    json!({
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "title": "SecretsRotatePayload",
        "type": "object",
        "required": ["environment_id", "path"],
        "additionalProperties": false,
        "properties": {
            "environment_id": {"type": "string"},
            "path": {"type": "string"}
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::tests_common::{make_binding, make_env};
    use tempfile::tempdir;

    fn env_with_secrets() -> greentic_deploy_spec::Environment {
        env_with_secrets_kind("greentic.secrets.dev-store@1.0.0")
    }

    /// A store-aligned credentials ref (`secret://<env>/<tenant>/<team>/<pack>/<name>`)
    /// and its `secrets://` store URI — the deployer's bound ServiceAccount token.
    const CREDS_REF: &str = "secret://local/default/_/k8s-deployer/sa_token";
    const CREDS_STORE_URI: &str = "secrets://local/default/_/k8s-deployer/sa_token";

    fn env_with_credentials_ref(ref_str: &str) -> greentic_deploy_spec::Environment {
        let mut env = make_env("local");
        env.credentials_ref = Some(SecretRef::try_new(ref_str).expect("well-formed ref"));
        env
    }

    #[test]
    fn resolve_credentials_token_none_when_no_ref() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        let env = make_env("local");
        store.save(&env).unwrap();
        let env_id = EnvId::try_from("local").unwrap();
        assert_eq!(
            resolve_credentials_token(&store, &env, &env_id).unwrap(),
            None
        );
    }

    #[test]
    fn resolve_credentials_token_reads_from_env_dev_store() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        let env = env_with_credentials_ref(CREDS_REF);
        store.save(&env).unwrap();
        let env_id = EnvId::try_from("local").unwrap();
        // Seed the token where `op secrets put` would write it, then resolve it.
        let dev_path = resolve_dev_store_path(&store.env_dir(&env_id).unwrap(), None);
        dev_store_put(&dev_path, CREDS_STORE_URI, "sa-bearer-xyz").unwrap();
        assert_eq!(
            resolve_credentials_token(&store, &env, &env_id).unwrap(),
            Some("sa-bearer-xyz".to_string())
        );
    }

    #[test]
    fn resolve_credentials_token_fails_closed_when_ref_present_but_unresolved() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        let env = env_with_credentials_ref(CREDS_REF);
        store.save(&env).unwrap();
        let env_id = EnvId::try_from("local").unwrap();
        // No material seeded anywhere → fail closed rather than silently
        // falling back to ambient identity.
        let err = resolve_credentials_token(&store, &env, &env_id).unwrap_err();
        assert!(matches!(err, OpError::Conflict(_)), "got {err:?}");
    }

    #[test]
    fn resolve_credentials_token_accepts_the_bootstrap_advertised_ref_shape() {
        // The K8s bootstrap README tells operators to bind
        // `secret://<env>/<DEPLOYER_TOKEN_STORE_PATH>`. That exact shape must be
        // store-aligned so the resolver can read it — regression for a ref that
        // `SecretRef::to_store_uri` would reject (e.g. the old `…/k8s/deployer-token`).
        use crate::env_packs::k8s::bootstrap::DEPLOYER_TOKEN_STORE_PATH;
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        let ref_str = format!("secret://local/{DEPLOYER_TOKEN_STORE_PATH}");
        let secret_ref = SecretRef::try_new(&ref_str).expect("documented ref must be well-formed");
        let env = env_with_credentials_ref(&ref_str);
        store.save(&env).unwrap();
        let env_id = EnvId::try_from("local").unwrap();
        // Seed at the store URI the documented ref maps to (this conversion is
        // exactly what the resolver does — and what the old shape failed).
        let store_uri =
            secret_ref_to_store_uri(&secret_ref).expect("documented ref is store-aligned");
        let dev_path = resolve_dev_store_path(&store.env_dir(&env_id).unwrap(), None);
        dev_store_put(&dev_path, &store_uri, "sa-bearer-doc").unwrap();
        assert_eq!(
            resolve_credentials_token(&store, &env, &env_id).unwrap(),
            Some("sa-bearer-doc".to_string())
        );
    }

    #[test]
    fn list_reports_namespace_and_kind() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        store.save(&env_with_secrets()).unwrap();
        let outcome = list(
            &store,
            &OpFlags::default(),
            Some(SecretsListPayload {
                environment_id: "local".to_string(),
            }),
        )
        .unwrap();
        assert_eq!(
            outcome.result.get("secrets_kind").and_then(|v| v.as_str()),
            Some("greentic.secrets.dev-store@1.0.0")
        );
        assert_eq!(
            outcome.result.get("namespace").and_then(|v| v.as_str()),
            Some("secret://local/")
        );
    }

    #[test]
    fn list_rejects_env_without_secrets_pack() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        store.save(&make_env("local")).unwrap();
        let err = list(
            &store,
            &OpFlags::default(),
            Some(SecretsListPayload {
                environment_id: "local".to_string(),
            }),
        )
        .unwrap_err();
        assert!(matches!(err, OpError::Conflict(_)), "got {err:?}");
    }

    fn env_with_secrets_kind(kind: &str) -> greentic_deploy_spec::Environment {
        let mut env = make_env("local");
        env.packs.push(make_binding(CapabilitySlot::Secrets, kind));
        env
    }

    fn read_back(store_path: &str, uri: &str) -> Vec<u8> {
        crate::cli::tests_common::dev_store_read(Path::new(store_path), uri)
    }

    #[test]
    fn put_vault_requires_tenant_owned_env() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        // A Vault-bound env with no tenant owner: seeding must fail closed
        // before any Vault I/O, because the runtime scopes a Vault SecretsCore
        // to the env owner (greentic-start #305).
        store
            .save(&env_with_secrets_kind("greentic.secrets.vault@0.1.0"))
            .unwrap();
        let err = put(
            &store,
            &OpFlags::default(),
            Some(SecretsPutPayload {
                environment_id: "local".to_string(),
                path: "tenant-default/_/messaging-telegram/telegram_bot_token".to_string(),
                value: "tok-dummy-123".to_string(),
                idempotency_key: None,
            }),
        )
        .unwrap_err();
        match err {
            OpError::InvalidArgument(m) => assert!(m.contains("tenant-owned"), "msg: {m}"),
            other => panic!("expected InvalidArgument, got {other:?}"),
        }
    }

    fn vault_backend_fixture(
        namespace: Option<&str>,
    ) -> crate::env_packs::k8s::manifests::VaultBackend {
        use crate::env_packs::k8s::manifests::{
            VAULT_DEFAULT_AUTH_MOUNT, VAULT_DEFAULT_KV_MOUNT, VAULT_DEFAULT_KV_PREFIX,
            VAULT_DEFAULT_TRANSIT_KEY, VAULT_DEFAULT_TRANSIT_MOUNT, VaultBackend,
        };
        VaultBackend {
            addr: "http://vault.example:8200".to_string(),
            k8s_role: "gtc-worker".to_string(),
            kv_mount: VAULT_DEFAULT_KV_MOUNT.to_string(),
            kv_prefix: VAULT_DEFAULT_KV_PREFIX.to_string(),
            auth_mount: VAULT_DEFAULT_AUTH_MOUNT.to_string(),
            transit_mount: VAULT_DEFAULT_TRANSIT_MOUNT.to_string(),
            transit_key: VAULT_DEFAULT_TRANSIT_KEY.to_string(),
            namespace: namespace.map(str::to_string),
        }
    }

    #[test]
    fn vault_seed_path_consistency_accepts_defaults_with_no_ambient() {
        // All-default binding + nothing exported ⇒ effective values == defaults.
        let vault = vault_backend_fixture(None);
        assert!(vault_seed_path_consistency(&vault, |_| None).is_ok());
    }

    #[test]
    fn vault_seed_path_consistency_rejects_kv_prefix_mismatch() {
        let mut vault = vault_backend_fixture(None);
        vault.kv_prefix = "tenant-a".to_string();
        // Ambient unset ⇒ effective prefix = default `greentic` != `tenant-a`.
        let err = vault_seed_path_consistency(&vault, |_| None).unwrap_err();
        match err {
            OpError::InvalidArgument(m) => assert!(m.contains("VAULT_KV_PREFIX"), "msg: {m}"),
            other => panic!("expected InvalidArgument, got {other:?}"),
        }
    }

    #[test]
    fn vault_seed_path_consistency_requires_ambient_namespace_when_binding_sets_one() {
        let vault = vault_backend_fixture(Some("team-a"));
        // Binding namespace `team-a`, ambient unset ⇒ effective `` != `team-a`.
        let err = vault_seed_path_consistency(&vault, |_| None).unwrap_err();
        match err {
            OpError::InvalidArgument(m) => assert!(m.contains("VAULT_NAMESPACE"), "msg: {m}"),
            other => panic!("expected InvalidArgument, got {other:?}"),
        }
    }

    #[test]
    fn vault_seed_path_consistency_rejects_stray_namespace_when_binding_has_none() {
        let vault = vault_backend_fixture(None);
        // Binding has no namespace, but the operator's env sets one ⇒ the seed
        // would land in `team-b` while the (namespace-less) worker reads root.
        let err = vault_seed_path_consistency(&vault, |var| {
            (var == "VAULT_NAMESPACE").then(|| "team-b".to_string())
        })
        .unwrap_err();
        match err {
            OpError::InvalidArgument(m) => assert!(m.contains("VAULT_NAMESPACE"), "msg: {m}"),
            other => panic!("expected InvalidArgument, got {other:?}"),
        }
    }

    #[test]
    fn vault_seed_path_consistency_accepts_matching_namespace() {
        let vault = vault_backend_fixture(Some("team-a"));
        let result = vault_seed_path_consistency(&vault, |var| {
            (var == "VAULT_NAMESPACE").then(|| "team-a".to_string())
        });
        assert!(result.is_ok());
    }

    #[test]
    fn put_non_dev_store_backend_returns_not_yet_implemented() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        store
            .save(&env_with_secrets_kind("greentic.secrets.aws-sm@1.0.0"))
            .unwrap();
        let err = put(
            &store,
            &OpFlags::default(),
            Some(SecretsPutPayload {
                environment_id: "local".to_string(),
                path: "credentials/aws".to_string(),
                value: "secret-material".to_string(),
                idempotency_key: None,
            }),
        )
        .unwrap_err();
        assert!(matches!(err, OpError::NotYetImplemented(_)), "got {err:?}");
    }

    #[test]
    fn put_writes_through_to_env_dev_store() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        store.save(&env_with_secrets()).unwrap();
        let outcome = put(
            &store,
            &OpFlags::default(),
            Some(SecretsPutPayload {
                environment_id: "local".to_string(),
                path: "default/_/messaging-telegram/telegram_bot_token".to_string(),
                value: "tok-dummy-123".to_string(),
                idempotency_key: None,
            }),
        )
        .unwrap();
        let result = &outcome.result;
        assert_eq!(
            result.get("store_uri").and_then(|v| v.as_str()),
            Some("secrets://local/default/_/messaging-telegram/telegram_bot_token")
        );
        assert_eq!(result.get("written").and_then(|v| v.as_bool()), Some(true));
        // The outcome must never echo the value.
        let envelope = serde_json::to_string(&outcome).unwrap();
        assert!(!envelope.contains("tok-dummy-123"));
        let store_path = result
            .get("store_path")
            .and_then(|v| v.as_str())
            .expect("store_path in outcome");
        let bytes = read_back(
            store_path,
            "secrets://local/default/_/messaging-telegram/telegram_bot_token",
        );
        assert_eq!(bytes, b"tok-dummy-123".to_vec());
    }

    #[test]
    fn put_rejects_default_team_segment() {
        // The runtime reads the default team as `_`; a literal `default`
        // segment would be written but never looked up.
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        store.save(&env_with_secrets()).unwrap();
        for team in ["default", "Default", "DEFAULT"] {
            let err = put(
                &store,
                &OpFlags::default(),
                Some(SecretsPutPayload {
                    environment_id: "local".to_string(),
                    path: format!("acme/{team}/messaging-telegram/telegram_bot_token"),
                    value: "tok-dummy".to_string(),
                    idempotency_key: None,
                }),
            )
            .unwrap_err();
            assert!(
                matches!(&err, OpError::InvalidArgument(msg) if msg.contains('_')),
                "team `{team}` got {err:?}"
            );
        }
    }

    #[test]
    fn canonical_team_accepts_placeholder_and_real_teams() {
        // The `_` placeholder IS the canonical team-less segment. Routing the
        // validator through the lib's `normalize_team` (which returns `None`
        // for `_`) must not make the documented `default/_/...` path
        // unwritable — regression for the secrets-lib consolidation.
        assert!(
            is_canonical_team("_"),
            "`_` is the canonical team-less segment"
        );
        assert!(is_canonical_team("legal"), "a real team name is canonical");
        assert!(!is_canonical_team("default"));
        assert!(!is_canonical_team("Default"));
        assert!(!is_canonical_team(""));
        assert!(!is_canonical_team(" _ "));
    }

    #[test]
    fn concurrent_puts_do_not_lose_writes() {
        // The dev backend is load-snapshot / persist-full-snapshot; without
        // the sidecar flock spanning open→put, concurrent writers lose
        // updates silently (each persists a snapshot missing the other's
        // key). With the lock, every key must survive.
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        store.save(&env_with_secrets()).unwrap();
        let names: Vec<String> = (0..8).map(|i| format!("concurrent_key_{i}")).collect();
        let store = &store;
        std::thread::scope(|scope| {
            for name in &names {
                scope.spawn(move || {
                    let outcome = put(
                        store,
                        &OpFlags::default(),
                        Some(SecretsPutPayload {
                            environment_id: "local".to_string(),
                            path: format!("default/_/demo-pack/{name}"),
                            value: format!("value-{name}"),
                            idempotency_key: None,
                        }),
                    )
                    .unwrap();
                    assert_eq!(
                        outcome.result.get("written").and_then(|v| v.as_bool()),
                        Some(true)
                    );
                });
            }
        });
        let store_path = dir
            .path()
            .join("local")
            .join(DEV_STORE_RELATIVE)
            .display()
            .to_string();
        for name in &names {
            let bytes = read_back(
                &store_path,
                &format!("secrets://local/default/_/demo-pack/{name}"),
            );
            assert_eq!(bytes, format!("value-{name}").into_bytes());
        }
    }

    #[test]
    fn dev_store_lock_path_is_sidecar() {
        assert_eq!(
            dev_store_lock_path(Path::new("/x/.greentic/dev/.dev.secrets.env")),
            Path::new("/x/.greentic/dev/.dev.secrets.env.lock")
        );
        assert_eq!(
            dev_store_lock_path(Path::new("state/dev-store.dat")),
            Path::new("state/dev-store.dat.lock")
        );
    }

    #[test]
    fn put_rejects_non_canonical_name_segment() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        store.save(&env_with_secrets()).unwrap();
        let err = put(
            &store,
            &OpFlags::default(),
            Some(SecretsPutPayload {
                environment_id: "local".to_string(),
                path: "default/_/messaging-telegram/TELEGRAM-BOT-TOKEN".to_string(),
                value: "tok-dummy".to_string(),
                idempotency_key: None,
            }),
        )
        .unwrap_err();
        assert!(matches!(err, OpError::InvalidArgument(_)), "got {err:?}");
    }

    #[test]
    fn put_rejects_wrong_depth_path() {
        // `DevStore::put` only accepts the 5-segment `secrets://` shape; the
        // verb rejects other depths upfront with a teachable message.
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        store.save(&env_with_secrets()).unwrap();
        for path in ["credentials/aws", "default/_/pack/extra/name", "a//b/c"] {
            let err = put(
                &store,
                &OpFlags::default(),
                Some(SecretsPutPayload {
                    environment_id: "local".to_string(),
                    path: path.to_string(),
                    value: "v".to_string(),
                    idempotency_key: None,
                }),
            )
            .unwrap_err();
            assert!(
                matches!(&err, OpError::InvalidArgument(msg) if msg.contains("<tenant>/<team>/<pack>/<name>")),
                "path `{path}` got {err:?}"
            );
        }
    }

    #[test]
    fn resolve_dev_store_path_override_wins() {
        let dir = tempdir().unwrap();
        let override_path = dir.path().join("custom.dat");
        assert_eq!(
            resolve_dev_store_path(dir.path(), Some(override_path.clone())),
            override_path
        );
    }

    #[test]
    fn resolve_dev_store_path_prefers_existing_candidate() {
        let dir = tempdir().unwrap();
        let fallback = dir.path().join(DEV_STORE_STATE_RELATIVE);
        std::fs::create_dir_all(fallback.parent().unwrap()).unwrap();
        std::fs::write(&fallback, b"").unwrap();
        assert_eq!(resolve_dev_store_path(dir.path(), None), fallback);
        // Once the primary exists it wins over the state fallback.
        let primary = dir.path().join(DEV_STORE_RELATIVE);
        std::fs::create_dir_all(primary.parent().unwrap()).unwrap();
        std::fs::write(&primary, b"").unwrap();
        assert_eq!(resolve_dev_store_path(dir.path(), None), primary);
    }

    #[test]
    fn resolve_dev_store_path_defaults_to_primary() {
        let dir = tempdir().unwrap();
        assert_eq!(
            resolve_dev_store_path(dir.path(), None),
            dir.path().join(DEV_STORE_RELATIVE)
        );
    }

    #[test]
    fn canonical_name_fixed_points() {
        assert!(is_canonical_secret_name("telegram_bot_token"));
        assert!(is_canonical_secret_name("a1"));
        assert!(!is_canonical_secret_name(""));
        assert!(!is_canonical_secret_name("TELEGRAM_BOT_TOKEN"));
        assert!(!is_canonical_secret_name("bot-token"));
        assert!(!is_canonical_secret_name("_leading"));
        assert!(!is_canonical_secret_name("trailing_"));
        assert!(!is_canonical_secret_name("double__underscore"));
    }

    #[test]
    fn put_rejects_empty_value() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        store.save(&env_with_secrets()).unwrap();
        let err = put(
            &store,
            &OpFlags::default(),
            Some(SecretsPutPayload {
                environment_id: "local".to_string(),
                path: "x".to_string(),
                value: "".to_string(),
                idempotency_key: None,
            }),
        )
        .unwrap_err();
        assert!(matches!(err, OpError::InvalidArgument(_)), "got {err:?}");
    }

    #[test]
    fn get_reads_back_put_value_from_dev_store() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        store.save(&env_with_secrets()).unwrap();
        let path = "default/_/messaging-telegram/telegram_bot_token";
        put(
            &store,
            &OpFlags::default(),
            Some(SecretsPutPayload {
                environment_id: "local".to_string(),
                path: path.to_string(),
                value: "tok-roundtrip-456".to_string(),
                idempotency_key: None,
            }),
        )
        .unwrap();

        // reveal=false → present, but the value never appears in the envelope.
        let outcome = get(
            &store,
            &OpFlags::default(),
            Some(SecretsGetPayload {
                environment_id: "local".to_string(),
                path: path.to_string(),
                reveal: false,
            }),
        )
        .unwrap();
        assert_eq!(
            outcome.result.get("present").and_then(|v| v.as_bool()),
            Some(true)
        );
        assert!(outcome.result.get("value").is_none());
        let envelope = serde_json::to_string(&outcome).unwrap();
        assert!(!envelope.contains("tok-roundtrip-456"));

        // reveal=true → the decrypted value is included.
        let outcome = get(
            &store,
            &OpFlags::default(),
            Some(SecretsGetPayload {
                environment_id: "local".to_string(),
                path: path.to_string(),
                reveal: true,
            }),
        )
        .unwrap();
        assert_eq!(
            outcome.result.get("value").and_then(|v| v.as_str()),
            Some("tok-roundtrip-456")
        );
    }

    #[test]
    fn get_absent_key_returns_present_false() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        store.save(&env_with_secrets()).unwrap();
        let outcome = get(
            &store,
            &OpFlags::default(),
            Some(SecretsGetPayload {
                environment_id: "local".to_string(),
                path: "default/_/messaging-telegram/never_written".to_string(),
                reveal: true,
            }),
        )
        .unwrap();
        assert_eq!(
            outcome.result.get("present").and_then(|v| v.as_bool()),
            Some(false)
        );
        assert!(outcome.result.get("value").is_none());
    }

    #[test]
    fn get_vault_requires_tenant_owned_env() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        // Mirror put: a Vault env with no tenant owner must fail closed before
        // any Vault I/O (the runtime scopes a Vault SecretsCore to the owner).
        store
            .save(&env_with_secrets_kind("greentic.secrets.vault@0.1.0"))
            .unwrap();
        let err = get(
            &store,
            &OpFlags::default(),
            Some(SecretsGetPayload {
                environment_id: "local".to_string(),
                path: "tenant-default/_/messaging-telegram/telegram_bot_token".to_string(),
                reveal: false,
            }),
        )
        .unwrap_err();
        match err {
            OpError::InvalidArgument(m) => assert!(m.contains("tenant-owned"), "msg: {m}"),
            other => panic!("expected InvalidArgument, got {other:?}"),
        }
    }

    #[test]
    fn get_non_dev_store_backend_returns_not_yet_implemented() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        store
            .save(&env_with_secrets_kind("greentic.secrets.aws-sm@1.0.0"))
            .unwrap();
        let err = get(
            &store,
            &OpFlags::default(),
            Some(SecretsGetPayload {
                environment_id: "local".to_string(),
                path: "default/_/pack/key_name".to_string(),
                reveal: false,
            }),
        )
        .unwrap_err();
        assert!(matches!(err, OpError::NotYetImplemented(_)), "got {err:?}");
    }
}