subc-transport 0.18.2

subc loopback-TCP + key transport: pre-envelope auth handshake, connection-file discovery, and async envelope frame I/O.
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
use std::{
    env,
    error::Error,
    ffi::{OsStr, OsString},
    fmt,
    fs::{self, File},
    io::{self, Read, Write},
    path::{Path, PathBuf},
    process,
    time::{Duration, SystemTime},
};

use std::fs::OpenOptions;

use serde::{Deserialize, Serialize};
use subc_protocol::PROTOCOL_VERSION;

pub const SCHEMA_VERSION: u32 = 1;
pub const MIN_KEY_LEN: usize = 32;
pub const KEY_LEN: usize = 32;
pub const DAEMON_ID_LEN: usize = 16;

/// The daemon's connection-file name. Public so the writer (bootstrap) and
/// every reader spell it once; three private copies of this literal used to
/// exist and nothing asserted they agreed.
pub const CONNECTION_FILE_NAME: &str = "subc-connection.json";
const PROD_CONNECTION_RELATIVE_PATH: &[&str] =
    &[".local", "share", "cortexkit", "run", CONNECTION_FILE_NAME];

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Endpoint {
    pub host: String,
    pub port: u16,
}

#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConnectionInfo {
    pub schema: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wire_version: Option<u8>,
    pub endpoints: Vec<Endpoint>,
    pub key: Vec<u8>,
    pub daemon_id: [u8; DAEMON_ID_LEN],
    pub pid: u32,
    pub daemon_ver: String,
}

// Hand-written so the transport key is never printed. A derived Debug would dump
// the raw key bytes into any log or panic message that formats a ConnectionInfo.
impl fmt::Debug for ConnectionInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ConnectionInfo")
            .field("schema", &self.schema)
            .field("wire_version", &self.wire_version)
            .field("endpoints", &self.endpoints)
            .field("key", &format_args!("<{} bytes redacted>", self.key.len()))
            .field("daemon_id", &self.daemon_id)
            .field("pid", &self.pid)
            .field("daemon_ver", &self.daemon_ver)
            .finish()
    }
}

/// The daemon's same-user local listener, published in the connection file under
/// the optional `local_endpoint` key: `{"kind":"unix","path":"…"}` for a
/// Unix-domain socket (macOS, Linux) or `{"kind":"pipe","name":"…"}` for a
/// Windows named pipe.
///
/// It lives beside `ConnectionInfo` rather than inside it because
/// `ConnectionInfo` has only public fields and other crates build it by struct
/// literal, so adding a field there would break them. `ConnectionInfo` ignores
/// unknown keys, so `read` still accepts a file that carries this one; only
/// `read_with_local_endpoint` and `write_atomic_with_local_endpoint` see it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
#[non_exhaustive]
pub enum LocalEndpoint {
    /// A Unix-domain socket at this filesystem path.
    Unix { path: PathBuf },
    /// A Windows named pipe with this full pipe name (`\\.\pipe\…`).
    Pipe { name: String },
}

impl LocalEndpoint {
    /// Refuses an empty path or pipe name: neither names a listener a client
    /// could connect to.
    pub fn validate(&self) -> Result<(), ConnectionFileError> {
        let empty = match self {
            Self::Unix { path } => path.as_os_str().is_empty(),
            Self::Pipe { name } => name.is_empty(),
        };
        if empty {
            return Err(ConnectionFileError::Invalid {
                reason: "connection file local_endpoint must name a path or pipe".to_owned(),
            });
        }
        Ok(())
    }
}

/// A connection file's `ConnectionInfo` together with its optional
/// `local_endpoint`, both read from the same owner-checked file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConnectionInfoWithLocalEndpoint {
    pub info: ConnectionInfo,
    /// `None` when the file has no `local_endpoint` key, as in every file
    /// written before the key existed or by a daemon with no local listener.
    pub local_endpoint: Option<LocalEndpoint>,
}

/// The `local_endpoint` key on its own, parsed from the same bytes as
/// `ConnectionInfo` so the `ConnectionInfo` parse is exactly the one `read`
/// performs.
#[derive(Deserialize)]
struct LocalEndpointField {
    #[serde(default)]
    local_endpoint: Option<LocalEndpoint>,
}

/// The on-disk shape written by `write_atomic_with_local_endpoint`: every
/// `ConnectionInfo` key in its usual order, then `local_endpoint` when present.
/// With no endpoint the bytes are identical to `write_atomic`'s.
#[derive(Serialize)]
struct ConnectionFileOut<'a> {
    #[serde(flatten)]
    info: &'a ConnectionInfo,
    #[serde(skip_serializing_if = "Option::is_none")]
    local_endpoint: Option<&'a LocalEndpoint>,
}

/// A connection file selected by reader-side discovery.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Discovered {
    pub path: PathBuf,
    pub info: ConnectionInfo,
}

/// One connection-file candidate that could not be read or parsed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TriedCandidate {
    pub path: PathBuf,
    pub reason: String,
}

/// Every connection-file candidate reader-side discovery tried.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiscoveryError {
    pub tried: Vec<TriedCandidate>,
}

impl fmt::Display for DiscoveryError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let rendered = self
            .tried
            .iter()
            .map(|attempt| format!("{} ({})", attempt.path.display(), attempt.reason))
            .collect::<Vec<_>>()
            .join(", ");
        write!(f, "no usable subc connection file found; tried: {rendered}")
    }
}

impl Error for DiscoveryError {}

impl ConnectionInfo {
    pub fn validate(&self) -> Result<(), ConnectionFileError> {
        if self.schema != SCHEMA_VERSION {
            return Err(ConnectionFileError::UnsupportedSchema {
                schema: self.schema,
                supported: SCHEMA_VERSION,
            });
        }
        if self.endpoints.is_empty() {
            return Err(ConnectionFileError::Invalid {
                reason: "connection file must include at least one endpoint".to_owned(),
            });
        }
        if self.key.len() < MIN_KEY_LEN {
            return Err(ConnectionFileError::KeyTooShort {
                len: self.key.len(),
                min: MIN_KEY_LEN,
            });
        }
        Ok(())
    }

    /// Validates a declared envelope version without rejecting older files that
    /// omit the additive field.
    pub fn validate_wire_version(&self, supported: u8) -> Result<(), ConnectionFileError> {
        if let Some(file) = self.wire_version {
            if file != supported {
                return Err(ConnectionFileError::WireVersionMismatch { file, supported });
            }
        }
        Ok(())
    }
}

#[derive(Debug)]
pub enum ConnectionFileError {
    MissingParent {
        path: PathBuf,
    },
    MissingFileName {
        path: PathBuf,
    },
    Io {
        op: &'static str,
        path: PathBuf,
        source: io::Error,
    },
    JsonRead {
        path: PathBuf,
        source: serde_json::Error,
    },
    JsonWrite {
        path: PathBuf,
        source: serde_json::Error,
    },
    Random(getrandom::Error),
    UnsupportedSchema {
        schema: u32,
        supported: u32,
    },
    WireVersionMismatch {
        file: u8,
        supported: u8,
    },
    Invalid {
        reason: String,
    },
    KeyTooShort {
        len: usize,
        min: usize,
    },
    InsecurePermissions {
        path: PathBuf,
        mode: u32,
    },
    InsecureParentDirectory {
        component: PathBuf,
        mode: u32,
    },
}

pub fn write_atomic(
    path: impl AsRef<Path>,
    info: &ConnectionInfo,
) -> Result<(), ConnectionFileError> {
    write_atomic_with_local_endpoint(path, info, None)
}

/// Like `write_atomic`, and also publishes `local_endpoint` when one is given.
/// With `None` the key is omitted and the file is byte-identical to the one
/// `write_atomic` writes.
pub fn write_atomic_with_local_endpoint(
    path: impl AsRef<Path>,
    info: &ConnectionInfo,
    local_endpoint: Option<&LocalEndpoint>,
) -> Result<(), ConnectionFileError> {
    let path = path.as_ref();
    info.validate()?;
    if let Some(endpoint) = local_endpoint {
        endpoint.validate()?;
    }
    // Serialise before touching the filesystem so a value that cannot be
    // written (a non-UTF-8 socket path) leaves no temp behind.
    let json = serde_json::to_vec_pretty(&ConnectionFileOut {
        info,
        local_endpoint,
    })
    .map_err(|source| ConnectionFileError::JsonWrite {
        path: path.to_path_buf(),
        source,
    })?;

    let parent = path
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
        .ok_or_else(|| ConnectionFileError::MissingParent {
            path: path.to_path_buf(),
        })?;
    let file_name = path
        .file_name()
        .ok_or_else(|| ConnectionFileError::MissingFileName {
            path: path.to_path_buf(),
        })?;
    ensure_parent_directory(parent)?;
    refuse_writable_ancestor(parent)?;
    // Sweep temps stranded by an earlier writer before creating our own. The
    // error path below removes this call's temp, but nothing removes one left by
    // a process that died BETWEEN create and rename -- and a connection file
    // carries the daemon's auth key, so a stranded temp is a stale credential
    // sitting in the runtime directory indefinitely. Owner-only mode means no
    // other user can read it and the key dies with the daemon that minted it;
    // the objection is to key material with no owner and no expiry, not to an
    // active leak.
    //
    // Best-effort and non-fatal: publishing must not fail because cleanup could
    // not remove somebody else's file.
    sweep_stale_temps(parent, file_name);

    let temp_path = temp_path(parent, file_name)?;
    let result = write_atomic_inner(path, &temp_path, &json);
    if result.is_err() {
        let _ = fs::remove_file(&temp_path);
    }
    result
}

/// Create the connection file's parent with owner-only permissions when it is
/// absent.
///
/// The daemon OWNS this directory, so it can make the misconfiguration
/// unproducible rather than only reporting it — which is strictly stronger than
/// the check below and is available to us precisely because we choose the path.
/// A caller that names its own destination has only the check.
///
/// An existing directory is left alone: changing modes under an operator is a
/// bigger act than refusing, and `refuse_writable_ancestor` reports it.
fn ensure_parent_directory(parent: &Path) -> Result<(), ConnectionFileError> {
    if parent.exists() {
        return Ok(());
    }
    #[cfg(unix)]
    let created = {
        use std::os::unix::fs::DirBuilderExt;
        fs::DirBuilder::new()
            .recursive(true)
            .mode(0o700)
            .create(parent)
    };
    #[cfg(windows)]
    let created = subc_os::windows_acl::create_private_dir(parent);
    #[cfg(not(any(unix, windows)))]
    let created = fs::create_dir_all(parent);

    created.map_err(|source| ConnectionFileError::Io {
        op: "create connection-file parent",
        path: parent.to_path_buf(),
        source,
    })
}

/// Refuse to publish key material beneath a directory another user can write.
///
/// This catches misconfiguration; it is not a security boundary. A process
/// running as the same user can read the finished 0600 file anyway, so the
/// check does nothing against one. What it catches is another user: whoever can
/// write a directory can unlink and create entries in it, whatever the mode or
/// owner of the file inside, so another user with write access to any ancestor
/// could delete the 0600 file and put their own in its place.
///
/// The check covers every ancestor up to `/`. Stopping at `$HOME` or an XDG
/// base would take the bound from the environment, which an attacker can
/// influence and which may be unset. It would also be wrong: an attacker who can
/// unlink in any ancestor can rename an intermediate directory aside and put
/// their own tree in its place, so a 0700 leaf under a 0777 grandparent protects
/// nothing.
///
/// The path is canonicalised first, resolving symlinks. Walking the unresolved
/// path would check the modes of a path other than the one written through: a
/// symlink component pointing somewhere permissive would pass every `stat`.
///
/// Each ancestor must be owned by the effective user or by root, and is refused
/// otherwise: even a 0755 directory can be renamed or have its permissions
/// changed by its owner. Root is trusted because the transport does not defend
/// against root processes.
///
/// A group- or world-writable ancestor is refused unless it is sticky. The
/// sticky bit lets only an entry's owner remove or rename it, and `/tmp` and
/// `/Users/Shared` are 1777 by design; without this exemption the check would
/// fire on correctly configured systems, and a check that refuses healthy
/// configuration gets disabled, after which it protects nothing. A sticky
/// directory must still pass the ownership check above.
#[cfg(unix)]
fn refuse_writable_ancestor(parent: &Path) -> Result<(), ConnectionFileError> {
    refuse_writable_ancestor_for_uid(parent, rustix::process::geteuid().as_raw())
}

#[cfg(unix)]
fn refuse_writable_ancestor_for_uid(parent: &Path, uid: u32) -> Result<(), ConnectionFileError> {
    use std::os::unix::fs::{MetadataExt, PermissionsExt};

    const GROUP_OR_WORLD_WRITABLE: u32 = 0o022;
    const STICKY: u32 = 0o1000;

    // A parent that cannot be canonicalised is reported by the write itself with
    // its own io::Error; refusing here would replace a precise errno with a
    // permissions verdict about a path we could not resolve.
    let Ok(resolved) = fs::canonicalize(parent) else {
        return Ok(());
    };

    let mut component = resolved.as_path();
    loop {
        // A component whose metadata cannot be read is SKIPPED, not refused, and
        // the silence is deliberate. Canonicalising above already required
        // traverse permission on every component, so a failure here is close to
        // unreachable and is a transient io error rather than evidence about
        // permissions; refusing on it would convert that error into a confident
        // verdict about a mode we never observed, which is the same trade the
        // canonicalise arm declines. Argued at the site because an UNARGUED
        // fail-open is the one a later reader tightens into a refusal.
        if let Ok(metadata) = fs::metadata(component) {
            if metadata.uid() != uid && metadata.uid() != 0 {
                return Err(ConnectionFileError::Invalid {
                    reason: format!(
                        "connection-file ancestor {} is owned by uid {}, expected effective uid {uid} or root",
                        component.display(), metadata.uid()
                    ),
                });
            }
            let mode = metadata.permissions().mode();
            if mode & GROUP_OR_WORLD_WRITABLE != 0 && mode & STICKY == 0 {
                return Err(ConnectionFileError::InsecureParentDirectory {
                    component: component.to_path_buf(),
                    mode: mode & 0o7777,
                });
            }
        }
        match component.parent() {
            Some(next) => component = next,
            None => return Ok(()),
        }
    }
}

#[cfg(windows)]
fn refuse_writable_ancestor(parent: &Path) -> Result<(), ConnectionFileError> {
    // Refuse a redirected publication directory with a foreign owner or broad
    // DACL; the writer must not repair an operator-supplied existing directory.
    subc_os::windows_acl::verify_private_dir(parent).map_err(|error| ConnectionFileError::Invalid {
        reason: format!(
            "connection-file directory {} is not owner-only: {error}",
            parent.display()
        ),
    })
}

#[cfg(not(any(unix, windows)))]
fn refuse_writable_ancestor(_parent: &Path) -> Result<(), ConnectionFileError> {
    Ok(())
}

/// Remove `.<file_name>.<pid>.<hex>.tmp` siblings older than ten minutes.
///
/// AGE IS THE SOLE PREDICATE. Testing whether the embedded pid is alive reads
/// false-positive on exactly the oldest files, because pid numbers are recycled:
/// an unrelated long-lived process inherits the number and the stalest temp
/// looks owned. That failure direction resembles caution, which is why nobody
/// investigates the survivors. Ten minutes is far longer than the window this
/// guards, which spans two syscalls.
fn sweep_stale_temps(parent: &Path, file_name: &std::ffi::OsStr) {
    const STALE_AFTER: Duration = Duration::from_secs(600);

    let prefix = format!(".{}.", file_name.to_string_lossy());
    let Ok(entries) = fs::read_dir(parent) else {
        return;
    };
    for entry in entries.flatten() {
        let name = entry.file_name();
        let name = name.to_string_lossy();
        if !name.starts_with(&prefix) || !name.ends_with(".tmp") {
            continue;
        }
        let stale = entry
            .metadata()
            .and_then(|meta| meta.modified())
            .map(|modified| {
                SystemTime::now()
                    .duration_since(modified)
                    .is_ok_and(|age| age >= STALE_AFTER)
            })
            .unwrap_or(false);
        if stale {
            let _ = fs::remove_file(entry.path());
        }
    }
}

pub fn read(path: impl AsRef<Path>) -> Result<ConnectionInfo, ConnectionFileError> {
    let path = path.as_ref();
    let bytes = read_owner_checked(path)?;
    parse_info(path, &bytes)
}

/// Reads `ConnectionInfo` and the optional `local_endpoint` from one read of
/// one owner-checked file, so the endpoint and the key always come from the
/// same file the same check accepted.
///
/// A missing `local_endpoint` is `None`. A key that is present but malformed
/// (unknown `kind`, missing or empty `path`/`name`) is an error rather than
/// `None`: a caller that asked for the local endpoint must not mistake a
/// damaged one for an absent one.
pub fn read_with_local_endpoint(
    path: impl AsRef<Path>,
) -> Result<ConnectionInfoWithLocalEndpoint, ConnectionFileError> {
    let path = path.as_ref();
    let bytes = read_owner_checked(path)?;
    let info = parse_info(path, &bytes)?;
    let LocalEndpointField { local_endpoint } =
        serde_json::from_slice(&bytes).map_err(|source| ConnectionFileError::JsonRead {
            path: path.to_path_buf(),
            source,
        })?;
    if let Some(endpoint) = &local_endpoint {
        endpoint.validate()?;
    }
    Ok(ConnectionInfoWithLocalEndpoint {
        info,
        local_endpoint,
    })
}

/// `read_with_local_endpoint` with the same wire-version check as
/// `read_for_client`.
pub fn read_for_client_with_local_endpoint(
    path: impl AsRef<Path>,
) -> Result<ConnectionInfoWithLocalEndpoint, ConnectionFileError> {
    let read = read_with_local_endpoint(path)?;
    read.info.validate_wire_version(PROTOCOL_VERSION)?;
    Ok(read)
}

fn read_owner_checked(path: &Path) -> Result<Vec<u8>, ConnectionFileError> {
    let mut options = OpenOptions::new();
    options.read(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        // A FIFO or device at a predictable path must not block the open;
        // the regular-file check below then refuses it.
        options.custom_flags(
            (rustix::fs::OFlags::NONBLOCK | rustix::fs::OFlags::NOCTTY).bits() as i32,
        );
    }
    let mut file = options
        .open(path)
        .map_err(|source| ConnectionFileError::Io {
            op: "open",
            path: path.to_path_buf(),
            source,
        })?;
    let is_file = file
        .metadata()
        .map_err(|source| ConnectionFileError::Io {
            op: "fstat",
            path: path.to_path_buf(),
            source,
        })?
        .is_file();
    if !is_file {
        return Err(ConnectionFileError::Invalid {
            reason: format!("connection file {} is not a regular file", path.display()),
        });
    }
    // Verify the opened inode, not a separate path lookup: replacing the path
    // between stat and read must not let an unverified key through.
    verify_owner_only(path, &file)?;
    let mut bytes = Vec::new();
    file.read_to_end(&mut bytes)
        .map_err(|source| ConnectionFileError::Io {
            op: "read",
            path: path.to_path_buf(),
            source,
        })?;
    Ok(bytes)
}

fn parse_info(path: &Path, bytes: &[u8]) -> Result<ConnectionInfo, ConnectionFileError> {
    let info: ConnectionInfo =
        serde_json::from_slice(bytes).map_err(|source| ConnectionFileError::JsonRead {
            path: path.to_path_buf(),
            source,
        })?;
    info.validate()?;
    Ok(info)
}

/// Reads connection information for a client and rejects a declared envelope
/// version this binary cannot decode before a TCP connection is attempted.
pub fn read_for_client(path: impl AsRef<Path>) -> Result<ConnectionInfo, ConnectionFileError> {
    let info = read(path)?;
    info.validate_wire_version(PROTOCOL_VERSION)?;
    Ok(info)
}

/// The paths a reader consults, most specific first. `explicit` is the
/// caller's own override (a `--subc` flag); `env_named` is the value of
/// `SUBC_CONNECTION_FILE` read by the caller. Either, when present, is the
/// ONLY candidate.
pub fn discovery_candidates(explicit: Option<&Path>, env_named: Option<&OsStr>) -> Vec<PathBuf> {
    let runtime_dir = non_empty_os_var("XDG_RUNTIME_DIR");
    let home = non_empty_os_var("HOME");
    discovery_candidates_with_environment(
        explicit,
        env_named,
        runtime_dir.as_deref(),
        home.as_deref(),
        &env::temp_dir(),
    )
}

/// Read the reader-side environment and return the first usable connection file.
/// Unlike writer-side `subc_daemon::bootstrap::connection_file_path()`, this searches
/// every location where an already-running daemon may have written its file.
pub fn discover(explicit: Option<&Path>) -> Result<Discovered, DiscoveryError> {
    let env_named = non_empty_os_var("SUBC_CONNECTION_FILE");
    discover_candidates(discovery_candidates(explicit, env_named.as_deref()))
}

fn discovery_candidates_with_environment(
    explicit: Option<&Path>,
    env_named: Option<&OsStr>,
    runtime_dir: Option<&OsStr>,
    home: Option<&OsStr>,
    temp_dir: &Path,
) -> Vec<PathBuf> {
    if let Some(path) = explicit {
        return vec![path.to_path_buf()];
    }

    let env_named = env_named.filter(|value| !value.is_empty());
    let runtime_dir = runtime_dir.filter(|value| !value.is_empty());

    // SUBC_CONNECTION_FILE names the daemon the caller means, so it is EXCLUSIVE
    // rather than first-in-a-list. It used to be pushed ahead of the discovery
    // candidates, which reads as honouring it and is not: a path that is set and
    // wrong falls through to discovery and answers from whichever daemon is found
    // -- in practice production. The reply is then true and about the wrong
    // machine, and every later verdict inherits that while the operator believes
    // they are reading a rig.
    //
    // A fallback is only a hazard where the primary is optional, so removing the
    // fallback for a deliberately supplied value removes the class. Returning a
    // single candidate keeps the existing error path: the file is stat-ed, and an
    // unreadable one is reported as a failure naming that path.
    if let Some(only) = env_named {
        return vec![PathBuf::from(only)];
    }

    let mut candidates = Vec::new();
    if let Some(runtime_dir) = runtime_dir {
        push_unique(
            &mut candidates,
            PathBuf::from(runtime_dir).join(CONNECTION_FILE_NAME),
        );
    }
    if let Some(home) = home {
        let mut path = PathBuf::from(home);
        for part in PROD_CONNECTION_RELATIVE_PATH {
            path.push(part);
        }
        push_unique(&mut candidates, path);
    }
    push_unique(
        &mut candidates,
        temp_dir.join(format!("subc-{}.connection.json", user_connection_token())),
    );
    candidates
}

fn discover_candidates(candidates: Vec<PathBuf>) -> Result<Discovered, DiscoveryError> {
    let mut tried = Vec::new();
    for path in candidates {
        match read_for_client(&path) {
            Ok(info) => return Ok(Discovered { path, info }),
            Err(source) => tried.push(TriedCandidate {
                path,
                reason: discovery_reason(&source),
            }),
        }
    }
    Err(DiscoveryError { tried })
}

/// A connection file chosen by [`discover_reachable`], with what implicit
/// discovery passed over to reach it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReachableDiscovery {
    pub discovered: Discovered,
    /// Readable default files skipped because nothing was listening at their
    /// endpoint: left behind by a daemon that is gone.
    pub stale: Vec<PathBuf>,
    /// Readable default files after the chosen one, never tried. A client
    /// that fails to authenticate to the chosen daemon names them rather
    /// than trying them: a different daemon is not a fallback for a failed
    /// identity check.
    pub others: Vec<PathBuf>,
}

/// Like [`discover`], but implicit discovery passes over a readable default
/// file whose endpoint has nothing listening (the connection is refused)
/// when another readable default file follows it. An explicit path or
/// `SUBC_CONNECTION_FILE` stays the only candidate. The last readable
/// default file is chosen without a check, so when every file is stale the
/// caller's own connection attempt reports the refusal.
pub fn discover_reachable(explicit: Option<&Path>) -> Result<ReachableDiscovery, DiscoveryError> {
    let env_named = non_empty_os_var("SUBC_CONNECTION_FILE");
    let named = explicit.is_some() || env_named.is_some();
    let candidates = discovery_candidates(explicit, env_named.as_deref());
    if named {
        return discover_candidates(candidates).map(|discovered| ReachableDiscovery {
            discovered,
            stale: Vec::new(),
            others: Vec::new(),
        });
    }
    discover_reachable_candidates(candidates, nothing_listening)
}

/// How long the listener check waits for a connection before treating the
/// endpoint as live: only a refusal proves a file stale.
const LISTENER_CHECK_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(500);

/// Whether the first endpoint a client dials refuses connections. Anything
/// short of a refusal (a timeout, an unparsable host) is not proof that the
/// daemon is gone, so it counts as listening.
fn nothing_listening(info: &ConnectionInfo) -> bool {
    let Some(endpoint) = info.endpoints.first() else {
        return false;
    };
    let Ok(ip) = endpoint.host.parse::<std::net::IpAddr>() else {
        return false;
    };
    let address = std::net::SocketAddr::new(ip, endpoint.port);
    listener_probe(address)
        .is_err_and(|error| error.kind() == std::io::ErrorKind::ConnectionRefused)
}

fn listener_probe(address: std::net::SocketAddr) -> io::Result<std::net::TcpStream> {
    #[cfg(windows)]
    if address.ip().is_loopback() {
        return subc_os::connect_loopback(address, LISTENER_CHECK_TIMEOUT);
    }
    std::net::TcpStream::connect_timeout(&address, LISTENER_CHECK_TIMEOUT)
}

/// Reads candidates in priority order and stops at the first one to use: a
/// lower-priority file is never opened while a higher one serves. A readable
/// file is checked for a listener only when a later candidate exists on disk
/// (a `stat`, which cannot block on a special file); a refusal there makes
/// it stale and the search goes on. When every readable file proved stale,
/// the first is returned so the caller's own connection reports it.
fn discover_reachable_candidates(
    candidates: Vec<PathBuf>,
    mut nothing_listening: impl FnMut(&ConnectionInfo) -> bool,
) -> Result<ReachableDiscovery, DiscoveryError> {
    let present = |paths: &[PathBuf]| -> Vec<PathBuf> {
        paths
            .iter()
            .filter(|path| fs::symlink_metadata(path).is_ok())
            .cloned()
            .collect()
    };
    let mut tried = Vec::new();
    let mut stale: Vec<Discovered> = Vec::new();
    for (index, path) in candidates.iter().enumerate() {
        match read_for_client(path) {
            Ok(info) => {
                let later = present(&candidates[index + 1..]);
                if later.is_empty() || !nothing_listening(&info) {
                    return Ok(ReachableDiscovery {
                        discovered: Discovered {
                            path: path.clone(),
                            info,
                        },
                        stale: stale.into_iter().map(|file| file.path).collect(),
                        others: later,
                    });
                }
                stale.push(Discovered {
                    path: path.clone(),
                    info,
                });
            }
            Err(source) => tried.push(TriedCandidate {
                path: path.clone(),
                reason: discovery_reason(&source),
            }),
        }
    }
    if stale.is_empty() {
        return Err(DiscoveryError { tried });
    }
    let first = stale.remove(0);
    let others = present(&candidates)
        .into_iter()
        .filter(|path| *path != first.path)
        .collect();
    Ok(ReachableDiscovery {
        discovered: first,
        stale: Vec::new(),
        others,
    })
}

fn push_unique(paths: &mut Vec<PathBuf>, path: PathBuf) {
    if !paths.iter().any(|existing| existing == &path) {
        paths.push(path);
    }
}

fn non_empty_os_var(key: &str) -> Option<OsString> {
    let value = env::var_os(key)?;
    if value.is_empty() {
        None
    } else {
        Some(value)
    }
}

fn discovery_reason(source: &ConnectionFileError) -> String {
    match source {
        ConnectionFileError::Io { source, .. } if source.kind() == io::ErrorKind::NotFound => {
            "not found".to_string()
        }
        other => other.to_string(),
    }
}

/// The per-user component of the temp-fallback connection-file name.
///
/// The daemon writer and every reader use this one implementation so a naming
/// drift cannot make a running daemon appear absent.
pub fn user_connection_token() -> String {
    // On Unix the token is the real uid, read from the kernel. Identity must not
    // depend on a fallible filesystem probe because a transient failure would
    // make the same user derive a different connection-file name.
    #[cfg(unix)]
    {
        rustix::process::getuid().as_raw().to_string()
    }

    #[cfg(not(unix))]
    {
        for key in ["USER", "USERNAME", "HOME", "USERPROFILE"] {
            if let Some(value) = non_empty_os_var(key) {
                return sanitize_token(&value.to_string_lossy());
            }
        }

        "unknown".to_string()
    }
}

#[cfg(not(unix))]
fn sanitize_token(raw: &str) -> String {
    let mut token = String::new();
    for ch in raw.chars() {
        if ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_') {
            token.push(ch);
        } else {
            token.push('_');
        }
    }
    if token.is_empty() {
        "unknown".to_string()
    } else {
        token
    }
}

#[cfg(unix)]
fn verify_owner_only(path: &Path, file: &File) -> Result<(), ConnectionFileError> {
    let meta = file.metadata().map_err(|source| ConnectionFileError::Io {
        op: "fstat",
        path: path.to_path_buf(),
        source,
    })?;
    verify_owner_only_for_uid(path, &meta, rustix::process::geteuid().as_raw())
}

#[cfg(unix)]
fn verify_owner_only_for_uid(
    path: &Path,
    meta: &fs::Metadata,
    uid: u32,
) -> Result<(), ConnectionFileError> {
    use std::os::unix::fs::{MetadataExt, PermissionsExt};
    // A foreign owner can substitute their own endpoint and key even at 0600.
    // This also refuses a foreign-owned file readable through an ACL or by root.
    if meta.uid() != uid {
        return Err(ConnectionFileError::Invalid {
            reason: format!(
                "connection file {} is owned by uid {}, expected effective uid {uid}",
                path.display(),
                meta.uid()
            ),
        });
    }
    let mode = meta.permissions().mode();
    // Any group or other permission bit means the key is exposed beyond the owner.
    if mode & 0o077 != 0 {
        return Err(ConnectionFileError::InsecurePermissions {
            path: path.to_path_buf(),
            mode: mode & 0o777,
        });
    }
    Ok(())
}

#[cfg(windows)]
fn verify_owner_only(path: &Path, file: &File) -> Result<(), ConnectionFileError> {
    subc_os::windows_acl::verify_owner_only(file).map_err(|error| ConnectionFileError::Invalid {
        reason: format!(
            "connection file {} is not owner-only: {error}",
            path.display()
        ),
    })
}

#[cfg(not(any(unix, windows)))]
fn verify_owner_only(_path: &Path, _file: &File) -> Result<(), ConnectionFileError> {
    Ok(())
}

pub fn generate_key() -> Result<Vec<u8>, ConnectionFileError> {
    let mut key = vec![0u8; KEY_LEN];
    getrandom::getrandom(&mut key).map_err(ConnectionFileError::Random)?;
    Ok(key)
}

pub fn generate_daemon_id() -> Result<[u8; DAEMON_ID_LEN], ConnectionFileError> {
    let mut daemon_id = [0u8; DAEMON_ID_LEN];
    getrandom::getrandom(&mut daemon_id).map_err(ConnectionFileError::Random)?;
    Ok(daemon_id)
}

fn write_atomic_inner(
    path: &Path,
    temp_path: &Path,
    json: &[u8],
) -> Result<(), ConnectionFileError> {
    {
        let mut file =
            open_owner_only_new(temp_path).map_err(|source| ConnectionFileError::Io {
                op: "create_temp",
                path: temp_path.to_path_buf(),
                source,
            })?;
        file.write_all(json)
            .and_then(|()| file.sync_all())
            .map_err(|source| ConnectionFileError::Io {
                op: "write_temp",
                path: temp_path.to_path_buf(),
                source,
            })?;
    }

    fs::rename(temp_path, path).map_err(|source| ConnectionFileError::Io {
        op: "rename",
        path: path.to_path_buf(),
        source,
    })?;
    Ok(())
}

#[cfg(not(windows))]
fn open_owner_only_new(path: &Path) -> io::Result<File> {
    let mut options = OpenOptions::new();
    options.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }
    options.open(path)
}

#[cfg(windows)]
fn open_owner_only_new(path: &Path) -> io::Result<File> {
    subc_os::windows_acl::create_private_file(path)
}

fn temp_path(parent: &Path, file_name: &std::ffi::OsStr) -> Result<PathBuf, ConnectionFileError> {
    let mut suffix = [0u8; 16];
    getrandom::getrandom(&mut suffix).map_err(ConnectionFileError::Random)?;
    let file_name = file_name.to_string_lossy();
    Ok(parent.join(format!(
        ".{file_name}.{}.{}.tmp",
        process::id(),
        hex(&suffix)
    )))
}

fn hex(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut out = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        out.push(HEX[(byte >> 4) as usize] as char);
        out.push(HEX[(byte & 0x0f) as usize] as char);
    }
    out
}

impl fmt::Display for ConnectionFileError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingParent { path } => {
                write!(f, "connection file path has no parent: {}", path.display())
            }
            Self::MissingFileName { path } => {
                write!(
                    f,
                    "connection file path has no file name: {}",
                    path.display()
                )
            }
            Self::Io { op, path, source } => write!(
                f,
                "connection file {op} failed for {}: {source}",
                path.display()
            ),
            Self::JsonRead { path, source } => write!(
                f,
                "connection file JSON read failed for {}: {source}",
                path.display()
            ),
            Self::JsonWrite { path, source } => write!(
                f,
                "connection file JSON write failed for {}: {source}",
                path.display()
            ),
            Self::Random(source) => write!(f, "connection file random generation failed: {source}"),
            Self::UnsupportedSchema { schema, supported } => write!(
                f,
                "unsupported connection file schema {schema}; expected {supported}"
            ),
            Self::WireVersionMismatch { file, supported } => write!(
                f,
                "connection file wire version {file} does not match supported wire version {supported}; the binary must be upgraded"
            ),
            Self::Invalid { reason } => write!(f, "invalid connection file: {reason}"),
            Self::KeyTooShort { len, min } => write!(
                f,
                "connection file key is too short: {len} bytes, need at least {min}"
            ),
            Self::InsecurePermissions { path, mode } => write!(
                f,
                "connection file {} has insecure permissions {mode:#o}; expected owner-only 0600",
                path.display()
            ),
            Self::InsecureParentDirectory { component, mode } => write!(
                f,
                "refusing to publish the connection file: ancestor {} is mode {mode:#o}, \
                 which lets another user replace the file regardless of its own 0600 mode; \
                 this is a misconfiguration check, not a defence against a same-uid caller",
                component.display()
            ),
        }
    }
}

impl Error for ConnectionFileError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Io { source, .. } => Some(source),
            Self::JsonRead { source, .. } | Self::JsonWrite { source, .. } => Some(source),
            Self::Random(_) => None,
            Self::MissingParent { .. }
            | Self::MissingFileName { .. }
            | Self::InsecureParentDirectory { .. }
            | Self::UnsupportedSchema { .. }
            | Self::WireVersionMismatch { .. }
            | Self::Invalid { .. }
            | Self::KeyTooShort { .. }
            | Self::InsecurePermissions { .. } => None,
        }
    }
}

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

    fn sample_info() -> ConnectionInfo {
        ConnectionInfo {
            schema: SCHEMA_VERSION,
            wire_version: None,
            endpoints: vec![Endpoint {
                host: "127.0.0.1".to_owned(),
                port: 8799,
            }],
            key: vec![0xABu8; KEY_LEN],
            daemon_id: [0x11u8; DAEMON_ID_LEN],
            pid: 4242,
            daemon_ver: "subc-test".to_owned(),
        }
    }

    #[cfg(windows)]
    #[test]
    fn windows_connection_temp_has_exact_protected_dacl_before_write() {
        use subc_os::windows_acl::test_support::{assert_owner_only, grant_everyone};
        let root = unique_temp_dir("windows-connection-temp");
        grant_everyone(root.path());
        let path = root.join("temp.json");
        let _file = open_owner_only_new(&path).unwrap();
        assert_owner_only(&path, false, true);
    }

    #[cfg(windows)]
    #[test]
    fn windows_connection_publication_has_exact_protected_dacl() {
        use subc_os::windows_acl::test_support::{assert_owner_only, grant_everyone};
        let root = unique_temp_dir("windows-connection-publication");
        grant_everyone(root.path());
        let parent = root.join("run");
        let path = parent.join(CONNECTION_FILE_NAME);
        write_atomic(&path, &sample_info()).unwrap();
        assert_owner_only(&parent, true, true);
        assert_owner_only(&path, false, true);
        assert_eq!(read(&path).unwrap(), sample_info());
    }

    #[cfg(windows)]
    #[test]
    fn windows_reader_refuses_everyone_read_without_repairing_file() {
        use subc_os::windows_acl::test_support::grant_everyone_read;
        let root = unique_temp_dir("windows-reader-everyone");
        subc_os::windows_acl::create_private_dir(root.path()).unwrap();
        let path = root.join(CONNECTION_FILE_NAME);
        write_atomic(&path, &sample_info()).unwrap();
        grant_everyone_read(&path);
        let json = fs::read(&path).unwrap();
        assert!(matches!(
            read(&path),
            Err(ConnectionFileError::Invalid { .. })
        ));
        assert_eq!(fs::read(&path).unwrap(), json);
        assert!(subc_os::windows_acl::verify_owner_only(&File::open(&path).unwrap()).is_err());
    }

    #[cfg(windows)]
    #[test]
    fn windows_reader_refuses_foreign_owner_when_token_can_assign_one() {
        use subc_os::windows_acl::test_support::apply_sddl;
        let root = unique_temp_dir("windows-reader-owner");
        subc_os::windows_acl::create_private_dir(root.path()).unwrap();
        let path = root.join(CONNECTION_FILE_NAME);
        write_atomic(&path, &sample_info()).unwrap();
        // BUILTIN\Users: an ordinary group, unlike the Administrators owner an
        // elevated writer produces, which the reader accepts.
        match apply_sddl(&path, "O:BU", true) {
            Ok(()) => {}
            Err(error) if matches!(error.raw_os_error(), Some(5 | 1300 | 1307 | 1314)) => {
                eprintln!("foreign owner fixture requires an elevated token: {error}");
                return;
            }
            Err(error) => panic!("assign foreign owner: {error}"),
        }
        assert!(matches!(
            read(&path),
            Err(ConnectionFileError::Invalid { .. })
        ));
    }

    #[cfg(windows)]
    #[test]
    fn windows_writer_refuses_existing_shared_directory_without_repair() {
        use subc_os::windows_acl::test_support::grant_everyone;
        let root = unique_temp_dir("windows-writer-shared");
        grant_everyone(root.path());
        let path = root.join(CONNECTION_FILE_NAME);
        assert!(matches!(
            write_atomic(&path, &sample_info()),
            Err(ConnectionFileError::Invalid { .. })
        ));
        assert!(!path.exists());
        assert!(subc_os::windows_acl::verify_private_dir(root.path()).is_err());
    }

    fn unique_temp_path() -> PathBuf {
        let mut suffix = [0u8; 8];
        getrandom::getrandom(&mut suffix).expect("random suffix");
        let mut name = String::from("subc-connfile-test-");
        for byte in suffix {
            name.push_str(&format!("{byte:02x}"));
        }
        name.push_str(".json");
        std::env::temp_dir().join(name)
    }

    fn unique_temp_dir(label: &str) -> ScratchDir {
        ScratchDir::new(label)
    }

    #[cfg(unix)]
    #[test]
    fn a_foreign_owned_ancestor_refuses_even_with_mode_0755() {
        use std::os::unix::fs::{MetadataExt, PermissionsExt};
        let root = unique_temp_dir("foreign-ancestor");
        let parent = root.join("run");
        fs::create_dir(&parent).unwrap();
        fs::set_permissions(&parent, fs::Permissions::from_mode(0o755)).unwrap();
        // Model a root writer inspecting an ordinary user's directory. The walk
        // uses actual filesystem metadata, without changing the test process uid.
        if fs::metadata(&parent).unwrap().uid() == 0 {
            assert!(process::Command::new("chown")
                .args(["65534"])
                .arg(&parent)
                .status()
                .unwrap()
                .success());
        }
        assert_ne!(fs::metadata(&parent).unwrap().uid(), 0);
        assert!(
            refuse_writable_ancestor_for_uid(&parent, 0).is_err(),
            "0755 does not prevent its owner replacing the key"
        );
        if rustix::process::geteuid().as_raw() != 0 {
            assert!(
                refuse_writable_ancestor(&parent).is_ok(),
                "the same directory is safe for its actual owner"
            );
        }
    }

    #[cfg(unix)]
    #[test]
    fn owner_only_file_validation_refuses_a_different_effective_uid() {
        use std::os::unix::fs::{MetadataExt, PermissionsExt};
        let root = unique_temp_dir("foreign-file");
        let path = root.join(CONNECTION_FILE_NAME);
        write_atomic(&path, &sample_info()).unwrap();
        fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
        let owner = fs::metadata(&path).unwrap().uid();
        let meta = fs::metadata(&path).unwrap();
        assert!(verify_owner_only_for_uid(&path, &meta, owner).is_ok());
        let different_uid = if owner == 0 { 1 } else { 0 };
        assert!(
            matches!(
                verify_owner_only_for_uid(&path, &meta, different_uid),
                Err(ConnectionFileError::Invalid { .. })
            ),
            "0600 is not proof that the file belongs to the reader"
        );
        assert_eq!(read(&path).unwrap(), sample_info());
    }

    /// A GROUP-writable ancestor must refuse, and the passing control on the same
    /// fixture minus the group bit is what makes this test discriminate.
    ///
    /// Both arms are here because the refusal MESSAGE is not the property: a test
    /// matching on message text passes through a removed check whenever the
    /// wording survives, which is how the adjacent guard in claustrum kept three
    /// green tests while examining only `0o002`. The arms differ by one bit on
    /// one directory and nothing else.
    #[cfg(unix)]
    #[test]
    fn a_group_writable_ancestor_refuses_and_the_same_tree_without_the_bit_publishes() {
        use std::os::unix::fs::PermissionsExt;

        for (ancestor_mode, expect_refusal) in [(0o770, true), (0o750, false)] {
            let root = unique_temp_dir(&format!("ancestor-{ancestor_mode:o}"));
            let ancestor = root.join("ancestor");
            let leaf = ancestor.join("run");
            fs::create_dir_all(&leaf).expect("create leaf");
            fs::set_permissions(&leaf, fs::Permissions::from_mode(0o700))
                .expect("tighten the leaf so only the ancestor differs");
            fs::set_permissions(&ancestor, fs::Permissions::from_mode(ancestor_mode))
                .expect("set ancestor mode");

            let result = write_atomic(leaf.join(CONNECTION_FILE_NAME), &sample_info());

            match (expect_refusal, result) {
                (true, Err(ConnectionFileError::InsecureParentDirectory { component, mode })) => {
                    let expected = ancestor.canonicalize().unwrap_or_else(|_| ancestor.clone());
                    assert_eq!(component, expected);
                    assert_eq!(mode & 0o020, 0o020, "the group bit is what refused");
                }
                (true, other) => panic!("a group-writable ancestor must refuse, got {other:?}"),
                (false, Ok(())) => {}
                (false, other) => panic!("0o750 is not writable by another user: {other:?}"),
            }

            let _ = fs::set_permissions(&ancestor, fs::Permissions::from_mode(0o700));
            let _ = fs::remove_dir_all(root);
        }
    }

    /// `/tmp` is 1777 by design. Without the sticky exemption this check fires on
    /// every correctly-configured system, and a check that refuses healthy
    /// configuration gets disabled -- after which it protects nothing.
    #[cfg(unix)]
    #[test]
    fn a_sticky_world_writable_ancestor_publishes() {
        use std::os::unix::fs::PermissionsExt;

        let root = unique_temp_dir("ancestor-sticky");
        let ancestor = root.join("sticky");
        let leaf = ancestor.join("run");
        fs::create_dir_all(&leaf).expect("create leaf");
        fs::set_permissions(&leaf, fs::Permissions::from_mode(0o700)).expect("tighten leaf");
        fs::set_permissions(&ancestor, fs::Permissions::from_mode(0o1777)).expect("sticky 1777");

        let published = write_atomic(leaf.join(CONNECTION_FILE_NAME), &sample_info());
        assert!(
            published.is_ok(),
            "a sticky 1777 ancestor is /tmp's own shape and must publish: {published:?}"
        );

        let _ = fs::set_permissions(&ancestor, fs::Permissions::from_mode(0o700));
        let _ = fs::remove_dir_all(root);
    }

    /// The daemon owns this directory, so the misconfiguration is unproducible
    /// rather than merely reported when the directory does not yet exist.
    #[cfg(unix)]
    #[test]
    fn an_absent_parent_is_created_owner_only() {
        use std::os::unix::fs::PermissionsExt;

        let root = unique_temp_dir("absent-parent");
        let parent = root.join("run");
        assert!(!parent.exists(), "fixture must start with no parent");

        write_atomic(parent.join(CONNECTION_FILE_NAME), &sample_info()).expect("publishes");

        let mode = fs::metadata(&parent)
            .expect("parent exists")
            .permissions()
            .mode()
            & 0o777;
        assert_eq!(mode, 0o700, "an absent parent is created owner-only");

        let _ = fs::remove_dir_all(root);
    }

    fn prod_connection_file(home: &Path) -> PathBuf {
        let mut path = home.to_path_buf();
        for part in PROD_CONNECTION_RELATIVE_PATH {
            path.push(part);
        }
        path
    }

    #[test]
    fn an_explicit_path_is_the_only_discovery_candidate() {
        let explicit = PathBuf::from("/rig/explicit.json");
        let env_named = OsStr::new("/rig/from-env.json");

        assert_eq!(
            discovery_candidates(Some(&explicit), Some(env_named)),
            vec![explicit],
            "the caller's explicit override must exclude every fallback"
        );
    }

    #[test]
    fn implicit_discovery_skips_a_default_file_nothing_listens_at() {
        let root = unique_temp_dir("reachable-stale");
        let stale_path = root.join("runtime").join(CONNECTION_FILE_NAME);
        let live_path = root.join("temp").join("subc-user.connection.json");
        // A daemon that crashed left its file; the live one listens elsewhere.
        let gone = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let gone_port = gone.local_addr().unwrap().port();
        let live = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let live_port = live.local_addr().unwrap().port();
        for (path, port) in [(&stale_path, gone_port), (&live_path, live_port)] {
            fs::create_dir_all(path.parent().unwrap()).unwrap();
            let mut info = sample_info();
            info.endpoints[0].port = port;
            write_atomic(path, &info).unwrap();
        }
        drop(gone);

        let found = discover_reachable_candidates(
            vec![stale_path.clone(), live_path.clone()],
            nothing_listening,
        )
        .unwrap();

        assert_eq!(found.discovered.path, live_path);
        assert_eq!(found.discovered.info.endpoints[0].port, live_port);
        assert_eq!(found.stale, vec![stale_path]);
        assert!(found.others.is_empty());
        drop(live);
    }

    #[test]
    fn implicit_discovery_keeps_a_listening_file_and_names_the_rest() {
        let root = unique_temp_dir("reachable-first");
        let first = root.join("runtime").join(CONNECTION_FILE_NAME);
        let second = root.join("temp").join("subc-user.connection.json");
        for path in [&first, &second] {
            fs::create_dir_all(path.parent().unwrap()).unwrap();
            write_atomic(path, &sample_info()).unwrap();
        }
        let mut checked = 0;
        let found = discover_reachable_candidates(vec![first.clone(), second.clone()], |_| {
            checked += 1;
            false
        })
        .unwrap();
        assert_eq!(found.discovered.path, first);
        assert!(found.stale.is_empty());
        assert_eq!(found.others, vec![second]);
        assert_eq!(
            checked, 1,
            "only files with a later alternative are checked"
        );

        // With every earlier file stale, the last is chosen unchecked and the
        // caller's own connection reports what it finds there.
        let mut checked = 0;
        let found =
            discover_reachable_candidates(vec![first.clone(), root.join("absent.json")], |_| {
                checked += 1;
                true
            })
            .unwrap();
        assert_eq!(found.discovered.path, first);
        assert_eq!(checked, 0, "a lone readable file is never checked");
    }

    /// A FIFO at a lower-priority candidate path (the temporary directory
    /// is shared) must neither be opened while a better candidate serves nor
    /// block discovery when it is the one being read.
    #[cfg(unix)]
    #[test]
    fn a_fifo_candidate_never_blocks_discovery() {
        let root = unique_temp_dir("reachable-fifo");
        let first = root.join("runtime").join(CONNECTION_FILE_NAME);
        fs::create_dir_all(first.parent().unwrap()).unwrap();
        write_atomic(&first, &sample_info()).unwrap();
        let fifo = root.join("subc-user.connection.json");
        assert!(std::process::Command::new("mkfifo")
            .arg(&fifo)
            .status()
            .unwrap()
            .success());
        let within = |candidates: Vec<PathBuf>| {
            let (done, finished) = std::sync::mpsc::channel();
            std::thread::spawn(move || {
                let _ = done.send(discover_reachable_candidates(candidates, |_| false));
            });
            finished
                .recv_timeout(Duration::from_secs(5))
                .expect("discovery blocked on a FIFO")
        };

        let found = within(vec![first.clone(), fifo.clone()]).unwrap();
        assert_eq!(found.discovered.path, first);

        let error = within(vec![fifo.clone()]).expect_err("a FIFO is no connection file");
        assert!(
            error.tried[0].reason.contains("regular file"),
            "{:?}",
            error.tried
        );
    }

    #[test]
    fn named_files_stay_exclusive_under_reachable_discovery() {
        let root = unique_temp_dir("reachable-named");
        let named = root.join("missing-rig.json");
        let error = discover_reachable(Some(&named)).expect_err("a missing named file fails");
        assert_eq!(
            error
                .tried
                .iter()
                .map(|tried| &tried.path)
                .collect::<Vec<_>>(),
            vec![&named]
        );
    }

    #[test]
    fn set_and_wrong_environment_path_fails_without_fallback() {
        let root = unique_temp_dir("env-exclusive");
        let runtime = root.join("runtime");
        let home = root.join("home");
        let temp = root.join("temp");
        let named = root.join("missing-rig.json");
        let production = prod_connection_file(&home);
        fs::create_dir_all(production.parent().expect("production parent"))
            .expect("create production parent");
        write_atomic(&production, &sample_info()).expect("write discoverable production file");

        assert_eq!(
            discovery_candidates(None, Some(named.as_os_str())),
            vec![named.clone()],
            "a named connection file must not be followed by discovery paths"
        );
        let candidates = discovery_candidates_with_environment(
            None,
            Some(named.as_os_str()),
            Some(runtime.as_os_str()),
            Some(home.as_os_str()),
            &temp,
        );
        let error = discover_candidates(candidates)
            .expect_err("set-and-wrong SUBC_CONNECTION_FILE must fail rather than use production");

        assert_eq!(
            error.tried,
            vec![TriedCandidate {
                path: named.clone(),
                reason: "not found".to_owned(),
            }],
            "the named rig path must be the only attempted file"
        );
        assert!(
            error.to_string().contains(&named.display().to_string()),
            "the failure must name the operator-selected rig path"
        );
        drop(root);
    }

    #[test]
    fn empty_environment_paths_are_unset_and_fallback_candidates_are_absolute() {
        let root = unique_temp_dir("empty-candidates");
        let runtime = root.join("runtime");
        let home = root.join("home");
        let temp = root.join("temp");
        let empty = OsStr::new("");

        let without_named_override = discovery_candidates_with_environment(
            None,
            None,
            Some(runtime.as_os_str()),
            Some(home.as_os_str()),
            &temp,
        );
        let with_empty_named_override = discovery_candidates_with_environment(
            None,
            Some(empty),
            Some(runtime.as_os_str()),
            Some(home.as_os_str()),
            &temp,
        );
        assert_eq!(with_empty_named_override, without_named_override);

        let without_runtime =
            discovery_candidates_with_environment(None, None, None, Some(home.as_os_str()), &temp);
        let with_empty_runtime = discovery_candidates_with_environment(
            None,
            None,
            Some(empty),
            Some(home.as_os_str()),
            &temp,
        );
        assert_eq!(with_empty_runtime, without_runtime);
        assert!(
            with_empty_named_override.iter().all(|path| path.is_absolute())
                && with_empty_runtime.iter().all(|path| path.is_absolute()),
            "every fallback candidate must be absolute: {with_empty_named_override:?} {with_empty_runtime:?}"
        );

        drop(root);
    }

    #[test]
    fn discovery_without_overrides_keeps_three_rung_order_and_deduplicates() {
        let root = unique_temp_dir("candidate-order");
        let runtime = root.join("runtime");
        let home = root.join("home");
        let temp = root.join("temp");

        let candidates = discovery_candidates_with_environment(
            None,
            None,
            Some(runtime.as_os_str()),
            Some(home.as_os_str()),
            &temp,
        );
        assert_eq!(
            candidates,
            vec![
                runtime.join(CONNECTION_FILE_NAME),
                prod_connection_file(&home),
                temp.join(format!("subc-{}.connection.json", user_connection_token())),
            ],
            "readers must try runtime, production, then the per-user temp fallback"
        );

        let production = prod_connection_file(&home);
        let production_dir = production.parent().expect("production directory");
        let deduplicated = discovery_candidates_with_environment(
            None,
            None,
            Some(production_dir.as_os_str()),
            Some(home.as_os_str()),
            &temp,
        );
        assert_eq!(
            deduplicated,
            vec![
                production,
                temp.join(format!("subc-{}.connection.json", user_connection_token())),
            ],
            "one path reached through two rungs must only be tried once"
        );
        drop(root);
    }

    #[test]
    fn discover_on_a_temp_home_returns_the_parsed_production_file() {
        const CHILD_MARKER: &str = "SUBC_TRANSPORT_DISCOVERY_CHILD_EXPECTED";
        if let Some(expected) = env::var_os(CHILD_MARKER) {
            let expected = PathBuf::from(expected);
            let discovered = discover(None).expect("discover production connection file");
            assert_eq!(discovered.path, expected);
            assert_eq!(discovered.info, sample_info());
            return;
        }

        let root = unique_temp_dir("discover-home");
        let home = root.join("home");
        let temp = root.join("temp");
        fs::create_dir_all(&temp).expect("create child temp directory");
        let production = prod_connection_file(&home);
        fs::create_dir_all(production.parent().expect("production parent"))
            .expect("create production parent");
        write_atomic(&production, &sample_info()).expect("write production connection file");

        // Run the public environment-reading API in a child so this test does not
        // mutate process-global environment while sibling tests execute.
        let output = process::Command::new(env::current_exe().expect("current test executable"))
            .args([
                "--exact",
                "connection_file::tests::discover_on_a_temp_home_returns_the_parsed_production_file",
                "--nocapture",
            ])
            .env(CHILD_MARKER, &production)
            .env_remove("SUBC_CONNECTION_FILE")
            .env_remove("XDG_RUNTIME_DIR")
            .env("HOME", &home)
            .env("TMPDIR", &temp)
            .env("TMP", &temp)
            .env("TEMP", &temp)
            .output()
            .expect("run isolated discovery child");
        assert!(
            output.status.success(),
            "discovery child failed\nstdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        drop(root);
    }

    #[test]
    fn write_atomic_sweeps_stale_temps_and_spares_recent_and_unrelated_files() {
        let dir = ScratchDir::new("subc-sweep");
        let target = dir.join("subc-connection.json");

        // A temp stranded by a dead writer: correct shape, old enough to sweep.
        let stale = dir.join(".subc-connection.json.99999.deadbeef.tmp");
        fs::write(&stale, b"stranded").expect("write stale");
        let old = SystemTime::now() - Duration::from_secs(3600);
        File::options()
            .write(true)
            .open(&stale)
            .expect("open stale")
            .set_modified(old)
            .expect("backdate stale");

        // A temp from a writer that may still be mid-rename: same shape, fresh.
        // Sweeping this would race a concurrent publish.
        let recent = dir.join(".subc-connection.json.99998.feedface.tmp");
        fs::write(&recent, b"in flight").expect("write recent");

        // An old file that is not one of our temps. Age alone must not condemn it.
        let unrelated = dir.join("unrelated.txt");
        fs::write(&unrelated, b"not ours").expect("write unrelated");
        File::options()
            .write(true)
            .open(&unrelated)
            .expect("open unrelated")
            .set_modified(old)
            .expect("backdate unrelated");

        write_atomic(&target, &sample_info()).expect("publish");

        assert!(!stale.exists(), "a stale temp must be swept");
        assert!(
            recent.exists(),
            "a recent temp may belong to an in-flight publish and must be spared"
        );
        assert!(
            unrelated.exists(),
            "age alone must not condemn a file that is not one of our temps"
        );
        assert!(target.exists(), "the publish itself must still land");
    }

    #[test]
    fn debug_redacts_key_bytes() {
        let info = sample_info();
        let rendered = format!("{info:?}");
        assert!(
            rendered.contains("redacted"),
            "Debug must mark the key as redacted: {rendered}"
        );
        // The raw key byte pattern (0xab) must not appear anywhere in the output.
        assert!(
            !rendered.contains("171") && !rendered.to_lowercase().contains("ab, ab"),
            "Debug must not leak raw key bytes: {rendered}"
        );
    }

    #[test]
    fn validate_rejects_unsupported_schema_empty_endpoints_and_short_key() {
        let mut unsupported_schema = sample_info();
        unsupported_schema.schema = SCHEMA_VERSION + 1;
        let before = unsupported_schema.clone();
        let err = unsupported_schema
            .validate()
            .expect_err("unsupported schema must be rejected");
        assert!(matches!(
            err,
            ConnectionFileError::UnsupportedSchema {
                schema,
                supported: SCHEMA_VERSION,
            } if schema == SCHEMA_VERSION + 1
        ));
        assert_eq!(unsupported_schema, before, "validate must not mutate input");

        let mut empty_endpoints = sample_info();
        empty_endpoints.endpoints.clear();
        let before = empty_endpoints.clone();
        let err = empty_endpoints
            .validate()
            .expect_err("empty endpoint list must be rejected");
        assert!(matches!(
            err,
            ConnectionFileError::Invalid { ref reason }
                if reason == "connection file must include at least one endpoint"
        ));
        assert_eq!(empty_endpoints, before, "validate must not mutate input");

        let mut short_key = sample_info();
        short_key.key = vec![0xAB; MIN_KEY_LEN - 1];
        let before = short_key.clone();
        let err = short_key
            .validate()
            .expect_err("short key must be rejected");
        assert!(matches!(
            err,
            ConnectionFileError::KeyTooShort {
                len,
                min: MIN_KEY_LEN,
            } if len == MIN_KEY_LEN - 1
        ));
        assert_eq!(short_key, before, "validate must not mutate input");
    }

    #[test]
    fn optional_wire_version_round_trips() {
        let path = unique_temp_path();
        let legacy = sample_info();
        write_atomic(&path, &legacy).expect("write legacy connection file");
        let legacy_json = fs::read_to_string(&path).expect("read legacy connection file");
        assert!(!legacy_json.contains("wire_version"));
        assert_eq!(
            read_for_client(&path).expect("legacy file remains readable"),
            legacy
        );

        let mut current = sample_info();
        current.wire_version = Some(PROTOCOL_VERSION);
        write_atomic(&path, &current).expect("write current connection file");
        let current_json = fs::read_to_string(&path).expect("read current connection file");
        let current_json: serde_json::Value =
            serde_json::from_str(&current_json).expect("parse current connection file");
        assert_eq!(
            current_json["wire_version"].as_u64(),
            Some(u64::from(PROTOCOL_VERSION))
        );
        assert_eq!(
            read_for_client(&path).expect("current file is readable"),
            current
        );
        let _ = fs::remove_file(&path);
    }

    #[test]
    fn read_for_client_rejects_mismatched_wire_version() {
        let path = unique_temp_path();
        let mut info = sample_info();
        let file_version = PROTOCOL_VERSION + 1;
        info.wire_version = Some(file_version);
        write_atomic(&path, &info).expect("write mismatched connection file");

        let err = read_for_client(&path).expect_err("mismatched wire version must fail discovery");
        assert!(matches!(
            err,
            ConnectionFileError::WireVersionMismatch { file, supported }
                if file == file_version && supported == PROTOCOL_VERSION
        ));
        let rendered = err.to_string();
        assert!(rendered.contains(&file_version.to_string()));
        assert!(rendered.contains(&PROTOCOL_VERSION.to_string()));
        assert!(rendered.contains("binary must be upgraded"));
        let _ = fs::remove_file(&path);
    }

    fn unix_endpoint() -> LocalEndpoint {
        LocalEndpoint::Unix {
            path: PathBuf::from("/run/user/1000/cortexkit/subc.sock"),
        }
    }

    fn pipe_endpoint() -> LocalEndpoint {
        LocalEndpoint::Pipe {
            name: r"\\.\pipe\subc-0123456789abcdef".to_owned(),
        }
    }

    /// Writes raw JSON as an owner-only file so a test can hand the readers a
    /// shape the writer would never produce.
    fn write_raw_owner_only(path: &Path, json: &serde_json::Value) {
        let mut file = open_owner_only_new(path).expect("create owner-only fixture");
        file.write_all(&serde_json::to_vec_pretty(json).unwrap())
            .expect("write fixture");
    }

    #[test]
    fn local_endpoint_serialises_as_kind_tagged_objects() {
        assert_eq!(
            serde_json::to_value(unix_endpoint()).unwrap(),
            serde_json::json!({"kind": "unix", "path": "/run/user/1000/cortexkit/subc.sock"})
        );
        assert_eq!(
            serde_json::to_value(pipe_endpoint()).unwrap(),
            serde_json::json!({"kind": "pipe", "name": r"\\.\pipe\subc-0123456789abcdef"})
        );
    }

    #[test]
    fn writer_without_local_endpoint_matches_write_atomic_byte_for_byte() {
        let dir = unique_temp_dir("local-endpoint-absent");
        let plain = dir.join("plain.json");
        let variant = dir.join("variant.json");
        write_atomic(&plain, &sample_info()).expect("write plain");
        write_atomic_with_local_endpoint(&variant, &sample_info(), None).expect("write variant");

        let variant_bytes = fs::read(&variant).unwrap();
        assert_eq!(fs::read(&plain).unwrap(), variant_bytes);
        assert!(
            !String::from_utf8(variant_bytes)
                .unwrap()
                .contains("local_endpoint"),
            "an absent endpoint must be omitted, never written as null"
        );

        let read_back = read_with_local_endpoint(&variant).expect("read variant");
        assert_eq!(read_back.info, sample_info());
        assert_eq!(read_back.local_endpoint, None);
    }

    #[test]
    fn local_endpoint_round_trips_and_the_plain_reader_still_parses_the_file() {
        for endpoint in [unix_endpoint(), pipe_endpoint()] {
            let dir = unique_temp_dir("local-endpoint-round-trip");
            let path = dir.join(CONNECTION_FILE_NAME);
            let mut info = sample_info();
            info.wire_version = Some(PROTOCOL_VERSION);
            write_atomic_with_local_endpoint(&path, &info, Some(&endpoint)).expect("write");

            let json: serde_json::Value =
                serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
            assert_eq!(
                json["local_endpoint"],
                serde_json::to_value(&endpoint).unwrap()
            );
            assert_eq!(json["schema"], serde_json::json!(SCHEMA_VERSION));

            assert_eq!(
                read_with_local_endpoint(&path).expect("read with endpoint"),
                ConnectionInfoWithLocalEndpoint {
                    info: info.clone(),
                    local_endpoint: Some(endpoint.clone()),
                }
            );
            assert_eq!(
                read_for_client_with_local_endpoint(&path)
                    .expect("client read with endpoint")
                    .local_endpoint,
                Some(endpoint)
            );
            // Existing readers ignore the key and see the same ConnectionInfo.
            assert_eq!(read(&path).expect("plain read"), info);
            assert_eq!(read_for_client(&path).expect("plain client read"), info);
        }
    }

    #[test]
    fn a_file_written_before_local_endpoint_existed_reads_as_absent() {
        let dir = unique_temp_dir("local-endpoint-legacy");
        let path = dir.join(CONNECTION_FILE_NAME);
        // The exact key set an older daemon writes, with no wire_version either.
        let key = vec![0xABu8; KEY_LEN];
        let daemon_id = [0x11u8; DAEMON_ID_LEN];
        write_raw_owner_only(
            &path,
            &serde_json::json!({
                "schema": SCHEMA_VERSION,
                "endpoints": [{"host": "127.0.0.1", "port": 8799}],
                "key": key,
                "daemon_id": daemon_id,
                "pid": 4242,
                "daemon_ver": "subc-test",
            }),
        );

        assert_eq!(read(&path).expect("legacy plain read"), sample_info());
        let read_back = read_with_local_endpoint(&path).expect("legacy read with endpoint");
        assert_eq!(read_back.info, sample_info());
        assert_eq!(read_back.local_endpoint, None);
    }

    #[test]
    fn a_malformed_local_endpoint_is_an_error_not_absent_and_the_plain_reader_ignores_it() {
        let malformed = [
            serde_json::json!({"kind": "tcp", "host": "127.0.0.1"}),
            serde_json::json!({"kind": "unix"}),
            serde_json::json!({"path": "/tmp/subc.sock"}),
            serde_json::json!("/tmp/subc.sock"),
            serde_json::json!({"kind": "unix", "path": ""}),
            serde_json::json!({"kind": "pipe", "name": ""}),
        ];
        for (index, endpoint) in malformed.into_iter().enumerate() {
            let dir = unique_temp_dir("local-endpoint-malformed");
            let path = dir.join(CONNECTION_FILE_NAME);
            let mut json = serde_json::to_value(sample_info()).unwrap();
            json["local_endpoint"] = endpoint.clone();
            write_raw_owner_only(&path, &json);

            assert!(
                matches!(
                    read_with_local_endpoint(&path),
                    Err(ConnectionFileError::JsonRead { .. } | ConnectionFileError::Invalid { .. })
                ),
                "case {index}: {endpoint} must not read as an absent endpoint"
            );
            assert_eq!(
                read(&path).expect("plain reader ignores local_endpoint"),
                sample_info(),
                "case {index}"
            );
        }
    }

    #[test]
    fn writer_refuses_an_empty_local_endpoint_without_publishing() {
        let dir = unique_temp_dir("local-endpoint-empty");
        let path = dir.join(CONNECTION_FILE_NAME);
        for endpoint in [
            LocalEndpoint::Unix {
                path: PathBuf::new(),
            },
            LocalEndpoint::Pipe {
                name: String::new(),
            },
        ] {
            assert!(matches!(
                write_atomic_with_local_endpoint(&path, &sample_info(), Some(&endpoint)),
                Err(ConnectionFileError::Invalid { .. })
            ));
            assert!(!path.exists());
        }
    }

    #[cfg(unix)]
    #[test]
    fn read_with_local_endpoint_keeps_the_owner_only_check() {
        use std::os::unix::fs::PermissionsExt;

        let dir = unique_temp_dir("local-endpoint-perms");
        let path = dir.join(CONNECTION_FILE_NAME);
        write_atomic_with_local_endpoint(&path, &sample_info(), Some(&unix_endpoint()))
            .expect("write");
        fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).expect("relax");
        assert!(matches!(
            read_with_local_endpoint(&path),
            Err(ConnectionFileError::InsecurePermissions { mode, .. }) if mode == 0o644
        ));
    }

    #[cfg(unix)]
    #[test]
    fn read_rejects_group_or_world_readable_file() {
        use std::os::unix::fs::PermissionsExt;

        let path = unique_temp_path();
        write_atomic(&path, &sample_info()).expect("write owner-only file");
        // Loosen permissions as if the key leaked to other local users.
        fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).expect("relax permissions");

        let err = read(&path).expect_err("group/world-readable key file must be rejected");
        assert!(
            matches!(err, ConnectionFileError::InsecurePermissions { mode, .. } if mode == 0o644),
            "expected InsecurePermissions, got {err:?}"
        );
        let _ = fs::remove_file(&path);
    }
}