alighieri 0.4.0

Alighieri — a lightweight, secure, asynchronous SOCKS5 proxy server with Dante-inspired configuration
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
//! Windows Service management commands.

use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::thread::sleep;
use std::time::{Duration, Instant};

use thiserror::Error;
use windows_service::service::{
    Service, ServiceAccess, ServiceAction, ServiceActionType, ServiceControlAccept,
    ServiceErrorControl, ServiceFailureActions, ServiceFailureResetPeriod, ServiceInfo,
    ServiceStartType, ServiceState, ServiceType,
};
use windows_service::service_manager::{ServiceManager, ServiceManagerAccess};

use crate::config::Config;
use crate::platform::windows::event_log;
use crate::platform::windows::service::{
    run_service_dispatcher, SERVICE_DISPLAY_NAME, SERVICE_NAME, SERVICE_RELOAD_CONTROL,
};
use crate::tls;

const DEFAULT_CONFIG: &str = r"C:\ProgramData\Alighieri\alighieri.conf";
const SERVICE_CONFIG_MARKER: &str = "service-config-path.txt";
const LOCAL_SERVICE_ACCOUNT: &str = r"NT AUTHORITY\LocalService";
const SERVICE_STOP_TIMEOUT: Duration = Duration::from_secs(30);
const SERVICE_STOP_POLL_INTERVAL: Duration = Duration::from_millis(250);

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ServiceCommand {
    Install { config_path: PathBuf },
    Uninstall,
    Start,
    Stop,
    Reload,
    Status,
    Run { config_path: Option<PathBuf> },
    Help,
}

#[derive(Debug, Error)]
pub enum ServiceCliError {
    #[error("{0}")]
    Usage(String),
    #[error("configuration error: {0}")]
    Config(String),
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),
    #[error("{0}")]
    Service(String),
}

pub type ServiceCliResult<T> = std::result::Result<T, ServiceCliError>;

pub trait ServiceController {
    fn install(&self, options: &InstallOptions) -> ServiceCliResult<()>;
    fn uninstall(&self) -> ServiceCliResult<()>;
    fn start(&self) -> ServiceCliResult<()>;
    fn stop(&self) -> ServiceCliResult<()>;
    fn reload(&self) -> ServiceCliResult<()>;
    fn status(&self) -> ServiceCliResult<String>;
    /// Records which config the service was installed with, so the CLI's
    /// `start`/`reload` validate the same file the service runs. Kept on the
    /// controller (rather than inlined) so install can roll back when it fails.
    fn persist_config_marker(&self, config_path: &Path) -> ServiceCliResult<()>;
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstallOptions {
    pub executable_path: PathBuf,
    pub config_path: PathBuf,
    pub account_name: OsString,
}

pub fn handle_service_cli(args: Vec<String>) -> ServiceCliResult<String> {
    let command = parse_service_command(args)?;
    if let ServiceCommand::Run { config_path } = command {
        return run_service_dispatcher(config_path).map_err(|e| {
            ServiceCliError::Service(format!("failed to run as Windows Service: {e}"))
        });
    }

    let controller = WindowsServiceController;
    execute_service_command(&controller, command)
}

pub fn parse_service_command(args: Vec<String>) -> ServiceCliResult<ServiceCommand> {
    if args.iter().any(|arg| arg == "-h" || arg == "--help") {
        return Ok(ServiceCommand::Help);
    }
    let Some(command) = args.first().map(String::as_str) else {
        return Err(ServiceCliError::Usage(service_usage()));
    };

    match command {
        "install" => {
            let config_path = parse_config_arg(&args[1..])?.unwrap_or_else(default_config_path);
            Ok(ServiceCommand::Install { config_path })
        }
        "uninstall" => Ok(ServiceCommand::Uninstall),
        "start" => Ok(ServiceCommand::Start),
        "stop" => Ok(ServiceCommand::Stop),
        "reload" => Ok(ServiceCommand::Reload),
        "status" => Ok(ServiceCommand::Status),
        "run" => {
            let config_path = parse_config_arg(&args[1..])?;
            Ok(ServiceCommand::Run { config_path })
        }
        _ => Err(ServiceCliError::Usage(service_usage())),
    }
}

pub fn execute_service_command<C: ServiceController>(
    controller: &C,
    command: ServiceCommand,
) -> ServiceCliResult<String> {
    match command {
        ServiceCommand::Install { config_path } => {
            // Freeze the config path as absolute before anything stores it: the
            // service runs under SCM from a different working directory, so a
            // relative `--config` (resolved here against the installer's CWD)
            // would otherwise resolve to a different file — or nothing — at
            // service start. The launch arguments, marker, and message all use
            // this absolute form.
            let config_path = absolute_config_path(&config_path)?;
            prepare_service_directories(&config_path)?;
            validate_config(&config_path)?;
            let options = InstallOptions {
                executable_path: std::env::current_exe()?,
                config_path: config_path.clone(),
                account_name: OsString::from(LOCAL_SERVICE_ACCOUNT),
            };
            controller.install(&options)?;
            finalize_install(controller, &config_path)?;
            Ok(format!(
                "installed {SERVICE_NAME} using config '{}'",
                config_path.display()
            ))
        }
        ServiceCommand::Uninstall => {
            controller.uninstall()?;
            Ok(format!("uninstalled {SERVICE_NAME}"))
        }
        ServiceCommand::Start => {
            let config_path = installed_config_path()?;
            validate_config(&config_path)?;
            controller.start()?;
            Ok(format!("started {SERVICE_NAME}"))
        }
        ServiceCommand::Stop => {
            controller.stop()?;
            Ok(format!("stopped {SERVICE_NAME}"))
        }
        ServiceCommand::Reload => {
            let config_path = installed_config_path()?;
            validate_config(&config_path)?;
            controller.reload()?;
            Ok(format!("requested reload of {SERVICE_NAME}"))
        }
        ServiceCommand::Status => controller.status(),
        ServiceCommand::Run { .. } => Err(ServiceCliError::Usage(
            "'service run' is reserved for the Windows Service Control Manager".into(),
        )),
        ServiceCommand::Help => Ok(service_usage()),
    }
}

fn parse_config_arg(args: &[String]) -> ServiceCliResult<Option<PathBuf>> {
    let mut config_path = None;
    let mut iter = args.iter();
    while let Some(arg) = iter.next() {
        match arg.as_str() {
            "--config" => {
                let Some(path) = iter.next() else {
                    return Err(ServiceCliError::Usage("--config requires a path".into()));
                };
                config_path = Some(PathBuf::from(path));
            }
            _ => return Err(ServiceCliError::Usage(service_usage())),
        }
    }
    Ok(config_path)
}

pub fn default_base_dir() -> PathBuf {
    std::env::var_os("ProgramData")
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from(r"C:\ProgramData"))
        .join("Alighieri")
}

pub fn default_config_path() -> PathBuf {
    std::env::var_os("ProgramData")
        .map(PathBuf::from)
        .map(|base| base.join("Alighieri").join("alighieri.conf"))
        .unwrap_or_else(|| PathBuf::from(DEFAULT_CONFIG))
}

pub fn default_log_dir() -> PathBuf {
    default_base_dir().join("logs")
}

fn config_marker_path() -> PathBuf {
    default_base_dir().join(SERVICE_CONFIG_MARKER)
}

/// Resolves the install `--config` path to an absolute path against the
/// installer's current directory, so the relative-vs-SCM working-directory
/// mismatch above cannot point the service at the wrong file.
fn absolute_config_path(config_path: &Path) -> ServiceCliResult<PathBuf> {
    Ok(std::path::absolute(config_path)?)
}

fn installed_config_path() -> ServiceCliResult<PathBuf> {
    read_installed_config_path(&config_marker_path())
}

/// Resolves the config path recorded at install time from `marker`. A genuinely
/// absent marker falls back to the default config (legacy installs predating the
/// marker, or a service that was never installed); a marker that is present but
/// unreadable, not a regular file, or empty/corrupt is an explicit error rather
/// than a silent fall back to validating a different config than the service
/// runs. The marker is opened without following a final-component symlink
/// (`ProgramData` subfolders can be standard-user-writable), mirroring the
/// userlist/wizard sidecar handling.
fn read_installed_config_path(marker: &Path) -> ServiceCliResult<PathBuf> {
    use std::io::Read;
    use std::os::windows::fs::OpenOptionsExt;
    use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;

    // Open the reparse point itself rather than following it, then require a
    // regular file, so a symlink planted at the marker path cannot redirect the
    // read to another file.
    let mut file = match std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
        .open(marker)
    {
        Ok(file) => file,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            // No marker (legacy/never-installed, or it was removed). Fall back to
            // the default config, but warn: if the service was installed with a
            // custom --config, the CLI would otherwise validate a different file
            // than the service actually runs.
            let default = default_config_path();
            eprintln!(
                "alighieri: warning: no service config marker at {}; validating the default \
                 config {}. If the service was installed with a custom --config, reinstall to \
                 restore the marker.",
                marker.display(),
                default.display()
            );
            return Ok(default);
        }
        Err(e) => {
            return Err(ServiceCliError::Service(format!(
                "cannot read the service config marker {}: {}",
                marker.display(),
                explain_io_error(&e)
            )))
        }
    };

    let metadata = file.metadata().map_err(|e| {
        ServiceCliError::Service(format!(
            "cannot inspect the service config marker {}: {}",
            marker.display(),
            explain_io_error(&e)
        ))
    })?;
    if !metadata.is_file() {
        return Err(ServiceCliError::Service(format!(
            "the service config marker {} is not a regular file; refusing to follow it",
            marker.display()
        )));
    }

    let mut contents = String::new();
    file.read_to_string(&mut contents).map_err(|e| {
        ServiceCliError::Service(format!(
            "cannot read the service config marker {}: {}",
            marker.display(),
            explain_io_error(&e)
        ))
    })?;
    let trimmed = contents.trim();
    if trimmed.is_empty() {
        return Err(ServiceCliError::Service(format!(
            "the service config marker {} is empty or corrupt; reinstall the service \
             with 'alighieri service install --config <path>'",
            marker.display()
        )));
    }
    let path = PathBuf::from(trimmed);
    if !path.is_absolute() {
        // Installs write an absolute path; a relative one means a marker from an
        // older install (before install absolutised the path) or a tampered one.
        // Resolving it would validate against the CLI's working directory, not the
        // service's — exactly the mismatch the install-side fix removed — so
        // refuse it rather than silently validating the wrong file.
        return Err(ServiceCliError::Service(format!(
            "the service config marker {} contains a relative path ({trimmed:?}); reinstall \
             the service with 'alighieri service install --config <absolute path>'",
            marker.display()
        )));
    }
    Ok(path)
}

/// The protected DACL (no owner) shared by the born-secure create and the
/// re-harden path so they cannot drift: `D:PAI` = protected, auto-inherited;
/// SYSTEM (SY) and Administrators (BA) Full, LocalService (LS) Modify (0x1301bf),
/// all object+container inheritable so children created afterward inherit them.
const HARDENED_DACL_SDDL: &str = "D:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1301bf;;;LS)";

fn prepare_service_directories(config_path: &Path) -> ServiceCliResult<()> {
    let base = default_base_dir();
    // A standard user who can write under `ProgramData` might pre-create the data
    // directory (or `logs/`) as a symlink/junction. Refuse a reparse point *before*
    // any filesystem write at this path: `create_dir_all` on a pre-planted link
    // would follow it and could create its target outside the intended directory.
    // Fatal, like the ACL hardening below — both fail the install rather than
    // proceed insecurely. (A link swapped in after this check is still caught: the
    // no-follow handle check in `secure_path_acl` refuses a reparse base too.)
    fail_if_reparse_point(&base)?;
    // Create the base directory with the protected DACL applied *atomically*, so a
    // fresh install never passes through a window where it inherits `ProgramData`'s
    // standard-user-writable ACL. Otherwise a standard user racing the install
    // could open a write handle to the directory (or a child) while it is still
    // permissive and keep it past the hardening step — Windows does not revoke
    // already-open handles when the DACL is later tightened. If it already exists
    // this is a no-op and `harden_directory_dacl` below secures the existing one.
    create_secure_base_dir(&base)?;
    // Restrict the base directory's ACL before populating it. A `ProgramData`
    // subfolder is otherwise writable (and readable) by standard users through
    // inherited permissions, so a non-admin could tamper with the config/userlist
    // the privileged service loads — local privilege escalation — or read the
    // userlist's secrets. Doing it before creating `logs/` and the config means
    // those inherit the restricted ACL. Fail closed: if the directory cannot be
    // secured, abort rather than run a service whose config a standard user can
    // rewrite — the very escalation this guards against. Hardening fails in
    // exactly the hostile case (a standard user pre-created the directory with a
    // DACL the installer cannot rewrite), so warn-and-continue would fail open
    // there; the common fresh install (we create and own the directory) is
    // unaffected. A genuinely exotic environment that cannot apply the DACL
    // surfaces as an install error to investigate, not a silently insecure
    // service.
    if let Err(e) = harden_directory_dacl(&base) {
        // `InvalidData` is the no-follow handle check reporting a reparse point —
        // the base swapped for a symlink after `fail_if_reparse_point` above, or a
        // pre-planted child surfaced by the walk — and `e` names the offending
        // path. Any other error means the ACL itself could not be applied. Both
        // are fatal.
        if e.kind() == std::io::ErrorKind::InvalidData {
            return Err(ServiceCliError::Service(format!(
                "refusing to install into {}: a symlink or reparse point is present ({e}). \
                 Remove it and reinstall.",
                base.display()
            )));
        }
        return Err(ServiceCliError::Service(format!(
            "refusing to install: could not secure {} ({e}). Its config and userlist would be \
             writable by standard users (local privilege escalation). Resolve the permission \
             problem — e.g. remove a data directory a standard user pre-created — and reinstall.",
            base.display()
        )));
    }
    // `logs/` is created under the now-protected base; reject (rather than follow)
    // a symlink planted in the brief window before the base was hardened.
    let logs = default_log_dir();
    fail_if_reparse_point(&logs)?;
    std::fs::create_dir_all(&logs)?;
    if let Some(parent) = config_path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    Ok(())
}

/// Fails if `path` exists and is a reparse point (symlink/junction). A path that
/// does not exist yet, or is a regular file/directory, is fine. Used to refuse
/// following a pre-planted link when populating the service data directory.
fn fail_if_reparse_point(path: &Path) -> ServiceCliResult<()> {
    use std::os::windows::fs::MetadataExt;
    const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400;
    match std::fs::symlink_metadata(path) {
        Ok(meta) if meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 => {
            Err(ServiceCliError::Service(format!(
                "refusing to install into {}: it is a symlink or reparse point. Remove it and \
                 reinstall.",
                path.display()
            )))
        }
        Ok(_) => Ok(()), // a regular file or directory
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), // not created yet
        // Any other error means we could not verify the path is safe — fail
        // closed rather than populate something we cannot inspect.
        Err(e) => Err(e.into()),
    }
}

/// Restricts the service data directory (and any pre-existing contents) so only
/// `SYSTEM`/`Administrators` (Full) and the `LocalService` service account
/// (Modify — read the config, write logs/ACME) can touch it, and standard users
/// cannot. Applies the protected DACL to the base, then walks and re-secures
/// existing children: a re-install over an unhardened directory does not retro-
/// actively update children's stored ACLs through the parent's new inheritable
/// ACEs, so each must be reset explicitly. Fails closed: any failure to secure
/// the base *or* an existing child (it cannot be enumerated, inspected, or have
/// its ACL reset), and any unexpected reparse point under the tree, is returned
/// so the caller aborts the install. An unsecured data directory — or a stale,
/// still-permissive config/userlist left under it — is the privilege-escalation
/// surface this exists to close, so leaving one in place is not acceptable. The
/// sole non-fatal case is a child that vanished mid-walk (it is simply gone).
fn harden_directory_dacl(base: &Path) -> std::io::Result<()> {
    secure_path_acl(base)?;
    secure_existing_children(base, 0)?;
    Ok(())
}

/// Depth cap for the re-secure walk. The service's own layout is shallow
/// (`logs/`, the ACME cache, the config); the contents of a pre-existing data
/// directory may be attacker-controlled, so a deeply nested tree must not be able
/// to overflow the stack via unbounded recursion (a denial-of-install). Far above
/// any legitimate nesting, well below a stack-exhausting depth.
const MAX_RESECURE_DEPTH: usize = 64;

fn secure_existing_children(dir: &Path, depth: usize) -> std::io::Result<()> {
    use std::os::windows::fs::MetadataExt;
    const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400;
    // Bound the recursion so an attacker-planted deep tree cannot crash the
    // installer. Exceeding the cap is fatal (fail closed), like the other walk
    // failures.
    if depth >= MAX_RESECURE_DEPTH {
        return Err(std::io::Error::other(format!(
            "service data directory nests deeper than {MAX_RESECURE_DEPTH} levels at {}; \
             refusing to continue",
            dir.display()
        )));
    }
    // Fail closed throughout, matching the caller: if we cannot enumerate,
    // inspect, or re-secure an existing child, propagate the error so the install
    // aborts rather than leave a possibly standard-user-writable sensitive file (a
    // stale config/userlist) under the now-protected base. The one benign
    // exception is a child that vanished mid-walk (`NotFound`) — it is simply gone,
    // not a redirection or a permissive file, so we skip it.
    let entries = std::fs::read_dir(dir)?;
    for entry in entries {
        let entry = entry?;
        let path = entry.path();
        // `symlink_metadata` does not follow the link (unambiguously, matching
        // `fail_if_reparse_point`). Check the reparse-point attribute — which
        // covers junctions/mount points, not just symlinks — so we never secure
        // or, worse, recurse *through* a planted reparse point onto a tree outside
        // the data directory.
        let meta = match std::fs::symlink_metadata(&path) {
            Ok(meta) => meta,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
            Err(e) => return Err(e),
        };
        if meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
            // We never create reparse points here, so an unexpected one is an
            // attacker-planted redirection. Locking the parent DACL does not undo
            // it — the link target is already fixed — so skipping it would leave a
            // live primitive for later privileged opens under the data directory
            // (config reads, log/ACME writes). Abort the install instead.
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!(
                    "unexpected reparse point under the service data directory: {}",
                    path.display()
                ),
            ));
        }
        if let Err(e) = secure_path_acl(&path) {
            // A reparse point swapped in after the `symlink_metadata` check above
            // (a TOCTOU race the point-in-time attribute check cannot close) makes
            // `secure_path_acl`'s no-follow handle check return `InvalidData`;
            // re-label it with the child path. A child that vanished in that same
            // window is benign (it is gone, not a permissive file), so skip it. Any
            // other error means this child's ACL could not be reset — if it is a
            // pre-existing config/userlist, its old (possibly permissive) ACL would
            // persist under the secured base, so it is fatal too.
            if e.kind() == std::io::ErrorKind::InvalidData {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!(
                        "unexpected reparse point under the service data directory: {}",
                        path.display()
                    ),
                ));
            }
            if e.kind() == std::io::ErrorKind::NotFound {
                continue;
            }
            return Err(e);
        }
        if meta.is_dir() {
            // A subdirectory that vanished between the check above and this descent
            // surfaces as `NotFound` from its `read_dir`; that is the same benign
            // mid-walk removal, so tolerate it rather than abort the install.
            match secure_existing_children(&path, depth + 1) {
                Ok(()) => {}
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
                Err(e) => return Err(e),
            }
        }
    }
    Ok(())
}

/// Creates `base` with the [`HARDENED_DACL_SDDL`] protected DACL applied
/// atomically (born secure), so a fresh install never passes through a window
/// where the directory inherits `ProgramData`'s standard-user-writable ACL — a
/// window in which a racing standard user could open a handle that survives the
/// later hardening. If `base` already exists this is a no-op (the caller hardens
/// the existing directory); any other failure propagates so the install fails
/// closed. The owner is left as the creator and `secure_path_acl` takes ownership
/// afterward — setting owner at create time would need elevation the SDDL omits.
fn create_secure_base_dir(base: &Path) -> std::io::Result<()> {
    use std::os::windows::ffi::OsStrExt;
    use windows_sys::Win32::Foundation::{LocalFree, ERROR_ALREADY_EXISTS};
    use windows_sys::Win32::Security::Authorization::{
        ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1,
    };
    use windows_sys::Win32::Security::{PSECURITY_DESCRIPTOR, SECURITY_ATTRIBUTES};
    use windows_sys::Win32::Storage::FileSystem::CreateDirectoryW;

    // The parent (`ProgramData`) already exists; create it defensively so only the
    // leaf is the security-sensitive create.
    if let Some(parent) = base.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let wide: Vec<u16> = base
        .as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect();
    let sddl_w: Vec<u16> = HARDENED_DACL_SDDL
        .encode_utf16()
        .chain(std::iter::once(0))
        .collect();

    // SAFETY: standard Win32 calls. `ConvertString...` allocates a self-relative
    // descriptor freed by `LocalFree`; it stays valid through the `CreateDirectoryW`
    // call that borrows it via `SECURITY_ATTRIBUTES`.
    unsafe {
        let mut psd: PSECURITY_DESCRIPTOR = std::ptr::null_mut();
        if ConvertStringSecurityDescriptorToSecurityDescriptorW(
            sddl_w.as_ptr(),
            SDDL_REVISION_1,
            &mut psd,
            std::ptr::null_mut(),
        ) == 0
        {
            return Err(std::io::Error::last_os_error());
        }
        let sa = SECURITY_ATTRIBUTES {
            nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
            lpSecurityDescriptor: psd,
            bInheritHandle: 0,
        };
        let created = CreateDirectoryW(wide.as_ptr(), &sa);
        // Capture the error before `LocalFree`, which can clobber the thread error.
        let err = std::io::Error::last_os_error();
        LocalFree(psd);
        if created == 0 {
            if err.raw_os_error() != Some(ERROR_ALREADY_EXISTS as i32) {
                return Err(err);
            }
            // `ERROR_ALREADY_EXISTS` is also returned when a *regular file* occupies
            // the path; only an existing directory is the benign idempotent case.
            // (A reparse point was already refused by `fail_if_reparse_point`; stat
            // without following regardless.) Reject anything else with a clear error
            // rather than let later steps fail obscurely on a non-directory.
            if !std::fs::symlink_metadata(base)?.is_dir() {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::AlreadyExists,
                    format!("{} already exists and is not a directory", base.display()),
                ));
            }
        }
    }
    Ok(())
}

/// Sets `path`'s owner to `Administrators` and a protected DACL (granting only
/// `SYSTEM`/`Administrators` Full and `LocalService` Modify), operating on a
/// handle opened **without following reparse points** so a symlink/junction a
/// standard user may have planted in `ProgramData` cannot redirect the change
/// onto a target outside the data directory (a TOCTOU). Taking ownership keeps a
/// pre-creating user from staying owner and later rewriting the DACL; it needs
/// elevation, so if it is refused the protected DACL is still applied on its own
/// (the essential protection). SIDs (not names) keep this locale-independent.
fn secure_path_acl(path: &Path) -> std::io::Result<()> {
    use std::os::windows::fs::OpenOptionsExt;
    use std::os::windows::io::AsRawHandle;
    use windows_sys::Win32::Foundation::LocalFree;
    use windows_sys::Win32::Security::Authorization::{
        ConvertStringSecurityDescriptorToSecurityDescriptorW, SetSecurityInfo, SDDL_REVISION_1,
        SE_FILE_OBJECT,
    };
    use windows_sys::Win32::Security::{
        GetSecurityDescriptorDacl, GetSecurityDescriptorOwner, ACL, DACL_SECURITY_INFORMATION,
        OWNER_SECURITY_INFORMATION, PROTECTED_DACL_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR,
        PSID,
    };
    use windows_sys::Win32::Storage::FileSystem::{
        FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT,
    };

    // Standard access bits (stable constants, avoiding feature churn):
    // READ_CONTROL to read the current descriptor (needed when switching the DACL
    // to protected), WRITE_DAC to set the DACL, WRITE_OWNER to take ownership,
    // FILE_READ_ATTRIBUTES so `handle.metadata()` can read the reparse-point
    // attribute below — the owner gets READ_CONTROL/WRITE_DAC implicitly but not
    // attribute-read, so without this the no-follow check could fail spuriously on
    // a child whose ACL does not grant it.
    const READ_CONTROL: u32 = 0x0002_0000;
    const WRITE_DAC: u32 = 0x0004_0000;
    const WRITE_OWNER: u32 = 0x0008_0000;
    const FILE_READ_ATTRIBUTES: u32 = 0x0000_0080;
    // `O:BA` (owner Administrators) prepended to the shared protected DACL, so the
    // born-secure create and this re-harden apply the same ACEs.
    let sddl = format!("O:BA{HARDENED_DACL_SDDL}");

    // `BACKUP_SEMANTICS` is required to open a directory handle; `OPEN_REPARSE_POINT`
    // opens the link itself rather than its target. Prefer a handle that can also
    // take ownership, but fall back to `WRITE_DAC` alone when taking ownership is
    // not permitted (an unprivileged caller has implicit `WRITE_DAC` over an owned
    // object but not `WRITE_OWNER`): the protected DACL is the essential lock-out.
    let open = |access: u32| {
        std::fs::OpenOptions::new()
            .access_mode(access)
            .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
            .open(path)
    };
    let (handle, with_owner) =
        match open(READ_CONTROL | WRITE_DAC | WRITE_OWNER | FILE_READ_ATTRIBUTES) {
            Ok(handle) => (handle, true),
            Err(_) => (
                open(READ_CONTROL | WRITE_DAC | FILE_READ_ATTRIBUTES)?,
                false,
            ),
        };
    // The handle refers to the link itself (OPEN_REPARSE_POINT). Refuse any
    // reparse point — symlink or junction/mount point — via the attribute, which
    // `file_type().is_symlink()` would miss for junctions.
    use std::os::windows::fs::MetadataExt;
    const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400;
    if handle.metadata()?.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "refusing to set permissions on a symlink/reparse point",
        ));
    }
    let raw = handle.as_raw_handle();
    let sddl_w: Vec<u16> = sddl.encode_utf16().chain(std::iter::once(0)).collect();

    // SAFETY: standard Win32 security calls. `ConvertString...` allocates a
    // self-relative descriptor freed by `LocalFree`; the DACL/owner pointers point
    // into it and stay valid until then. `raw` is a live directory handle.
    unsafe {
        let mut psd: PSECURITY_DESCRIPTOR = std::ptr::null_mut();
        if ConvertStringSecurityDescriptorToSecurityDescriptorW(
            sddl_w.as_ptr(),
            SDDL_REVISION_1,
            &mut psd,
            std::ptr::null_mut(),
        ) == 0
        {
            return Err(std::io::Error::last_os_error());
        }
        let mut present = 0;
        let mut pdacl: *mut ACL = std::ptr::null_mut();
        let mut defaulted = 0;
        let mut powner: PSID = std::ptr::null_mut();
        let mut owner_defaulted = 0;
        if GetSecurityDescriptorDacl(psd, &mut present, &mut pdacl, &mut defaulted) == 0
            || present == 0
            || GetSecurityDescriptorOwner(psd, &mut powner, &mut owner_defaulted) == 0
        {
            let err = std::io::Error::last_os_error();
            LocalFree(psd);
            return Err(err);
        }
        let dacl_only = DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION;
        // With the owner handle, set owner + protected DACL; if setting the owner
        // is still refused, or we only have the DACL handle, apply just the
        // protected DACL — what actually locks out standard users.
        let mut rc = if with_owner {
            SetSecurityInfo(
                raw as _,
                SE_FILE_OBJECT,
                OWNER_SECURITY_INFORMATION | dacl_only,
                powner,
                std::ptr::null_mut(),
                pdacl,
                std::ptr::null_mut(),
            )
        } else {
            1 // skip straight to the DACL-only path below
        };
        if rc != 0 {
            rc = SetSecurityInfo(
                raw as _,
                SE_FILE_OBJECT,
                dacl_only,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                pdacl,
                std::ptr::null_mut(),
            );
        }
        LocalFree(psd);
        if rc != 0 {
            return Err(std::io::Error::from_raw_os_error(rc as i32));
        }
    }
    Ok(())
}

fn write_config_marker(config_path: &Path) -> ServiceCliResult<()> {
    write_marker_atomically(&config_marker_path(), &config_path.display().to_string())?;
    Ok(())
}

/// Writes the marker crash-safely: a fresh sibling temp file is written and
/// flushed, then renamed over `marker`. A direct `std::fs::write` truncates in
/// place, so a crash mid-write could leave a truncated/partial path that later
/// makes the CLI validate the wrong (or default) config; with the rename, readers
/// always see a complete old-or-new file (the rename also replaces a destination
/// link rather than writing through it). Mirrors the atomic persistence used for
/// the userlist/config writes; separated from `config_marker_path` for testing.
fn write_marker_atomically(marker: &Path, contents: &str) -> std::io::Result<()> {
    use std::io::Write;

    let (temp, mut file) = create_marker_temp(marker)?;
    let result = file
        .write_all(contents.as_bytes())
        .and_then(|()| file.sync_all());
    drop(file);
    // Clean the temp up on any failure after it was created (write, fsync, or
    // rename) so a partial temp never lingers.
    if let Err(e) = result.and_then(|()| std::fs::rename(&temp, marker)) {
        let _ = std::fs::remove_file(&temp);
        return Err(e);
    }
    Ok(())
}

/// Creates a fresh, uniquely-named sibling temp file with `create_new`
/// (`CREATE_NEW`). Because it refuses to open an existing name, it cannot follow
/// a symlink/reparse point pre-planted in the directory — a real concern under
/// `ProgramData`, whose subfolders a standard user may be able to write — and a
/// unique `pid`-`nonce` name avoids collisions and stale-temp wedging. Mirrors
/// `create_userlist_temp`.
fn create_marker_temp(marker: &Path) -> std::io::Result<(PathBuf, std::fs::File)> {
    use std::ffi::{OsStr, OsString};
    use std::sync::atomic::{AtomicU64, Ordering};

    static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);

    let parent = marker
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."));
    let file_name = marker
        .file_name()
        .unwrap_or_else(|| OsStr::new(SERVICE_CONFIG_MARKER));

    for _ in 0..100 {
        let nonce = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
        let mut temp_name = OsString::from(".");
        temp_name.push(file_name);
        temp_name.push(format!(".tmp-{}-{nonce}", std::process::id()));
        let temp = parent.join(temp_name);
        match std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&temp)
        {
            Ok(file) => return Ok((temp, file)),
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(e) => return Err(e),
        }
    }

    Err(std::io::Error::new(
        std::io::ErrorKind::AlreadyExists,
        "failed to create unique temporary marker path",
    ))
}

/// Records the installed config marker after the service is created, rolling the
/// install back if it cannot be written.
///
/// The service's config path is baked into its SCM launch arguments, and the
/// marker mirrors it for the CLI's `start`/`reload`. If the two disagreed the CLI
/// would validate a different config than the service actually runs (a missing
/// marker falls back to the default path), so a failed marker write must not
/// leave an installed service behind. A successful rollback returns the original
/// marker error (net state: not installed); if the rollback *also* fails the
/// service is still installed, so both failures are surfaced and the operator is
/// pointed at a manual uninstall rather than the leftover service being hidden
/// behind the marker error alone.
fn finalize_install<C: ServiceController>(
    controller: &C,
    config_path: &Path,
) -> ServiceCliResult<()> {
    let Err(persist_err) = controller.persist_config_marker(config_path) else {
        return Ok(());
    };
    match controller.uninstall() {
        Ok(()) => Err(persist_err),
        Err(uninstall_err) => Err(ServiceCliError::Service(format!(
            "failed to record the installed config ({persist_err}); rolling the install back \
             also failed ({uninstall_err}), so the {SERVICE_NAME} service may still be installed \
             - run 'alighieri service uninstall' to remove it"
        ))),
    }
}

fn validate_config(config_path: &Path) -> ServiceCliResult<()> {
    Config::load(config_path)
        .and_then(|config| {
            // Mirror the checks `Server::bind` runs at startup (same order as the
            // `check` command) so `service install`/`start`/`reload` reject a
            // config that would otherwise fail the moment the service binds —
            // e.g. an unauthenticated public metrics endpoint.
            config.validate_startup()?;
            tls::validate_config(&config)?;
            Ok(())
        })
        .map_err(|e| ServiceCliError::Config(format!("{} ({})", config_path.display(), e)))
}

fn service_usage() -> String {
    "usage: alighieri service install --config CONFIG | uninstall | start | stop | reload | status"
        .into()
}

pub fn explain_service_error(err: &windows_service::Error) -> String {
    let base = err.to_string();
    if matches!(err, windows_service::Error::Winapi(io) if io.raw_os_error() == Some(5)) {
        return format!("{base}; run this command from an elevated Administrator shell");
    }
    let lower = base.to_ascii_lowercase();
    if lower.contains("access is denied") || lower.contains("os error 5") {
        format!("{base}; run this command from an elevated Administrator shell")
    } else {
        base
    }
}

fn explain_io_error(err: &std::io::Error) -> String {
    let base = err.to_string();
    if err.raw_os_error() == Some(5) || base.to_ascii_lowercase().contains("access is denied") {
        format!("I/O error: {base}; run this command from an elevated Administrator shell")
    } else {
        format!("I/O error: {base}")
    }
}

fn ensure_service_stopped(service: &Service) -> ServiceCliResult<()> {
    let status = service
        .query_status()
        .map_err(|e| ServiceCliError::Service(explain_service_error(&e)))?;
    if status.current_state == ServiceState::Stopped {
        return Ok(());
    }

    if should_request_stop(status.current_state, status.controls_accepted) {
        if let Err(err) = service.stop() {
            if wait_for_service_stopped(service, SERVICE_STOP_TIMEOUT).is_ok() {
                return Ok(());
            }
            return Err(ServiceCliError::Service(explain_service_error(&err)));
        }
    }
    wait_for_service_stopped(service, SERVICE_STOP_TIMEOUT)
}

fn should_request_stop(
    current_state: ServiceState,
    controls_accepted: ServiceControlAccept,
) -> bool {
    current_state != ServiceState::Stopped
        && current_state != ServiceState::StopPending
        && controls_accepted.contains(ServiceControlAccept::STOP)
}

fn wait_for_service_stopped(service: &Service, timeout: Duration) -> ServiceCliResult<()> {
    let start = Instant::now();
    while start.elapsed() < timeout {
        let status = service
            .query_status()
            .map_err(|e| ServiceCliError::Service(explain_service_error(&e)))?;
        if status.current_state == ServiceState::Stopped {
            return Ok(());
        }
        sleep(SERVICE_STOP_POLL_INTERVAL);
    }

    Err(ServiceCliError::Service(format!(
        "timed out waiting for {SERVICE_NAME} to stop before uninstalling"
    )))
}

pub struct WindowsServiceController;

/// A failed `WindowsServiceController::install` attempt: the error to report, and
/// whether an SCM service was left behind because cleanup could not remove it (so
/// the caller knows not to unregister the event source out from under it).
struct InstallFailure {
    error: ServiceCliError,
    service_remains: bool,
}

impl From<ServiceCliError> for InstallFailure {
    /// Failures before or while creating the service leave nothing behind.
    fn from(error: ServiceCliError) -> Self {
        InstallFailure {
            error,
            service_remains: false,
        }
    }
}

/// Builds the error for a post-create configuration failure, given the result of
/// rolling the just-created service back. A successful rollback reports only the
/// configuration error (net state: not installed); if the rollback `delete` also
/// failed the service may still be installed, so both failures are surfaced and
/// the operator is pointed at a manual uninstall. Mirrors `finalize_install`.
fn configure_rollback_error(configure_err: &str, delete: ServiceCliResult<()>) -> InstallFailure {
    match delete {
        Ok(()) => InstallFailure {
            error: ServiceCliError::Service(configure_err.to_string()),
            service_remains: false,
        },
        Err(delete_err) => InstallFailure {
            error: ServiceCliError::Service(format!(
                "{configure_err}; rolling back the partially configured service also failed \
                 ({delete_err}), so the {SERVICE_NAME} service may still be installed - run \
                 'alighieri service uninstall' to remove it"
            )),
            service_remains: true,
        },
    }
}

/// `create_service` failed because the service is already installed. Sourced
/// from `windows_sys` (a `WIN32_ERROR`, i.e. `u32`) rather than hardcoding the
/// numeric code, and narrowed to `i32` to match the `Option<i32>` that
/// `io::Error::raw_os_error` returns.
const ERROR_SERVICE_EXISTS: i32 = windows_sys::Win32::Foundation::ERROR_SERVICE_EXISTS as i32;

/// Classifies a `create_service` failure. `ERROR_SERVICE_EXISTS` means an
/// installation already exists, so a failed reinstall must NOT unregister the
/// event source that existing installation relies on; any other failure created
/// no service, so the source registered earlier in `install` is ours to drop.
fn create_failure(e: windows_service::Error) -> InstallFailure {
    let service_remains = matches!(
        &e,
        windows_service::Error::Winapi(io) if io.raw_os_error() == Some(ERROR_SERVICE_EXISTS)
    );
    InstallFailure {
        error: ServiceCliError::Service(explain_service_error(&e)),
        service_remains,
    }
}

impl ServiceController for WindowsServiceController {
    fn install(&self, options: &InstallOptions) -> ServiceCliResult<()> {
        event_log::register_source().map_err(|e| ServiceCliError::Service(explain_io_error(&e)))?;

        let install_result = || -> Result<(), InstallFailure> {
            let manager_access =
                ServiceManagerAccess::CONNECT | ServiceManagerAccess::CREATE_SERVICE;
            let manager = ServiceManager::local_computer(None::<&str>, manager_access)
                .map_err(|e| ServiceCliError::Service(explain_service_error(&e)))?;

            let service_info = ServiceInfo {
                name: OsString::from(SERVICE_NAME),
                display_name: OsString::from(SERVICE_DISPLAY_NAME),
                service_type: ServiceType::OWN_PROCESS,
                start_type: ServiceStartType::AutoStart,
                error_control: ServiceErrorControl::Normal,
                executable_path: options.executable_path.clone(),
                launch_arguments: vec![
                    OsString::from("service"),
                    OsString::from("run"),
                    OsString::from("--config"),
                    options.config_path.clone().into_os_string(),
                ],
                dependencies: vec![],
                account_name: Some(options.account_name.clone()),
                account_password: None,
            };

            let service_access = ServiceAccess::QUERY_STATUS
                | ServiceAccess::QUERY_CONFIG
                | ServiceAccess::CHANGE_CONFIG
                | ServiceAccess::START
                | ServiceAccess::STOP
                | ServiceAccess::DELETE;

            let service = manager
                .create_service(&service_info, service_access)
                .map_err(create_failure)?;
            // Configure the freshly created service. On any failure, best-effort
            // delete it so a half-configured service is not left behind for the
            // operator to clean up by hand.
            //
            // Auto-restart on crash mirrors the systemd unit's
            // `Restart=on-failure`: escalating delays avoid a tight restart loop,
            // and the reset period clears the failure count after a stable hour.
            // (Left at the default of recovering only from real crashes — a clean
            // exit with a config-error code is not restarted, since a restart
            // would not fix a broken config.)
            let configure = service
                .set_description(SERVICE_DISPLAY_NAME)
                .and_then(|()| {
                    service.update_failure_actions(ServiceFailureActions {
                        reset_period: ServiceFailureResetPeriod::After(Duration::from_secs(
                            60 * 60,
                        )),
                        reboot_msg: None,
                        command: None,
                        actions: Some(vec![
                            ServiceAction {
                                action_type: ServiceActionType::Restart,
                                delay: Duration::from_secs(5),
                            },
                            ServiceAction {
                                action_type: ServiceActionType::Restart,
                                delay: Duration::from_secs(30),
                            },
                            ServiceAction {
                                action_type: ServiceActionType::Restart,
                                delay: Duration::from_secs(60),
                            },
                        ]),
                    })
                });
            if let Err(e) = configure {
                let configure_err = explain_service_error(&e);
                let delete = service
                    .delete()
                    .map_err(|de| ServiceCliError::Service(explain_service_error(&de)));
                return Err(configure_rollback_error(&configure_err, delete));
            }
            Ok(())
        };

        match install_result() {
            Ok(()) => {}
            Err(InstallFailure {
                error,
                service_remains,
            }) => {
                // Keep the event source registered if a service survived a failed
                // cleanup (it still needs it for its own logging; the eventual
                // manual uninstall unregisters it). Otherwise drop it.
                if !service_remains {
                    let _ = event_log::unregister_source();
                }
                return Err(error);
            }
        }
        // The "was installed" Event Log entry is reported from
        // `persist_config_marker` (the final install step), not here: a failed
        // marker write rolls the install back, so reporting here would leave a
        // misleading "was installed" record with no service behind it.
        Ok(())
    }

    fn uninstall(&self) -> ServiceCliResult<()> {
        let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT)
            .map_err(|e| ServiceCliError::Service(explain_service_error(&e)))?;
        let service = manager
            .open_service(
                SERVICE_NAME,
                ServiceAccess::QUERY_STATUS | ServiceAccess::STOP | ServiceAccess::DELETE,
            )
            .map_err(|e| ServiceCliError::Service(explain_service_error(&e)))?;
        ensure_service_stopped(&service)?;
        service
            .delete()
            .map_err(|e| ServiceCliError::Service(explain_service_error(&e)))?;
        // The service is gone now; failing to remove its Event Log source leaves
        // only a stray registry key, not an installed service. Keep this
        // best-effort so a failing `uninstall` means the *delete* failed (service
        // still installed) — which `finalize_install`'s rollback relies on to
        // report state accurately — rather than a leftover registration.
        let _ = event_log::unregister_source();
        Ok(())
    }

    fn start(&self) -> ServiceCliResult<()> {
        let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT)
            .map_err(|e| ServiceCliError::Service(explain_service_error(&e)))?;
        let service = manager
            .open_service(SERVICE_NAME, ServiceAccess::START)
            .map_err(|e| ServiceCliError::Service(explain_service_error(&e)))?;
        service
            .start::<&str>(&[])
            .map_err(|e| ServiceCliError::Service(explain_service_error(&e)))
    }

    fn stop(&self) -> ServiceCliResult<()> {
        let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT)
            .map_err(|e| ServiceCliError::Service(explain_service_error(&e)))?;
        let service = manager
            .open_service(SERVICE_NAME, ServiceAccess::STOP)
            .map_err(|e| ServiceCliError::Service(explain_service_error(&e)))?;
        service
            .stop()
            .map(|_| ())
            .map_err(|e| ServiceCliError::Service(explain_service_error(&e)))
    }

    fn reload(&self) -> ServiceCliResult<()> {
        let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT)
            .map_err(|e| ServiceCliError::Service(explain_service_error(&e)))?;
        let service = manager
            .open_service(SERVICE_NAME, ServiceAccess::USER_DEFINED_CONTROL)
            .map_err(|e| ServiceCliError::Service(explain_service_error(&e)))?;
        service
            .notify(SERVICE_RELOAD_CONTROL)
            .map(|_| ())
            .map_err(|e| ServiceCliError::Service(explain_service_error(&e)))
    }

    fn status(&self) -> ServiceCliResult<String> {
        let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT)
            .map_err(|e| ServiceCliError::Service(explain_service_error(&e)))?;
        let service = manager
            .open_service(SERVICE_NAME, ServiceAccess::QUERY_STATUS)
            .map_err(|e| ServiceCliError::Service(explain_service_error(&e)))?;
        let status = service
            .query_status()
            .map_err(|e| ServiceCliError::Service(explain_service_error(&e)))?;
        Ok(format!("{SERVICE_NAME}: {:?}", status.current_state))
    }

    fn persist_config_marker(&self, config_path: &Path) -> ServiceCliResult<()> {
        write_config_marker(config_path)?;
        // Reported here rather than in `install` so the "was installed" entry is
        // logged only once the whole install has succeeded (service created and
        // marker persisted). A marker-write failure rolls the install back, so
        // emitting this from `install` would misreport an install the command
        // ultimately failed and removed.
        event_log::report(
            event_log::EventLevel::Info,
            event_log::EVENT_SERVICE_INSTALLED,
            format!("{SERVICE_DISPLAY_NAME} was installed"),
        );
        Ok(())
    }
}

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

    #[test]
    fn parses_install_with_config() {
        let command = parse_service_command(vec![
            "install".into(),
            "--config".into(),
            r"C:\ProgramData\Alighieri\alighieri.conf".into(),
        ])
        .unwrap();
        assert_eq!(
            command,
            ServiceCommand::Install {
                config_path: PathBuf::from(r"C:\ProgramData\Alighieri\alighieri.conf")
            }
        );
    }

    #[test]
    fn parses_lifecycle_commands() {
        assert_eq!(
            parse_service_command(vec!["uninstall".into()]).unwrap(),
            ServiceCommand::Uninstall
        );
        assert_eq!(
            parse_service_command(vec!["start".into()]).unwrap(),
            ServiceCommand::Start
        );
        assert_eq!(
            parse_service_command(vec!["stop".into()]).unwrap(),
            ServiceCommand::Stop
        );
        assert_eq!(
            parse_service_command(vec!["reload".into()]).unwrap(),
            ServiceCommand::Reload
        );
        assert_eq!(
            parse_service_command(vec!["status".into()]).unwrap(),
            ServiceCommand::Status
        );
    }

    #[test]
    fn validate_config_rejects_public_metrics_without_allowpublic() {
        // The service validation path must enforce the same startup checks as
        // `Server::bind`, so installing/starting a config that binds public
        // metrics without `metrics.allowpublic` fails up front rather than only
        // when the service later tries to bind.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("alighieri.conf");
        std::fs::write(
            &path,
            "internal: 127.0.0.1 port = 1080\nmetrics.listen: 0.0.0.0:9090\nsocks pass { from: 0.0.0.0/0 to: 0.0.0.0/0 }",
        )
        .unwrap();

        let Err(err) = validate_config(&path) else {
            panic!("service validation should refuse public metrics without metrics.allowpublic");
        };
        assert!(err.to_string().contains("metrics.allowpublic"), "{err}");
    }

    #[test]
    fn parses_service_help() {
        assert_eq!(
            parse_service_command(vec!["install".into(), "--help".into()]).unwrap(),
            ServiceCommand::Help
        );
    }

    #[test]
    fn default_paths_use_program_data() {
        let config = default_config_path();
        assert!(config.ends_with(Path::new("Alighieri").join("alighieri.conf")));
        let logs = default_log_dir();
        assert!(logs.ends_with(Path::new("Alighieri").join("logs")));
    }

    #[test]
    fn absolute_config_path_makes_a_relative_path_absolute() {
        // A relative `--config` must not be stored verbatim: the service runs
        // from a different working directory and would resolve it elsewhere.
        let abs = absolute_config_path(Path::new("alighieri.conf")).unwrap();
        assert!(abs.is_absolute(), "not absolute: {}", abs.display());
        assert!(abs.ends_with("alighieri.conf"), "{}", abs.display());
        assert_ne!(abs, PathBuf::from("alighieri.conf"));

        // An already-absolute path stays absolute.
        assert!(
            absolute_config_path(Path::new(r"C:\configs\alighieri.conf"))
                .unwrap()
                .is_absolute()
        );
    }

    #[test]
    fn read_installed_config_path_reads_and_trims_the_marker() {
        let dir = tempfile::tempdir().unwrap();
        let marker = dir.path().join("service-config-path.txt");
        std::fs::write(&marker, "  C:\\configs\\alighieri.conf  \r\n").unwrap();
        assert_eq!(
            read_installed_config_path(&marker).unwrap(),
            PathBuf::from(r"C:\configs\alighieri.conf")
        );
    }

    #[test]
    fn read_installed_config_path_falls_back_to_default_when_absent() {
        let dir = tempfile::tempdir().unwrap();
        let marker = dir.path().join("does-not-exist.txt");
        assert_eq!(
            read_installed_config_path(&marker).unwrap(),
            default_config_path()
        );
    }

    #[test]
    fn read_installed_config_path_rejects_an_empty_marker() {
        let dir = tempfile::tempdir().unwrap();
        let marker = dir.path().join("service-config-path.txt");
        std::fs::write(&marker, "   \r\n").unwrap();
        let err = read_installed_config_path(&marker).unwrap_err();
        assert!(err.to_string().contains("empty or corrupt"), "{err}");
    }

    #[test]
    fn read_installed_config_path_rejects_a_relative_marker() {
        // A marker from an older install (or tampering) holding a relative path
        // would resolve against the CLI's working directory, not the service's.
        let dir = tempfile::tempdir().unwrap();
        let marker = dir.path().join("service-config-path.txt");
        std::fs::write(&marker, "alighieri.conf\r\n").unwrap();
        let err = read_installed_config_path(&marker).unwrap_err();
        assert!(err.to_string().contains("relative path"), "{err}");
    }

    #[test]
    fn read_installed_config_path_rejects_a_symlinked_marker() {
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("target.txt");
        std::fs::write(&target, r"C:\evil\redirected.conf").unwrap();
        let marker = dir.path().join("service-config-path.txt");

        // Creating a symlink needs SeCreateSymbolicLinkPrivilege (admin or
        // Developer Mode). Skip if unavailable so this still covers CI (which can
        // create symlinks) without failing on a non-elevated dev box.
        if std::os::windows::fs::symlink_file(&target, &marker).is_err() {
            eprintln!("skipping symlink test: cannot create symlinks in this environment");
            return;
        }

        // The marker is opened as the reparse point itself and rejected as a
        // non-regular file — the target's contents are never read.
        let result = read_installed_config_path(&marker);
        assert!(
            matches!(&result, Err(ServiceCliError::Service(msg)) if msg.contains("not a regular file")),
            "a symlinked marker must be rejected without following it, got {result:?}"
        );
    }

    #[test]
    fn permission_error_mentions_elevation() {
        let err = windows_service::Error::Winapi(std::io::Error::from_raw_os_error(5));
        let message = explain_service_error(&err);
        assert!(message.contains("Administrator"));
    }

    #[test]
    fn event_log_permission_error_mentions_elevation() {
        let err = std::io::Error::from_raw_os_error(5);
        let message = explain_io_error(&err);
        assert!(message.contains("I/O error"));
        assert!(message.contains("Administrator"));
    }

    #[test]
    fn stop_pending_service_is_waited_without_second_stop_request() {
        assert!(!should_request_stop(
            ServiceState::StopPending,
            ServiceControlAccept::STOP
        ));
    }

    #[test]
    fn running_service_requests_stop_only_when_control_is_accepted() {
        assert!(should_request_stop(
            ServiceState::Running,
            ServiceControlAccept::STOP
        ));
        assert!(!should_request_stop(
            ServiceState::Running,
            ServiceControlAccept::empty()
        ));
    }

    #[derive(Default)]
    struct FakeController {
        persist_should_fail: bool,
        uninstall_should_fail: bool,
        uninstalled: std::cell::Cell<bool>,
    }

    impl ServiceController for FakeController {
        fn install(&self, _options: &InstallOptions) -> ServiceCliResult<()> {
            Ok(())
        }

        fn uninstall(&self) -> ServiceCliResult<()> {
            self.uninstalled.set(true);
            if self.uninstall_should_fail {
                Err(ServiceCliError::Service(
                    "simulated uninstall failure".into(),
                ))
            } else {
                Ok(())
            }
        }

        fn start(&self) -> ServiceCliResult<()> {
            Ok(())
        }

        fn stop(&self) -> ServiceCliResult<()> {
            Ok(())
        }

        fn reload(&self) -> ServiceCliResult<()> {
            Ok(())
        }

        fn status(&self) -> ServiceCliResult<String> {
            Ok("Alighieri: Running".into())
        }

        fn persist_config_marker(&self, _config_path: &Path) -> ServiceCliResult<()> {
            if self.persist_should_fail {
                Err(ServiceCliError::Io(std::io::Error::other(
                    "simulated marker write failure",
                )))
            } else {
                Ok(())
            }
        }
    }

    #[test]
    fn command_layer_dispatches_status() {
        let message =
            execute_service_command(&FakeController::default(), ServiceCommand::Status).unwrap();
        assert_eq!(message, "Alighieri: Running");
    }

    #[test]
    fn finalize_install_rolls_back_when_config_marker_write_fails() {
        // If the marker cannot be written after the service is created, the
        // freshly installed service must be rolled back so the SCM launch
        // arguments and the CLI's marker can never point at different configs.
        let controller = FakeController {
            persist_should_fail: true,
            ..FakeController::default()
        };
        let err = finalize_install(
            &controller,
            Path::new(r"C:\ProgramData\Alighieri\alighieri.conf"),
        )
        .unwrap_err();
        assert!(matches!(err, ServiceCliError::Io(_)), "{err}");
        assert!(
            controller.uninstalled.get(),
            "a failed marker write must roll back (uninstall) the service"
        );
    }

    #[test]
    fn finalize_install_surfaces_a_failed_rollback() {
        // Marker write fails AND the rollback uninstall fails: the service may
        // still be installed, so the error must say so (and name both failures)
        // instead of returning only the marker error.
        let controller = FakeController {
            persist_should_fail: true,
            uninstall_should_fail: true,
            ..FakeController::default()
        };
        let err = finalize_install(
            &controller,
            Path::new(r"C:\ProgramData\Alighieri\alighieri.conf"),
        )
        .unwrap_err();
        assert!(
            controller.uninstalled.get(),
            "rollback uninstall must be attempted"
        );
        let msg = err.to_string();
        assert!(msg.contains("may still be installed"), "{msg}");
        assert!(msg.contains("simulated marker write failure"), "{msg}");
        assert!(msg.contains("simulated uninstall failure"), "{msg}");
    }

    #[test]
    fn finalize_install_succeeds_and_keeps_the_service_when_marker_writes() {
        let controller = FakeController::default();
        finalize_install(
            &controller,
            Path::new(r"C:\ProgramData\Alighieri\alighieri.conf"),
        )
        .unwrap();
        assert!(
            !controller.uninstalled.get(),
            "a successful install must not be rolled back"
        );
    }

    #[test]
    fn configure_rollback_error_reports_only_config_error_when_rollback_succeeds() {
        let failure = configure_rollback_error("set_description failed", Ok(()));
        assert!(!failure.service_remains);
        let msg = failure.error.to_string();
        assert!(msg.contains("set_description failed"), "{msg}");
        assert!(!msg.contains("may still be installed"), "{msg}");
    }

    #[test]
    fn configure_rollback_error_surfaces_both_failures_when_rollback_fails() {
        // Configuration failed AND the rollback delete failed: the service may
        // still be installed, so both failures and a manual-uninstall hint must
        // appear, and the caller must learn the service survived.
        let failure = configure_rollback_error(
            "set_description failed",
            Err(ServiceCliError::Service("delete access denied".into())),
        );
        assert!(failure.service_remains);
        let msg = failure.error.to_string();
        assert!(msg.contains("set_description failed"), "{msg}");
        assert!(msg.contains("delete access denied"), "{msg}");
        assert!(msg.contains("may still be installed"), "{msg}");
    }

    #[test]
    fn create_failure_keeps_the_source_when_the_service_already_exists() {
        // ERROR_SERVICE_EXISTS: a reinstall over an existing service must not
        // unregister the event source that existing installation relies on.
        let err =
            windows_service::Error::Winapi(std::io::Error::from_raw_os_error(ERROR_SERVICE_EXISTS));
        assert!(create_failure(err).service_remains);
    }

    #[test]
    fn create_failure_drops_the_source_for_other_failures() {
        // A non-"already exists" failure created no service, so the source
        // registered earlier in `install` is ours to drop.
        let err = windows_service::Error::Winapi(std::io::Error::from_raw_os_error(5));
        assert!(!create_failure(err).service_remains);
    }

    #[test]
    fn write_marker_atomically_replaces_existing_without_leaving_temp() {
        let dir = tempfile::tempdir().unwrap();
        let marker = dir.path().join("service-config-path.txt");
        std::fs::write(&marker, "old-path").unwrap();

        write_marker_atomically(&marker, r"C:\new\alighieri.conf").unwrap();

        assert_eq!(
            std::fs::read_to_string(&marker).unwrap(),
            r"C:\new\alighieri.conf"
        );
        // No temp sibling lingers after a successful write: the directory holds
        // only the marker file itself.
        let names: Vec<_> = std::fs::read_dir(dir.path())
            .unwrap()
            .map(|entry| entry.unwrap().file_name())
            .collect();
        assert_eq!(
            names,
            vec![std::ffi::OsString::from("service-config-path.txt")]
        );
    }

    /// Reads back a directory's DACL as an SDDL string. Uses the well-known
    /// 2-letter SID abbreviations (`SY`/`BA`/`LS`/...), so assertions on it are
    /// locale-independent (unlike `icacls`'s resolved account names).
    ///
    /// Returns `None` when the descriptor cannot be read because the account is
    /// denied access (`ERROR_ACCESS_DENIED`) — a non-elevated account that has just
    /// hardened a directory can be locked out of its own temp dir, so it can no
    /// longer read the DACL back. The caller then skips: the hardening succeeded
    /// (it locked us out), we just cannot verify the exact ACEs in this privilege
    /// context. `service install` always runs elevated, and CI has the privileges.
    fn read_dacl_sddl(dir: &Path) -> Option<String> {
        use std::os::windows::ffi::OsStrExt;
        use windows_sys::Win32::Foundation::LocalFree;
        use windows_sys::Win32::Security::Authorization::{
            ConvertSecurityDescriptorToStringSecurityDescriptorW, GetNamedSecurityInfoW,
            SDDL_REVISION_1, SE_FILE_OBJECT,
        };
        use windows_sys::Win32::Security::{DACL_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR};

        let path_w: Vec<u16> = dir
            .as_os_str()
            .encode_wide()
            .chain(std::iter::once(0))
            .collect();
        unsafe {
            let mut psd: PSECURITY_DESCRIPTOR = std::ptr::null_mut();
            let rc = GetNamedSecurityInfoW(
                path_w.as_ptr(),
                SE_FILE_OBJECT,
                DACL_SECURITY_INFORMATION,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                &mut psd,
            );
            // ERROR_ACCESS_DENIED (5): the just-applied DACL excluded this account,
            // so it can no longer read the descriptor. Signal a skip, not a failure.
            const ERROR_ACCESS_DENIED: u32 = 5;
            if rc == ERROR_ACCESS_DENIED {
                // `psd` is null on failure (nothing to free), but free it
                // defensively in case the API ever sets it on error —
                // `LocalFree(null)` is a no-op.
                LocalFree(psd);
                return None;
            }
            assert_eq!(rc, 0, "GetNamedSecurityInfoW failed (code {rc})");
            let mut sddl_ptr: *mut u16 = std::ptr::null_mut();
            let mut len = 0u32;
            let ok = ConvertSecurityDescriptorToStringSecurityDescriptorW(
                psd,
                SDDL_REVISION_1,
                DACL_SECURITY_INFORMATION,
                &mut sddl_ptr,
                &mut len,
            );
            assert_ne!(ok, 0, "converting the descriptor to SDDL failed");
            // `len` counts the terminating NUL; exclude it so the string has no
            // trailing `\0`.
            let chars = (len as usize).saturating_sub(1);
            let sddl = String::from_utf16_lossy(std::slice::from_raw_parts(sddl_ptr, chars));
            LocalFree(sddl_ptr.cast());
            LocalFree(psd);
            Some(sddl)
        }
    }

    /// Drops the protection and grants everyone, so the temp directory can be
    /// removed afterward whatever account runs the test (the owner can always
    /// rewrite the DACL).
    fn reset_dacl_for_cleanup(dir: &Path) {
        use std::os::windows::ffi::OsStrExt;
        use windows_sys::Win32::Security::Authorization::{SetNamedSecurityInfoW, SE_FILE_OBJECT};
        use windows_sys::Win32::Security::{
            DACL_SECURITY_INFORMATION, UNPROTECTED_DACL_SECURITY_INFORMATION,
        };
        let mut path_w: Vec<u16> = dir
            .as_os_str()
            .encode_wide()
            .chain(std::iter::once(0))
            .collect();
        let rc = unsafe {
            SetNamedSecurityInfoW(
                path_w.as_mut_ptr(),
                SE_FILE_OBJECT,
                DACL_SECURITY_INFORMATION | UNPROTECTED_DACL_SECURITY_INFORMATION,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(), // a NULL DACL grants full access to everyone
                std::ptr::null_mut(),
            )
        };
        // Best-effort: normally the owner can always rewrite the DACL, but an
        // account that hardening locked itself out of (a non-elevated account whose
        // owner became Administrators) cannot reset it. Warn rather than panic so
        // the lock-out path still skips cleanly; `tempfile` cleanup is best-effort
        // anyway and the OS reclaims the temp dir.
        if rc != 0 {
            eprintln!("note: could not reset the test DACL (code {rc}); temp dir may linger");
        }
    }

    /// A DACL test cannot run in this privilege context (it could not apply or read
    /// back the protected DACL). Skips by default so an ordinary developer machine
    /// stays green, but if `ALIGHIERI_REQUIRE_DACL_TESTS` is set — CI sets it on the
    /// Windows job — the skip becomes a hard failure, so a non-elevated runner
    /// cannot report green without ever verifying the hardened DACL.
    fn skip_dacl_test_or_panic(reason: &str) {
        if std::env::var_os("ALIGHIERI_REQUIRE_DACL_TESTS").is_some_and(|v| !v.is_empty()) {
            panic!("a DACL test would skip but ALIGHIERI_REQUIRE_DACL_TESTS is set: {reason}");
        }
        eprintln!("skipping DACL test: {reason}");
    }

    #[test]
    fn harden_directory_dacl_locks_out_standard_users() {
        let parent = tempfile::tempdir().unwrap();
        let dir = parent.path().join("svc-data");
        std::fs::create_dir(&dir).unwrap();

        // Applying the DACL needs privileges a non-elevated account may lack
        // (`service install` always runs elevated, as does CI). Treat an
        // access-denied here as a skip — like the symlink tests nearby — so the
        // suite stays green on an ordinary developer machine rather than failing
        // before the read-back skip below can even run.
        if let Err(e) = harden_directory_dacl(&dir) {
            if e.kind() == std::io::ErrorKind::PermissionDenied {
                skip_dacl_test_or_panic(&format!("this account cannot apply the DACL ({e})"));
                reset_dacl_for_cleanup(&dir);
                return;
            }
            panic!("hardening an owned directory must succeed: {e}");
        }
        let sddl = read_dacl_sddl(&dir);
        // Restore access immediately so the temp dir is always removable.
        reset_dacl_for_cleanup(&dir);
        let Some(sddl) = sddl else {
            skip_dacl_test_or_panic("the hardened DACL is not readable by this account");
            return;
        };

        // Protected (no inherited ACEs from ProgramData).
        assert!(sddl.starts_with("D:P"), "DACL must be protected: {sddl}");
        // The DACL is *exactly* three allow ACEs, one each for SYSTEM,
        // Administrators, and LocalService. Parsing the ACEs (not just the trustee
        // set) means a duplicate or deny ACE for an existing trustee — which would
        // leave the trustee set unchanged — is caught too, alongside any stray
        // principal. (Masks are not asserted: their read-back form varies, e.g. `FA`
        // may expand to a hex bitmask.)
        // Split on both delimiters so each ACE body is isolated and the trailing
        // `)` (and the read-back string's NUL artifact) lands in a `;`-less chunk
        // that the filter drops — robust to that junk, unlike trimming a lone `)`.
        let aces: Vec<&str> = sddl
            .split(['(', ')'])
            .filter(|chunk| chunk.contains(';'))
            .collect();
        assert_eq!(aces.len(), 3, "DACL must have exactly three ACEs: {sddl}");
        assert!(
            aces.iter().all(|ace| ace.starts_with("A;")),
            "every ACE must be an allow ACE, never a deny: {sddl}"
        );
        let trustees: std::collections::BTreeSet<&str> = aces
            .iter()
            .filter_map(|ace| ace.rsplit(';').next())
            .collect();
        assert_eq!(
            trustees,
            std::collections::BTreeSet::from(["SY", "BA", "LS"]),
            "DACL trustees must be exactly SYSTEM/Administrators/LocalService: {sddl}"
        );
    }

    #[test]
    fn create_secure_base_dir_is_born_protected() {
        // The base must be created already locked down, never passing through a
        // window with ProgramData's inherited (standard-user-writable) ACL.
        let parent = tempfile::tempdir().unwrap();
        let base = parent.path().join("born-secure");

        // Creating with the protected DACL needs privileges a non-elevated account
        // may lack; skip on access-denied (see the harden test above).
        if let Err(e) = create_secure_base_dir(&base) {
            if e.kind() == std::io::ErrorKind::PermissionDenied {
                skip_dacl_test_or_panic(&format!(
                    "this account cannot create the secured directory ({e})"
                ));
                return;
            }
            panic!("creating the secured base must succeed: {e}");
        }
        // Read the protected DACL back *before* resetting; that is what we assert
        // on. If this account is locked out of reading it (non-elevated), skip.
        let sddl = read_dacl_sddl(&base);
        // Restore access so the temp dir is removable — and so the directory checks
        // below run with full access rather than through the locked-down ACL.
        reset_dacl_for_cleanup(&base);
        let Some(sddl) = sddl else {
            skip_dacl_test_or_panic("the born-secure DACL is not readable by this account");
            return;
        };
        assert!(
            base.is_dir(),
            "the base directory must exist: {}",
            base.display()
        );
        // Idempotent: a second call over the existing directory is a no-op success.
        create_secure_base_dir(&base).expect("an existing base must be a no-op");

        assert!(
            sddl.starts_with("D:P"),
            "born-secure DACL must be protected: {sddl}"
        );
        let trustees: std::collections::BTreeSet<&str> = sddl
            .split(['(', ')'])
            .filter(|chunk| chunk.contains(';'))
            .filter_map(|ace| ace.rsplit(';').next())
            .collect();
        assert_eq!(
            trustees,
            std::collections::BTreeSet::from(["SY", "BA", "LS"]),
            "born-secure DACL trustees must be exactly SYSTEM/Administrators/LocalService: {sddl}"
        );
    }

    #[test]
    fn create_secure_base_dir_rejects_a_file_at_the_path() {
        // ERROR_ALREADY_EXISTS also fires for a regular file; that is not the benign
        // idempotent case and must be a clear error, not a silent success.
        let parent = tempfile::tempdir().unwrap();
        let base = parent.path().join("not-a-dir");
        std::fs::write(&base, b"x").unwrap();
        let err =
            create_secure_base_dir(&base).expect_err("a file at the base path must be rejected");
        assert_eq!(err.kind(), std::io::ErrorKind::AlreadyExists);
    }

    #[test]
    fn secure_existing_children_bounds_recursion_depth() {
        // At the depth cap the walk refuses rather than recursing further, so an
        // attacker-planted deep tree cannot overflow the installer's stack.
        let parent = tempfile::tempdir().unwrap();
        let dir = parent.path().join("d");
        std::fs::create_dir(&dir).unwrap();
        let err = secure_existing_children(&dir, MAX_RESECURE_DEPTH)
            .expect_err("hitting the depth cap must fail");
        assert_eq!(err.kind(), std::io::ErrorKind::Other);
    }

    #[test]
    fn harden_directory_dacl_refuses_a_symlinked_base() {
        // A standard user who plants a symlink/junction where the data directory
        // goes must not redirect the ACL change onto its target (TOCTOU). The
        // reparse-point-aware open + check refuses it instead.
        let parent = tempfile::tempdir().unwrap();
        let real = parent.path().join("real");
        std::fs::create_dir(&real).unwrap();
        let link = parent.path().join("link");
        // Creating a symlink needs privilege (Developer Mode / admin); skip if not.
        if std::os::windows::fs::symlink_dir(&real, &link).is_err() {
            eprintln!(
                "skipping harden_directory_dacl_refuses_a_symlinked_base: cannot create symlinks"
            );
            return;
        }
        let err = harden_directory_dacl(&link).expect_err("a symlinked base must be refused");
        assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
    }

    #[test]
    fn harden_directory_dacl_refuses_a_planted_reparse_child() {
        // A reparse point planted *inside* the data directory (before a re-install
        // hardens it) must abort the install, not be skipped: locking the parent
        // DACL leaves the link's target fixed, so a later privileged open under the
        // directory would still be redirected through it.
        let parent = tempfile::tempdir().unwrap();
        let base = parent.path().join("base");
        std::fs::create_dir(&base).unwrap();
        let target = parent.path().join("target");
        std::fs::create_dir(&target).unwrap();
        let link = base.join("evil");
        // Creating a symlink needs privilege (Developer Mode / admin); skip if not.
        if std::os::windows::fs::symlink_dir(&target, &link).is_err() {
            eprintln!(
                "skipping harden_directory_dacl_refuses_a_planted_reparse_child: cannot create \
                 symlinks"
            );
            return;
        }
        let err =
            harden_directory_dacl(&base).expect_err("a planted reparse child must be refused");
        // Restore base access so the temp dir is always removable (it was hardened
        // before the walk reached the child).
        reset_dacl_for_cleanup(&base);
        assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
        assert!(
            err.to_string().contains("evil"),
            "error should name the offending child: {err}"
        );
    }

    #[test]
    fn fail_if_reparse_point_rejects_a_symlink() {
        let parent = tempfile::tempdir().unwrap();
        let real = parent.path().join("real");
        std::fs::create_dir(&real).unwrap();
        // A regular directory and a not-yet-existing path are both allowed.
        fail_if_reparse_point(&real).expect("a regular directory is allowed");
        fail_if_reparse_point(&parent.path().join("missing")).expect("a missing path is allowed");
        // A symlink is rejected (skip where symlink creation needs privilege).
        let link = parent.path().join("link");
        if std::os::windows::fs::symlink_dir(&real, &link).is_err() {
            eprintln!("skipping fail_if_reparse_point_rejects_a_symlink: cannot create symlinks");
            return;
        }
        assert!(matches!(
            fail_if_reparse_point(&link),
            Err(ServiceCliError::Service(_))
        ));
    }
}