secretspec 0.15.0

Declarative secrets, every environment, any provider
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
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
//! # SecretSpec Core Configuration Types
//!
//! This module provides the core type definitions and parsing logic for the SecretSpec
//! configuration system.
//!
//! SecretSpec uses a declarative TOML-based configuration format to define secrets
//! and their requirements across different environments (profiles). The type system
//! supports configuration inheritance, allowing projects to extend shared configurations
//! while maintaining type safety and preventing circular dependencies.
//!
//! ## Key Features
//!
//! - **Profile-based configuration**: Define different sets of secrets for development, staging, production, etc.
//! - **Configuration inheritance**: Extend other configurations to share common secrets
//! - **Provider abstraction**: Support for multiple secret storage backends
//! - **Type-safe parsing**: Strong typing with comprehensive error handling
//!
//! ## Configuration Structure
//!
//! A typical `secretspec.toml` file has this structure:
//!
//! ```toml
//! [project]
//! name = "my-app"
//! revision = "1.0"
//! extends = ["../shared/common"]  # Optional inheritance
//!
//! [profiles.default]
//! DATABASE_URL = { description = "PostgreSQL connection string", required = true }
//! API_KEY = { description = "External API key", required = false, default = "dev-key" }
//!
//! [profiles.production]
//! DATABASE_URL = { description = "Production database", required = true }
//! ```

use crate::manifest::CompiledManifest;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet, hash_map};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::str::FromStr;

/// Where one credential required by a provider comes from.
///
/// Written in an alias's `credentials` map either as a bare provider spec,
/// which reads the credential from that provider at the convention path for
/// the active project and profile:
///
/// ```toml
/// credentials = { access_token = "keyring" }
/// ```
///
/// or as a table that pins the exact location with the same `ref` coordinates a
/// secret uses:
///
/// ```toml
/// credentials = { role_id = { provider = "onepassword", ref = { vault = "Infra", item = "approle", field = "role_id" } } }
/// ```
///
/// Reusing `ref` means provider credentials are addressed exactly like every
/// other secret — no separate storage convention. A bare spec round-trips back
/// to a bare string.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CredentialSource {
    /// Provider spec (alias, bare provider name, or URI) supplying the credential.
    pub provider: String,
    /// Native coordinates within that provider. When absent, the credential is
    /// read at the convention path (the credential name as key) for the active
    /// project and profile.
    pub reference: Option<NativeAddress>,
}

impl CredentialSource {
    /// A source that reads from `provider` using convention naming.
    pub fn from_provider(provider: impl Into<String>) -> Self {
        Self {
            provider: provider.into(),
            reference: None,
        }
    }
}

impl From<String> for CredentialSource {
    fn from(provider: String) -> Self {
        Self::from_provider(provider)
    }
}

impl From<&str> for CredentialSource {
    fn from(provider: &str) -> Self {
        Self::from_provider(provider)
    }
}

impl Serialize for CredentialSource {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match &self.reference {
            // A ref-less source round-trips back to the bare-string form.
            None => serializer.serialize_str(&self.provider),
            Some(reference) => {
                use serde::ser::SerializeStruct;
                let mut table = serializer.serialize_struct("CredentialSource", 2)?;
                table.serialize_field("provider", &self.provider)?;
                table.serialize_field("ref", reference)?;
                table.end()
            }
        }
    }
}

impl<'de> Deserialize<'de> for CredentialSource {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct SourceVisitor;

        impl<'de> serde::de::Visitor<'de> for SourceVisitor {
            type Value = CredentialSource;

            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str("a provider spec string or a { provider, ref } table")
            }

            fn visit_str<E: serde::de::Error>(self, provider: &str) -> Result<CredentialSource, E> {
                Ok(CredentialSource::from_provider(provider))
            }

            fn visit_map<M: serde::de::MapAccess<'de>>(
                self,
                map: M,
            ) -> Result<CredentialSource, M::Error> {
                #[derive(Deserialize)]
                #[serde(deny_unknown_fields)]
                struct Table {
                    provider: String,
                    #[serde(default, rename = "ref")]
                    reference: Option<NativeAddress>,
                }
                let table = Table::deserialize(serde::de::value::MapAccessDeserializer::new(map))?;
                Ok(CredentialSource {
                    provider: table.provider,
                    reference: table.reference,
                })
            }
        }

        deserializer.deserialize_any(SourceVisitor)
    }
}

/// A provider alias: a provider URI plus an optional credential-source map.
///
/// In TOML an alias is written either as a bare string, which is just the URI:
///
/// ```toml
/// [providers]
/// keyring = "keyring://"
/// ```
///
/// or as a table carrying a `credentials` map, whose entries name semantic
/// credentials the provider needs and the provider spec to source them from:
///
/// ```toml
/// [providers]
/// bws = { uri = "bws://project-uuid", credentials = { access_token = "keyring" } }
/// ```
///
/// The two forms round-trip losslessly: an alias with no credentials serializes
/// back to a bare string, so existing configs are untouched.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ProviderAlias {
    /// The provider URI (e.g. `keyring://`, `bws://project-uuid`).
    pub uri: String,
    /// Semantic credential name to the [`CredentialSource`] that supplies it.
    /// Empty for a bare string alias, so "declares no credentials" has exactly
    /// one representation.
    pub credentials: HashMap<String, CredentialSource>,
}

impl ProviderAlias {
    /// A bare alias carrying only a URI and no credentials.
    pub fn from_uri(uri: impl Into<String>) -> Self {
        Self {
            uri: uri.into(),
            credentials: HashMap::new(),
        }
    }
}

impl From<String> for ProviderAlias {
    fn from(uri: String) -> Self {
        Self::from_uri(uri)
    }
}

impl From<&str> for ProviderAlias {
    fn from(uri: &str) -> Self {
        Self::from_uri(uri)
    }
}

impl std::fmt::Display for ProviderAlias {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.uri)?;
        if !self.credentials.is_empty() {
            let mut names: Vec<&str> = self.credentials.keys().map(String::as_str).collect();
            names.sort();
            write!(f, " (credentials: {})", names.join(", "))?;
        }
        Ok(())
    }
}

impl Serialize for ProviderAlias {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        if self.credentials.is_empty() {
            // A bare alias serializes back to the plain-string form, so an alias
            // that was written as a string round-trips unchanged.
            serializer.serialize_str(&self.uri)
        } else {
            use serde::ser::SerializeStruct;
            let mut table = serializer.serialize_struct("ProviderAlias", 2)?;
            table.serialize_field("uri", &self.uri)?;
            table.serialize_field("credentials", &self.credentials)?;
            table.end()
        }
    }
}

impl<'de> Deserialize<'de> for ProviderAlias {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct AliasVisitor;

        impl<'de> serde::de::Visitor<'de> for AliasVisitor {
            type Value = ProviderAlias;

            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str("a provider URI string or a { uri, credentials } table")
            }

            fn visit_str<E: serde::de::Error>(self, uri: &str) -> Result<ProviderAlias, E> {
                Ok(ProviderAlias::from_uri(uri))
            }

            fn visit_map<M: serde::de::MapAccess<'de>>(
                self,
                map: M,
            ) -> Result<ProviderAlias, M::Error> {
                // A dedicated struct gives precise field-level errors (unknown
                // key, missing `uri`) rather than the opaque message an
                // `#[serde(untagged)]` enum would produce on any typo.
                #[derive(Deserialize)]
                #[serde(deny_unknown_fields)]
                struct Table {
                    uri: String,
                    #[serde(default)]
                    credentials: Option<HashMap<String, CredentialSource>>,
                }
                let table = Table::deserialize(serde::de::value::MapAccessDeserializer::new(map))?;
                Ok(ProviderAlias {
                    uri: table.uri,
                    credentials: table.credentials.unwrap_or_default(),
                })
            }
        }

        deserializer.deserialize_any(AliasVisitor)
    }
}

/// The root configuration structure for a SecretSpec project.
///
/// This is the top-level type that represents the entire `secretspec.toml` file.
/// It contains project metadata and profile-specific secret definitions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    /// Project metadata including name, revision, and optional inheritance
    pub project: Project,
    /// Map of profile names to their configurations (e.g., "default", "production", "staging")
    pub profiles: HashMap<String, Profile>,
    /// Project-level provider aliases that map alias names to provider URIs.
    ///
    /// Take precedence over aliases in the user-global config
    /// (`~/.config/secretspec/config.toml`), so teams can check vault mappings
    /// into version control instead of replicating them on every machine.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub providers: Option<HashMap<String, ProviderAlias>>,
}

impl Config {
    /// Validate the configuration.
    ///
    /// Ensures that:
    /// - Project name is not empty
    /// - At least one profile is defined
    /// - All secrets have valid configurations
    /// - Secret names are valid identifiers
    ///
    /// # Errors
    ///
    /// Returns a `ParseError` if validation fails.
    pub fn validate(&self) -> Result<(), ParseError> {
        self.validate_and_compile().map(|_| ())
    }

    /// Validate and return the compiled manifest, so callers that also need the
    /// effective view (e.g. [`crate::Secrets::load_from`]) reuse the single
    /// compile validation already performed instead of recompiling.
    pub(crate) fn validate_and_compile(&self) -> Result<CompiledManifest, ParseError> {
        if self.project.name.is_empty() {
            return Err(ParseError::Validation(
                "Project name cannot be empty".into(),
            ));
        }

        if self.profiles.is_empty() {
            return Err(ParseError::Validation(
                "At least one profile must be defined".into(),
            ));
        }

        // Raw syntax checks stay on the document model; effective semantic
        // checks consume the same compiled manifest as runtime and codegen.
        // Validate `default` first, then remaining profiles in name order so
        // error attribution is deterministic.
        let compiled = CompiledManifest::compile(self);
        let default_profile = self.profiles.get("default");
        if let Some(default_profile) = default_profile {
            default_profile
                .validate_raw(false)
                .map_err(|e| ParseError::Validation(format!("Profile 'default': {}", e)))?;
            validate_compiled_profile(&compiled, "default")?;
        }

        let mut profile_names: Vec<&String> = self
            .profiles
            .keys()
            .filter(|name| name.as_str() != "default")
            .collect();
        profile_names.sort();

        for profile_name in profile_names {
            self.profiles[profile_name]
                .validate_raw(default_profile.is_some())
                .map_err(|e| {
                    ParseError::Validation(format!("Profile '{}': {}", profile_name, e))
                })?;
            validate_compiled_profile(&compiled, profile_name)?;
        }

        Ok(compiled)
    }

    /// Get a profile by name.
    pub fn get_profile(&self, name: &str) -> Option<&Profile> {
        self.profiles.get(name)
    }

    /// Get a mutable profile by name.
    pub fn get_profile_mut(&mut self, name: &str) -> Option<&mut Profile> {
        self.profiles.get_mut(name)
    }

    /// Overlay a later manifest document onto an earlier one.
    ///
    /// A source graph is linearized from least to most specific, so folding it
    /// means every later source wins while fields the later source leaves absent
    /// continue to inherit from the earlier one.
    fn overlay_with(&mut self, later: Config) {
        let inherited_require_reason = self.project.require_reason;
        self.project = later.project;
        if self.project.require_reason.is_none() {
            self.project.require_reason = inherited_require_reason;
        }

        for (profile_name, later_profile) in later.profiles {
            match self.profiles.get_mut(&profile_name) {
                Some(profile) => profile.overlay_with(later_profile),
                None => {
                    self.profiles.insert(profile_name, later_profile);
                }
            }
        }

        if let Some(later_providers) = later.providers {
            self.providers
                .get_or_insert_with(HashMap::new)
                .extend(later_providers);
        }
    }

    // Internal methods

    fn parse_document(content: &str) -> Result<Self, ParseError> {
        let config: Config = toml::from_str(content)?;
        if config.project.revision != "1.0" {
            return Err(ParseError::UnsupportedRevision(config.project.revision));
        }
        Ok(config)
    }
}

fn validate_compiled_profile(
    manifest: &CompiledManifest,
    profile_name: &str,
) -> Result<(), ParseError> {
    let profile = manifest
        .profile(profile_name)
        .expect("compiled profiles mirror parsed profiles");
    for (name, secret) in &profile.secrets {
        secret.config.validate_effective().map_err(|e| {
            ParseError::Validation(format!(
                "Profile '{}': Secret '{}': {}",
                profile_name, name, e
            ))
        })?;
    }
    Ok(())
}

/// Loads an inheritance graph and emits each source exactly once in deterministic
/// post-order. `active` detects genuine back-edges; `emitted` separately handles
/// shared ancestors, which are valid DAG nodes rather than cycles.
struct ConfigGraphLoader {
    active: HashSet<PathBuf>,
    emitted: HashSet<PathBuf>,
    documents: Vec<Config>,
}

impl ConfigGraphLoader {
    fn load(path: &Path) -> Result<Config, ParseError> {
        let mut loader = Self {
            active: HashSet::new(),
            emitted: HashSet::new(),
            documents: Vec::new(),
        };
        loader.visit(path)?;

        let mut documents = loader.documents.into_iter();
        let mut merged = documents
            .next()
            .expect("visiting a root always emits at least one document");
        for document in documents {
            merged.overlay_with(document);
        }
        Ok(merged)
    }

    fn visit(&mut self, path: &Path) -> Result<(), ParseError> {
        let canonical_path = path.canonicalize().map_err(|e| {
            ParseError::Io(io::Error::new(
                e.kind(),
                format!("Failed to resolve path {}: {}", path.display(), e),
            ))
        })?;

        if self.emitted.contains(&canonical_path) {
            return Ok(());
        }
        if !self.active.insert(canonical_path.clone()) {
            return Err(ParseError::CircularDependency(format!(
                "Configuration file {} is part of a circular dependency chain",
                canonical_path.display()
            )));
        }

        let content = fs::read_to_string(&canonical_path)?;
        let config = Config::parse_document(&content)?;
        // Resolve `extends` relative to the manifest's referenced location, not
        // its canonicalized target: a symlinked manifest inherits from paths
        // relative to the symlink, not to the file it points at. Cycle detection
        // and dedup still key on `canonical_path`.
        let base_dir = path.parent().unwrap_or(Path::new("."));
        for extend_path in config.project.extends.iter().flatten() {
            let joined_path = base_dir.join(extend_path);
            let full_path = if extend_path.ends_with(".toml") {
                joined_path
            } else {
                joined_path.join("secretspec.toml")
            };
            if !full_path.exists() {
                return Err(ParseError::ExtendedConfigNotFound(
                    full_path.display().to_string(),
                ));
            }
            self.visit(&full_path)?;
        }

        self.active.remove(&canonical_path);
        self.emitted.insert(canonical_path);
        self.documents.push(config);
        Ok(())
    }
}

impl FromStr for Config {
    type Err = ParseError;

    /// Parse configuration from a TOML string.
    ///
    /// Note: Configuration inheritance (`extends`) is not supported when parsing
    /// from a string since there's no base path to resolve relative paths.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse_document(s)
    }
}

impl TryFrom<&Path> for Config {
    type Error = ParseError;

    /// Load configuration from a file path.
    ///
    /// This supports configuration inheritance via `extends` and circular dependency detection.
    fn try_from(path: &Path) -> Result<Self, Self::Error> {
        ConfigGraphLoader::load(path)
    }
}

/// When secretspec requires a reason for secret access.
///
/// Parsed from `[project].require_reason`, which accepts a boolean or the string
/// `"agents"`. Defaults to [`RequireReason::Agents`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RequireReason {
    /// Never require a reason.
    Never,
    /// Require a reason only when an AI agent is detected (the default).
    #[default]
    Agents,
    /// Require a reason from every caller.
    Always,
}

impl Serialize for RequireReason {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            RequireReason::Never => serializer.serialize_bool(false),
            RequireReason::Always => serializer.serialize_bool(true),
            RequireReason::Agents => serializer.serialize_str("agents"),
        }
    }
}

impl<'de> Deserialize<'de> for RequireReason {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        // A reason policy is a boolean or the string "agents". A hand-written visitor
        // (rather than an untagged enum) lets serde report a precise, located error for
        // a wrong *type*, not just for unknown strings. For example `require_reason = 1`
        // yields "invalid type: integer `1`, expected a boolean or the string \"agents\"".
        struct RequireReasonVisitor;

        impl serde::de::Visitor<'_> for RequireReasonVisitor {
            type Value = RequireReason;

            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_str(r#"a boolean or the string "agents""#)
            }

            fn visit_bool<E: serde::de::Error>(self, v: bool) -> Result<RequireReason, E> {
                Ok(if v {
                    RequireReason::Always
                } else {
                    RequireReason::Never
                })
            }

            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<RequireReason, E> {
                match v {
                    "agents" => Ok(RequireReason::Agents),
                    other => Err(E::custom(format!(
                        "invalid require_reason value '{other}': expected true, false, or \"agents\""
                    ))),
                }
            }
        }

        deserializer.deserialize_any(RequireReasonVisitor)
    }
}

/// Project metadata and inheritance configuration.
///
/// Contains essential project information and optional configuration inheritance.
/// The `extends` field allows projects to inherit secrets from other configurations,
/// enabling shared configuration patterns across multiple projects.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Project {
    /// The name of the project, used for identification and namespacing
    pub name: String,
    /// Configuration format revision (currently must be "1.0")
    pub revision: String,
    /// Optional list of relative paths to other SecretSpec projects to inherit from
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extends: Option<Vec<String>>,
    /// Policy controlling when secret access must supply a reason. Accepts a boolean
    /// or `"agents"`; enforced by [`crate::Secrets`]. `None` means "unspecified": it
    /// resolves to [`RequireReason::default`] unless a parent config supplies a value
    /// via `extends`, in which case the overlay from that parent fills it in.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub require_reason: Option<RequireReason>,
}

impl Default for Project {
    /// A minimal project: empty name, current revision, no inheritance, unspecified
    /// reason policy. Lets call sites build a `Project` with `..Default::default()`
    /// so adding a field here does not require touching every literal.
    fn default() -> Self {
        Self {
            name: String::new(),
            revision: "1.0".to_string(),
            extends: None,
            require_reason: None,
        }
    }
}

/// Audit logging configuration, parsed from the top-level `[audit]` table in the
/// user-global config (`~/.config/secretspec/config.toml`).
///
/// Auditing is an operator/per-machine concern (where the log lives, whether it is
/// on), so it lives in the user config rather than the project's `secretspec.toml`:
/// a cloned repository must not be able to redirect or silence your local audit
/// log. secretspec records every secret read/write to a local JSON Lines file so
/// that access is reviewable after the fact. Auditing is **on by default**; set
/// `enabled = false` to turn it off. Secret values are never written to the log.
///
/// ```toml
/// [audit]
/// enabled = false
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AuditConfig {
    /// Whether to record secret access. Defaults to `true`.
    pub enabled: bool,
    /// Where to write the JSON Lines log. Must be an absolute path (a leading `~`
    /// is expanded to the home directory); a relative path is rejected and
    /// auditing is disabled, because it would resolve against the current working
    /// directory and scatter the log per-CWD. When unset, defaults to the per-user
    /// XDG state directory (`~/.local/state/secretspec/audit.log` on Linux).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<PathBuf>,
    /// Hard cap on the log file size in bytes (default 1 MiB). At the cap the file
    /// is truncated and restarted; no rotated backups are kept, so the log is a
    /// rolling-by-reset record bounded to this size, not a complete history.
    pub max_size_bytes: u64,
}

impl Default for AuditConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            path: None,
            max_size_bytes: 1_048_576,
        }
    }
}

impl AuditConfig {
    /// The resolved on-disk path: the configured `path` (with a leading `~`
    /// expanded to the home directory), or the default per-user audit log
    /// location when no `path` is set.
    ///
    /// Returns `None` when the location cannot be honored: either no `path` is set
    /// and no default can be determined (no home/state directory), or the
    /// configured `path` is **relative**. A relative path is rejected rather than
    /// resolved against the current working directory — that would write a separate
    /// log in every directory secretspec runs from. Use [`Self::has_relative_path`]
    /// to distinguish the relative-path case for a precise diagnostic.
    pub fn resolved_path(&self) -> Option<PathBuf> {
        match self.path.clone() {
            // Reject a relative configured path; only an absolute one is honored.
            Some(path) => Some(expand_tilde(path)).filter(|p| p.is_absolute()),
            None => default_audit_path(),
        }
    }

    /// Whether a `path` is configured but is not absolute (after `~` expansion).
    /// Such a path is rejected by [`Self::resolved_path`]; this lets callers emit a
    /// "path is not absolute" message instead of a generic "no location" one.
    pub fn has_relative_path(&self) -> bool {
        self.path
            .as_ref()
            .is_some_and(|p| !expand_tilde(p.clone()).is_absolute())
    }
}

/// Shared etcetera arguments identifying secretspec, so the app identity (used
/// to derive config/state/data dirs) lives in a single place.
fn app_strategy_args() -> etcetera::app_strategy::AppStrategyArgs {
    etcetera::app_strategy::AppStrategyArgs {
        top_level_domain: String::new(),
        author: String::new(),
        app_name: "secretspec".into(),
    }
}

/// Default audit log location: the per-user state directory chosen by
/// `choose_app_strategy`. That is the XDG strategy on both Linux and macOS (the
/// CLI convention etcetera uses), so the log lives at
/// `~/.local/state/secretspec/audit.log` on each. The `data_dir` fallback only
/// applies on platforms whose strategy reports no distinct state dir.
fn default_audit_path() -> Option<PathBuf> {
    use etcetera::app_strategy::{AppStrategy, choose_app_strategy};
    let strategy = choose_app_strategy(app_strategy_args()).ok()?;
    let dir = strategy.state_dir().unwrap_or_else(|| strategy.data_dir());
    Some(dir.join("audit.log"))
}

/// Expands a leading `~` (or `~/`) in a configured path to the user's home
/// directory. A documented `path = "~/.local/state/..."` would otherwise become
/// a literal `./~` directory. Paths without a leading `~`, or paths that cannot
/// be resolved to a home directory, are returned unchanged.
fn expand_tilde(path: PathBuf) -> PathBuf {
    let Ok(rest) = path.strip_prefix("~") else {
        return path;
    };
    let Some(home) = home_dir() else {
        return path;
    };
    home.join(rest)
}

/// Best-effort home directory, via etcetera with an `HOME` env fallback.
fn home_dir() -> Option<PathBuf> {
    etcetera::home_dir()
        .ok()
        .or_else(|| std::env::var_os("HOME").map(PathBuf::from))
}

/// Configuration for a specific profile (environment).
///
/// A profile represents a specific environment or context (e.g., "default", "production", "staging").
/// Each profile contains its own set of secret definitions with their requirements.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Profile {
    /// Default configuration for secrets in this profile
    #[serde(skip_serializing_if = "Option::is_none")]
    pub defaults: Option<ProfileDefaults>,
    /// Map of secret names to their configurations, flattened in TOML for cleaner syntax
    #[serde(flatten)]
    pub secrets: HashMap<String, Secret>,
}

/// Default configuration for a profile.
///
/// Provides defaults that apply to all secrets within the profile.
/// Individual secrets can override any of these defaults.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileDefaults {
    /// Default value for the required field of secrets in this profile.
    /// If not specified, secrets default to required=true.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub required: Option<bool>,

    /// Default value to use for secrets in this profile if they are not found.
    /// Individual secrets can override this with their own default value.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,

    /// List of provider aliases to use for secrets in this profile.
    /// Providers are tried in order until one has the secret.
    /// Individual secrets can override this with their own providers field.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub providers: Option<Vec<String>>,
}

impl ProfileDefaults {
    /// Fill fields this table leaves unset from an earlier, less specific
    /// defaults table. Lets `extends` inherit `[profiles.*.defaults]` field by
    /// field, with the later (more specific) document winning.
    fn inherit_missing_from(&mut self, earlier: &ProfileDefaults) {
        self.required = self.required.or(earlier.required);
        if self.default.is_none() {
            self.default = earlier.default.clone();
        }
        if self.providers.is_none() {
            self.providers = earlier.providers.clone();
        }
    }
}

impl Profile {
    /// Create a new empty profile configuration.
    pub fn new() -> Self {
        Self {
            defaults: None,
            secrets: HashMap::new(),
        }
    }

    /// Validate declarations before profile/default inheritance is compiled.
    fn validate_raw(&self, can_inherit_secrets: bool) -> Result<(), String> {
        // A non-default profile may be an empty marker that inherits every
        // secret from `default`. Profiles with nothing to inherit still need
        // to declare at least one secret.
        if self.secrets.is_empty() && !can_inherit_secrets {
            return Err("Profile must define at least one secret".into());
        }

        for name in self.sorted_secret_names() {
            let secret = &self.secrets[&name];
            if !is_valid_identifier(&name) {
                return Err(format!(
                    "Invalid secret name '{}': must be a valid identifier (alphanumeric and underscores, not starting with a number)",
                    name
                ));
            }
            secret
                .validate_required_default()
                .map_err(|e| format!("Secret '{}': {}", name, e))?;
        }

        Ok(())
    }

    /// Overlay a later profile document while inheriting individual default
    /// fields that the later document leaves absent.
    fn overlay_with(&mut self, later: Profile) {
        if let Some(mut later_defaults) = later.defaults {
            if let Some(earlier_defaults) = &self.defaults {
                later_defaults.inherit_missing_from(earlier_defaults);
            }
            self.defaults = Some(later_defaults);
        }
        self.secrets.extend(later.secrets);
    }

    /// Returns an iterator over the secrets in this profile.
    ///
    /// The iterator yields (&String, &Secret) pairs, where the string is the secret name
    /// and the Secret contains the configuration for that secret.
    pub fn iter(&self) -> hash_map::Iter<'_, String, Secret> {
        self.secrets.iter()
    }

    /// Secret names declared in this profile, sorted for deterministic
    /// ordering (grouping, missing lists) instead of the map's hash order.
    pub(crate) fn sorted_secret_names(&self) -> Vec<String> {
        let mut names: Vec<String> = self.secrets.keys().cloned().collect();
        names.sort();
        names
    }
}

impl Default for Profile {
    fn default() -> Self {
        Self::new()
    }
}

impl<'a> IntoIterator for &'a Profile {
    type Item = (&'a String, &'a Secret);
    type IntoIter = hash_map::Iter<'a, String, Secret>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.secrets.iter()
    }
}

impl IntoIterator for Profile {
    type Item = (String, Secret);
    type IntoIter = hash_map::IntoIter<String, Secret>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.secrets.into_iter()
    }
}

/// Configuration for auto-generation of a secret.
///
/// Can be either a simple boolean (`generate = true`) or a table with
/// type-specific options (`generate = { length = 64 }`).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GenerateConfig {
    /// Simple boolean flag to enable/disable generation with defaults
    Bool(bool),
    /// Detailed generation options
    Options(GenerateOptions),
}

impl GenerateConfig {
    /// Returns true if generation is enabled.
    pub fn is_enabled(&self) -> bool {
        match self {
            GenerateConfig::Bool(b) => *b,
            GenerateConfig::Options(_) => true,
        }
    }
}

/// Type-specific options for secret generation.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct GenerateOptions {
    /// Length of generated password (for `password` type)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub length: Option<usize>,
    /// Number of random bytes (for `hex` and `base64` types)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bytes: Option<usize>,
    /// Character set for password generation ("alphanumeric" or "ascii")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub charset: Option<String>,
    /// Shell command to run (for `command` type)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    /// Key size in bits (for `rsa` type, default 2048)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bits: Option<usize>,
}

/// Native coordinates of one externally managed secret: the value of a
/// secret's `ref` field.
///
/// The coordinates carry naming only; *routing* (which store to consult) stays
/// with the ordinary provider resolution (`providers` chains, `--provider`
/// override, defaults). Each provider translates the coordinates into its own
/// namespace — the 1Password item title, the Vault KV path plus field, the AWS
/// secret name plus JSON key, the `.env` key — and rejects coordinates it has
/// no equivalent for, so the same `ref` re-resolves against whichever store
/// routing selects.
///
/// The coordinates are *not* uniformly provider-independent, and this type does
/// not pretend they are:
///
/// - `item` (required) and `field` are shared vocabulary every relevant store
///   maps: a name, and an optional component within it.
/// - `vault`, `section` (1Password), and `version` (GCSM) are coordinates only
///   some stores have an equivalent for. Each is named for the concept, not the
///   vendor, so another store can adopt one by adding it to its
///   [`supported_coords`](crate::provider::Provider::supported_coords); a store
///   that has not rejects it rather than guessing. They are deliberately *not*
///   collapsed into one generalized coordinate: a 1Password vault (a per-secret
///   naming axis) and a Vault mount (set-once connection topology, whose
///   per-secret hierarchy already lives in `item`) are different concepts and
///   should not be forced to look alike. A store whose container is genuinely
///   connection-level (a Vault mount, a GCSM project, an AWS region) takes it
///   from the provider URI instead.
///
/// Unknown TOML keys are rejected at parse time.
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize)]
pub struct NativeAddress {
    /// The store's own name for the secret: item title (1Password, Proton
    /// Pass, LastPass), entry path (pass), KV path (Vault), secret name/ARN
    /// (AWS), secret id (GCSM), key name (BWS, dotenv), variable name (env),
    /// service (keyring).
    pub item: String,
    /// A component within the item: field label (1Password), KV field
    /// (Vault), JSON key (AWS), account (keyring). Providers whose secrets
    /// have no sub-components reject it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub field: Option<String>,
    /// 1Password only: the vault holding the item, overriding the store's
    /// default vault for this secret.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vault: Option<String>,
    /// 1Password only: the section containing the field.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub section: Option<String>,
    /// GCSM only: the secret version to read; defaults to the latest.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
}

impl NativeAddress {
    /// Every coordinate name paired with its value, outer scope first. The
    /// single enumeration that the renderer, the validator, and the
    /// provider-side coordinate rejection all consume, so a new coordinate
    /// cannot be added to one and silently missed by the others.
    pub(crate) fn coordinates(&self) -> [(&'static str, Option<&str>); 5] {
        [
            ("vault", self.vault.as_deref()),
            ("item", Some(self.item.as_str())),
            ("section", self.section.as_deref()),
            ("field", self.field.as_deref()),
            ("version", self.version.as_deref()),
        ]
    }

    /// Canonical single-line rendering for logs and audit events, outer scope
    /// first: `vault=Production item=db field=password`. Only present
    /// coordinates appear.
    pub fn render(&self) -> String {
        let mut out = String::new();
        for (name, value) in self.coordinates() {
            if let Some(value) = value {
                if !out.is_empty() {
                    out.push(' ');
                }
                out.push_str(name);
                out.push('=');
                out.push_str(value);
            }
        }
        out
    }
}

/// Derived deserialization target for [`NativeAddress`]. The manual
/// [`Deserialize`] below delegates table input here so serde's precise
/// `deny_unknown_fields` messages ("unknown field \`filed\`, expected one of
/// ...") survive, while string input gets a translation hint instead of the
/// useless "invalid type" default.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct NativeAddressFields {
    item: String,
    field: Option<String>,
    vault: Option<String>,
    section: Option<String>,
    version: Option<String>,
}

impl From<NativeAddressFields> for NativeAddress {
    fn from(f: NativeAddressFields) -> Self {
        NativeAddress {
            item: f.item,
            field: f.field,
            vault: f.vault,
            section: f.section,
            version: f.version,
        }
    }
}

/// Renders the `ref = { ... }` TOML inline table used by the error hints that
/// translate a rejected provider-URI address into the exact table to write.
/// Shared by the string-`ref` deserialization hint below and by every provider
/// that rejects a URI-embedded address, so the renderings cannot drift.
pub(crate) fn ref_table_hint(
    vault: Option<&str>,
    item: &str,
    section: Option<&str>,
    field: Option<&str>,
) -> String {
    let coords = NativeAddress {
        item: item.to_string(),
        field: field.map(str::to_string),
        vault: vault.map(str::to_string),
        section: section.map(str::to_string),
        version: None,
    };
    let rendered: Vec<String> = coords
        .coordinates()
        .into_iter()
        .filter_map(|(name, value)| value.map(|v| format!("{name} = \"{v}\"")))
        .collect();
    format!("ref = {{ {} }}", rendered.join(", "))
}

/// The error shown when `ref` is written as a string. Earlier iterations of
/// the feature accepted provider URIs here, so pasted `op://vault/item/field`
/// strings are the expected mistake: translate the common shapes into the
/// exact table to write.
fn ref_string_hint(s: &str) -> String {
    if let Some(rest) = s.strip_prefix("op://") {
        let segments: Vec<&str> = rest.split('/').collect();
        match segments[..] {
            [vault, item, field] if !vault.is_empty() && !item.is_empty() && !field.is_empty() => {
                return format!(
                    "`ref` takes a table of coordinates, not a URI. Use: {}",
                    ref_table_hint(Some(vault), item, None, Some(field))
                );
            }
            [vault, item, section, field]
                if !vault.is_empty()
                    && !item.is_empty()
                    && !section.is_empty()
                    && !field.is_empty() =>
            {
                return format!(
                    "`ref` takes a table of coordinates, not a URI. Use: {}",
                    ref_table_hint(Some(vault), item, Some(section), Some(field))
                );
            }
            _ => {}
        }
    }
    format!(
        "`ref` takes a table of native secret coordinates, not a string: got '{s}'. \
         Write e.g. {}; which store resolves \
         the coordinates comes from `providers` (or the default provider).",
        ref_table_hint(None, "db", None, Some("password"))
    )
}

impl<'de> Deserialize<'de> for NativeAddress {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct AddressVisitor;

        impl<'de> serde::de::Visitor<'de> for AddressVisitor {
            type Value = NativeAddress;

            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                write!(
                    f,
                    "a table of native secret coordinates like {{ item = \"db\", field = \"password\" }}"
                )
            }

            fn visit_map<A>(self, map: A) -> std::result::Result<Self::Value, A::Error>
            where
                A: serde::de::MapAccess<'de>,
            {
                NativeAddressFields::deserialize(serde::de::value::MapAccessDeserializer::new(map))
                    .map(NativeAddress::from)
            }

            fn visit_str<E>(self, s: &str) -> std::result::Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Err(E::custom(ref_string_hint(s)))
            }
        }

        deserializer.deserialize_any(AddressVisitor)
    }
}

/// Configuration for an individual secret.
///
/// Defines the properties of a secret including its documentation,
/// whether it's required, an optional default value, and optionally
/// which providers to use for retrieving this secret (in fallback order).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Secret {
    /// Human-readable description of what this secret is used for
    pub description: Option<String>,
    /// Whether this secret must be provided (no default value)
    /// If not specified, defaults to true unless overridden by profile defaults
    #[serde(skip_serializing_if = "Option::is_none")]
    pub required: Option<bool>,
    /// Optional default value if the secret is not provided
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,
    /// Optional list of provider aliases for retrieving this secret.
    /// Providers are tried in order until one has the secret.
    /// If not specified, uses the profile defaults.providers or global provider.
    /// Each alias is resolved against the providers map in GlobalConfig.
    /// Example: providers = ["keyring", "env"] will try keyring first, then env.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub providers: Option<Vec<String>>,
    /// Native coordinates naming one externally managed secret (see
    /// [`NativeAddress`]): `ref = { item = "db", field = "password" }`.
    ///
    /// The coordinates supply *naming only*, replacing SecretSpec's own
    /// `{project}/{profile}/{key}` scheme for this secret. Which store
    /// resolves them follows ordinary provider resolution — the secret's
    /// `providers` chain, the `--provider` override, or the default provider —
    /// so the same `ref` can be re-routed (e.g. at a fixtures store during
    /// tests) without editing it, and composes with `providers`. Also composes
    /// with `generate`: a missing referenced secret is minted and written to
    /// its coordinates. Serialized as `ref` in TOML.
    #[serde(rename = "ref", skip_serializing_if = "Option::is_none")]
    pub reference: Option<NativeAddress>,
    /// Whether to write the secret value to a temporary file and return the path.
    /// If true, the secret will be written to a temporary file and the field
    /// will contain the path to that file instead of the secret value.
    /// The temporary file will be cleaned up when the resolved secrets are dropped.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub as_path: Option<bool>,
    /// The type of secret, used for generation (e.g., "password", "hex", "base64", "uuid", "command", "rsa_private_key")
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub secret_type: Option<String>,
    /// Auto-generation configuration. Either `true` for defaults or a table with options.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub generate: Option<GenerateConfig>,
}

impl Secret {
    /// Validate the secret configuration.
    ///
    /// Ensures that required secrets don't have default values,
    /// and that generation config is consistent with type.
    pub fn validate(&self) -> Result<(), String> {
        self.validate_description()?;
        self.validate_required_default()?;
        self.validate_semantics()
    }

    /// Rules that apply to the effective (merged) configuration of a secret,
    /// i.e. what a resolver actually acts on. `Config::validate` calls this on
    /// the merged view so overrides may inherit fields (description, type,
    /// generate, ...) from the default profile.
    fn validate_effective(&self) -> Result<(), String> {
        self.validate_description()?;
        self.validate_semantics()
    }

    fn validate_description(&self) -> Result<(), String> {
        match self.description.as_deref() {
            Some("") => Err("description cannot be empty".into()),
            None => Err("missing description".into()),
            Some(_) => Ok(()),
        }
    }

    /// If required is explicitly true and default is set, that's an error.
    /// Checked on raw entries only, not on merged views (see
    /// [`Profile::validate_raw`]).
    fn validate_required_default(&self) -> Result<(), String> {
        if self.required == Some(true) && self.default.is_some() {
            return Err("Required secrets cannot have default values".into());
        }
        Ok(())
    }

    /// Whether this secret mints its own value: it declares an enabled
    /// `generate` config. The single source of truth for "resolution can supply
    /// this without a provider", shared by manifest compilation and semantic
    /// validation.
    pub(crate) fn would_generate(&self) -> bool {
        self.generate.as_ref().is_some_and(|g| g.is_enabled())
    }

    fn validate_semantics(&self) -> Result<(), String> {
        // A `ref` supplies naming only: it composes with `providers` routing
        // and with `generate` (a missing referenced secret is minted and
        // written to its coordinates, like any other generated value).
        if let Some(reference) = &self.reference {
            // `coordinates()` yields `item` too, so this covers the required
            // coordinate as well as the optional ones. Whitespace-only is a
            // typo, not a name: no store has a secret titled "   ".
            for (name, value) in reference.coordinates() {
                if value.is_some_and(|v| v.trim().is_empty()) {
                    return Err(format!(
                        "`ref` coordinate `{}` cannot be empty or whitespace",
                        name
                    ));
                }
            }
        }

        // Validate generate config
        if let Some(ref gen_config) = self.generate
            && gen_config.is_enabled()
        {
            // generate requires type
            if self.secret_type.is_none() {
                return Err(
                    "'generate' requires 'type' to be set (e.g., type = \"password\")".into(),
                );
            }

            // generate + default is a conflict
            if self.default.is_some() {
                return Err("'generate' and 'default' cannot both be set".into());
            }

            // type = "command" requires generate = { command = "..." }
            if self.secret_type.as_deref() == Some("command") {
                match gen_config {
                    GenerateConfig::Bool(true) => {
                        return Err(
                            "type = \"command\" requires generate = { command = \"...\" }".into(),
                        );
                    }
                    GenerateConfig::Options(opts) if opts.command.is_none() => {
                        return Err(
                            "type = \"command\" requires generate = { command = \"...\" }".into(),
                        );
                    }
                    _ => {}
                }
            }

            // Validate known types
            if let Some(ref t) = self.secret_type {
                match t.as_str() {
                    "password" | "hex" | "base64" | "uuid" | "command" | "rsa_private_key" => {}
                    unknown => {
                        return Err(format!("unknown secret type '{}'", unknown));
                    }
                }
            }
        }

        // Validate type even without generate
        if let Some(ref t) = self.secret_type
            && !self.would_generate()
        {
            // Type is informational when not generating, but still validate known values
            match t.as_str() {
                "password" | "hex" | "base64" | "uuid" | "command" | "rsa_private_key" => {}
                unknown => {
                    return Err(format!("unknown secret type '{}'", unknown));
                }
            }
        }

        Ok(())
    }

    /// Field-level merge producing the effective configuration a resolver
    /// acts on.
    ///
    /// Precedence (highest to lowest): the current profile's entry, the
    /// default profile's entry, then the current profile's `[defaults]` table
    /// (for the fields it can supply). Shared by secret resolution
    /// (`Secrets::resolve_secret_config`) and `Config::validate` so the two
    /// can never disagree about what a merged secret looks like.
    pub(crate) fn resolved(
        current: Option<&Secret>,
        default: Option<&Secret>,
        defaults: Option<&ProfileDefaults>,
    ) -> Option<Secret> {
        if current.is_none() && default.is_none() {
            return None;
        }

        // One field's value from the profile entries in precedence order: the
        // current profile's entry, then the default profile's. A missing
        // entry simply contributes nothing. The `[defaults]` table tail is
        // appended per field below, for the fields it can supply.
        fn inherit<T>(
            current: Option<&Secret>,
            default: Option<&Secret>,
            field: impl Fn(&Secret) -> Option<T>,
        ) -> Option<T> {
            current
                .and_then(&field)
                .or_else(|| default.and_then(&field))
        }

        Some(Secret {
            description: inherit(current, default, |s| s.description.clone()),
            required: inherit(current, default, |s| s.required)
                .or(defaults.and_then(|d| d.required)),
            default: inherit(current, default, |s| s.default.clone())
                .or_else(|| defaults.and_then(|d| d.default.clone())),
            providers: inherit(current, default, |s| s.providers.clone())
                .or_else(|| defaults.and_then(|d| d.providers.clone())),
            reference: inherit(current, default, |s| s.reference.clone()),
            as_path: inherit(current, default, |s| s.as_path),
            secret_type: inherit(current, default, |s| s.secret_type.clone()),
            generate: inherit(current, default, |s| s.generate.clone()),
        })
    }
}

/// Check if a string is a valid identifier.
fn is_valid_identifier(s: &str) -> bool {
    if s.is_empty() {
        return false;
    }

    let mut chars = s.chars();
    if let Some(first) = chars.next()
        && !first.is_alphabetic()
        && first != '_'
    {
        return false;
    }

    chars.all(|c| c.is_alphanumeric() || c == '_')
}

/// Global user configuration for SecretSpec.
///
/// This configuration is stored in the user's config directory and provides
/// defaults that apply across all projects.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[doc(hidden)]
pub struct GlobalConfig {
    /// Default settings
    #[serde(default)]
    pub defaults: GlobalDefaults,
    /// Audit logging configuration (top-level `[audit]` table). Auditing is a
    /// per-machine/operator concern, so it lives here rather than in the project's
    /// `secretspec.toml`. `None` means "unspecified" and resolves to
    /// [`AuditConfig::default`] (auditing on).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub audit: Option<AuditConfig>,
}

/// Default settings in the global configuration.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[doc(hidden)]
pub struct GlobalDefaults {
    /// Default provider to use when not specified
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,
    /// Default profile to use when not specified
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile: Option<String>,
    /// Named provider aliases that map alias names to provider URIs.
    /// Used by per-secret provider configuration to avoid storing sensitive
    /// provider details in secretspec.toml. Example user config:
    /// ```toml
    /// [defaults.providers]
    /// shared = "onepassword://Shared"
    /// local = "dotenv://.env.local"
    /// ```
    #[serde(skip_serializing_if = "Option::is_none")]
    pub providers: Option<HashMap<String, ProviderAlias>>,
}

impl GlobalConfig {
    /// Gets the path to the global configuration file.
    ///
    /// The configuration file is stored in the system's config directory,
    /// typically `~/.config/secretspec/config.toml` on Unix systems.
    ///
    /// # Returns
    ///
    /// The path to the global configuration file
    ///
    /// # Errors
    ///
    /// Returns an error if the config directory cannot be determined
    pub fn path() -> Result<PathBuf, io::Error> {
        use etcetera::app_strategy::{AppStrategy, choose_app_strategy};
        let strategy = choose_app_strategy(app_strategy_args())
            .map_err(|e| io::Error::new(io::ErrorKind::NotFound, e.to_string()))?;
        Ok(strategy.config_dir().join("config.toml"))
    }

    /// Loads the global user configuration.
    ///
    /// This method looks for the configuration file in the system's config
    /// directory. If the file doesn't exist, it returns `Ok(None)`.
    ///
    /// # Returns
    ///
    /// The loaded global configuration, or `None` if not found
    ///
    /// # Errors
    ///
    /// Returns an error if the config path cannot be checked/read or if parsing fails
    pub fn load() -> Result<Option<Self>, ParseError> {
        let config_path = Self::path().map_err(ParseError::Io)?;

        #[cfg(target_os = "macos")]
        let config_path = Self::migrate_macos_config(&config_path).map_err(ParseError::Io)?;

        if !config_path.try_exists().map_err(ParseError::Io)? {
            return Ok(None);
        }
        let content = std::fs::read_to_string(&config_path).map_err(ParseError::Io)?;
        toml::from_str(&content).map(Some).map_err(ParseError::Toml)
    }

    /// Saves the global configuration to disk.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The config directory cannot be created
    /// - The file cannot be written
    /// - The configuration cannot be serialized
    pub fn save(&self) -> Result<(), io::Error> {
        let config_path = Self::path()?;

        // Ensure the parent directory exists
        if let Some(parent) = config_path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        let content = toml::to_string_pretty(self)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
        std::fs::write(&config_path, content)?;

        Ok(())
    }

    /// Migrate config from the old macOS location (~/Library/Application Support/secretspec/)
    /// to the XDG location (~/.config/secretspec/).
    ///
    /// Returns the path that should be used for loading.
    /// If migration fails, the legacy path is returned as a fallback when available.
    ///
    /// # Errors
    ///
    /// Returns an error if the new path cannot be checked and no legacy fallback can be determined.
    #[cfg(target_os = "macos")]
    fn migrate_macos_config(new_path: &Path) -> Result<PathBuf, io::Error> {
        match new_path.try_exists() {
            Ok(true) => return Ok(new_path.to_path_buf()),
            Ok(false) => {}
            Err(err) => {
                if let Ok(home) = etcetera::home_dir() {
                    let old_path = home
                        .join("Library/Application Support/secretspec")
                        .join("config.toml");
                    if old_path.exists() {
                        return Ok(old_path);
                    }
                }
                return Err(err);
            }
        }

        let old_path = match etcetera::home_dir() {
            Ok(home) => home
                .join("Library/Application Support/secretspec")
                .join("config.toml"),
            Err(_) => return Ok(new_path.to_path_buf()),
        };

        match old_path.try_exists() {
            Ok(true) => {}
            Ok(false) => return Ok(new_path.to_path_buf()),
            Err(err) => {
                eprintln!(
                    "Warning: failed to check legacy config path {}: {}. Continuing to use legacy path.",
                    old_path.display(),
                    err
                );
                return Ok(old_path);
            }
        }

        // Create parent directories for the new path
        if let Some(parent) = new_path.parent() {
            if let Err(err) = std::fs::create_dir_all(parent) {
                eprintln!(
                    "Warning: failed to create config directory {} while migrating from {}: {}. Continuing to use legacy config path.",
                    parent.display(),
                    old_path.display(),
                    err
                );
                return Ok(old_path);
            }
        }

        // Copy old config to new location
        if let Err(err) = std::fs::copy(&old_path, new_path) {
            eprintln!(
                "Warning: failed to migrate config from {} to {}: {}. Continuing to use legacy config path.",
                old_path.display(),
                new_path.display(),
                err
            );
            return Ok(old_path);
        }

        // Rename old file to indicate it has been migrated
        let old_backup = old_path.with_extension("toml.old");
        if let Err(err) = std::fs::rename(&old_path, &old_backup) {
            eprintln!(
                "Warning: migrated config to {}, but failed to back up {} to {}: {}",
                new_path.display(),
                old_path.display(),
                old_backup.display(),
                err
            );
        }

        eprintln!(
            "Migrated config from {} to {}",
            old_path.display(),
            new_path.display()
        );
        Ok(new_path.to_path_buf())
    }
}

/// Container for resolved secrets with their context.
///
/// This generic struct wraps the actual secret values along with
/// information about which provider and profile were used to retrieve them.
/// The generic parameter `T` is typically a struct generated by the
/// `secretspec-derive` macro containing the actual secret values.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Resolved<T> {
    /// The actual secret values, typically a generated struct
    pub secrets: T,
    /// The provider name that was used to retrieve these secrets
    pub provider: String,
    /// The profile that was active when retrieving these secrets
    pub profile: String,
}

impl<T> Resolved<T> {
    /// Create a new container for secrets with their retrieval context.
    ///
    /// # Arguments
    ///
    /// * `secrets` - The actual secret values
    /// * `provider` - The provider name used to retrieve the secrets
    /// * `profile` - The active profile when the secrets were retrieved
    pub fn new(secrets: T, provider: String, profile: String) -> Self {
        Self {
            secrets,
            provider,
            profile,
        }
    }
}

/// Errors that can occur when parsing SecretSpec configuration files.
///
/// This enum represents various failure modes when loading and parsing
/// configuration files, including I/O errors, TOML syntax errors,
/// validation failures, and circular dependency detection.
#[derive(Debug)]
pub enum ParseError {
    /// I/O error when reading configuration files
    Io(io::Error),
    /// TOML parsing error
    Toml(toml::de::Error),
    /// Unsupported configuration revision
    UnsupportedRevision(String),
    /// Circular dependency detected in configuration inheritance
    CircularDependency(String),
    /// Validation error
    Validation(String),
    /// Extended configuration file not found
    ExtendedConfigNotFound(String),
}

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ParseError::Io(e) => write!(f, "I/O error: {}", e),
            ParseError::Toml(e) => write!(f, "TOML parsing error: {}", e),
            ParseError::UnsupportedRevision(rev) => {
                write!(
                    f,
                    "Unsupported revision '{}'. Only '1.0' is supported.",
                    rev
                )
            }
            ParseError::CircularDependency(msg) => {
                write!(f, "Circular dependency detected: {}", msg)
            }
            ParseError::Validation(msg) => write!(f, "Validation error: {}", msg),
            ParseError::ExtendedConfigNotFound(path) => {
                write!(f, "Extended config file not found: {}", path)
            }
        }
    }
}

impl std::error::Error for ParseError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            ParseError::Io(e) => Some(e),
            ParseError::Toml(e) => Some(e),
            _ => None,
        }
    }
}

impl From<io::Error> for ParseError {
    fn from(e: io::Error) -> Self {
        ParseError::Io(e)
    }
}

impl From<toml::de::Error> for ParseError {
    fn from(e: toml::de::Error) -> Self {
        ParseError::Toml(e)
    }
}

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

    fn parse(line: &str) -> Option<RequireReason> {
        let toml = format!("name = \"t\"\nrevision = \"1.0\"\n{line}");
        toml::from_str::<Project>(&toml).unwrap().require_reason
    }

    #[test]
    fn accepts_bool_and_agents_string() {
        assert_eq!(parse("require_reason = true"), Some(RequireReason::Always));
        assert_eq!(parse("require_reason = false"), Some(RequireReason::Never));
        assert_eq!(
            parse("require_reason = \"agents\""),
            Some(RequireReason::Agents)
        );
    }

    #[test]
    fn unspecified_require_reason_is_none_and_resolves_to_agents() {
        // Absent in TOML parses to `None` so `extends` can fill it from a parent;
        // the runtime default is applied at use via `unwrap_or_default`.
        assert_eq!(parse(""), None);
        assert_eq!(parse("").unwrap_or_default(), RequireReason::Agents);
    }

    #[test]
    fn extends_inherits_parent_require_reason_when_unspecified() {
        use std::collections::HashMap;
        let cfg = |rr: Option<RequireReason>| Config {
            project: Project {
                name: "t".to_string(),
                require_reason: rr,
                ..Default::default()
            },
            profiles: HashMap::new(),
            providers: None,
        };

        // `extends` folds least-specific (parent) into most-specific (child) via
        // `overlay_with`: the later document wins, absent fields inherit.

        // Child leaves the policy unspecified -> it inherits the parent's value.
        let mut merged = cfg(Some(RequireReason::Always));
        merged.overlay_with(cfg(None));
        assert_eq!(merged.project.require_reason, Some(RequireReason::Always));

        // Child sets the policy explicitly -> its own value wins over the parent's.
        let mut merged = cfg(Some(RequireReason::Always));
        merged.overlay_with(cfg(Some(RequireReason::Never)));
        assert_eq!(merged.project.require_reason, Some(RequireReason::Never));
    }

    #[test]
    fn rejects_unknown_or_wrong_typed_values() {
        // Invalid values must surface as a parse error (not silently default), now
        // that the policy is parsed through the canonical config path.
        let base = "name = \"t\"\nrevision = \"1.0\"\n";

        // An unknown string names the accepted values.
        let err = toml::from_str::<Project>(&format!("{base}require_reason = \"nope\""))
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("expected true, false, or \"agents\""),
            "unexpected error: {err}"
        );

        // A wrong *type* reports a precise type mismatch rather than a vague
        // "did not match any variant" message.
        let err = toml::from_str::<Project>(&format!("{base}require_reason = 1"))
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("invalid type") && err.contains("boolean or the string"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn round_trips_through_serialize() {
        // An unspecified policy (None) is omitted; explicit values are preserved.
        let toml = toml::to_string(&Project {
            name: "t".to_string(),
            revision: "1.0".to_string(),
            extends: None,
            require_reason: None,
        })
        .unwrap();
        assert!(!toml.contains("require_reason"));

        let toml = toml::to_string(&Project {
            name: "t".to_string(),
            revision: "1.0".to_string(),
            extends: None,
            require_reason: Some(RequireReason::Always),
        })
        .unwrap();
        assert_eq!(
            toml::from_str::<Project>(&toml).unwrap().require_reason,
            Some(RequireReason::Always)
        );
    }
}

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

    fn with_path(path: &str) -> AuditConfig {
        AuditConfig {
            path: Some(PathBuf::from(path)),
            ..Default::default()
        }
    }

    #[test]
    fn resolved_path_keeps_absolute_and_rejects_relative() {
        // An absolute configured path is honored verbatim. What counts as absolute
        // is platform-specific (Windows requires a drive prefix), so pick one that
        // `Path::is_absolute` accepts on the host.
        let abs_path = if cfg!(windows) {
            r"C:\var\log\secretspec\audit.log"
        } else {
            "/var/log/secretspec/audit.log"
        };
        let abs = with_path(abs_path);
        assert_eq!(abs.resolved_path(), Some(PathBuf::from(abs_path)));
        assert!(!abs.has_relative_path());

        // A relative path (bare filename or nested) is rejected: it would resolve
        // against the current working directory and scatter the log per-CWD.
        for rel in ["audit.log", "logs/audit.log", "./audit.log"] {
            let cfg = with_path(rel);
            assert_eq!(
                cfg.resolved_path(),
                None,
                "relative path {rel:?} must reject"
            );
            assert!(
                cfg.has_relative_path(),
                "{rel:?} should be flagged relative"
            );
        }
    }

    #[test]
    fn unset_path_is_not_flagged_relative() {
        // No configured path falls back to the per-user default and is never
        // reported as a relative-path error.
        let cfg = AuditConfig::default();
        assert!(!cfg.has_relative_path());
    }

    #[test]
    fn expand_tilde_expands_leading_tilde_only() {
        // Paths without a leading `~` are returned unchanged...
        assert_eq!(
            expand_tilde(PathBuf::from("/abs/path")),
            PathBuf::from("/abs/path")
        );
        assert_eq!(
            expand_tilde(PathBuf::from("relative/path")),
            PathBuf::from("relative/path")
        );
        // ...including a `~` that is not the leading component.
        assert_eq!(
            expand_tilde(PathBuf::from("/a/~/b")),
            PathBuf::from("/a/~/b")
        );

        // A leading `~/...` expands against the resolved home directory.
        if let Some(home) = home_dir() {
            assert_eq!(
                expand_tilde(PathBuf::from("~/.local/state/secretspec/audit.log")),
                home.join(".local/state/secretspec/audit.log")
            );
        }
    }

    #[test]
    fn audit_config_omitted_fields_default_to_on() {
        // The security-relevant defaults: auditing on, no explicit path, 1 MiB cap.
        // A missing field must not silently disable logging.
        let cfg: AuditConfig = toml::from_str("").unwrap();
        assert!(cfg.enabled);
        assert_eq!(cfg.path, None);
        assert_eq!(cfg.max_size_bytes, 1_048_576);
    }

    #[test]
    fn global_config_wires_audit_table() {
        // A present `[audit]` table populates `GlobalConfig::audit`...
        let g: GlobalConfig =
            toml::from_str("[defaults]\nprovider = \"keyring\"\n\n[audit]\nenabled = false\n")
                .unwrap();
        assert_eq!(g.audit.map(|a| a.enabled), Some(false));

        // ...and an absent one leaves it unspecified (resolving to on-by-default).
        let g: GlobalConfig = toml::from_str("[defaults]\nprovider = \"keyring\"\n").unwrap();
        assert!(g.audit.is_none());
    }
}

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

    fn secret(description: Option<&str>) -> Secret {
        Secret {
            description: description.map(String::from),
            ..Default::default()
        }
    }

    fn config_with(name: &str, profiles: Vec<(&str, Vec<(&str, Secret)>)>) -> Config {
        let profiles = profiles
            .into_iter()
            .map(|(pname, secrets)| {
                let secrets = secrets
                    .into_iter()
                    .map(|(k, v)| (k.to_string(), v))
                    .collect();
                (
                    pname.to_string(),
                    Profile {
                        defaults: None,
                        secrets,
                    },
                )
            })
            .collect();
        Config {
            project: Project {
                name: name.to_string(),
                ..Default::default()
            },
            profiles,
            providers: None,
        }
    }

    #[test]
    fn is_valid_identifier_accepts_and_rejects() {
        for ok in ["ok", "_ok", "VALID_NAME9", "a"] {
            assert!(is_valid_identifier(ok), "expected valid: {ok}");
        }
        for bad in ["", "1abc", "a-b", "has space", "a.b"] {
            assert!(!is_valid_identifier(bad), "expected invalid: {bad}");
        }
    }

    #[test]
    fn config_validate_rejects_empty_name() {
        let err = config_with("", vec![("default", vec![("A", secret(Some("d")))])])
            .validate()
            .unwrap_err();
        assert!(matches!(err, ParseError::Validation(_)));
        assert!(err.to_string().contains("name cannot be empty"));
    }

    #[test]
    fn config_validate_rejects_no_profiles() {
        let err = config_with("proj", vec![]).validate().unwrap_err();
        assert!(err.to_string().contains("At least one profile"));
    }

    #[test]
    fn config_validate_rejects_empty_profile() {
        let err = config_with("proj", vec![("default", vec![])])
            .validate()
            .unwrap_err();
        assert!(err.to_string().contains("at least one secret"));
    }

    /// Regression for https://github.com/cachix/secretspec/issues/144: an
    /// explicitly declared empty profile inherits the complete default
    /// profile and is therefore not empty from the resolver's perspective.
    #[test]
    fn config_validate_allows_empty_profile_to_inherit_default_secrets() {
        let config: Config = toml::from_str(
            r#"
[project]
name = "lm04-stats"
revision = "1.0"

[profiles.default]
ADMIN_PASSWORD = { description = "Password securing the admin page", required = true, type = "password" }

[profiles.production]
"#,
        )
        .unwrap();

        config.validate().unwrap();

        let spec = crate::Secrets::new(config, None, None, Some("production".to_string()));
        let resolved = spec
            .resolve_secret_config("ADMIN_PASSWORD", Some("production"))
            .expect("production should inherit ADMIN_PASSWORD from default");
        assert_eq!(
            resolved.description.as_deref(),
            Some("Password securing the admin page")
        );
        assert_eq!(resolved.required, Some(true));
        assert_eq!(resolved.secret_type.as_deref(), Some("password"));
    }

    #[test]
    fn config_validate_rejects_invalid_secret_name() {
        let err = config_with("proj", vec![("default", vec![("1BAD", secret(Some("d")))])])
            .validate()
            .unwrap_err();
        assert!(err.to_string().contains("Invalid secret name"));
    }

    #[test]
    fn config_validate_accepts_valid_config() {
        assert!(
            config_with(
                "proj",
                vec![("default", vec![("API_KEY", secret(Some("d")))])]
            )
            .validate()
            .is_ok()
        );
    }

    #[test]
    fn config_validate_allows_profile_override_to_inherit_description() {
        // required = true in the default profile plus a default value from
        // the override is also fine: only that combination within a single
        // raw entry is a contradiction.
        let config: Config = toml::from_str(
            r#"
[project]
name = "tmp"
revision = "1.0"

[profiles.default]
DATABASE_URL = { description = "Database connection string", required = true }

[profiles.development]
DATABASE_URL = { default = "sqlite:///dev.db" }
"#,
        )
        .unwrap();

        config.validate().unwrap();

        let spec = crate::Secrets::new(config, None, None, Some("development".to_string()));
        let resolved = spec
            .resolve_secret_config("DATABASE_URL", Some("development"))
            .unwrap();
        assert_eq!(
            resolved.description.as_deref(),
            Some("Database connection string")
        );
        assert_eq!(resolved.default.as_deref(), Some("sqlite:///dev.db"));
    }

    #[test]
    fn config_validate_requires_description_for_profile_only_secret() {
        let config = config_with(
            "proj",
            vec![
                ("default", vec![("API_KEY", secret(Some("API key")))]),
                ("development", vec![("DATABASE_URL", secret(None))]),
            ],
        );

        let err = config.validate().unwrap_err();
        assert!(err.to_string().contains("missing description"));
    }

    #[test]
    fn config_validate_rejects_generate_and_default_split_across_profiles() {
        // The merged production config carries generate (inherited) plus an
        // inline default; the executor would generate and silently ignore the
        // default, so validation must reject the combination.
        let config: Config = toml::from_str(
            r#"
[project]
name = "tmp"
revision = "1.0"

[profiles.default]
API_TOKEN = { description = "t", type = "password", generate = true }

[profiles.production]
API_TOKEN = { default = "placeholder" }
"#,
        )
        .unwrap();

        let err = config.validate().unwrap_err().to_string();
        assert!(err.contains("Profile 'production'"), "{err}");
        assert!(
            err.contains("'generate' and 'default' cannot both be set"),
            "{err}"
        );
    }

    #[test]
    fn config_validate_allows_generate_with_type_inherited_from_default_profile() {
        // Resolution merges `type` from the default profile, so the override
        // only enabling `generate` is a coherent effective config.
        let config: Config = toml::from_str(
            r#"
[project]
name = "tmp"
revision = "1.0"

[profiles.default]
TOKEN = { description = "t", type = "password" }

[profiles.production]
TOKEN = { generate = true }
"#,
        )
        .unwrap();

        config.validate().unwrap();
    }

    #[test]
    fn config_validate_blames_default_profile_for_empty_inherited_description() {
        // The empty description lives in the default profile; the error must
        // name that profile deterministically, not the override that inherits
        // the empty value. The config is rebuilt each iteration so every
        // HashMap gets a fresh hash seed and seed-dependent iteration order
        // would surface here.
        for _ in 0..8 {
            let config = config_with(
                "proj",
                vec![
                    ("default", vec![("DB", secret(Some("")))]),
                    ("development", vec![("DB", secret(None))]),
                ],
            );
            let err = config.validate().unwrap_err().to_string();
            assert!(err.contains("Profile 'default'"), "{err}");
            assert!(err.contains("description cannot be empty"), "{err}");
        }
    }

    #[test]
    fn config_validate_checks_profile_defaults_in_merged_config() {
        // A [defaults] table participates in resolution, so a default value it
        // injects next to an inherited generate must fail validation too, even
        // though the production profile never declares the secret itself.
        let config: Config = toml::from_str(
            r#"
[project]
name = "tmp"
revision = "1.0"

[profiles.default]
API_TOKEN = { description = "t", type = "password", generate = true }

[profiles.production]
OTHER = { description = "o" }

[profiles.production.defaults]
default = "placeholder"
"#,
        )
        .unwrap();

        let err = config.validate().unwrap_err().to_string();
        assert!(err.contains("Profile 'production'"), "{err}");
        assert!(
            err.contains("'generate' and 'default' cannot both be set"),
            "{err}"
        );
    }

    #[test]
    fn secret_validate_requires_nonempty_description() {
        assert_eq!(secret(None).validate().unwrap_err(), "missing description");
        assert_eq!(
            secret(Some("")).validate().unwrap_err(),
            "description cannot be empty"
        );
    }

    #[test]
    fn secret_validate_rejects_required_with_default() {
        let s = Secret {
            description: Some("d".to_string()),
            required: Some(true),
            default: Some("v".to_string()),
            ..Default::default()
        };
        assert!(
            s.validate()
                .unwrap_err()
                .contains("Required secrets cannot have default")
        );
    }

    #[test]
    fn secret_validate_generate_requires_type() {
        let s = Secret {
            description: Some("d".to_string()),
            generate: Some(GenerateConfig::Bool(true)),
            ..Default::default()
        };
        assert!(s.validate().unwrap_err().contains("requires 'type'"));
    }

    #[test]
    fn secret_validate_rejects_unknown_type() {
        let s = Secret {
            description: Some("d".to_string()),
            secret_type: Some("banana".to_string()),
            ..Default::default()
        };
        assert!(s.validate().unwrap_err().contains("unknown secret type"));
    }

    #[test]
    fn secret_validate_command_type_requires_command() {
        let s = Secret {
            description: Some("d".to_string()),
            secret_type: Some("command".to_string()),
            generate: Some(GenerateConfig::Bool(true)),
            ..Default::default()
        };
        assert!(
            s.validate()
                .unwrap_err()
                .contains("requires generate = { command")
        );
    }

    /// Shorthand for a native address in tests.
    fn addr(item: &str, field: Option<&str>) -> NativeAddress {
        NativeAddress {
            item: item.to_string(),
            field: field.map(str::to_string),
            ..Default::default()
        }
    }

    #[test]
    fn secret_validate_accepts_reference() {
        let s = Secret {
            description: Some("Sentry DSN".to_string()),
            reference: Some(addr("shared", Some("SENTRY_DSN"))),
            ..Default::default()
        };
        assert!(s.validate().is_ok());
    }

    /// A `ref` supplies naming and `providers` supplies routing; they compose.
    #[test]
    fn secret_validate_accepts_ref_with_providers() {
        let s = Secret {
            description: Some("d".to_string()),
            reference: Some(addr("db", Some("password"))),
            providers: Some(vec!["keyring".to_string()]),
            ..Default::default()
        };
        assert!(s.validate().is_ok());
    }

    #[test]
    fn secret_validate_allows_ref_with_generate() {
        // `ref` names where the secret lives; `generate` mints an initial
        // value and sets it there when missing. The two compose.
        let s = Secret {
            description: Some("d".to_string()),
            reference: Some(addr("db", Some("password"))),
            secret_type: Some("password".to_string()),
            generate: Some(GenerateConfig::Bool(true)),
            ..Default::default()
        };
        assert!(s.validate().is_ok());
    }

    #[test]
    fn secret_validate_rejects_empty_ref_coordinates() {
        let s = Secret {
            description: Some("d".to_string()),
            reference: Some(addr("", None)),
            ..Default::default()
        };
        assert!(s.validate().unwrap_err().contains("`item` cannot be empty"));

        let s = Secret {
            description: Some("d".to_string()),
            reference: Some(addr("db", Some(""))),
            ..Default::default()
        };
        assert!(
            s.validate()
                .unwrap_err()
                .contains("`field` cannot be empty")
        );

        // Whitespace-only is the same typo as empty: no store names a secret
        // "   ", and an unrejected one resolves against the store verbatim.
        for blank in ["   ", "\t", "\n"] {
            let s = Secret {
                description: Some("d".to_string()),
                reference: Some(addr(blank, None)),
                ..Default::default()
            };
            assert!(
                s.validate().unwrap_err().contains("`item` cannot be empty"),
                "item {blank:?} should be rejected"
            );

            let s = Secret {
                description: Some("d".to_string()),
                reference: Some(addr("db", Some(blank))),
                ..Default::default()
            };
            assert!(
                s.validate()
                    .unwrap_err()
                    .contains("`field` cannot be empty"),
                "field {blank:?} should be rejected"
            );
        }
    }

    #[test]
    fn secret_reference_round_trips_as_ref_in_toml() {
        // The field is `reference` in Rust but `ref` in TOML, and is omitted
        // when unset so `secretspec config`/init output stays clean.
        let s = Secret {
            description: Some("d".to_string()),
            reference: Some(NativeAddress {
                item: "db".to_string(),
                field: Some("password".to_string()),
                vault: Some("Production".to_string()),
                ..Default::default()
            }),
            ..Default::default()
        };
        let toml = toml::to_string(&s).unwrap();
        assert!(toml.contains("item = \"db\""), "{toml}");
        let parsed = toml::from_str::<Secret>(&toml).unwrap();
        assert_eq!(parsed.reference, s.reference);

        let toml = toml::to_string(&Secret {
            description: Some("d".to_string()),
            ..Default::default()
        })
        .unwrap();
        assert!(!toml.contains("ref"));
    }

    /// All coordinate keys parse from the inline table form.
    #[test]
    fn ref_table_parses_every_coordinate() {
        let s: Secret = toml::from_str(
            r#"description = "d"
ref = { vault = "Production", item = "db", section = "api", field = "password", version = "3" }"#,
        )
        .unwrap();
        let reference = s.reference.unwrap();
        assert_eq!(reference.vault.as_deref(), Some("Production"));
        assert_eq!(reference.item, "db");
        assert_eq!(reference.section.as_deref(), Some("api"));
        assert_eq!(reference.field.as_deref(), Some("password"));
        assert_eq!(reference.version.as_deref(), Some("3"));
    }

    /// A misspelled coordinate fails with serde's precise unknown-field
    /// message rather than an opaque untagged-enum error.
    #[test]
    fn ref_table_rejects_unknown_keys() {
        let err = toml::from_str::<Secret>(
            r#"description = "d"
ref = { item = "db", filed = "password" }"#,
        )
        .unwrap_err();
        assert!(err.to_string().contains("unknown field `filed`"), "{err}");
    }

    /// A string `ref` (the shape earlier iterations accepted) errors with the
    /// exact table translation for the common `op://` paste.
    #[test]
    fn ref_string_gets_translation_hint() {
        let err = toml::from_str::<Secret>(
            r#"description = "d"
ref = "op://Production/db/password""#,
        )
        .unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("ref = { vault = \"Production\", item = \"db\", field = \"password\" }"),
            "{msg}"
        );

        let err = toml::from_str::<Secret>(
            r#"description = "d"
ref = "just-a-string""#,
        )
        .unwrap_err();
        assert!(
            err.to_string()
                .contains("table of native secret coordinates"),
            "{err}"
        );
    }

    /// A non-string, non-table value reports the expected shape.
    #[test]
    fn ref_wrong_type_reports_expected_shape() {
        let err = toml::from_str::<Secret>(
            r#"description = "d"
ref = 3"#,
        )
        .unwrap_err();
        assert!(
            err.to_string().contains("native secret coordinates"),
            "{err}"
        );
    }

    #[test]
    fn generate_config_is_enabled() {
        assert!(!GenerateConfig::Bool(false).is_enabled());
        assert!(GenerateConfig::Bool(true).is_enabled());
        assert!(GenerateConfig::Options(GenerateOptions::default()).is_enabled());
    }
}

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

    fn parse(providers_toml: &str) -> HashMap<String, ProviderAlias> {
        toml::from_str(providers_toml).expect("valid [providers] table")
    }

    #[test]
    fn bare_string_parses_as_uri_without_credentials() {
        let map = parse(r#"keyring = "keyring://""#);
        assert_eq!(map["keyring"], ProviderAlias::from("keyring://"));
        assert!(map["keyring"].credentials.is_empty());
    }

    #[test]
    fn table_with_credentials_parses_uri_and_credentials() {
        let map =
            parse(r#"bws = { uri = "bws://proj", credentials = { access_token = "keyring" } }"#);
        let alias = &map["bws"];
        assert_eq!(alias.uri, "bws://proj");
        let source = alias
            .credentials
            .get("access_token")
            .expect("credentials carries the semantic name");
        assert_eq!(source, &CredentialSource::from("keyring"));
    }

    #[test]
    fn credential_source_with_ref_parses_provider_and_coordinates() {
        let map = parse(
            r#"vault = { uri = "vault://kv", credentials = { role_id = { provider = "onepassword", ref = { vault = "Infra", item = "approle", field = "role_id" } } } }"#,
        );
        let source = map["vault"].credentials["role_id"].clone();
        assert_eq!(source.provider, "onepassword");
        let reference = source.reference.expect("ref present");
        assert_eq!(reference.vault.as_deref(), Some("Infra"));
        assert_eq!(reference.item, "approle");
        assert_eq!(reference.field.as_deref(), Some("role_id"));
    }

    #[test]
    fn credential_source_round_trips() {
        let bare = CredentialSource::from("keyring");
        let with_ref = CredentialSource {
            provider: "onepassword".to_string(),
            reference: Some(NativeAddress {
                item: "approle".to_string(),
                field: Some("role_id".to_string()),
                ..Default::default()
            }),
        };
        for source in [bare, with_ref] {
            let alias = ProviderAlias {
                uri: "vault://kv".to_string(),
                credentials: HashMap::from([("role_id".to_string(), source.clone())]),
            };
            let map = HashMap::from([("vault".to_string(), alias.clone())]);
            let serialized = toml::to_string(&map).unwrap();
            assert_eq!(parse(&serialized)["vault"], alias);
        }
    }

    #[test]
    fn table_without_credentials_is_equivalent_to_bare_string() {
        let map = parse(r#"bws = { uri = "bws://proj" }"#);
        assert_eq!(map["bws"], ProviderAlias::from("bws://proj"));
    }

    #[test]
    fn empty_credentials_table_is_equivalent_to_no_credentials() {
        // `credentials = {}` declares nothing: the alias equals its bare-string form
        // and serializes back to it.
        let map = parse(r#"keyring = { uri = "keyring://", credentials = {} }"#);
        assert_eq!(map["keyring"], ProviderAlias::from("keyring://"));
    }

    #[test]
    fn unknown_table_field_is_rejected() {
        let err = toml::from_str::<HashMap<String, ProviderAlias>>(
            r#"bws = { uri = "bws://proj", oops = "x" }"#,
        )
        .unwrap_err();
        assert!(
            err.to_string().contains("oops") || err.to_string().contains("unknown"),
            "error should point at the unknown field, got: {err}"
        );
    }

    #[test]
    fn environment_shaped_credential_field_is_rejected() {
        let error = toml::from_str::<HashMap<String, ProviderAlias>>(
            r#"bws = { uri = "bws://proj", env = { BWS_ACCESS_TOKEN = "keyring" } }"#,
        )
        .unwrap_err();
        assert!(error.to_string().contains("env"), "{error}");
    }

    #[test]
    fn credential_less_alias_round_trips_as_a_bare_string() {
        let alias = ProviderAlias::from("keyring://");
        let map = HashMap::from([("keyring".to_string(), alias.clone())]);
        let serialized = toml::to_string(&map).unwrap();
        // The bare-string form is preserved so existing configs are untouched.
        assert_eq!(serialized.trim(), r#"keyring = "keyring://""#);
        assert_eq!(parse(&serialized)["keyring"], alias);
    }

    #[test]
    fn alias_with_credentials_round_trips_through_toml() {
        let alias = ProviderAlias {
            uri: "bws://proj".to_string(),
            credentials: HashMap::from([(
                "access_token".to_string(),
                CredentialSource::from("keyring"),
            )]),
        };
        let map = HashMap::from([("bws".to_string(), alias.clone())]);
        let serialized = toml::to_string(&map).unwrap();
        assert_eq!(parse(&serialized)["bws"], alias);
    }

    #[test]
    fn config_providers_accepts_both_forms_end_to_end() {
        let config: Config = toml::from_str(
            r#"
[project]
name = "app"
revision = "1.0"

[providers]
keyring = "keyring://"
bws = { uri = "bws://proj", credentials = { access_token = "keyring" } }

[profiles.default]
API_KEY = { description = "key", required = true }
"#,
        )
        .unwrap();
        let providers = config.providers.expect("[providers] present");
        assert_eq!(providers["keyring"], ProviderAlias::from("keyring://"));
        assert_eq!(providers["bws"].uri, "bws://proj");
        assert!(providers["bws"].credentials.contains_key("access_token"));
    }
}