rightkit-daemon 0.3.0

One discovery/auth convention for Right Suite local services: service.json, ranking and takeover, current-user-only Unix socket / named pipe, per-app request allowlist.
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
//! Verifying the HOST from the client side.
//!
//! The server side of this crate has always checked its peer: the kernel says the client runs as
//! the same user. A client used to check only the mirror image of that, that whatever answered at
//! the recorded endpoint also runs as the same user. That says nothing about WHICH program it is,
//! so a program that managed to get the client to dial it (by redirecting the suite root, by
//! writing a `service.json`, or by binding the socket path first) received the client's `hello`
//! and every request after it, including any secret in them.
//!
//! [`HostExpectation`] closes that. The caller names the executable(s) the host may be;
//! [`Client::connect_expecting`](crate::Client::connect_expecting) asks the kernel who is on the
//! listening end of the connected socket and refuses anyone else before a single application
//! byte is written. See the README section "Verifying the host" for the threat model.

use std::ffi::OsStr;
use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;

/// The process the OS says is on the listening end of a connection this client opened, as it was
/// when every check passed. Returned by
/// [`Client::verified_host`](crate::Client::verified_host) and handed to a caller-supplied
/// verifier ([`HostExpectation::with_verifier`]).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct HostProcess {
    /// The host's process id as the kernel recorded it for the socket. A pid names a process
    /// only while it runs: use it for an audit trail, not as a credential.
    pub pid: u32,
    /// Unix: the host's effective uid (always the client's own). Windows: `None`.
    pub uid: Option<u32>,
    /// Windows: the host process token's user SID. Unix: `None`.
    pub sid: Option<String>,
    /// The host's executable path as the kernel reports it for `pid` (macOS `proc_pidpath`,
    /// Linux `/proc/<pid>/exe`), canonicalised when it still exists on disk.
    pub executable: PathBuf,
    /// macOS: the host's audit token (`audit_token_t`, eight words: pid at index 5, pid version
    /// at index 7) from `LOCAL_PEERTOKEN`, when the kernel provides it. It is the race-free
    /// handle for code-signature checks (`SecCodeCopyGuestWithAttributes` with
    /// `kSecGuestAttributeAudit`), which a [`HostExpectation::with_verifier`] closure can use.
    /// `None` elsewhere.
    pub audit_token: Option<[u32; 8]>,
}

/// Why a host was refused. Always the host's identity, never a connection problem.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum HostIdentityReason {
    /// The expectation names no executable, so no host can match. Fails closed.
    NoExpectation,
    /// The host runs as another user than this client.
    UidMismatch { host: Option<u32>, client: u32 },
    /// The OS did not report the host's process id (a BSD, or a pid namespace that hides it).
    PidUnavailable,
    /// The kernel would not describe the host process (permission, or the call failed).
    Unreadable(String),
    /// The host's executable is not one of the expected executables.
    ExecutableMismatch,
    /// The process behind the socket exited or changed while it was being identified, so the pid
    /// could not be proven to name one process throughout.
    HostChanged(String),
    /// The executable matched but the caller's extra verification refused the host.
    Refused(String),
    /// Identifying the host is not implemented for this platform. Fails closed: it never means
    /// "assume it is the right one".
    Unverified {
        platform: &'static str,
        detail: &'static str,
    },
    /// The OS could not answer the peer-credential query.
    Query(String),
    /// The caller is not a local app (a remote device has no OS peer), so there is no process
    /// to identify. Fails closed.
    NotLocalPeer,
}

impl fmt::Display for HostIdentityReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            HostIdentityReason::NoExpectation => {
                write!(
                    f,
                    "no expected host executable was supplied, so no host can match"
                )
            }
            HostIdentityReason::UidMismatch { host, client } => match host {
                Some(host) => write!(
                    f,
                    "the host runs as uid {host}, this client as uid {client}"
                ),
                None => write!(
                    f,
                    "the host's uid is unknown, this client runs as uid {client}"
                ),
            },
            HostIdentityReason::PidUnavailable => {
                write!(f, "the OS did not report the host's process id")
            }
            HostIdentityReason::Unreadable(why) => {
                write!(f, "the OS would not describe the host process ({why})")
            }
            HostIdentityReason::ExecutableMismatch => {
                write!(
                    f,
                    "the host's executable is not one of the expected executables"
                )
            }
            HostIdentityReason::HostChanged(why) => {
                write!(
                    f,
                    "the host process changed while it was identified ({why})"
                )
            }
            HostIdentityReason::Refused(why) => {
                write!(f, "the caller's extra host verification refused it ({why})")
            }
            HostIdentityReason::Unverified { platform, detail } => {
                write!(
                    f,
                    "host verification is unavailable on {platform} ({detail})"
                )
            }
            HostIdentityReason::Query(why) => {
                write!(f, "the OS could not identify the peer ({why})")
            }
            HostIdentityReason::NotLocalPeer => {
                write!(
                    f,
                    "the caller is not a local app, so it has no process to identify"
                )
            }
        }
    }
}

/// The process behind the endpoint is not the host the caller expected. No `hello` and no request
/// frame was written to it.
///
/// Distinct from a connection error: something answered, and the OS says it is the wrong program.
/// It is not retryable (reconnecting reaches the same program). Content-free: pids and paths
/// only, never request data.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct HostIdentityError {
    /// The executables the caller said the host may be, as supplied (not canonicalised).
    pub expected: Vec<PathBuf>,
    /// The pid the kernel reported for the host, when it reported one.
    pub found_pid: Option<u32>,
    /// The host's executable, when it could be read before the refusal.
    pub found_executable: Option<PathBuf>,
    pub reason: HostIdentityReason,
}

impl fmt::Display for HostIdentityError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "the service host failed identity verification: {}",
            self.reason
        )?;
        if let Some(pid) = self.found_pid {
            write!(f, "; host pid {pid}")?;
        }
        if let Some(exe) = &self.found_executable {
            write!(f, "; host executable {}", exe.display())?;
        }
        if self.expected.is_empty() {
            write!(f, "; expected: none supplied")
        } else {
            write!(f, "; expected ")?;
            for (i, path) in self.expected.iter().enumerate() {
                if i > 0 {
                    write!(f, " or ")?;
                }
                write!(f, "{}", path.display())?;
            }
            Ok(())
        }
    }
}

impl std::error::Error for HostIdentityError {}

/// Internal: why opening a host-verified connection failed.
#[derive(Debug)]
pub(crate) enum HostConnectError {
    /// The connection itself failed, or the host left before it could be identified.
    Io(io::Error),
    /// The host answered and is not the expected one.
    Identity(HostIdentityError),
}

type Verifier = Arc<dyn Fn(&HostProcess) -> Result<(), String> + Send + Sync>;

/// Which program the client is willing to talk to, passed to
/// [`Client::connect_expecting`](crate::Client::connect_expecting).
///
/// The host must run as the client's own user (always) and its executable, read from the kernel
/// for the connected socket's process, must be one of the paths named here. Both sides of the
/// comparison are canonicalised when the check runs, so a symlink, a `..` or a case difference on
/// a case-insensitive volume does not matter; the same file reached by another name (a hard link)
/// is the same executable.
///
/// An expectation with no path matches nothing: it fails closed.
///
/// The install-relative constructors ([`sibling_executable`](Self::sibling_executable),
/// [`bundle_executable`](Self::bundle_executable),
/// [`relative_to_current_exe`](Self::relative_to_current_exe)) derive the host's path from where
/// THIS process's executable lives, so an engine shipped inside an app can name its app without a
/// hard-coded path. They inherit the trust of that location: see the README, "What this does not
/// do".
#[derive(Clone, Default)]
pub struct HostExpectation {
    executables: Vec<PathBuf>,
    verifier: Option<Verifier>,
}

impl fmt::Debug for HostExpectation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HostExpectation")
            .field("executables", &self.executables)
            .field("verifier", &self.verifier.as_ref().map(|_| "<fn>"))
            .finish()
    }
}

fn invalid(what: &str) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidInput, what.to_string())
}

fn current_exe_canonical() -> io::Result<PathBuf> {
    std::fs::canonicalize(std::env::current_exe()?)
}

/// A bare file name: one normal component, no separators, no `..`.
fn is_single_component(name: &OsStr) -> bool {
    let path = Path::new(name);
    path.file_name() == Some(name) && path.components().count() == 1
}

/// `<ancestor of exe, levels_up levels above it>/<relative>`. `levels_up` 1 is the directory that
/// holds `exe`. `None` for 0 levels, a path with no such ancestor, or a `relative` that is not
/// relative: absolute, or (Windows) rooted without a drive (`\x`, `/x`) or carrying a drive
/// (`C:x`), each of which `join` would let replace the base.
fn up_and_join(exe: &Path, levels_up: usize, relative: &Path) -> Option<PathBuf> {
    use std::path::Component;
    let leaves_base = relative
        .components()
        .any(|part| matches!(part, Component::Prefix(_) | Component::RootDir));
    if levels_up == 0 || relative.is_absolute() || leaves_base {
        return None;
    }
    exe.ancestors()
        .nth(levels_up)
        .map(|base| base.join(relative))
}

/// `<enclosing>.app/Contents/MacOS/<file_name>` for the first `.app` directory above `exe`.
fn bundle_main(exe: &Path, file_name: &OsStr) -> Option<PathBuf> {
    exe.ancestors()
        .skip(1)
        .find(|dir| dir.extension() == Some(OsStr::new("app")))
        .map(|bundle| bundle.join("Contents").join("MacOS").join(file_name))
}

impl HostExpectation {
    /// The host is the program at `path`.
    pub fn executable(path: impl Into<PathBuf>) -> Self {
        Self {
            executables: vec![path.into()],
            verifier: None,
        }
    }

    /// The host is any one of `paths` (a release path and a QA path, say). Empty matches nothing.
    pub fn any_of<I, P>(paths: I) -> Self
    where
        I: IntoIterator<Item = P>,
        P: Into<PathBuf>,
    {
        Self {
            executables: paths.into_iter().map(Into::into).collect(),
            verifier: None,
        }
    }

    /// Also accept the program at `path`.
    pub fn or_executable(mut self, path: impl Into<PathBuf>) -> Self {
        self.executables.push(path.into());
        self
    }

    /// The host is the executable `file_name` in the same directory as THIS process's executable
    /// (symlinks resolved first). Fails when the running executable cannot be located or
    /// `file_name` is not a bare file name.
    pub fn sibling_executable(file_name: impl AsRef<OsStr>) -> io::Result<Self> {
        let name = file_name.as_ref();
        if !is_single_component(name) {
            return Err(invalid("the host file name must be a bare file name"));
        }
        Self::relative_to_current_exe(1, name)
    }

    /// The host is the main executable `file_name` of the macOS app bundle that contains THIS
    /// process's executable: `<App>.app/Contents/MacOS/<file_name>`. For an engine or command
    /// line tool shipped inside the app, whether it sits in `Contents/Resources/bin` or in
    /// `Contents/MacOS` itself. Fails when the running executable is not inside an `.app`
    /// directory or `file_name` is not a bare file name.
    pub fn bundle_executable(file_name: impl AsRef<OsStr>) -> io::Result<Self> {
        let name = file_name.as_ref();
        if !is_single_component(name) {
            return Err(invalid("the host file name must be a bare file name"));
        }
        let exe = current_exe_canonical()?;
        let path = bundle_main(&exe, name).ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::NotFound,
                "the running executable is not inside an .app bundle",
            )
        })?;
        Ok(Self::executable(path))
    }

    /// The host is `relative` under the directory `levels_up` levels above THIS process's
    /// executable (symlinks resolved first; 1 is the directory that holds it). For install
    /// layouts that are neither a sibling nor a macOS bundle, for example
    /// `relative_to_current_exe(2, "bin/app")` for `<root>/libexec/engine` and `<root>/bin/app`.
    pub fn relative_to_current_exe(
        levels_up: usize,
        relative: impl AsRef<Path>,
    ) -> io::Result<Self> {
        let exe = current_exe_canonical()?;
        let path = up_and_join(&exe, levels_up, relative.as_ref()).ok_or_else(|| {
            invalid("no such directory above the running executable, or the path is absolute")
        })?;
        Ok(Self::executable(path))
    }

    /// Add a check that runs AFTER the executable matched, with the host the OS identified. A
    /// returned `Err(reason)` refuses the host as [`HostIdentityReason::Refused`]. The check runs
    /// before the first application byte is written.
    ///
    /// This is the hook for a stronger identity than a path. This crate links no code-signing API,
    /// so the macOS team-identifier check is the caller's: link Security.framework in the app,
    /// build a `SecCode` for the host from [`HostProcess::audit_token`] with
    /// `SecCodeCopyGuestWithAttributes` and `kSecGuestAttributeAudit` (never from the pid alone,
    /// which can be reused), read `kSecCodeInfoTeamIdentifier` with `SecCodeCopySigningInformation`
    /// and compare it with your own (`SecCodeCopySelf`). On Windows the same hook carries an
    /// Authenticode (`WinVerifyTrust`) check of [`HostProcess::executable`].
    pub fn with_verifier(
        mut self,
        check: impl Fn(&HostProcess) -> Result<(), String> + Send + Sync + 'static,
    ) -> Self {
        self.verifier = Some(Arc::new(check));
        self
    }

    /// The executables this expectation names, as supplied.
    pub fn executables(&self) -> &[PathBuf] {
        &self.executables
    }
}

/// Server side of [`HostExpectation`]: does the process behind `peer` (the OS-verified identity
/// of a local caller) run the program `expect` names? `None` (a caller with no OS peer) and any
/// platform that cannot answer are refused. Used by `CallContext::verify_peer_executable`.
pub(crate) fn verify_peer_process(
    peer: Option<&crate::peer::PeerIdentity>,
    expect: &HostExpectation,
) -> Result<HostProcess, HostIdentityError> {
    let Some(peer) = peer else {
        return Err(HostIdentityError {
            expected: expect.executables.clone(),
            found_pid: None,
            found_executable: None,
            reason: HostIdentityReason::NotLocalPeer,
        });
    };
    #[cfg(unix)]
    {
        verify_unix_pid(peer, expect)
    }
    #[cfg(windows)]
    {
        verify_pid_host(peer, expect)
    }
    #[cfg(not(any(unix, windows)))]
    {
        Err(HostIdentityError {
            expected: expect.executables.clone(),
            found_pid: peer.pid,
            found_executable: None,
            reason: HostIdentityReason::Unverified {
                platform: std::env::consts::OS,
                detail: "no process identification is implemented for this platform",
            },
        })
    }
}

/// The start marker of process `pid` as the OS reports it now (`None` when unreadable or gone).
/// Recorded at accept into `PeerIdentity::started`, compared by the server-side executable check.
pub(crate) fn process_start_marker(pid: u32) -> Option<(u64, u64)> {
    #[cfg(unix)]
    {
        unix_impl::start_marker_of(pid)
    }
    #[cfg(windows)]
    {
        windows_impl::start_marker_of(pid)
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = pid;
        None
    }
}

#[cfg(unix)]
pub(crate) use unix_impl::{peer_audit_token, verify_unix_host, verify_unix_pid};

#[cfg(unix)]
mod unix_impl {
    use super::{
        HostConnectError, HostExpectation, HostIdentityError, HostIdentityReason, HostProcess,
    };
    use crate::peer::{current_euid, verify_peer_is_current_user, PeerError, PeerIdentity};
    use std::io;
    use std::os::unix::fs::MetadataExt;
    use std::os::unix::net::UnixStream;
    use std::path::{Path, PathBuf};

    /// `(device, inode)`: names one file whatever path it is reached by.
    pub type FileId = (u64, u64);

    pub fn file_id(path: &Path) -> Option<FileId> {
        let md = std::fs::metadata(path).ok()?;
        Some((md.dev(), md.ino()))
    }

    /// A running process's executable as the kernel reports it.
    pub struct ExeInfo {
        pub path: PathBuf,
        /// The file the process is actually running, when the kernel lets us stat it (Linux:
        /// through `/proc/<pid>/exe`, exact even if the file was replaced; macOS: by path).
        pub id: Option<FileId>,
    }

    /// What must be unchanged across the executable-path read to prove the pid named one process
    /// throughout: its start time, and (macOS) its audit token, which carries a pid version.
    #[derive(PartialEq, Eq)]
    struct Witness {
        start: (u64, u64),
        token: Option<[u32; 8]>,
    }

    enum ObserveError {
        Gone,
        Unreadable(String),
    }

    impl From<ObserveError> for HostIdentityReason {
        fn from(e: ObserveError) -> Self {
            match e {
                ObserveError::Gone => HostIdentityReason::HostChanged(
                    "it exited before it could be identified".to_string(),
                ),
                ObserveError::Unreadable(why) => HostIdentityReason::Unreadable(why),
            }
        }
    }

    /// macOS: the errno that says "no such process" (ESRCH, 3), or a stale zero, is `Ok(None)`;
    /// anything else is an error. Read right after a `proc_*` call that returned 0.
    #[cfg(target_os = "macos")]
    fn missing_or_err<T>() -> io::Result<Option<T>> {
        let e = io::Error::last_os_error();
        match e.raw_os_error() {
            Some(3) | Some(0) | None => Ok(None),
            _ => Err(e),
        }
    }

    fn witness(stream: &UnixStream, pid: u32) -> Result<Witness, ObserveError> {
        let token = os::audit_token(stream);
        let start = match os::start_marker(pid) {
            Ok(Some(start)) => start,
            Ok(None) => return Err(ObserveError::Gone),
            Err(e) => return Err(ObserveError::Unreadable(format!("process start time: {e}"))),
        };
        Ok(Witness { start, token })
    }

    /// Is the running executable (`found`, canonical, with its file identity `found_id`) the one
    /// `expected` names? Equal after canonicalisation, or the very same file (device and inode),
    /// which covers a case-insensitive volume (macOS `realpath` does not normalise case, so
    /// `/applications/x` and `/Applications/x` differ as strings) and a hard link. An expected
    /// path that does not exist matches nothing.
    pub fn same_executable(expected: &Path, found: &Path, found_id: Option<FileId>) -> bool {
        let Ok(canonical) = std::fs::canonicalize(expected) else {
            return false;
        };
        if canonical == found {
            return true;
        }
        match (found_id, file_id(&canonical)) {
            (Some(running), Some(named)) => running == named,
            _ => false,
        }
    }

    /// Ask the kernel who is on the listening end of `stream` and decide whether it is the host
    /// `expect` names. Reads and writes nothing on the stream.
    ///
    /// Order, each step failing closed:
    /// 1. the peer's uid equals ours (`getpeereid` / `SO_PEERCRED`, the existing same-user check);
    /// 2. the pid the kernel reports for the socket (`LOCAL_PEERPID` / `SO_PEERCRED`);
    /// 3. the pid's start time (and, on macOS, the audit token), then its executable path
    ///    (`proc_pidpath` / `/proc/<pid>/exe`), then the start time and token again, then the pid
    ///    from the socket again: all must agree, or the pid cannot be proven to name one process;
    /// 4. the executable is one of the expected executables;
    /// 5. the caller's extra verifier, if any.
    pub(crate) fn verify_unix_host(
        stream: &UnixStream,
        expect: &HostExpectation,
    ) -> Result<HostProcess, HostConnectError> {
        let refuse = |pid: Option<u32>, exe: Option<PathBuf>, reason: HostIdentityReason| {
            HostConnectError::Identity(HostIdentityError {
                expected: expect.executables.clone(),
                found_pid: pid,
                found_executable: exe,
                reason,
            })
        };
        if expect.executables.is_empty() {
            return Err(refuse(None, None, HostIdentityReason::NoExpectation));
        }
        if !os::SUPPORTED {
            return Err(refuse(
                None,
                None,
                HostIdentityReason::Unverified {
                    platform: std::env::consts::OS,
                    detail: "reading a process's executable path is not implemented for this Unix",
                },
            ));
        }

        let first = match verify_peer_is_current_user(stream) {
            Ok(id) => id,
            Err(PeerError::Mismatch(id)) => {
                return Err(refuse(
                    id.pid,
                    None,
                    HostIdentityReason::UidMismatch {
                        host: id.uid,
                        client: current_euid(),
                    },
                ))
            }
            Err(PeerError::Unsupported(detail)) => {
                return Err(refuse(
                    None,
                    None,
                    HostIdentityReason::Unverified {
                        platform: std::env::consts::OS,
                        detail,
                    },
                ))
            }
            Err(e) => {
                // The host hung up before it could be identified: a connection problem.
                if e.peer_gone() {
                    return Err(HostConnectError::Io(io::Error::from(e)));
                }
                return Err(refuse(None, None, HostIdentityReason::Query(e.to_string())));
            }
        };
        let Some(pid) = first.pid else {
            return Err(refuse(None, None, HostIdentityReason::PidUnavailable));
        };

        let observe = |e: ObserveError| refuse(Some(pid), None, e.into());
        let changed = |why: &str| {
            refuse(
                Some(pid),
                None,
                HostIdentityReason::HostChanged(why.to_string()),
            )
        };

        let before = witness(stream, pid).map_err(&observe)?;
        let exe = match os::executable_of(pid) {
            Ok(Some(exe)) => exe,
            Ok(None) => return Err(observe(ObserveError::Gone)),
            Err(e) => {
                return Err(observe(ObserveError::Unreadable(format!(
                    "executable path: {e}"
                ))))
            }
        };
        let after = witness(stream, pid).map_err(&observe)?;
        if before != after {
            return Err(changed(
                "its identity differed before and after its executable path was read",
            ));
        }
        match verify_peer_is_current_user(stream) {
            Ok(again) if again.pid == Some(pid) => {}
            _ => return Err(changed("the socket no longer reports the same process id")),
        }

        conclude(expect, pid, exe, after.token).map_err(HostConnectError::Identity)
    }

    /// The last steps, shared by the client-side and the server-side check: the process's
    /// executable (canonicalised) must be one of the expected executables, then the caller's
    /// extra verifier, if any, must accept the process.
    fn conclude(
        expect: &HostExpectation,
        pid: u32,
        exe: ExeInfo,
        audit_token: Option<[u32; 8]>,
    ) -> Result<HostProcess, HostIdentityError> {
        let refuse = |exe: Option<PathBuf>, reason: HostIdentityReason| HostIdentityError {
            expected: expect.executables.clone(),
            found_pid: Some(pid),
            found_executable: exe,
            reason,
        };
        let ExeInfo { path, id } = exe;
        let found = std::fs::canonicalize(&path).unwrap_or(path);
        if !expect
            .executables
            .iter()
            .any(|expected| same_executable(expected, &found, id))
        {
            return Err(refuse(Some(found), HostIdentityReason::ExecutableMismatch));
        }

        let host = HostProcess {
            pid,
            uid: Some(current_euid()),
            sid: None,
            executable: found,
            audit_token,
        };
        if let Some(verifier) = &expect.verifier {
            if let Err(why) = verifier(&host) {
                return Err(refuse(
                    Some(host.executable.clone()),
                    HostIdentityReason::Refused(why),
                ));
            }
        }
        Ok(host)
    }

    /// Server side: identify the process that opened a connection, from the OS-verified
    /// [`PeerIdentity`] recorded when it connected, and decide whether it is the program
    /// `expect` names. Same decision as [`verify_unix_host`] (same executable comparison, same
    /// verifier), but the socket is no longer at hand, so the process is pinned by its pid, its
    /// start time read before and after its executable path, and (macOS) the audit token the
    /// kernel captured at connect time.
    ///
    /// Each step fails closed: no uid or a different uid, no pid, a process that is gone, a
    /// start time that changed, an audit token that names another pid, an unreadable executable,
    /// no expected executable, an executable that is not expected, a refusing verifier.
    pub(crate) fn verify_unix_pid(
        peer: &PeerIdentity,
        expect: &HostExpectation,
    ) -> Result<HostProcess, HostIdentityError> {
        let refuse = |pid: Option<u32>, exe: Option<PathBuf>, reason: HostIdentityReason| {
            HostIdentityError {
                expected: expect.executables.clone(),
                found_pid: pid,
                found_executable: exe,
                reason,
            }
        };
        if expect.executables.is_empty() {
            return Err(refuse(None, None, HostIdentityReason::NoExpectation));
        }
        if !os::SUPPORTED {
            return Err(refuse(
                None,
                None,
                HostIdentityReason::Unverified {
                    platform: std::env::consts::OS,
                    detail: "reading a process's executable path is not implemented for this Unix",
                },
            ));
        }
        if peer.uid != Some(current_euid()) {
            return Err(refuse(
                peer.pid,
                None,
                HostIdentityReason::UidMismatch {
                    host: peer.uid,
                    client: current_euid(),
                },
            ));
        }
        let Some(pid) = peer.pid else {
            return Err(refuse(None, None, HostIdentityReason::PidUnavailable));
        };
        if let Some(token) = peer.audit_token {
            // `audit_token_t`: the pid is word 5.
            if token[5] != pid {
                return Err(refuse(
                    Some(pid),
                    None,
                    HostIdentityReason::HostChanged(
                        "the audit token and the process id name different processes".to_string(),
                    ),
                ));
            }
        }
        let observe = |e: ObserveError| refuse(Some(pid), None, e.into());
        let start = |pid| match os::start_marker(pid) {
            Ok(Some(start)) => Ok(start),
            Ok(None) => Err(ObserveError::Gone),
            Err(e) => Err(ObserveError::Unreadable(format!("process start time: {e}"))),
        };
        let before = start(pid).map_err(&observe)?;
        // The pid must still be the process that connected: its start time was recorded when
        // the connection was accepted. No record, or a different one, is a pid that may have
        // been reused. Fails closed.
        if peer.started != Some(before) {
            return Err(refuse(
                Some(pid),
                None,
                HostIdentityReason::HostChanged(
                    concat!(
                        "the process is not the one that connected (its start time differs ",
                        "from the one recorded at connect, or none was recorded)"
                    )
                    .to_string(),
                ),
            ));
        }
        let exe = match os::executable_of(pid) {
            Ok(Some(exe)) => exe,
            Ok(None) => return Err(observe(ObserveError::Gone)),
            Err(e) => {
                return Err(observe(ObserveError::Unreadable(format!(
                    "executable path: {e}"
                ))))
            }
        };
        let after = start(pid).map_err(&observe)?;
        if before != after {
            return Err(refuse(
                Some(pid),
                None,
                HostIdentityReason::HostChanged(
                    "its start time differed before and after its executable path was read"
                        .to_string(),
                ),
            ));
        }
        conclude(expect, pid, exe, peer.audit_token)
    }

    pub(crate) fn start_marker_of(pid: u32) -> Option<(u64, u64)> {
        os::start_marker(pid).ok().flatten()
    }

    /// The peer's audit token for [`PeerIdentity::audit_token`]; `None` off macOS.
    pub(crate) fn peer_audit_token(stream: &UnixStream) -> Option<[u32; 8]> {
        os::audit_token(stream)
    }

    #[cfg(target_os = "macos")]
    mod os {
        use super::{file_id, missing_or_err, ExeInfo};
        use std::ffi::{c_void, OsString};
        use std::io;
        use std::os::fd::AsRawFd;
        use std::os::unix::ffi::OsStringExt;
        use std::os::unix::net::UnixStream;
        use std::path::PathBuf;

        pub const SUPPORTED: bool = true;

        /// `struct proc_bsdinfo` from `<sys/proc_info.h>`. Checked on macOS (Darwin 27): 136 bytes,
        /// `pbi_pid` at offset 12, `pbi_start_tvsec` at offset 120.
        #[repr(C)]
        #[allow(dead_code)]
        struct ProcBsdInfo {
            pbi_flags: u32,
            pbi_status: u32,
            pbi_xstatus: u32,
            pbi_pid: u32,
            pbi_ppid: u32,
            pbi_uid: u32,
            pbi_gid: u32,
            pbi_ruid: u32,
            pbi_rgid: u32,
            pbi_svuid: u32,
            pbi_svgid: u32,
            rfu_1: u32,
            pbi_comm: [u8; 16],
            pbi_name: [u8; 32],
            pbi_nfiles: u32,
            pbi_pgid: u32,
            pbi_pjobc: u32,
            e_tdev: u32,
            e_tpgid: u32,
            pbi_nice: i32,
            pbi_start_tvsec: u64,
            pbi_start_tvusec: u64,
        }
        const _: () = assert!(std::mem::size_of::<ProcBsdInfo>() == 136);

        const PROC_PIDTBSDINFO: i32 = 3;
        const PROC_PIDPATHINFO_MAXSIZE: usize = 4 * 1024;
        const SOL_LOCAL: i32 = 0;
        const LOCAL_PEERTOKEN: i32 = 0x006;

        extern "C" {
            fn proc_pidinfo(
                pid: i32,
                flavor: i32,
                arg: u64,
                buffer: *mut c_void,
                buffersize: i32,
            ) -> i32;
            fn proc_pidpath(pid: i32, buffer: *mut c_void, buffersize: u32) -> i32;
            fn getsockopt(fd: i32, level: i32, name: i32, val: *mut c_void, len: *mut u32) -> i32;
        }

        fn to_pid(pid: u32) -> io::Result<i32> {
            i32::try_from(pid)
                .ok()
                .filter(|p| *p > 0)
                .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))
        }

        /// The process's start time (seconds, microseconds) from `proc_pidinfo`. `Ok(None)` when
        /// there is no such process.
        pub fn start_marker(pid: u32) -> io::Result<Option<(u64, u64)>> {
            let raw_pid = to_pid(pid)?;
            let mut info = std::mem::MaybeUninit::<ProcBsdInfo>::zeroed();
            let size = std::mem::size_of::<ProcBsdInfo>() as i32;
            // SAFETY: `info` is a writable buffer of exactly `size` bytes; the call fills it.
            let written = unsafe {
                proc_pidinfo(
                    raw_pid,
                    PROC_PIDTBSDINFO,
                    0,
                    info.as_mut_ptr().cast::<c_void>(),
                    size,
                )
            };
            if written != size {
                return missing_or_err();
            }
            // SAFETY: the kernel wrote the whole struct (`written == size`), and every field is
            // a plain integer or byte array, so any bit pattern is valid.
            let info = unsafe { info.assume_init() };
            Ok((info.pbi_pid == pid).then_some((info.pbi_start_tvsec, info.pbi_start_tvusec)))
        }

        /// The process's executable path from `proc_pidpath`. `Ok(None)` when there is no such
        /// process.
        pub fn executable_of(pid: u32) -> io::Result<Option<ExeInfo>> {
            let raw_pid = to_pid(pid)?;
            let mut buf = vec![0u8; PROC_PIDPATHINFO_MAXSIZE];
            // SAFETY: `buf` is a writable buffer of the length passed.
            let n = unsafe {
                proc_pidpath(raw_pid, buf.as_mut_ptr().cast::<c_void>(), buf.len() as u32)
            };
            if n <= 0 {
                return missing_or_err();
            }
            buf.truncate(n as usize);
            if let Some(nul) = buf.iter().position(|b| *b == 0) {
                buf.truncate(nul);
            }
            let path = PathBuf::from(OsString::from_vec(buf));
            let id = file_id(&path);
            Ok(Some(ExeInfo { path, id }))
        }

        /// The peer's audit token (`LOCAL_PEERTOKEN`), when the kernel provides it.
        pub fn audit_token(stream: &UnixStream) -> Option<[u32; 8]> {
            let mut token = [0u32; 8];
            let mut len = std::mem::size_of_val(&token) as u32;
            // SAFETY: valid fd borrowed from `stream`; `token` and `len` describe a writable
            // 32-byte `audit_token_t`.
            let rc = unsafe {
                getsockopt(
                    stream.as_raw_fd(),
                    SOL_LOCAL,
                    LOCAL_PEERTOKEN,
                    token.as_mut_ptr().cast::<c_void>(),
                    &mut len,
                )
            };
            (rc == 0 && len as usize == std::mem::size_of_val(&token)).then_some(token)
        }
    }

    #[cfg(any(target_os = "linux", target_os = "android"))]
    mod os {
        use super::{is_no_such_process, ExeInfo};
        use std::io;
        use std::os::unix::fs::MetadataExt;
        use std::os::unix::net::UnixStream;

        pub const SUPPORTED: bool = true;

        /// The process's start time in clock ticks since boot (field 22 of `/proc/<pid>/stat`).
        /// `Ok(None)` when there is no such process.
        pub fn start_marker(pid: u32) -> io::Result<Option<(u64, u64)>> {
            let text = match std::fs::read_to_string(format!("/proc/{pid}/stat")) {
                Ok(text) => text,
                Err(e) if is_no_such_process(&e) => return Ok(None),
                Err(e) => return Err(e),
            };
            let malformed = || io::Error::new(io::ErrorKind::InvalidData, "unreadable /proc stat");
            // `pid (comm) state ...`: comm may hold spaces and parentheses, so split after the
            // last ')'. The state is the first field after it, starttime the 20th.
            let rest = text.rsplit_once(')').ok_or_else(malformed)?.1;
            let ticks = rest
                .split_whitespace()
                .nth(19)
                .and_then(|field| field.parse::<u64>().ok())
                .ok_or_else(malformed)?;
            Ok(Some((ticks, 0)))
        }

        /// The process's executable from `/proc/<pid>/exe`; its identity is the file the process
        /// is really running (the magic link is followed, so a replaced or deleted binary is
        /// still named exactly). `Ok(None)` when there is no such process.
        pub fn executable_of(pid: u32) -> io::Result<Option<ExeInfo>> {
            let link = format!("/proc/{pid}/exe");
            let path = match std::fs::read_link(&link) {
                Ok(path) => path,
                Err(e) if is_no_such_process(&e) => return Ok(None),
                Err(e) => return Err(e),
            };
            let id = std::fs::metadata(&link).ok().map(|md| (md.dev(), md.ino()));
            Ok(Some(ExeInfo { path, id }))
        }

        /// Linux has no audit token; the start time is the witness.
        pub fn audit_token(_stream: &UnixStream) -> Option<[u32; 8]> {
            None
        }
    }

    /// Any other Unix: the executable of a process cannot be read here, so no host is verified.
    #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "android")))]
    mod os {
        use super::ExeInfo;
        use std::io;
        use std::os::unix::net::UnixStream;

        pub const SUPPORTED: bool = false;

        pub fn start_marker(_pid: u32) -> io::Result<Option<(u64, u64)>> {
            Err(io::Error::from(io::ErrorKind::Unsupported))
        }
        pub fn executable_of(_pid: u32) -> io::Result<Option<ExeInfo>> {
            Err(io::Error::from(io::ErrorKind::Unsupported))
        }
        pub fn audit_token(_stream: &UnixStream) -> Option<[u32; 8]> {
            None
        }
    }

    /// Linux: is this the error of a process that does not exist (`ENOENT` on the `/proc` entry,
    /// or `ESRCH` when it died mid-read)?
    #[cfg(any(target_os = "linux", target_os = "android"))]
    fn is_no_such_process(e: &io::Error) -> bool {
        e.kind() == io::ErrorKind::NotFound || e.raw_os_error() == Some(3)
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use std::os::unix::net::UnixListener;

        fn canonical_current_exe() -> PathBuf {
            std::fs::canonicalize(std::env::current_exe().unwrap()).unwrap()
        }

        #[test]
        fn the_kernel_describes_this_process_and_a_missing_pid_is_gone_not_an_error() {
            let me = std::process::id();
            let exe = os::executable_of(me).unwrap().expect("this process exists");
            assert_eq!(
                std::fs::canonicalize(&exe.path).unwrap(),
                canonical_current_exe()
            );
            let start = os::start_marker(me).unwrap().expect("this process exists");
            assert!(start.0 > 0);
            assert_eq!(os::start_marker(me).unwrap(), Some(start));

            let nobody = i32::MAX as u32;
            assert!(os::start_marker(nobody).unwrap().is_none());
            assert!(os::executable_of(nobody).unwrap().is_none());
        }

        #[test]
        fn a_listener_in_this_process_is_identified_and_matched_by_its_executable() {
            let dir = tempfile::tempdir().unwrap();
            let sock = dir.path().join("h.sock");
            let _listener = UnixListener::bind(&sock).unwrap();
            let stream = UnixStream::connect(&sock).unwrap();

            let me = canonical_current_exe();
            let host = verify_unix_host(&stream, &HostExpectation::executable(&me))
                .unwrap_or_else(|e| panic!("this binary is the host: {e:?}"));
            assert_eq!(host.pid, std::process::id());
            assert_eq!(host.executable, me);
            assert_eq!(host.uid, Some(current_euid()));

            // Another existing file is not the host: refused with what was found.
            let other = dir.path().join("other");
            std::fs::write(&other, b"x").unwrap();
            let Err(HostConnectError::Identity(e)) =
                verify_unix_host(&stream, &HostExpectation::executable(&other))
            else {
                panic!("a different executable must be refused");
            };
            assert_eq!(e.reason, HostIdentityReason::ExecutableMismatch);
            assert_eq!(e.found_pid, Some(std::process::id()));
            assert_eq!(e.found_executable, Some(me.clone()));
            assert_eq!(e.expected, vec![other.clone()]);

            // One matching path among several is enough; a missing one matches nothing.
            let any = HostExpectation::any_of([other, dir.path().join("missing"), me]);
            assert!(verify_unix_host(&stream, &any).is_ok());
        }

        #[test]
        fn no_expectation_and_a_refusing_verifier_both_fail_closed() {
            let dir = tempfile::tempdir().unwrap();
            let sock = dir.path().join("h.sock");
            let _listener = UnixListener::bind(&sock).unwrap();
            let stream = UnixStream::connect(&sock).unwrap();

            let Err(HostConnectError::Identity(e)) =
                verify_unix_host(&stream, &HostExpectation::any_of(Vec::<PathBuf>::new()))
            else {
                panic!("an empty expectation must refuse");
            };
            assert_eq!(e.reason, HostIdentityReason::NoExpectation);

            let expect = HostExpectation::executable(canonical_current_exe())
                .with_verifier(|host| Err(format!("pid {} is not signed by us", host.pid)));
            let Err(HostConnectError::Identity(e)) = verify_unix_host(&stream, &expect) else {
                panic!("a refusing verifier must refuse");
            };
            assert!(
                matches!(e.reason, HostIdentityReason::Refused(ref why) if why.contains("not signed"))
            );
            assert_eq!(e.found_executable, Some(canonical_current_exe()));
        }

        #[test]
        fn a_symlink_a_hard_link_and_an_unknown_path_are_judged_by_the_file_not_the_spelling() {
            let dir = tempfile::tempdir().unwrap();
            let real = dir.path().join("real");
            std::fs::write(&real, b"binary").unwrap();
            let found = std::fs::canonicalize(&real).unwrap();
            let id = file_id(&found);
            assert!(id.is_some());

            let link = dir.path().join("link");
            std::os::unix::fs::symlink(&real, &link).unwrap();
            assert!(same_executable(&link, &found, id));

            let hard = dir.path().join("hard");
            std::fs::hard_link(&real, &hard).unwrap();
            assert!(same_executable(&hard, &found, id), "same file, other name");

            // Same bytes, different file: not the running executable.
            let copy = dir.path().join("copy");
            std::fs::copy(&real, &copy).unwrap();
            assert!(!same_executable(&copy, &found, id));

            assert!(!same_executable(&dir.path().join("missing"), &found, id));
            // Without a file identity only the canonical path can match.
            assert!(same_executable(&link, &found, None));
            assert!(!same_executable(&hard, &found, None));
        }

        /// macOS volumes are case-insensitive by default and `realpath` keeps the spelling it was
        /// given, so the same file must still match by identity. Skipped on a case-sensitive
        /// volume, where the upper-case spelling does not name the file at all.
        #[cfg(target_os = "macos")]
        #[test]
        fn a_case_variant_spelling_of_the_expected_path_names_the_same_file() {
            let dir = tempfile::tempdir().unwrap();
            let real = dir.path().join("hostbin");
            std::fs::write(&real, b"binary").unwrap();
            let found = std::fs::canonicalize(&real).unwrap();
            let id = file_id(&found);
            let upper = dir.path().join("HOSTBIN");
            if std::fs::metadata(&upper).is_err() {
                return;
            }
            assert!(same_executable(&upper, &found, id));
        }
    }
}

#[cfg(windows)]
pub(crate) use windows_impl::{verify_pid_host, verify_pipe_host};

/// Windows: which program holds the server end of a named pipe this client opened.
#[cfg(windows)]
mod windows_impl {
    use super::*;
    use crate::peer::{verify_pipe_server_is_current_user, PeerError, PeerIdentity};
    use std::ffi::OsString;
    use std::os::windows::ffi::OsStringExt;
    use std::os::windows::io::{AsRawHandle, RawHandle};

    const PROCESS_QUERY_LIMITED_INFORMATION: u32 = 0x1000;
    const SYNCHRONIZE: u32 = 0x0010_0000;
    const WAIT_TIMEOUT: u32 = 258;
    const ERROR_INVALID_PARAMETER: i32 = 87;
    /// The longest path `QueryFullProcessImageNameW` can return, in UTF-16 units.
    const LONGEST_PATH: usize = 32_768;

    #[repr(C)]
    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
    #[allow(dead_code)]
    struct FileTime {
        low: u32,
        high: u32,
    }

    /// `BY_HANDLE_FILE_INFORMATION`.
    #[repr(C)]
    #[derive(Default)]
    #[allow(dead_code)]
    struct ByHandleFileInformation {
        attributes: u32,
        creation: FileTime,
        access: FileTime,
        write: FileTime,
        volume_serial: u32,
        size_high: u32,
        size_low: u32,
        links: u32,
        index_high: u32,
        index_low: u32,
    }

    #[link(name = "kernel32")]
    unsafe extern "system" {
        fn GetNamedPipeServerProcessId(pipe: RawHandle, pid: *mut u32) -> i32;
        fn OpenProcess(access: u32, inherit: i32, pid: u32) -> RawHandle;
        fn GetProcessTimes(
            process: RawHandle,
            creation: *mut FileTime,
            exit: *mut FileTime,
            kernel: *mut FileTime,
            user: *mut FileTime,
        ) -> i32;
        fn QueryFullProcessImageNameW(
            process: RawHandle,
            flags: u32,
            name: *mut u16,
            size: *mut u32,
        ) -> i32;
        fn WaitForSingleObject(handle: RawHandle, milliseconds: u32) -> u32;
        fn CloseHandle(handle: RawHandle) -> i32;
        fn GetFileInformationByHandle(file: RawHandle, info: *mut ByHandleFileInformation) -> i32;
    }

    /// A process handle. While it is open the process object stays, so its pid is not reused.
    struct Process(RawHandle);

    impl Drop for Process {
        fn drop(&mut self) {
            // SAFETY: the handle came from OpenProcess and is closed once.
            unsafe { CloseHandle(self.0) };
        }
    }

    impl Process {
        fn open(pid: u32) -> io::Result<Process> {
            // SAFETY: plain call; a null result is the failure.
            let handle =
                unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, 0, pid) };
            if handle.is_null() {
                return Err(io::Error::last_os_error());
            }
            Ok(Process(handle))
        }

        /// When the process was created: with the pid, the identity of one process.
        fn created(&self) -> io::Result<FileTime> {
            let mut times = [FileTime::default(); 4];
            let [creation, exit, kernel, user] = &mut times;
            // SAFETY: four valid out-parameters for an open process handle.
            if unsafe { GetProcessTimes(self.0, creation, exit, kernel, user) } == 0 {
                return Err(io::Error::last_os_error());
            }
            Ok(times[0])
        }

        fn running(&self) -> bool {
            // SAFETY: the handle was opened with SYNCHRONIZE.
            unsafe { WaitForSingleObject(self.0, 0) == WAIT_TIMEOUT }
        }

        /// The Win32 path of the image the process runs.
        fn image(&self) -> io::Result<PathBuf> {
            let mut buffer = vec![0u16; LONGEST_PATH];
            let mut length = buffer.len() as u32;
            // SAFETY: `buffer` holds `length` units; the call writes at most that many and
            // sets `length` to the number written, without the terminator.
            if unsafe { QueryFullProcessImageNameW(self.0, 0, buffer.as_mut_ptr(), &mut length) }
                == 0
            {
                return Err(io::Error::last_os_error());
            }
            Ok(PathBuf::from(OsString::from_wide(
                &buffer[..length as usize],
            )))
        }
    }

    fn server_pid(pipe: RawHandle) -> io::Result<u32> {
        let mut pid = 0u32;
        // SAFETY: `pipe` is the client end of a named pipe; `pid` is a valid out-parameter.
        if unsafe { GetNamedPipeServerProcessId(pipe, &mut pid) } == 0 {
            return Err(io::Error::last_os_error());
        }
        Ok(pid)
    }

    /// Volume serial number and file index: the same file under any name, as device and inode
    /// are on Unix.
    pub(super) fn file_id(path: &Path) -> Option<(u32, u64)> {
        let file = std::fs::File::open(path).ok()?;
        let mut info = ByHandleFileInformation::default();
        // SAFETY: an open file handle and a valid out-parameter of the documented layout.
        if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } == 0 {
            return None;
        }
        Some((
            info.volume_serial,
            (u64::from(info.index_high) << 32) | u64::from(info.index_low),
        ))
    }

    /// Whether `expected` names the file at `found` (already canonical): the same canonical path
    /// without regard to case (NTFS keeps case and ignores it), or the same file by identity (a
    /// hard link).
    pub(super) fn same_executable(
        expected: &Path,
        found: &Path,
        found_id: Option<(u32, u64)>,
    ) -> bool {
        let Ok(expected) = std::fs::canonicalize(expected) else {
            return false;
        };
        let lower = |path: &Path| path.to_string_lossy().to_lowercase();
        if lower(&expected) == lower(found) {
            return true;
        }
        found_id.is_some() && file_id(&expected) == found_id
    }

    /// A canonical path as a person writes it: without the `\\?\` prefix.
    fn plain(path: PathBuf) -> PathBuf {
        let text = path.to_string_lossy();
        match text.strip_prefix(r"\\?\UNC\") {
            Some(rest) => PathBuf::from(format!(r"\\{rest}")),
            None => match text.strip_prefix(r"\\?\") {
                Some(rest) => PathBuf::from(rest),
                None => path,
            },
        }
    }

    /// Identify the process that holds the server end of `pipe` (the client end, opened with
    /// `SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION`) and check it against `expect`, before
    /// any byte is written:
    ///
    /// 1. the pipe's server pid, and that process's token user is this client's (the existing
    ///    same-user check, repeated here for its identity);
    /// 2. a handle to that process, kept until the end: it pins the process object, so the pid
    ///    cannot be given to another process while it is held;
    /// 3. the process's creation time, its image path, then the creation time again, that it is
    ///    still running, and that the pipe still reports the same pid;
    /// 4. the image path, canonicalised, is one of the expected executables (same canonical
    ///    path ignoring case, or the same file by volume and index);
    /// 5. the caller's extra verifier, if any. A code-signature check (`WinVerifyTrust` on
    ///    [`HostProcess::executable`]) belongs there.
    pub(crate) fn verify_pipe_host(
        pipe: RawHandle,
        expect: &HostExpectation,
    ) -> Result<HostProcess, HostConnectError> {
        let refuse = |pid: Option<u32>, exe: Option<PathBuf>, reason: HostIdentityReason| {
            HostConnectError::Identity(HostIdentityError {
                expected: expect.executables.clone(),
                found_pid: pid,
                found_executable: exe,
                reason,
            })
        };
        if expect.executables.is_empty() {
            return Err(refuse(None, None, HostIdentityReason::NoExpectation));
        }

        let first = match verify_pipe_server_is_current_user(pipe) {
            Ok(id) => id,
            Err(e) => {
                // The host hung up before it could be identified: a connection problem.
                if e.peer_gone() {
                    return Err(HostConnectError::Io(io::Error::from(e)));
                }
                let pid = match &e {
                    PeerError::Mismatch(id) => id.pid,
                    _ => None,
                };
                return Err(refuse(pid, None, HostIdentityReason::Query(e.to_string())));
            }
        };
        let Some(pid) = first.pid else {
            return Err(refuse(None, None, HostIdentityReason::PidUnavailable));
        };
        let unreadable = |what: &str, e: io::Error| {
            refuse(
                Some(pid),
                None,
                HostIdentityReason::Unreadable(format!("{what}: {e}")),
            )
        };
        let changed = |why: &str| {
            refuse(
                Some(pid),
                None,
                HostIdentityReason::HostChanged(why.to_string()),
            )
        };

        let process = match Process::open(pid) {
            Ok(process) => process,
            // No process has this id any more.
            Err(e) if e.raw_os_error() == Some(ERROR_INVALID_PARAMETER) => {
                return Err(changed("it exited before it could be opened"))
            }
            Err(e) => return Err(unreadable("open process", e)),
        };
        let before = process
            .created()
            .map_err(|e| unreadable("creation time", e))?;
        let image = process
            .image()
            .map_err(|e| unreadable("executable path", e))?;
        let after = process
            .created()
            .map_err(|e| unreadable("creation time", e))?;
        if before != after {
            return Err(changed(
                "its creation time differed before and after its executable path was read",
            ));
        }
        if !process.running() {
            return Err(changed("it exited while it was being identified"));
        }
        match server_pid(pipe) {
            Ok(again) if again == pid => {}
            _ => return Err(changed("the pipe no longer reports the same process id")),
        }

        let found = std::fs::canonicalize(&image).unwrap_or(image);
        let id = file_id(&found);
        if !expect
            .executables
            .iter()
            .any(|expected| same_executable(expected, &found, id))
        {
            return Err(refuse(
                Some(pid),
                Some(plain(found)),
                HostIdentityReason::ExecutableMismatch,
            ));
        }

        let host = HostProcess {
            pid,
            uid: None,
            sid: first.sid,
            executable: plain(found),
            audit_token: None,
        };
        if let Some(verifier) = &expect.verifier {
            if let Err(why) = verifier(&host) {
                return Err(refuse(
                    Some(pid),
                    Some(host.executable.clone()),
                    HostIdentityReason::Refused(why),
                ));
            }
        }
        // The process handle is released only now: every check above saw one process.
        drop(process);
        Ok(host)
    }

    pub(super) fn start_marker_of(pid: u32) -> Option<(u64, u64)> {
        let t = Process::open(pid).ok()?.created().ok()?;
        Some(((u64::from(t.high) << 32) | u64::from(t.low), 0))
    }

    /// Server side: identify the process that opened a named-pipe connection, from the
    /// OS-verified [`PeerIdentity`] recorded when it connected, and decide whether it is the
    /// program `expect` names. The same executable comparison and verifier as
    /// [`verify_pipe_host`], with the pipe handle no longer at hand: a handle to the process is
    /// opened and kept until every check has run (it pins the process object, so its pid cannot
    /// name another process meanwhile), and the creation time is read before and after the image
    /// path.
    ///
    /// Fails closed: no pid or no user SID recorded for the peer, no expected executable, a
    /// process that cannot be opened or has exited, a creation time that changed, an unreadable
    /// image, an executable that is not expected, a refusing verifier. An Authenticode check
    /// (`WinVerifyTrust` on [`HostProcess::executable`]) belongs in the verifier.
    pub(crate) fn verify_pid_host(
        peer: &PeerIdentity,
        expect: &HostExpectation,
    ) -> Result<HostProcess, HostIdentityError> {
        let refuse = |pid: Option<u32>, exe: Option<PathBuf>, reason: HostIdentityReason| {
            HostIdentityError {
                expected: expect.executables.clone(),
                found_pid: pid,
                found_executable: exe,
                reason,
            }
        };
        if expect.executables.is_empty() {
            return Err(refuse(None, None, HostIdentityReason::NoExpectation));
        }
        let Some(pid) = peer.pid else {
            return Err(refuse(None, None, HostIdentityReason::PidUnavailable));
        };
        let Some(sid) = peer.sid.clone() else {
            return Err(refuse(
                Some(pid),
                None,
                HostIdentityReason::Query("no user SID was recorded for the peer".to_string()),
            ));
        };
        let unreadable = |what: &str, e: io::Error| {
            refuse(
                Some(pid),
                None,
                HostIdentityReason::Unreadable(format!("{what}: {e}")),
            )
        };
        let changed = |why: &str| {
            refuse(
                Some(pid),
                None,
                HostIdentityReason::HostChanged(why.to_string()),
            )
        };
        let process = match Process::open(pid) {
            Ok(process) => process,
            Err(e) if e.raw_os_error() == Some(ERROR_INVALID_PARAMETER) => {
                return Err(changed("it exited before it could be opened"))
            }
            Err(e) => return Err(unreadable("open process", e)),
        };
        let before = process
            .created()
            .map_err(|e| unreadable("creation time", e))?;
        // The pid must still be the process that connected (creation time recorded at accept).
        let marker = ((u64::from(before.high) << 32) | u64::from(before.low), 0);
        if peer.started != Some(marker) {
            return Err(changed(concat!(
                "the process is not the one that connected (its creation time differs ",
                "from the one recorded at connect, or none was recorded)"
            )));
        }
        let image = process
            .image()
            .map_err(|e| unreadable("executable path", e))?;
        let after = process
            .created()
            .map_err(|e| unreadable("creation time", e))?;
        if before != after {
            return Err(changed(
                "its creation time differed before and after its executable path was read",
            ));
        }
        if !process.running() {
            return Err(changed("it exited while it was being identified"));
        }

        let found = std::fs::canonicalize(&image).unwrap_or(image);
        let id = file_id(&found);
        if !expect
            .executables
            .iter()
            .any(|expected| same_executable(expected, &found, id))
        {
            return Err(refuse(
                Some(pid),
                Some(plain(found)),
                HostIdentityReason::ExecutableMismatch,
            ));
        }
        let host = HostProcess {
            pid,
            uid: None,
            sid: Some(sid),
            executable: plain(found),
            audit_token: None,
        };
        if let Some(verifier) = &expect.verifier {
            if let Err(why) = verifier(&host) {
                return Err(refuse(
                    Some(pid),
                    Some(host.executable.clone()),
                    HostIdentityReason::Refused(why),
                ));
            }
        }
        // Released only now: every check above saw one process.
        drop(process);
        Ok(host)
    }

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

        #[test]
        fn the_same_file_matches_by_path_in_any_case_and_by_identity_through_a_hard_link() {
            let dir = tempfile::tempdir().unwrap();
            let real = dir.path().join("HostBin.exe");
            std::fs::write(&real, b"binary").unwrap();
            let found = std::fs::canonicalize(&real).unwrap();
            let id = file_id(&found);
            assert!(id.is_some());

            assert!(same_executable(&real, &found, id));
            // NTFS ignores case: another spelling names the same file.
            assert!(same_executable(&dir.path().join("hostbin.EXE"), &found, id));
            assert!(same_executable(
                &dir.path().join("hostbin.EXE"),
                &found,
                None
            ));

            let hard = dir.path().join("hard.exe");
            std::fs::hard_link(&real, &hard).unwrap();
            assert!(same_executable(&hard, &found, id), "same file, other name");
            // Without a file identity only the canonical path can match.
            assert!(!same_executable(&hard, &found, None));

            // Same bytes, different file: not the running executable.
            let copy = dir.path().join("copy.exe");
            std::fs::copy(&real, &copy).unwrap();
            assert!(!same_executable(&copy, &found, id));
            assert!(!same_executable(
                &dir.path().join("missing.exe"),
                &found,
                id
            ));
        }

        #[test]
        fn this_process_is_described_by_its_own_handle() {
            let process = Process::open(std::process::id()).unwrap();
            assert!(process.running());
            assert_eq!(process.created().unwrap(), process.created().unwrap());
            let image = std::fs::canonicalize(process.image().unwrap()).unwrap();
            let me = std::fs::canonicalize(std::env::current_exe().unwrap()).unwrap();
            assert!(same_executable(&me, &image, file_id(&image)));
            assert!(!plain(image).to_string_lossy().starts_with(r"\\?\"));
        }

        #[test]
        fn a_process_id_nothing_holds_cannot_be_opened() {
            // Process ids are multiples of four; this one is not.
            assert!(Process::open(0xFFFF_FFF3).is_err());
        }
    }
}

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

    #[test]
    fn a_bare_file_name_is_one_component() {
        assert!(is_single_component(OsStr::new("mailright")));
        assert!(is_single_component(OsStr::new("mailright.exe")));
        assert!(!is_single_component(OsStr::new("")));
        assert!(!is_single_component(OsStr::new("..")));
        assert!(!is_single_component(OsStr::new("a/b")));
        assert!(!is_single_component(OsStr::new("/abs")));
    }

    #[test]
    fn install_relative_paths_are_derived_from_where_the_engine_lives() {
        let engine = Path::new("/Applications/MailRight.app/Contents/Resources/bin/engine");
        assert_eq!(
            bundle_main(engine, OsStr::new("mailright")),
            Some(PathBuf::from(
                "/Applications/MailRight.app/Contents/MacOS/mailright"
            ))
        );
        assert_eq!(
            up_and_join(engine, 1, Path::new("app")),
            Some(PathBuf::from(
                "/Applications/MailRight.app/Contents/Resources/bin/app"
            ))
        );
        assert_eq!(
            up_and_join(engine, 3, Path::new("MacOS/mailright")),
            Some(PathBuf::from(
                "/Applications/MailRight.app/Contents/MacOS/mailright"
            ))
        );
        // Not in a bundle; level 0 is the executable itself; absolute relative paths are refused.
        assert_eq!(
            bundle_main(Path::new("/opt/app/bin/engine"), OsStr::new("x")),
            None
        );
        assert_eq!(up_and_join(engine, 0, Path::new("x")), None);
        assert_eq!(up_and_join(engine, 1, Path::new("/etc/passwd")), None);
        // Windows: a rooted path without a drive, and a drive-relative one, are not relative.
        #[cfg(windows)]
        for escape in [r"\Windows\System32\cmd.exe", "C:cmd.exe", r"C:\cmd.exe"] {
            assert_eq!(up_and_join(engine, 1, Path::new(escape)), None, "{escape}");
        }
        assert_eq!(up_and_join(Path::new("engine"), 5, Path::new("x")), None);
    }

    #[test]
    fn helpers_resolve_against_the_running_test_binary() {
        let exe = std::fs::canonicalize(std::env::current_exe().unwrap()).unwrap();
        let sibling = HostExpectation::sibling_executable("host-binary").unwrap();
        assert_eq!(
            sibling.executables(),
            [exe.parent().unwrap().join("host-binary")]
        );
        assert!(HostExpectation::sibling_executable("a/b").is_err());
        assert!(HostExpectation::sibling_executable("..").is_err());
        assert!(HostExpectation::bundle_executable("x/y").is_err());
        let up2 = HostExpectation::relative_to_current_exe(2, "bin/host").unwrap();
        assert_eq!(
            up2.executables(),
            [exe.parent().unwrap().parent().unwrap().join("bin/host")]
        );
        assert!(HostExpectation::relative_to_current_exe(0, "x").is_err());
    }

    #[test]
    fn the_error_says_what_was_expected_and_what_was_found() {
        let e = HostIdentityError {
            expected: vec![PathBuf::from("/a/app"), PathBuf::from("/b/app")],
            found_pid: Some(42),
            found_executable: Some(PathBuf::from("/tmp/evil")),
            reason: HostIdentityReason::ExecutableMismatch,
        };
        let text = e.to_string();
        assert!(
            text.contains("pid 42") && text.contains("/tmp/evil"),
            "{text}"
        );
        assert!(text.contains("/a/app or /b/app"), "{text}");
        let none = HostIdentityError {
            expected: Vec::new(),
            found_pid: None,
            found_executable: None,
            reason: HostIdentityReason::NoExpectation,
        };
        assert!(none.to_string().contains("none supplied"));
    }

    #[test]
    fn a_refusal_collapses_to_a_non_retryable_wire_error() {
        let e = HostIdentityError {
            expected: vec![PathBuf::from("/a/app")],
            found_pid: Some(7),
            found_executable: None,
            reason: HostIdentityReason::PidUnavailable,
        };
        let wire: crate::ServiceError = e.clone().into();
        assert_eq!(wire.code, crate::ERROR_HOST_IDENTITY);
        assert!(!wire.retryable);
        assert!(wire.message.contains("pid 7"));
        let c: crate::ConnectError = e.into();
        assert_eq!(c.into_service_error(), wire);
    }
}