sysknife-daemon 0.26.0

Policy-enforced, audit-logged Linux action daemon for SysKnife
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
use crate::executor::ExecutorError;

// ---------------------------------------------------------------------------
// Field bounds
// ---------------------------------------------------------------------------
//
// Every validator below rejects over-long input. The bounds are named because
// most are not arbitrary: they come from a standard (DNS, TCP, email) or from
// the file format the value ends up in (/etc/fstab, sudoers, sysctl.d). A bare
// `> 253` in a hostname check reads as a guess; `MAX_DNS_NAME_LEN` says where
// the number is from, and stops the next validator inventing a different
// number for the same concept.

/// Longest local account name accepted. `useradd` enforces 32 on Linux.
const MAX_USERNAME_LEN: usize = 32;
/// Longest presentation-format DNS name (RFC 1035). Applies to hostnames and
/// to bare domains, which is why both validators share it.
const MAX_DNS_NAME_LEN: usize = 253;
/// Longest single DNS label between dots (RFC 1035).
const MAX_DNS_LABEL_LEN: usize = 63;
/// Highest TCP/UDP port number.
pub(crate) const MAX_PORT: u32 = 65_535;
/// Longest LVM volume/group name (LVM's own limit is 128 including NUL).
const MAX_LVM_NAME_LEN: usize = 127;
/// Longest LVM size expression, e.g. `20G`, `100%FREE`.
const MAX_LVM_SIZE_LEN: usize = 32;
/// Longest `journalctl --since/--until` expression.
const MAX_JOURNAL_TIME_LEN: usize = 64;
/// Longest `journalctl --grep` pattern.
const MAX_JOURNAL_GREP_LEN: usize = 256;
/// Longest sysctl key, e.g. `net.ipv4.tcp_syncookies`.
const MAX_SYSCTL_KEY_LEN: usize = 128;
/// Longest sysctl value.
const MAX_SYSCTL_VALUE_LEN: usize = 200;
/// Longest systemd memory/CPU limit expression, e.g. `500M`, `infinity`.
const MAX_MEMORY_LIMIT_LEN: usize = 24;
/// Longest `TasksMax` digit string — u64 needs 20, so 12 is already generous.
const MAX_TASKS_MAX_DIGITS: usize = 12;
/// Longest field written into an `/etc/fstab` line: device, mount point,
/// options, and swap file path all land there, so one bound governs them.
const MAX_FSTAB_FIELD_LEN: usize = 256;
/// Longest sudoers drop-in file name under `/etc/sudoers.d/`.
const MAX_SUDOERS_NAME_LEN: usize = 64;
/// Longest absolute path accepted for log and audit targets. `NAME_MAX` is 255
/// on ext4/xfs, used here as a whole-path bound.
const MAX_ABSOLUTE_PATH_LEN: usize = 255;
/// The only directory tree SysKnife will configure log rotation for. Must stay
/// in step with `LOG_ROOT` in `packaging/sysknife-log-edit`; the trailing slash
/// is load-bearing, as it is what stops `/var/logs` matching `/var/log`.
const LOG_ROOT: &str = "/var/log/";
/// Longest remote syslog host, which may be an address rather than a name.
const MAX_SYSLOG_HOST_LEN: usize = 255;
/// Longest Debian package name. Policy allows far less; this only stops abuse.
const MAX_APT_PACKAGE_LEN: usize = 128;
/// Longest apt pin expression, e.g. `version 1.24.*`, `release a=noble`.
const MAX_APT_PIN_EXPR_LEN: usize = 200;
/// Longest command list in a sudoers grant — several absolute paths.
const MAX_SUDO_COMMANDS_LEN: usize = 1024;
/// Longest email address (RFC 5321 path limit).
const MAX_EMAIL_LEN: usize = 254;
/// Shortest possible email address: `a@b`.
const MIN_EMAIL_LEN: usize = 3;

/// Validate a username: `[a-zA-Z0-9._-]`, 1-32 chars, must not start with `-`
/// or `.`, and must not contain `..`.
///
/// The leading-`-` guard blocks option injection; the leading-`.` and `..`
/// guards block path traversal, because usernames are interpolated directly
/// into `/home/<username>/...` filesystem paths (see `actions/ssh.rs`). Without
/// them a username of `..` yields `/home/../.ssh/authorized_keys` = `/.ssh/...`,
/// escaping the per-user home directory. `.` and `..` are also caught by the
/// leading-`.` check; the `..` substring guard additionally rejects `a..b`.
pub fn validated_username(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s.is_empty() || s.len() > MAX_USERNAME_LEN {
        return Err(ExecutorError::InvalidParam(param));
    }
    if s.starts_with('-') || s.starts_with('.') || s.contains("..") {
        return Err(ExecutorError::InvalidParam(param));
    }
    if !s
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-')
    {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Validate a group name: same rules as username.
pub fn validated_group(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    validated_username(s, param)
}

/// Local accounts that must never be deleted or locked via SysKnife's account
/// actions, even though they pass the generic username charset check: they
/// gate package management, cron, syslog, sudo, or (for `root`) the ability
/// to log in as anyone at all. This is enforced in addition to, not instead
/// of, the RBAC gate — an Admin-role caller must still not be able to lock
/// every account out of the box via a single `DeleteUser` or
/// `LockUserAccount` call. `root` is also the canonical uid-0 account;
/// SysKnife's account actions address accounts by name (there is no uid
/// parameter), so a differently-named uid-0 alias is out of scope for this
/// name-based denylist.
const CRITICAL_ACCOUNTS: &[&str] = &["root", "daemon", "bin", "sys", "sudo", "adm"];

/// Local groups that must never be deleted via `DeleteGroup`: `sudo`/`wheel`/
/// `adm` gate privilege escalation; `sys`/`daemon`/`bin`/`staff`/`disk` are
/// owned by core system tooling and file permissions; `shadow` gates access to
/// the shadow password database. Removing any of them can strip access from
/// every member or break core system tooling.
const CRITICAL_GROUPS: &[&str] = &[
    "root", "sudo", "wheel", "adm", "sys", "daemon", "bin", "staff", "shadow", "disk",
];

/// Validate a username for an irreversible or access-revoking account action
/// (`DeleteUser`, `LockUserAccount`): the generic [`validated_username`]
/// charset check, plus a hard denylist of critical system accounts. Mirrors
/// the `CRITICAL_MOUNTPOINTS` pattern below — a fixed denylist checked before
/// the command is ever built, independent of the RBAC gate.
pub fn validated_username_not_critical(
    s: &str,
    param: &'static str,
) -> Result<String, ExecutorError> {
    let s = validated_username(s, param)?;
    if CRITICAL_ACCOUNTS.contains(&s.as_str()) {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s)
}

/// Validate a group name for `DeleteGroup`: the generic [`validated_group`]
/// charset check, plus a hard denylist of critical system groups.
pub fn validated_group_not_critical(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    let s = validated_group(s, param)?;
    if CRITICAL_GROUPS.contains(&s.as_str()) {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s)
}

/// Validate a systemd unit name: must match `[a-zA-Z0-9@._:-]+` (no slashes, no
/// spaces), and must not start with `-`.
///
/// The leading-`-` guard prevents a unit name from being parsed as an option by
/// `systemctl` (option injection). This intentionally rejects the special
/// `-.mount` root-mount unit, which SysKnife's service actions never target.
pub fn validated_unit_name(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s.is_empty() || s.starts_with('-') {
        return Err(ExecutorError::InvalidParam(param));
    }
    if !s
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '@' | '.' | '_' | ':' | '-'))
    {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Units that hand out a root shell when activated. Matched case-insensitively
/// against the unit name with any `.service`/`.target` suffix stripped, so both
/// `debug-shell` and `debug-shell.service` are caught.
///
/// `debug-shell` is an unauthenticated root shell on tty9; `emergency` and
/// `rescue` drop to a root maintenance shell. Bringing any of them up is an
/// Admin-or-above act, but the generic service actions are Medium-risk (Dev), so
/// the name has to be refused rather than relying on the risk tier.
/// `runlevel1` is a stock systemd alias of `rescue.target` on both Debian and
/// Fedora, so it must be denied too or `StartService runlevel1.target` reaches
/// the same root maintenance shell. A name-based denylist cannot catch every
/// alias a site might add; the residual risk is documented in issue #144, and
/// the operator note there recommends masking these units outright.
///
/// **Shared with the kernel-argument screen.** `executor.rs` kept its own copy of
/// this idea for `systemd.unit=` boot arguments, and the two drifted: it had
/// `single` but was missing `debug-shell` and `runlevel1`, so
/// `StartService debug-shell.service` was refused while
/// `SetKernelArguments add=["systemd.unit=debug-shell.service"]` was accepted —
/// the worse of the two, since it persists across a reboot and hands out a root
/// shell before anyone logs in. One list now, so they cannot drift again.
///
/// `single` is not a real unit name, but it is accepted here so the shared list
/// is a superset of both original lists; refusing to activate a unit that does
/// not exist costs nothing.
pub(crate) const ROOT_SHELL_UNITS: &[&str] =
    &["debug-shell", "emergency", "rescue", "runlevel1", "single"];

/// Validate a unit name that an action will **activate** (start, restart, enable,
/// unmask), refusing units that would yield a root shell.
///
/// Layered on [`validated_unit_name`]: same syntax rules, plus the denylist. The
/// safe verbs (stop, mask, status, logs) keep using `validated_unit_name` — the
/// risk is in bringing a unit up, not in reading or stopping it.
pub fn validated_activatable_unit(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    let unit = validated_unit_name(s, param)?;
    if ROOT_SHELL_UNITS.contains(&bare_unit_name(&unit).as_str()) {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(unit)
}

/// The unit-type suffixes a name-based screen has to strip before it compares.
///
/// systemd unit names are case-insensitive and a unit can wear more than one
/// type, so a screen that only knows `.service` lets `rescue.socket` through by
/// spelling it differently.
const UNIT_TYPE_SUFFIXES: &[&str] = &[
    ".service", ".target", ".socket", ".mount", ".path", ".slice", ".scope",
];

/// Lowercase a unit name and strip its type suffix, so one denylist entry
/// matches every spelling of the same unit.
///
/// Both unit denylists below run through this rather than each carrying its own
/// copy of the suffix list. Two hand-copied screens of this shape drifted once
/// already: `executor.rs` kept a second kernel-argument denylist that was
/// missing `debug-shell`, so one path refused a root shell and the other
/// granted it. A suffix added to one copy and not the other is that bug again
/// in a new place.
fn bare_unit_name(unit: &str) -> String {
    let lower = unit.to_ascii_lowercase();
    let stripped = UNIT_TYPE_SUFFIXES
        .iter()
        .find_map(|suffix| lower.strip_suffix(suffix))
        .unwrap_or(&lower);
    // An instance carries its template name before the `@`, and systemd treats
    // the two as one unit for every purpose a denylist cares about. Without
    // this, `sshd@1.service` reduces to `sshd@1` and misses a list holding
    // `sshd`, which is an instance-shaped bypass of both screens below.
    match stripped.split_once('@') {
        Some((template, _)) => template.to_string(),
        None => stripped.to_string(),
    }
}

/// Units whose resource limits a Medium-risk caller must not set.
///
/// `SetServiceResourceLimits` is Medium, which `role_for_risk_level` maps to
/// `CallerRole::Dev`, and it validated its unit by charset alone. That let the
/// lowest mutating tier run `systemctl set-property sysknife-daemon.service
/// TasksMax=0`, which writes a persistent drop-in and stops the process that
/// enforces the tiers and signs the audit chain. The same call against `auditd`
/// or `systemd-journald` stops the host recording what happened next, and
/// against `sshd` it removes the way an operator would reach the box to undo
/// any of it.
///
/// `validated_activatable_unit` does not cover this. Its list is about units
/// that hand out a root shell when started, which is a different question from
/// "may this tier disable the security infrastructure". Setting a property is
/// not an activation, so that screen never ran.
///
/// Four categories, and nothing beyond them: SysKnife's own enforcement, the
/// host's evidence, the authorization path every privileged action crosses, and
/// remote administrative access. Throttling NetworkManager is bad, and it is the
/// ordinary blast radius of an action that exists to cap services; that stays a
/// Dev decision.
///
/// This is a name-based screen and it inherits the limit named in issue #144: a
/// site-local alias pointing at one of these units is spelled differently and
/// will not match. Masking the units an operator does not want touched is still
/// the stronger control.
pub(crate) const RESOURCE_LIMIT_PROTECTED_UNITS: &[&str] = &[
    // SysKnife's own enforcement and the process that signs the audit chain.
    "sysknife-daemon",
    // The host's record of what happened.
    "auditd",
    "systemd-journald",
    "rsyslog",
    // The authorization path every privileged action crosses.
    "dbus",
    "dbus-broker",
    "polkit",
    "polkitd",
    "systemd-logind",
    // The way an operator reaches the machine to undo the above. Debian ships
    // it as `ssh.service` and Fedora as `sshd.service`; both are listed because
    // the daemon does not know which distribution it is screening for here.
    "ssh",
    "sshd",
];

/// Unit-name prefixes whose whole family belongs to a protected category.
///
/// Naming the reader and leaving its pipes protects nothing.
/// `systemd-journald` ships as a service and as `systemd-journald.socket`,
/// `systemd-journald-audit.socket`, `systemd-journald-dev-log.socket` and
/// `systemd-journald-varlink@…​.socket`; the audit socket is how the kernel's
/// audit stream reaches the journal, and an exact-match list covering only
/// `systemd-journald` let every one of those through. `auditd` fans out the same
/// way through `audit-rules.service`.
///
/// These are prefixes rather than a longer exact list because the families grow
/// between systemd releases, and refusing a site's own
/// `systemd-journald-something` costs nothing next to missing the next stock
/// socket. Everything outside these two families is matched exactly, so
/// `sysknife-nightly-backup.service` stays cappable while `sysknife-daemon` does
/// not.
const RESOURCE_LIMIT_PROTECTED_PREFIXES: &[&str] = &["systemd-journald", "auditd", "audit-rules"];

/// Validate a unit name whose **resource limits** an action will set.
///
/// Layered on [`validated_unit_name`]: same syntax rules, plus a refusal of
/// [`RESOURCE_LIMIT_PROTECTED_UNITS`] and of every cgroup container.
///
/// Slices and scopes are refused as a class rather than by name. A slice holds
/// every unit beneath it, so capping `system.slice` is a decision about the
/// whole host and not about one service, and there is no list to keep current:
/// the caller has to spell the suffix, because `systemctl set-property system
/// MemoryMax=1` resolves to `system.service` rather than to the slice.
pub fn validated_resource_limit_unit(
    s: &str,
    param: &'static str,
) -> Result<String, ExecutorError> {
    let unit = validated_unit_name(s, param)?;
    let lower = unit.to_ascii_lowercase();
    if lower.ends_with(".slice") || lower.ends_with(".scope") {
        return Err(ExecutorError::InvalidParam(param));
    }
    let bare = bare_unit_name(&unit);
    if RESOURCE_LIMIT_PROTECTED_UNITS.contains(&bare.as_str())
        || RESOURCE_LIMIT_PROTECTED_PREFIXES
            .iter()
            .any(|family| bare.starts_with(family))
    {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(unit)
}

/// Validate a hostname per RFC 1123: `[a-zA-Z0-9.-]`, 1-253 chars, labels 1-63
/// chars, must not start with `-`.
///
/// A leading `-` is both invalid per RFC 1123 (labels start alphanumeric) and
/// an option-injection vector when interpolated into `hostnamectl set-hostname`.
pub fn validated_hostname(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s.is_empty() || s.len() > MAX_DNS_NAME_LEN || s.starts_with('-') {
        return Err(ExecutorError::InvalidParam(param));
    }
    if !s
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-')
    {
        return Err(ExecutorError::InvalidParam(param));
    }
    // Each label between dots must be 1-63 chars.
    for label in s.split('.') {
        if label.is_empty() || label.len() > MAX_DNS_LABEL_LEN {
            return Err(ExecutorError::InvalidParam(param));
        }
    }
    Ok(s.to_string())
}

/// Validate a timezone: `[a-zA-Z0-9/_+-]`, no `..`, must not start with `-`.
///
/// The leading-`-` guard prevents option injection into `timedatectl
/// set-timezone`; no IANA timezone name begins with `-`.
pub fn validated_timezone(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s.is_empty() || s.starts_with('-') {
        return Err(ExecutorError::InvalidParam(param));
    }
    if s.contains("..") {
        return Err(ExecutorError::InvalidParam(param));
    }
    if !s
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '_' | '+' | '-'))
    {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Validate a locale: `[a-zA-Z0-9._-]`, must not start with `-`.
///
/// The leading-`-` guard prevents option injection into `localectl set-locale`;
/// no locale identifier begins with `-`.
pub fn validated_locale(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s.is_empty() || s.starts_with('-') {
        return Err(ExecutorError::InvalidParam(param));
    }
    if !s
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-')
    {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Validate a PPA name in `<user>/<ppa>` format.
///
/// Both components must consist of `[a-zA-Z0-9._-]`, be non-empty, and be
/// separated by exactly one `/`.  The combined length must not exceed
/// [`SAFE_ARG_MAX_BYTES`] (checked after the format split to avoid
/// double-counting).
///
/// The validator runs before `ppa:<name>` is interpolated into the
/// `add-apt-repository` command string — any shell-special character in either
/// component would allow command injection.
pub fn validated_ppa_name(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    // Split on the first slash. A second slash inside `ppa` still enforces
    // "exactly one slash overall": the charset check below has no `/` in its
    // allowlist, so a `ppa` half that itself contains a slash is rejected
    // there instead of here — same outcome, no Vec needed to count pieces.
    let Some((user, ppa)) = s.split_once('/') else {
        return Err(ExecutorError::InvalidParam(param));
    };
    if user.is_empty() || ppa.is_empty() {
        return Err(ExecutorError::InvalidParam(param));
    }
    let is_valid_component = |c: char| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-');
    if !user.chars().all(is_valid_component) || !ppa.chars().all(is_valid_component) {
        return Err(ExecutorError::InvalidParam(param));
    }
    if s.len() > SAFE_ARG_MAX_BYTES {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Maximum byte length for an AppArmor profile name (no-slash form).
///
/// AppArmor profile names are short identifiers — the cap is intentionally
/// tight to prevent log-flooding and to match realistic profile name lengths
/// seen under `/etc/apparmor.d/`.
const APPARMOR_PROFILE_NAME_MAX: usize = 128;

/// Validate an AppArmor profile argument.
///
/// Accepts two forms:
///
/// - **Absolute path** — must start with `/etc/apparmor.d/`, must not contain
///   `..` anywhere, and the suffix after the prefix must consist only of
///   `[A-Za-z0-9._/-]`.
/// - **Profile name** (no `/`) — `[A-Za-z0-9._-]` only, no leading dot or dash,
///   length 1–[`APPARMOR_PROFILE_NAME_MAX`].
pub fn validated_apparmor_profile(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    const PREFIX: &str = "/etc/apparmor.d/";

    if s.is_empty() {
        return Err(ExecutorError::InvalidParam(param));
    }

    if s.starts_with('/') {
        // Absolute path form.
        if !s.starts_with(PREFIX) {
            return Err(ExecutorError::InvalidParam(param));
        }
        if s.contains("..") {
            return Err(ExecutorError::InvalidParam(param));
        }
        let suffix = &s[PREFIX.len()..];
        if suffix.is_empty() {
            return Err(ExecutorError::InvalidParam(param));
        }
        let ok = suffix
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '/'));
        if !ok {
            return Err(ExecutorError::InvalidParam(param));
        }
    } else {
        // Profile name form — no slash allowed.
        if s.contains('/') {
            return Err(ExecutorError::InvalidParam(param));
        }
        // Reject leading `.` (hidden-file form) and leading `-` (option
        // injection into `aa-complain` / `aa-enforce`).
        if s.starts_with('.') || s.starts_with('-') {
            return Err(ExecutorError::InvalidParam(param));
        }
        if s.len() > APPARMOR_PROFILE_NAME_MAX {
            return Err(ExecutorError::InvalidParam(param));
        }
        let ok = s
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'));
        if !ok {
            return Err(ExecutorError::InvalidParam(param));
        }
    }

    Ok(s.to_string())
}

/// Maximum byte length for a UFW app-profile name.
///
/// UFW app profile names are short identifiers defined in
/// `/etc/ufw/applications.d/`; 64 bytes is well above the longest real-world
/// name while still tight enough to prevent padding attacks.
const UFW_APP_NAME_MAX: usize = 64;

/// Validate a UFW port-or-service argument.
///
/// Accepts three forms:
///
/// - **Bare port** — `^\d+$` — integer 1–65535.
/// - **Port/protocol** — `^\d+/(tcp|udp)$` — same numeric range.
/// - **App profile name** — starts with a letter, then `[A-Za-z0-9_ -]*` (a
///   single interior space is allowed — real UFW profiles like `"Nginx
///   Full"`/`"Apache Full"` are two words), length 1–[`UFW_APP_NAME_MAX`],
///   must not end in a space. The value is passed as a single argv element
///   (never through a shell), so a space carries no injection risk; every
///   shell metacharacter and control character remains rejected by the
///   allowlist.
pub fn validated_port_or_service(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s.is_empty() {
        return Err(ExecutorError::InvalidParam(param));
    }

    // Port/protocol form: digits, a slash, then "tcp" or "udp" — nothing else.
    if let Some(slash_pos) = s.find('/') {
        let port_part = &s[..slash_pos];
        let proto_part = &s[slash_pos + 1..];
        if proto_part != "tcp" && proto_part != "udp" {
            return Err(ExecutorError::InvalidParam(param));
        }
        if port_part.is_empty() || !port_part.chars().all(|c| c.is_ascii_digit()) {
            return Err(ExecutorError::InvalidParam(param));
        }
        let port: u32 = port_part
            .parse()
            .map_err(|_| ExecutorError::InvalidParam(param))?;
        if port == 0 || port > MAX_PORT {
            return Err(ExecutorError::InvalidParam(param));
        }
        return Ok(s.to_string());
    }

    // Bare-port form: all digits.
    if s.chars().all(|c| c.is_ascii_digit()) {
        let port: u32 = s.parse().map_err(|_| ExecutorError::InvalidParam(param))?;
        if port == 0 || port > MAX_PORT {
            return Err(ExecutorError::InvalidParam(param));
        }
        return Ok(s.to_string());
    }

    // App profile name form: first char must be a letter. Internal spaces are
    // allowed (real UFW profiles like "Nginx Full"/"Apache Full" contain
    // them); a trailing space is rejected as almost certainly a copy-paste
    // artifact rather than an intentional profile name.
    if !s.starts_with(|c: char| c.is_ascii_alphabetic()) {
        return Err(ExecutorError::InvalidParam(param));
    }
    if s.len() > UFW_APP_NAME_MAX || s.ends_with(' ') {
        return Err(ExecutorError::InvalidParam(param));
    }
    let ok = s
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | ' '));
    if !ok {
        return Err(ExecutorError::InvalidParam(param));
    }

    Ok(s.to_string())
}

/// Maximum byte length for any string passed through [`validated_safe_arg`].
///
/// 254 bytes is one byte under the Linux per-argument limit imposed by the
/// kernel's argv parser when an argv element is processed via execve in
/// historically narrow buffers; it also stays well under typical filename,
/// app-id, and remote-name lengths in the action catalogue.  Lift this only
/// alongside a corresponding adjustment to whatever downstream consumer
/// drove the cap — the limit is intentionally tight, not a placeholder.
pub const SAFE_ARG_MAX_BYTES: usize = 254;

/// General safe-arg validator with strict allowlist `[A-Za-z0-9._:/+@-]`,
/// 1-[`SAFE_ARG_MAX_BYTES`] bytes, must not start with `-`.
///
/// This is the last line of defence against shell injection when arguments are
/// interpolated into command strings (e.g. `runuser -l user -c "<cmd>"`). The
/// allowlist deliberately excludes every shell metacharacter — quotes,
/// backticks, `$`, `;`, `&`, `|`, `>`, `<`, `\`, whitespace, control bytes,
/// and all non-ASCII. Callers that need richer character sets must use a
/// dedicated validator (e.g. `validated_hostname`, `validated_unit_name`).
pub fn validated_safe_arg(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s.is_empty() || s.len() > SAFE_ARG_MAX_BYTES {
        return Err(ExecutorError::InvalidParam(param));
    }
    if s.starts_with('-') {
        return Err(ExecutorError::InvalidParam(param));
    }
    if !s
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | ':' | '/' | '+' | '@' | '-'))
    {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Validate an LVM volume-group / logical-volume / snapshot name.
///
/// LVM permits `[a-zA-Z0-9+_.-]`; we additionally require the first character to
/// be alphanumeric or `_` (blocks the leading `-` option-injection vector and
/// the reserved `.`/`..` names), forbid `/` (the `vg/lv` separator is added by
/// the action, never by the caller), and cap the length at 127. Reserved bare
/// names `.` and `..` are rejected by the first-char rule.
pub fn validated_lvm_name(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s.is_empty() || s.len() > MAX_LVM_NAME_LEN {
        return Err(ExecutorError::InvalidParam(param));
    }
    let mut chars = s.chars();
    let first = chars.next().unwrap();
    if !(first.is_ascii_alphanumeric() || first == '_') {
        return Err(ExecutorError::InvalidParam(param));
    }
    if !s
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '_' | '.' | '-'))
    {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Validate an LVM size expression for `lvextend -L` / `lvcreate -L`.
///
/// Accepts an absolute size (`20G`, `512M`, `1.5T`) or an additive relative size
/// (`+10G`). The leading `+` is the only sign permitted: a leading `-` is both a
/// shrink (data-loss) and an option-injection vector, so it is rejected. The
/// unit suffix is one of `kKmMgGtTpP` (kibi..pebi) and is optional. Percent
/// forms (`+50%FREE`) are intentionally not accepted here — add a dedicated
/// extent-percent path if needed rather than widening this validator.
pub fn validated_lvm_size(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s.len() > MAX_LVM_SIZE_LEN {
        return Err(ExecutorError::InvalidParam(param));
    }
    let body = s.strip_prefix('+').unwrap_or(s);
    let (digits, suffix) = match body.chars().last() {
        Some(c) if c.is_ascii_alphabetic() => (&body[..body.len() - 1], Some(c)),
        _ => (body, None),
    };
    if let Some(c) = suffix {
        if !matches!(c, 'k' | 'K' | 'm' | 'M' | 'g' | 'G' | 't' | 'T' | 'p' | 'P') {
            return Err(ExecutorError::InvalidParam(param));
        }
    }
    // digits may carry a single decimal point (e.g. "1.5"); require at least one
    // digit and reject anything else.
    if digits.is_empty()
        || digits.matches('.').count() > 1
        || !digits.chars().all(|c| c.is_ascii_digit() || c == '.')
        || digits.starts_with('.')
        || digits.ends_with('.')
    {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Valid `journalctl --priority` levels, lowest (most severe) to highest.
const JOURNAL_PRIORITY_NAMES: &[&str] = &[
    "emerg", "alert", "crit", "err", "warning", "notice", "info", "debug",
];

/// Validate a `journalctl --priority` value: a single level (numeric `0`–`7` or
/// a name like `err`) or an inclusive range (`0..3`, `err..info`).
pub fn validated_journal_priority(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    let is_level = |lvl: &str| -> bool {
        matches!(lvl, "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7")
            || JOURNAL_PRIORITY_NAMES.contains(&lvl)
    };
    let ok = match s.split_once("..") {
        Some((lo, hi)) => is_level(lo) && is_level(hi),
        None => is_level(s),
    };
    if ok {
        Ok(s.to_string())
    } else {
        Err(ExecutorError::InvalidParam(param))
    }
}

/// Validate a `journalctl --since=` / `--until=` time expression.
///
/// journalctl accepts absolute (`2026-07-22 10:00:00`), keyword (`yesterday`,
/// `today`, `now`), and relative (`-1h`, `2 days ago`) forms. Because the value
/// is passed in attached `--since=<value>` form there is no option-injection
/// surface, and there is no shell, so we only enforce a printable-ASCII
/// allowlist (letters, digits, space, and `:-+.,`) and a length cap.
pub fn validated_journal_time(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s.is_empty() || s.len() > MAX_JOURNAL_TIME_LEN {
        return Err(ExecutorError::InvalidParam(param));
    }
    if !s
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | ':' | '-' | '+' | '.' | ','))
    {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Validate a `journalctl --grep=` regex pattern.
///
/// The pattern is handed to journalctl's own matcher (no shell), so any regex
/// metacharacter is inert. We only reject control characters (which have no
/// place in a single-line pattern) and cap the length.
pub fn validated_journal_grep(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s.is_empty() || s.len() > MAX_JOURNAL_GREP_LEN {
        return Err(ExecutorError::InvalidParam(param));
    }
    if s.chars().any(|c| c.is_control()) {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Validate a sysctl key in dotted form (`net.ipv4.ip_forward`, `vm.swappiness`).
///
/// First character must be alphanumeric (blocks the leading-dash
/// option-injection vector); the rest is `[a-z0-9._-]`. Slashes are rejected —
/// SysKnife always uses the dotted form, never `net/ipv4/...`. Length ≤ 128.
/// Mirrors `KEY_RE` in `packaging/sysknife-sysctl-edit`.
pub fn validated_sysctl_key(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s.is_empty() || s.len() > MAX_SYSCTL_KEY_LEN {
        return Err(ExecutorError::InvalidParam(param));
    }
    let first = s.chars().next().unwrap();
    if !first.is_ascii_lowercase() && !first.is_ascii_digit() {
        return Err(ExecutorError::InvalidParam(param));
    }
    if !s
        .chars()
        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '_' | '-'))
    {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Validate a sysctl value: printable, no control characters, from a
/// numeric/token/list allowlist (sysctl values are numbers or space-separated
/// lists such as `4096 87380 6291456`). Length 1..=200. Mirrors `VALUE_RE` in
/// `packaging/sysknife-sysctl-edit`.
pub fn validated_sysctl_value(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s.is_empty() || s.len() > MAX_SYSCTL_VALUE_LEN {
        return Err(ExecutorError::InvalidParam(param));
    }
    if !s
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | '.' | '_' | '/' | ':' | ',' | '-'))
    {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Validate a systemd memory limit (`MemoryMax` / `MemoryHigh`): a byte count
/// with an optional `K`/`M`/`G`/`T` suffix, or the literal `infinity`.
pub fn validated_memory_limit(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s == "infinity" {
        return Ok(s.to_string());
    }
    if s.len() > MAX_MEMORY_LIMIT_LEN {
        return Err(ExecutorError::InvalidParam(param));
    }
    let digits = match s.chars().last() {
        Some('K' | 'M' | 'G' | 'T') => &s[..s.len() - 1],
        _ => s,
    };
    if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Validate a systemd `CPUQuota`: `<n>%` where `n` is a positive integer (values
/// above 100% are legal — they mean more than one core's worth).
pub fn validated_cpu_quota(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    let digits = s
        .strip_suffix('%')
        .ok_or(ExecutorError::InvalidParam(param))?;
    if digits.is_empty() || digits.len() > 7 || !digits.chars().all(|c| c.is_ascii_digit()) {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Validate a systemd `TasksMax`: a positive integer or the literal `infinity`.
pub fn validated_tasks_max(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s == "infinity" {
        return Ok(s.to_string());
    }
    if s.is_empty() || s.len() > MAX_TASKS_MAX_DIGITS || !s.chars().all(|c| c.is_ascii_digit()) {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Filesystem types SysKnife will mount. Mirrors `FSTYPE_ALLOW` in
/// `packaging/sysknife-mount-edit`.
const FSTYPE_ALLOW: &[&str] = &[
    "ext4", "ext3", "ext2", "xfs", "btrfs", "vfat", "exfat", "ntfs3", "nfs", "nfs4", "cifs",
];

/// Mountpoints SysKnife must never touch (remounting them can break the box).
/// Mirrors `CRITICAL_MOUNTPOINTS` in the helper.
const CRITICAL_MOUNTPOINTS: &[&str] = &[
    "/",
    "/boot",
    "/boot/efi",
    "/etc",
    "/usr",
    "/bin",
    "/sbin",
    "/lib",
    "/lib64",
    "/var",
    "/home",
    "/root",
    "/proc",
    "/sys",
    "/dev",
    "/run",
];

/// Validate a mount source: a `/dev/…` node, `UUID=…`, `LABEL=…`, a cifs
/// `//host/share`, or an nfs `host:/export`. No leading dash / shell metachars.
pub fn validated_mount_device(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s.is_empty() || s.len() > MAX_FSTAB_FIELD_LEN || s.starts_with('-') || s.contains("..") {
        return Err(ExecutorError::InvalidParam(param));
    }
    let dev_like = s.starts_with("/dev/")
        && s[5..]
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '_' | '.' | '-'));
    let uuid = s
        .strip_prefix("UUID=")
        .is_some_and(|u| u.len() >= 8 && u.chars().all(|c| c.is_ascii_hexdigit() || c == '-'));
    let label = s.strip_prefix("LABEL=").is_some_and(|l| {
        !l.is_empty()
            && l.chars()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | ':' | '-'))
    });
    let cifs = s.starts_with("//")
        && s.matches('/').count() >= 3
        && s.chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '.' | '_' | '-'));
    let nfs = {
        match s.split_once(":/") {
            Some((host, _)) => {
                !host.is_empty()
                    && !host.starts_with('/')
                    && s.chars().all(|c| {
                        c.is_ascii_alphanumeric() || matches!(c, ':' | '/' | '.' | '_' | '-')
                    })
            }
            None => false,
        }
    };
    if dev_like || uuid || label || cifs || nfs {
        Ok(s.to_string())
    } else {
        Err(ExecutorError::InvalidParam(param))
    }
}

/// Shared charset/traversal check for a bare absolute filesystem path: must
/// start with `/`, must not contain `..`, and must consist only of
/// `[A-Za-z0-9/._-]`. `validated_mount_point`, `validated_swap_path`, and
/// `validated_audit_path` are this exact check with three different,
/// independently-documented length ceilings layered on top — factored out so
/// the charset itself (the security-relevant half) cannot drift between the
/// three call sites the way their length bounds are allowed to.
fn validated_absolute_path(
    s: &str,
    param: &'static str,
    max_len: usize,
) -> Result<String, ExecutorError> {
    if !s.starts_with('/') || s.len() > max_len || s.contains("..") {
        return Err(ExecutorError::InvalidParam(param));
    }
    if !s
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '_' | '.' | '-'))
    {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Validate a home directory: absolute, no `..`, safe charset.
///
/// `CreateUser` passes this to `useradd --create-home --home-dir <home>`, which
/// runs as root, so the caller names a path and root acts on it. It used to go
/// through [`validated_safe_arg`], which enforces a charset and rejects a
/// leading dash and accepts both a relative path and `..`. The stricter
/// validator was already in this file and already used by every other
/// root-acting path parameter; the weaker of the two was guarding the more
/// dangerous one.
pub fn validated_home_dir(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    validated_absolute_path(s, param, MAX_FSTAB_FIELD_LEN)
}

/// Validate a mountpoint: absolute, no `..`, safe charset, and not a critical
/// system mountpoint. Mirrors `valid_mountpoint` in the helper.
pub fn validated_mount_point(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    let s = validated_absolute_path(s, param, MAX_FSTAB_FIELD_LEN)?;
    if CRITICAL_MOUNTPOINTS.contains(&s.as_str()) {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s)
}

/// Validate a filesystem type against the mount allowlist.
pub fn validated_fstype(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if FSTYPE_ALLOW.contains(&s) {
        Ok(s.to_string())
    } else {
        Err(ExecutorError::InvalidParam(param))
    }
}

/// Validate a comma-separated mount options string (charset only; the helper
/// forces `nofail` in). Empty is allowed (helper defaults to `defaults`).
/// Mount options that hand out privilege, refused outright.
///
/// `suid` lets a setuid-root binary on the mounted filesystem escalate whoever
/// runs it; `dev` lets a device node on it reach any block device. Both are the
/// standard reason `nosuid,nodev` is the default for anything an administrator
/// did not author. `exec` is deliberately absent: running an ordinary binary
/// from a mounted volume is a legitimate need, and with `nosuid` and `nodev`
/// enforced it grants nothing extra.
const MOUNT_OPTIONS_DENY: &[&str] = &["suid", "dev"];

/// The options this mount will actually be made with.
///
/// `mount(8)` takes the last of a conflicting pair, so appending is enough and
/// the operator's own list is left intact ahead of it. Appending rather than
/// only refusing matters because omitting the parameter reaches the helper as
/// `defaults`, which Linux expands to `rw,suid,dev,exec,auto,nouser,async`: the
/// charset check saw an empty string and had nothing to object to, and the
/// mount still came up with `suid` and `dev` set.
///
/// `ensure_nofail` in `packaging/sysknife-mount-edit` is the same move for
/// `nofail`, which is where the shape comes from.
pub fn hardened_mount_options(requested: &str) -> String {
    let mut out: Vec<&str> = requested.split(',').filter(|o| !o.is_empty()).collect();
    for required in ["nosuid", "nodev"] {
        if !out.iter().any(|o| o.eq_ignore_ascii_case(required)) {
            out.push(required);
        }
    }
    out.join(",")
}

/// Validate a comma-separated mount option list: charset, length, and the two
/// options that grant privilege.
///
/// Every other dangerous-value validator in this file layers a denylist on top
/// of its charset check. This one did not, so `suid` and `dev` passed a
/// High-risk, Admin-only action whose ordinary phrasing is "mount my USB
/// drive".
pub fn validated_mount_options(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s.len() > MAX_FSTAB_FIELD_LEN {
        return Err(ExecutorError::InvalidParam(param));
    }
    if !s.chars().all(|c| {
        c.is_ascii_alphanumeric()
            || matches!(c, '=' | ',' | '.' | '_' | ':' | '@' | '/' | '+' | '-')
    }) {
        return Err(ExecutorError::InvalidParam(param));
    }
    // Refuse rather than silently strip. An operator who asked for `suid` has
    // to be told it was refused, or they will believe the mount carries it.
    if s.split(',').any(|opt| {
        MOUNT_OPTIONS_DENY
            .iter()
            .any(|deny| opt.eq_ignore_ascii_case(deny))
    }) {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(hardened_mount_options(s))
}

/// Validate an absolute file path for a swap file (no `..`, safe charset).
pub fn validated_swap_path(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    validated_absolute_path(s, param, MAX_FSTAB_FIELD_LEN)
}

/// Validate a SysKnife sudoers drop-in name: `^[a-z0-9][a-z0-9_-]{0,63}$`.
///
/// No dots or tildes: sudo SILENTLY ignores drop-in files whose names contain
/// them, which would make a "grant" quietly not apply. Mirrors `NAME_RE` in
/// `packaging/sysknife-sudoers-edit`. The file lands at
/// `/etc/sudoers.d/sysknife-grant-<name>`.
pub fn validated_sudoers_name(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s.is_empty() || s.len() > MAX_SUDOERS_NAME_LEN {
        return Err(ExecutorError::InvalidParam(param));
    }
    let first = s.chars().next().unwrap();
    if !(first.is_ascii_lowercase() || first.is_ascii_digit()) {
        return Err(ExecutorError::InvalidParam(param));
    }
    if !s
        .chars()
        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '-'))
    {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Validate an apt pin drop-in name: `^[a-z0-9][a-z0-9_-]{0,63}$` (no dots — apt
/// ignores preferences.d files with unexpected extensions). File lands at
/// `/etc/apt/preferences.d/sysknife-<name>`. Mirrors `NAME_RE` in the helper.
pub fn validated_apt_pin_name(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    validated_sudoers_name(s, param)
}

/// Validate a log path/glob for logrotate: under [`LOG_ROOT`], no `..`, charset
/// `[A-Za-z0-9/._*-]`, 1..=255. Mirrors `valid_log_glob` in
/// `packaging/sysknife-log-edit`.
///
/// The root confinement is the security-relevant half. The path becomes the
/// stanza header of a config that root's logrotate acts on, so accepting any
/// absolute path made `ConfigureLogRotation` — a Medium-risk, Dev-tier action —
/// a way to schedule root-level truncation, rename, or deletion of `/etc/shadow`
/// or `/boot/*`. A glob cannot be resolved with realpath, so confinement is by
/// literal prefix: `//var/log/x` and `/var/logs/x` both fail it.
pub fn validated_log_path(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if !s.starts_with(LOG_ROOT) || s.len() > MAX_ABSOLUTE_PATH_LEN || s.contains("..") {
        return Err(ExecutorError::InvalidParam(param));
    }
    if !s
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '.' | '_' | '*' | '-'))
    {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Validate a syslog collector host: a hostname or IPv4/IPv6 literal
/// (`[A-Za-z0-9.:_-]`, no `..`, 1..=255). Mirrors `HOST_RE` in the helper.
pub fn validated_syslog_host(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s.is_empty() || s.len() > MAX_SYSLOG_HOST_LEN || s.contains("..") || s.starts_with('-') {
        return Err(ExecutorError::InvalidParam(param));
    }
    if !s
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | ':' | '_' | '-'))
    {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Validate a package name used as an **install or remove target**, where a
/// filesystem path would make the package manager operate on a local file.
///
/// `apt-get install /tmp/x.deb` and `rpm-ostree install /tmp/x.rpm` both install
/// a caller-supplied file and run its maintainer scripts as root, so a Dev-role
/// caller who can drop a file would get root through a Medium-risk action. The
/// generic [`validated_safe_arg`] allows `/`, `.`, and a `.deb`/`.rpm` suffix,
/// which is exactly what makes a local file. This validator refuses all three:
///
/// - no `/` anywhere (blocks `/abs`, `./rel`, and apt's `pkg/suite` selector,
///   which is dropped deliberately for safety),
/// - no leading `-` (option injection) or `.` (relative path),
/// - no `.deb`/`.rpm` suffix (apt treats a bare `foo.deb` in the cwd as a file),
/// - no `*`/`?` (an install is never a glob),
/// - charset `[A-Za-z0-9+._:=~^-]`, which covers `name`, `name=version`,
///   `name:arch`, and rpm epoch/version punctuation.
pub fn validated_install_package(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    let first_ok = s.chars().next().is_some_and(|c| c.is_ascii_alphanumeric());
    let charset_ok = s.chars().all(|c| {
        c.is_ascii_alphanumeric() || matches!(c, '+' | '.' | '_' | ':' | '=' | '~' | '^' | '-')
    });
    if s.is_empty()
        || s.len() > MAX_APT_PACKAGE_LEN
        || !first_ok
        || !charset_ok
        || s.contains('/')
        || s.ends_with(".deb")
        || s.ends_with(".rpm")
    {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Validate an apt package-name glob (`[A-Za-z0-9.+*?_:-]`, 1..=128).
pub fn validated_apt_package(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    // A leading `-` would land in flag position when the value is passed as a
    // bare argument (`apt-cache policy <package>`), letting a package name act
    // as an option. Every sibling validator in this file rejects it; this one
    // was the sole exception.
    if s.is_empty()
        || s.starts_with('-')
        || s.len() > MAX_APT_PACKAGE_LEN
        || !s.chars().all(|c| {
            c.is_ascii_alphanumeric() || matches!(c, '.' | '+' | '*' | '?' | '_' | ':' | '-')
        })
    {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Validate an apt `Pin:` expression (e.g. `release a=noble-security`,
/// `version 1.2.*`). Charset only, no control characters, 1..=200. Mirrors
/// `PIN_RE` in the helper.
pub fn validated_apt_pin_expr(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s.is_empty()
        || s.len() > MAX_APT_PIN_EXPR_LEN
        || !s.chars().all(|c| {
            c.is_ascii_alphanumeric()
                || matches!(c, ' ' | '=' | '.' | ',' | ':' | '/' | '*' | '_' | '+' | '-')
        })
    {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Validate a sudoers command spec: the literal `ALL`, or a comma-separated
/// list of ABSOLUTE command paths with no wildcards, no `..`, and no shell
/// metacharacters. Mirrors `build_rule`/`CMD_RE` in the helper.
/// Command basenames that make a sudoers command list equivalent to `ALL`.
///
/// `packaging/sysknife-sudoers` opens by stating the invariant it keeps: no
/// shell or general runuser grant is permitted. `GrantSudoAccess` enforced that
/// against the string `"ALL"` and nothing else, while
/// [`validated_sudo_commands`] happily accepts `/bin/bash`, which is the same
/// capability spelled differently. `user ALL=(root) NOPASSWD: /bin/bash` is a
/// standing passwordless root shell, and `visudo -cf` accepts it.
///
/// Matched on the **basename**, lowercased. The charset check in
/// [`validated_sudo_commands`] already refuses `..` and wildcards, so
/// `/usr/bin/../bin/bash` cannot arrive, and a basename match covers both
/// `/bin/bash` and `/usr/bin/bash` on merged-`/usr` and split-`/usr` hosts
/// without the daemon having to know which it is running on.
///
/// **What this list is, and is not.** It covers programs that hand back an
/// interactive shell or run an arbitrary command directly. It deliberately does
/// not try to cover every root-equivalent primitive: `cp`, `dd` and `tee` give
/// arbitrary file write as root, which is just as severe and is a different
/// class, and chasing it turns this into an unbounded list that refuses grants
/// an operator has good reason to want. GTFOBins documents several hundred
/// techniques and no name-based list will hold all of them.
///
/// Two things carry the rest. The refusal below only fires together with
/// `nopasswd`, which is the same line `"ALL"` has always been held to: this
/// repository permits granting broad authority and does not permit granting it
/// as a standing passwordless credential. And the preview names the equivalence
/// whenever it sees one, with or without `nopasswd`, because at Admin tier the
/// control that matters is the human understanding what they are about to sign.
///
/// A copy of this list lives in `packaging/sysknife-sudoers-edit`, which is
/// callable directly through its wildcard `NOPASSWD` grant and so needs its own
/// screen. `tests/release/sudoers-edit.test.sh` parses this constant and fails
/// when the two disagree, because the last time two screens of this shape were
/// kept in step by a comment claiming parity, they drifted and one of them
/// granted a root shell the other refused (GHSA-f8vp-j3jh-7wjx).
pub(crate) const SHELL_EQUIVALENT_COMMANDS: &[&str] = &[
    // Shells.
    "sh",
    "bash",
    "rbash",
    "dash",
    "ash",
    "zsh",
    "ksh",
    "ksh93",
    "mksh",
    "csh",
    "tcsh",
    "fish",
    "busybox",
    "pwsh",
    "powershell",
    // Run-as and namespace tools: they carry a command, so the grant is
    // whatever they are asked to run.
    "su",
    "sudo",
    "sudoedit",
    "doas",
    "runuser",
    "pkexec",
    "setpriv",
    "chroot",
    "unshare",
    "nsenter",
    "capsh",
    // Interpreters. Each of these runs a program given on its command line.
    "python",
    "python2",
    "python3",
    "perl",
    "perl5",
    "ruby",
    "irb",
    "lua",
    "luac",
    "node",
    "nodejs",
    "php",
    "tclsh",
    "wish",
    "expect",
    "gdb",
    "julia",
    "guile",
    "rscript",
    "awk",
    "gawk",
    "mawk",
    "nawk",
    "sed",
    "ed",
    // Editors and pagers with a documented shell escape.
    "vi",
    "vim",
    "vimdiff",
    "view",
    "ex",
    "nvim",
    "emacs",
    "nano",
    "less",
    "more",
    "most",
    "man",
    "pg",
    "info",
    // Utilities that exist to run another program, or that document an escape.
    "env",
    "nice",
    "ionice",
    "taskset",
    "stdbuf",
    "setarch",
    "timeout",
    "watch",
    "flock",
    "xargs",
    "find",
    "script",
    "scriptreplay",
    "socat",
    "nc",
    "ncat",
    "netcat",
    "tar",
    "cpio",
    "zip",
    "unzip",
    "rsync",
    "scp",
    "sftp",
    "ftp",
    "ssh",
    "tmux",
    "screen",
    "byobu",
    "make",
    "cmake",
    "strace",
    "ltrace",
    "tcpdump",
    "docker",
    "podman",
    "git",
    "crontab",
    "at",
    "systemctl",
    "journalctl",
    "apt",
    "apt-get",
    "dpkg",
    "rpm",
    "yum",
    "dnf",
    "zypper",
    "pip",
    "pip3",
    "gem",
    "npm",
    "mount",
];

/// The first command in a validated sudoers list that makes it equivalent to
/// `ALL`, or `None` when every entry is narrower than that.
///
/// Takes the list as [`validated_sudo_commands`] returns it, so the charset and
/// absolute-path rules already hold. `"ALL"` answers `None`: it is not
/// shell-*equivalent*, it is the thing itself, and its own refusal predates
/// this one.
pub fn shell_equivalent_sudo_command(commands: &str) -> Option<String> {
    if commands == "ALL" {
        return None;
    }
    commands
        .split(',')
        .filter(|c| !c.is_empty())
        .find(|c| {
            let base = c.rsplit('/').next().unwrap_or(c).to_ascii_lowercase();
            SHELL_EQUIVALENT_COMMANDS.contains(&base.as_str())
        })
        .map(str::to_string)
}

pub fn validated_sudo_commands(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s == "ALL" {
        return Ok(s.to_string());
    }
    if s.is_empty() || s.len() > MAX_SUDO_COMMANDS_LEN {
        return Err(ExecutorError::InvalidParam(param));
    }
    // No Vec needed just to detect "zero non-empty commands" — track it
    // while validating each one instead of collecting first.
    let mut saw_command = false;
    for c in s.split(',').filter(|c| !c.is_empty()) {
        saw_command = true;
        if !c.starts_with('/')
            || c.contains("..")
            || c.contains('*')
            || !c
                .chars()
                .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '/' | '.' | '_' | '-'))
        {
            return Err(ExecutorError::InvalidParam(param));
        }
    }
    if !saw_command {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Validate an Ubuntu Pro service name against a fixed allowlist. Prevents both
/// option injection and typos reaching `pro enable/disable`. The list matches
/// the services `pro` recognises across supported releases.
pub fn validated_pro_service(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    const SERVICES: &[&str] = &[
        "esm-apps",
        "esm-infra",
        "livepatch",
        "usg",
        "fips",
        "fips-updates",
        "fips-preview",
        "cis",
        "ros",
        "ros-updates",
        "cc-eal",
        "realtime-kernel",
        "landscape",
        "anbox-cloud",
    ];
    if SERVICES.contains(&s) {
        Ok(s.to_string())
    } else {
        Err(ExecutorError::InvalidParam(param))
    }
}

/// Validate an auditd watch path: absolute, no `..`, charset `[A-Za-z0-9/._-]`
/// (no `*` — audit watches a concrete file/dir), 1..=255. Mirrors `PATH_RE` in
/// `packaging/sysknife-audit-edit`.
pub fn validated_audit_path(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    validated_absolute_path(s, param, MAX_ABSOLUTE_PATH_LEN)
}

/// Validate auditd watch permissions: a subset of `r`/`w`/`x`/`a`, 1..=4 chars,
/// no repeats. Mirrors `PERMS_RE` + the repeat check in the helper.
pub fn validated_audit_perms(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s.is_empty() || s.len() > 4 || !s.chars().all(|c| matches!(c, 'r' | 'w' | 'x' | 'a')) {
        return Err(ExecutorError::InvalidParam(param));
    }
    // no repeated flags
    let mut seen = [false; 4];
    for c in s.chars() {
        let i = match c {
            'r' => 0,
            'w' => 1,
            'x' => 2,
            _ => 3,
        };
        if seen[i] {
            return Err(ExecutorError::InvalidParam(param));
        }
        seen[i] = true;
    }
    Ok(s.to_string())
}

/// Validate a DNS domain for certbot: labels of `[A-Za-z0-9-]` joined by `.`,
/// no leading `-`/`.`, no `..`, total 1..=253. Blocks option/argument injection.
pub fn validated_domain(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s.is_empty()
        || s.len() > MAX_DNS_NAME_LEN
        || s.contains("..")
        || s.starts_with('-')
        || s.starts_with('.')
        || s.ends_with('.')
    {
        return Err(ExecutorError::InvalidParam(param));
    }
    if !s
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-'))
    {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

/// Validate an email address for certbot registration: exactly one `@`,
/// non-empty local + domain parts, conservative charset, 3..=254. Not a full
/// RFC 5322 parser — just enough to block injection and obvious garbage.
pub fn validated_email(s: &str, param: &'static str) -> Result<String, ExecutorError> {
    if s.len() < MIN_EMAIL_LEN || s.len() > MAX_EMAIL_LEN {
        return Err(ExecutorError::InvalidParam(param));
    }
    let parts: Vec<&str> = s.split('@').collect();
    if parts.len() != 2 || parts[0].is_empty() || parts[1].is_empty() || !parts[1].contains('.') {
        return Err(ExecutorError::InvalidParam(param));
    }
    if !s
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '@' | '.' | '_' | '+' | '-'))
    {
        return Err(ExecutorError::InvalidParam(param));
    }
    Ok(s.to_string())
}

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

    #[test]
    fn activatable_unit_rejects_root_shell_units() {
        // Starting or enabling these hands an unauthenticated root shell to
        // anyone at the console. A Dev-role caller must not be able to activate
        // them through the generic Medium-risk service actions.
        for evil in [
            "debug-shell.service",
            "debug-shell",
            "DEBUG-SHELL.SERVICE",
            "emergency.service",
            "emergency",
            "rescue.service",
            "rescue.target",
        ] {
            assert!(
                validated_activatable_unit(evil, "unit").is_err(),
                "{evil:?} must not be activatable"
            );
        }
    }

    #[test]
    fn activatable_unit_accepts_ordinary_services() {
        for ok in [
            "nginx.service",
            "sshd.service",
            "podman.socket",
            "my-app@1.service",
        ] {
            assert!(
                validated_activatable_unit(ok, "unit").is_ok(),
                "{ok:?} is an ordinary unit and must be activatable"
            );
        }
        // The denylist rides on top of the syntax check: garbage is still
        // rejected for the same reason `validated_unit_name` rejects it.
        assert!(validated_activatable_unit("-x.service", "unit").is_err());
    }

    #[test]
    fn resource_limit_unit_rejects_the_enforcement_and_evidence_path() {
        // `systemctl set-property <unit> TasksMax=0` is not an activation, so
        // the activatable denylist never saw it, and it is Medium-risk, so a
        // Dev-tier caller reaches it. Throttling any of these disables the
        // machinery that would have recorded or refused what came next.
        for protected in [
            "sysknife-daemon.service",
            "sysknife-daemon",
            "SYSKNIFE-DAEMON.SERVICE",
            "auditd.service",
            "systemd-journald.service",
            "systemd-journald.socket",
            "rsyslog.service",
            "polkit.service",
            "dbus.service",
            "dbus-broker.service",
            "systemd-logind.service",
            "sshd.service",
            "ssh.service",
            // Family members and instances. An exact-match list holding only
            // `systemd-journald` let the socket carrying the kernel audit
            // stream through, and `sshd@1.service` reduced to `sshd@1`.
            "systemd-journald-audit.socket",
            "systemd-journald-dev-log.socket",
            "systemd-journald-varlink@7.socket",
            "audit-rules.service",
            "sshd@1.service",
            "sysknife-daemon.socket",
            "dbus.socket",
        ] {
            assert!(
                validated_resource_limit_unit(protected, "unit").is_err(),
                "{protected:?} resource limits must not be settable at Dev tier"
            );
        }
    }

    #[test]
    fn resource_limit_unit_rejects_every_slice_and_scope() {
        // A slice holds every unit beneath it, so capping one is a decision
        // about the whole host rather than about one service. There is no
        // name list to keep current here: the caller has to spell the suffix,
        // because `systemctl set-property system MemoryMax=1` resolves to
        // `system.service`, not to the slice.
        for container in [
            "system.slice",
            "user.slice",
            "machine.slice",
            "user-1000.slice",
            "init.scope",
            "session-3.scope",
            "SYSTEM.SLICE",
        ] {
            assert!(
                validated_resource_limit_unit(container, "unit").is_err(),
                "{container:?} is a cgroup container, not one service"
            );
        }
    }

    #[test]
    fn resource_limit_unit_accepts_ordinary_services() {
        // The common case stays at Dev tier: capping a runaway application is
        // why this action is Medium-risk, and narrowing it further would push
        // routine work to Admin for no gain.
        for ok in [
            "nginx.service",
            "postgresql.service",
            "my-app@1.service",
            "podman.socket",
            "sysknife-nightly-backup.service",
        ] {
            assert!(
                validated_resource_limit_unit(ok, "unit").is_ok(),
                "{ok:?} is an ordinary unit and must stay cappable"
            );
        }
        // The denylist rides on top of the syntax check, as the activatable
        // screen does: malformed names are still refused for the old reason.
        assert!(validated_resource_limit_unit("-x.service", "unit").is_err());
        assert!(validated_resource_limit_unit("", "unit").is_err());
    }

    #[test]
    fn install_package_rejects_local_file_paths() {
        // A package name that installs a local file runs that file's maintainer
        // scripts as root. `apt-get install /tmp/x.deb` and
        // `rpm-ostree install /tmp/x.rpm` both do this, so a Dev-role caller who
        // can drop a file gets root. The generic safe-arg validator allowed `/`;
        // this one must not.
        for evil in [
            "/tmp/evil.deb",
            "./evil.deb",
            "../evil.rpm",
            "/home/attacker/x.rpm",
            "evil.deb", // apt treats a bare *.deb in cwd as a local file too
            "evil.rpm",
            "nginx/bookworm", // suite pinning uses `/`; dropped for safety
            "-oAPT::foo=bar", // option injection
            "pkg;rm -rf /",   // shell metacharacter, though args are not shelled
        ] {
            assert!(
                validated_install_package(evil, "package").is_err(),
                "{evil:?} must be rejected as an install target"
            );
        }
    }

    #[test]
    fn install_package_accepts_real_names() {
        for ok in [
            "nginx",
            "python3-pip",
            "lib32-glibc",
            "gcc-c++",
            "nginx=1.24.0-1",
            "nginx:amd64",
            "container-selinux",
            "2:openssl", // rpm epoch-ish
        ] {
            assert!(
                validated_install_package(ok, "package").is_ok(),
                "{ok:?} is a legitimate package spec and must be accepted"
            );
        }
    }

    #[test]
    fn audit_path_and_perms() {
        assert!(validated_audit_path("/etc/passwd", "p").is_ok());
        assert!(validated_audit_path("relative", "p").is_err());
        assert!(validated_audit_path("/etc/../shadow", "p").is_err());
        assert!(validated_audit_path("/var/log/*.log", "p").is_err()); // no glob
        assert!(validated_audit_perms("wa", "p").is_ok());
        assert!(validated_audit_perms("rwxa", "p").is_ok());
        assert!(validated_audit_perms("ww", "p").is_err()); // repeat
        assert!(validated_audit_perms("z", "p").is_err());
        assert!(validated_audit_perms("", "p").is_err());
    }

    #[test]
    fn domain_and_email() {
        assert!(validated_domain("example.com", "d").is_ok());
        assert!(validated_domain("a.b.example.co.uk", "d").is_ok());
        assert!(validated_domain("-bad.com", "d").is_err());
        assert!(validated_domain("a..b.com", "d").is_err());
        assert!(validated_domain("ex ample.com", "d").is_err());
        assert!(validated_email("ops@example.com", "e").is_ok());
        assert!(validated_email("no-at-sign", "e").is_err());
        assert!(validated_email("a@b", "e").is_err()); // domain needs a dot
        assert!(validated_email("a@b@c.com", "e").is_err());
    }

    #[test]
    fn pro_service_allowlist() {
        assert!(validated_pro_service("esm-apps", "service").is_ok());
        assert!(validated_pro_service("livepatch", "service").is_ok());
        assert!(validated_pro_service("realtime-kernel", "service").is_ok());
        // rejects unknown names and injection attempts
        assert!(validated_pro_service("bogus", "service").is_err());
        assert!(validated_pro_service("--help", "service").is_err());
        assert!(validated_pro_service("esm-apps; rm -rf /", "service").is_err());
        assert!(validated_pro_service("", "service").is_err());
    }

    // ── validated_username / validated_group ──────────────────────────────

    #[test]
    fn username_accepts_valid() {
        assert_eq!(
            validated_username("alice", "username").unwrap(),
            "alice".to_string()
        );
        assert_eq!(
            validated_username("bob_99", "username").unwrap(),
            "bob_99".to_string()
        );
        assert_eq!(
            validated_username("user.name", "username").unwrap(),
            "user.name".to_string()
        );
        assert_eq!(
            validated_username("a-b", "username").unwrap(),
            "a-b".to_string()
        );
    }

    #[test]
    fn username_rejects_empty() {
        assert!(validated_username("", "username").is_err());
    }

    #[test]
    fn username_rejects_starts_with_dash() {
        assert!(validated_username("-alice", "username").is_err());
    }

    #[test]
    fn username_rejects_traversal_forms() {
        // Path-traversal guard: usernames feed `/home/<username>/...` in ssh.rs.
        assert!(validated_username("..", "username").is_err());
        assert!(validated_username(".", "username").is_err());
        assert!(validated_username(".hidden", "username").is_err());
        assert!(validated_username("a..b", "username").is_err());
    }

    #[test]
    fn username_rejects_too_long() {
        let long = "a".repeat(33);
        assert!(validated_username(&long, "username").is_err());
    }

    #[test]
    fn username_accepts_max_length() {
        let max = "a".repeat(32);
        assert!(validated_username(&max, "username").is_ok());
    }

    #[test]
    fn username_rejects_spaces() {
        assert!(validated_username("al ice", "username").is_err());
    }

    #[test]
    fn username_rejects_slashes() {
        assert!(validated_username("al/ice", "username").is_err());
    }

    #[test]
    fn username_rejects_null_bytes() {
        assert!(validated_username("al\0ice", "username").is_err());
    }

    #[test]
    fn group_delegates_to_username_rules() {
        assert!(validated_group("wheel", "group").is_ok());
        assert!(validated_group("-bad", "group").is_err());
        assert!(validated_group("", "group").is_err());
    }

    // ── validated_username_not_critical / validated_group_not_critical ────

    #[test]
    fn username_not_critical_rejects_denylisted_accounts() {
        for name in CRITICAL_ACCOUNTS {
            assert!(
                validated_username_not_critical(name, "username").is_err(),
                "{name} must be rejected as a critical account"
            );
        }
    }

    #[test]
    fn username_not_critical_allows_normal_user() {
        assert_eq!(
            validated_username_not_critical("alice", "username").unwrap(),
            "alice".to_string()
        );
    }

    #[test]
    fn username_not_critical_still_enforces_charset() {
        // The denylist is layered on top of, not instead of, the charset check.
        assert!(validated_username_not_critical("-alice", "username").is_err());
        assert!(validated_username_not_critical("", "username").is_err());
    }

    #[test]
    fn group_not_critical_rejects_denylisted_groups() {
        for name in CRITICAL_GROUPS {
            assert!(
                validated_group_not_critical(name, "group").is_err(),
                "{name} must be rejected as a critical group"
            );
        }
    }

    #[test]
    fn group_not_critical_allows_normal_group() {
        assert_eq!(
            validated_group_not_critical("developers", "group").unwrap(),
            "developers".to_string()
        );
    }

    // ── validated_unit_name ──────────────────────────────────────────────

    #[test]
    fn unit_name_accepts_valid() {
        assert!(validated_unit_name("sshd.service", "unit").is_ok());
        assert!(validated_unit_name("NetworkManager.service", "unit").is_ok());
        assert!(validated_unit_name("user@1000.service", "unit").is_ok());
        assert!(validated_unit_name("dbus-org.freedesktop.resolve1.service", "unit").is_ok());
        assert!(validated_unit_name("system-getty.slice:0", "unit").is_ok());
    }

    #[test]
    fn unit_name_rejects_empty() {
        assert!(validated_unit_name("", "unit").is_err());
    }

    #[test]
    fn unit_name_rejects_leading_dash() {
        // Option-injection guard for `systemctl <verb> <unit>`.
        assert!(validated_unit_name("--version", "unit").is_err());
        assert!(validated_unit_name("-.mount", "unit").is_err());
    }

    #[test]
    fn unit_name_rejects_slashes() {
        assert!(validated_unit_name("foo/bar.service", "unit").is_err());
    }

    #[test]
    fn unit_name_rejects_spaces() {
        assert!(validated_unit_name("foo bar.service", "unit").is_err());
    }

    #[test]
    fn unit_name_rejects_null_bytes() {
        assert!(validated_unit_name("foo\0.service", "unit").is_err());
    }

    // ── validated_hostname ───────────────────────────────────────────────

    #[test]
    fn hostname_accepts_valid() {
        assert!(validated_hostname("sysknife-lab", "hostname").is_ok());
        assert!(validated_hostname("my.host.example", "hostname").is_ok());
        assert!(validated_hostname("a", "hostname").is_ok());
    }

    #[test]
    fn hostname_rejects_empty() {
        assert!(validated_hostname("", "hostname").is_err());
    }

    #[test]
    fn hostname_rejects_too_long() {
        let long = format!(
            "{}.{}",
            "a".repeat(63),
            "b".repeat(253 - 63 - 1 + 1) // total > 253
        );
        assert!(validated_hostname(&long, "hostname").is_err());
    }

    #[test]
    fn hostname_accepts_max_length() {
        // 4 labels of 63 chars separated by dots = 63*4+3 = 255, too long.
        // 3 labels of 63 chars separated by dots = 63*3+2 = 191, fine.
        let hostname = format!("{}.{}.{}", "a".repeat(63), "b".repeat(63), "c".repeat(63));
        assert!(validated_hostname(&hostname, "hostname").is_ok());
    }

    #[test]
    fn hostname_rejects_label_too_long() {
        let long_label = "a".repeat(64);
        assert!(validated_hostname(&long_label, "hostname").is_err());
    }

    #[test]
    fn hostname_rejects_empty_label() {
        assert!(validated_hostname("foo..bar", "hostname").is_err());
        assert!(validated_hostname(".foo", "hostname").is_err());
        assert!(validated_hostname("foo.", "hostname").is_err());
    }

    #[test]
    fn hostname_rejects_spaces() {
        assert!(validated_hostname("my host", "hostname").is_err());
    }

    #[test]
    fn hostname_rejects_underscores() {
        assert!(validated_hostname("my_host", "hostname").is_err());
    }

    #[test]
    fn hostname_rejects_leading_dash() {
        // Invalid per RFC 1123 and an option-injection vector for hostnamectl.
        assert!(validated_hostname("-host", "hostname").is_err());
    }

    // ── validated_timezone ───────────────────────────────────────────────

    #[test]
    fn timezone_accepts_valid() {
        assert!(validated_timezone("America/Mexico_City", "timezone").is_ok());
        assert!(validated_timezone("UTC", "timezone").is_ok());
        assert!(validated_timezone("Etc/GMT+5", "timezone").is_ok());
        assert!(validated_timezone("US/Eastern", "timezone").is_ok());
    }

    #[test]
    fn timezone_rejects_empty() {
        assert!(validated_timezone("", "timezone").is_err());
    }

    #[test]
    fn timezone_rejects_dot_dot() {
        assert!(validated_timezone("America/../etc/passwd", "timezone").is_err());
        assert!(validated_timezone("..", "timezone").is_err());
    }

    #[test]
    fn timezone_rejects_spaces() {
        assert!(validated_timezone("US/ Eastern", "timezone").is_err());
    }

    #[test]
    fn timezone_rejects_leading_dash() {
        assert!(validated_timezone("-America/Mexico_City", "timezone").is_err());
    }

    #[test]
    fn timezone_rejects_null_bytes() {
        assert!(validated_timezone("UTC\0", "timezone").is_err());
    }

    // ── validated_locale ─────────────────────────────────────────────────

    #[test]
    fn locale_accepts_valid() {
        assert!(validated_locale("en_US.UTF-8", "locale").is_ok());
        assert!(validated_locale("C", "locale").is_ok());
        assert!(validated_locale("POSIX", "locale").is_ok());
    }

    #[test]
    fn locale_rejects_empty() {
        assert!(validated_locale("", "locale").is_err());
    }

    #[test]
    fn locale_rejects_spaces() {
        assert!(validated_locale("en US.UTF-8", "locale").is_err());
    }

    #[test]
    fn locale_rejects_slashes() {
        assert!(validated_locale("en/US", "locale").is_err());
    }

    #[test]
    fn locale_rejects_leading_dash() {
        assert!(validated_locale("-en_US.UTF-8", "locale").is_err());
    }

    #[test]
    fn locale_rejects_null_bytes() {
        assert!(validated_locale("en\0US", "locale").is_err());
    }

    // ── validated_safe_arg ───────────────────────────────────────────────

    #[test]
    fn safe_arg_accepts_valid() {
        assert!(validated_safe_arg("org.mozilla.firefox", "app_id").is_ok());
        assert!(validated_safe_arg("flathub", "remote").is_ok());
        assert!(validated_safe_arg("my-container", "name").is_ok());
        assert!(validated_safe_arg("registry.example.com/image:tag", "image").is_ok());
    }

    #[test]
    fn safe_arg_rejects_empty() {
        assert!(validated_safe_arg("", "name").is_err());
    }

    #[test]
    fn safe_arg_rejects_null_bytes() {
        assert!(validated_safe_arg("hello\0world", "name").is_err());
    }

    #[test]
    fn safe_arg_rejects_starts_with_dash() {
        assert!(validated_safe_arg("-evil", "name").is_err());
        assert!(validated_safe_arg("--rm", "name").is_err());
    }

    #[test]
    fn safe_arg_accepts_dash_not_at_start() {
        assert!(validated_safe_arg("my-container", "name").is_ok());
    }

    #[test]
    fn safe_arg_rejects_unicode_and_non_ascii() {
        // Strict ASCII allowlist — non-ASCII (including printable Unicode) is rejected
        // because it can include homoglyphs / control codepoints that survive shell
        // interpolation in surprising ways.
        assert!(validated_safe_arg("café", "name").is_err());
        assert!(validated_safe_arg("über", "name").is_err());
    }

    #[test]
    fn safe_arg_rejects_every_shell_metacharacter() {
        // CVE-class regression: every one of these has been used to inject a
        // command into a `sh -c "<arg>"` style call somewhere in the wild.
        for meta in [
            "a b",   // space
            "a\tb",  // tab
            "a\nb",  // newline
            "a\rb",  // CR
            "a\0b",  // NUL
            "a;b",   // command separator
            "a&b",   // background / AND
            "a|b",   // pipe
            "a$b",   // var expansion
            "a`b`",  // command substitution
            "a$(b)", // command substitution
            "a>b",   // redirect
            "a<b",   // redirect
            "a\\b",  // backslash
            "a\"b",  // double quote
            "a'b",   // single quote
            "a*b",   // glob
            "a?b",   // glob
            "a[b]",  // glob
            "a{b}",  // brace expansion
            "a~b",   // tilde
            "a!b",   // history
            "a#b",   // comment
            "a%b",   // job control / printf
            "a^b",   // history quick-substitution (csh)
            "a=b",   // assignment in some contexts
            "a,b",   // brace expansion list
            "a(b)",  // subshell
        ] {
            assert!(
                validated_safe_arg(meta, "arg").is_err(),
                "should reject metacharacter sequence {meta:?}"
            );
        }
    }

    #[test]
    fn safe_arg_rejects_oversized_input() {
        let over = "a".repeat(SAFE_ARG_MAX_BYTES + 1);
        assert!(validated_safe_arg(&over, "name").is_err());
        let max = "a".repeat(SAFE_ARG_MAX_BYTES);
        assert!(validated_safe_arg(&max, "name").is_ok());
    }

    // ── validated_ppa_name ───────────────────────────────────────────────

    #[test]
    fn ppa_name_accepts_valid() {
        assert!(validated_ppa_name("deadsnakes/ppa", "name").is_ok());
        assert!(validated_ppa_name("user123/my-ppa", "name").is_ok());
        assert!(validated_ppa_name("team.name/repo_name", "name").is_ok());
    }

    #[test]
    fn ppa_name_rejects_no_slash() {
        assert!(validated_ppa_name("nodeownerppa", "name").is_err());
    }

    #[test]
    fn ppa_name_rejects_empty_user() {
        assert!(validated_ppa_name("/ppa", "name").is_err());
    }

    #[test]
    fn ppa_name_rejects_empty_ppa() {
        assert!(validated_ppa_name("user/", "name").is_err());
    }

    #[test]
    fn ppa_name_rejects_multiple_slashes() {
        assert!(validated_ppa_name("a/b/c", "name").is_err());
    }

    #[test]
    fn ppa_name_rejects_shell_metacharacters() {
        assert!(validated_ppa_name("user/ppa;evil", "name").is_err());
        assert!(validated_ppa_name("user$(cmd)/ppa", "name").is_err());
    }

    // ── validated_apparmor_profile ───────────────────────────────────────

    #[test]
    fn apparmor_profile_accepts_absolute_path() {
        assert!(
            validated_apparmor_profile("/etc/apparmor.d/usr.bin.firefox", "profile_path").is_ok()
        );
        assert!(
            validated_apparmor_profile("/etc/apparmor.d/abstractions/base", "profile_path").is_ok()
        );
    }

    #[test]
    fn apparmor_profile_accepts_profile_name() {
        assert!(validated_apparmor_profile("usr.bin.firefox", "profile_path").is_ok());
    }

    #[test]
    fn apparmor_profile_rejects_traversal_relative() {
        assert!(validated_apparmor_profile("../../../tmp/evil", "profile_path").is_err());
    }

    #[test]
    fn apparmor_profile_rejects_wrong_prefix() {
        assert!(validated_apparmor_profile("/etc/passwd", "profile_path").is_err());
    }

    #[test]
    fn apparmor_profile_rejects_traversal_in_path() {
        assert!(
            validated_apparmor_profile("/etc/apparmor.d/../../etc/passwd", "profile_path").is_err()
        );
    }

    #[test]
    fn apparmor_profile_rejects_relative_with_slash() {
        assert!(validated_apparmor_profile("evil/profile", "profile_path").is_err());
    }

    #[test]
    fn apparmor_profile_rejects_shell_metachars() {
        assert!(validated_apparmor_profile("; rm -rf /", "profile_path").is_err());
    }

    #[test]
    fn apparmor_profile_rejects_empty() {
        assert!(validated_apparmor_profile("", "profile_path").is_err());
    }

    #[test]
    fn apparmor_profile_rejects_too_long() {
        let long = "a".repeat(APPARMOR_PROFILE_NAME_MAX + 1);
        assert!(validated_apparmor_profile(&long, "profile_path").is_err());
    }

    // ── validated_port_or_service ─────────────────────────────────────────

    #[test]
    fn port_or_service_accepts_bare_ports() {
        assert!(validated_port_or_service("22", "port_or_service").is_ok());
        assert!(validated_port_or_service("1", "port_or_service").is_ok());
        assert!(validated_port_or_service("65535", "port_or_service").is_ok());
    }

    #[test]
    fn port_or_service_accepts_port_protocol() {
        assert!(validated_port_or_service("22/tcp", "port_or_service").is_ok());
        assert!(validated_port_or_service("53/udp", "port_or_service").is_ok());
        assert!(validated_port_or_service("8080/tcp", "port_or_service").is_ok());
    }

    #[test]
    fn port_or_service_accepts_app_profile_names() {
        assert!(validated_port_or_service("OpenSSH", "port_or_service").is_ok());
        assert!(validated_port_or_service("Apache", "port_or_service").is_ok());
        assert!(validated_port_or_service("Nginx-Full", "port_or_service").is_ok());
    }

    #[test]
    fn port_or_service_accepts_app_profile_names_with_internal_spaces() {
        // Real UFW application profiles from /etc/ufw/applications.d/ commonly
        // have two-word names; a leading-dash / bare-metachar guard is enough
        // to keep these safe since the value is a single argv element, never
        // interpolated through a shell.
        assert_eq!(
            validated_port_or_service("Nginx Full", "port_or_service").unwrap(),
            "Nginx Full".to_string()
        );
        assert!(validated_port_or_service("Apache Full", "port_or_service").is_ok());
    }

    #[test]
    fn port_or_service_rejects_out_of_range_ports() {
        assert!(validated_port_or_service("0", "port_or_service").is_err());
        assert!(validated_port_or_service("65536", "port_or_service").is_err());
        assert!(validated_port_or_service("99999", "port_or_service").is_err());
    }

    #[test]
    fn port_or_service_rejects_bad_protocol_forms() {
        assert!(validated_port_or_service("22/sctp", "port_or_service").is_err());
        assert!(validated_port_or_service("22/tcp/extra", "port_or_service").is_err());
        assert!(validated_port_or_service("22/", "port_or_service").is_err());
    }

    #[test]
    fn port_or_service_rejects_port_without_slash() {
        assert!(validated_port_or_service("22tcp", "port_or_service").is_err());
    }

    #[test]
    fn port_or_service_rejects_empty() {
        assert!(validated_port_or_service("", "port_or_service").is_err());
    }

    #[test]
    fn port_or_service_rejects_too_long_app_name() {
        let long = "A".repeat(UFW_APP_NAME_MAX + 1);
        assert!(validated_port_or_service(&long, "port_or_service").is_err());
    }

    #[test]
    fn port_or_service_rejects_shell_metachars() {
        assert!(validated_port_or_service("; rm -rf /", "port_or_service").is_err());
    }

    #[test]
    fn port_or_service_rejects_trailing_space_in_app_name() {
        // Internal spaces are allowed ("Nginx Full"), but a trailing space is
        // almost certainly a copy-paste artifact, not an intentional name.
        assert!(validated_port_or_service("Nginx Full ", "port_or_service").is_err());
    }

    #[test]
    fn port_or_service_rejects_metachar_with_space_in_app_name() {
        // Spaces are allowed, but every shell metacharacter is still rejected.
        assert!(validated_port_or_service("hello; rm -rf /", "port_or_service").is_err());
    }

    #[test]
    fn port_or_service_rejects_digit_leading_non_port() {
        // "2hello" is not all-digits (not a bare port) and starts with a digit
        // (not a valid app-name) — must be rejected.
        assert!(validated_port_or_service("2hello", "port_or_service").is_err());
    }

    // ── error variant check ──────────────────────────────────────────────

    #[test]
    fn validators_return_invalid_param_with_correct_field_name() {
        let err = validated_username("", "username").unwrap_err();
        assert!(matches!(err, ExecutorError::InvalidParam("username")));

        let err = validated_group("-bad", "group").unwrap_err();
        assert!(matches!(err, ExecutorError::InvalidParam("group")));

        let err = validated_unit_name("foo/bar", "unit").unwrap_err();
        assert!(matches!(err, ExecutorError::InvalidParam("unit")));

        let err = validated_hostname("", "hostname").unwrap_err();
        assert!(matches!(err, ExecutorError::InvalidParam("hostname")));

        let err = validated_timezone("..", "timezone").unwrap_err();
        assert!(matches!(err, ExecutorError::InvalidParam("timezone")));

        let err = validated_locale("", "locale").unwrap_err();
        assert!(matches!(err, ExecutorError::InvalidParam("locale")));

        let err = validated_safe_arg("-x", "name").unwrap_err();
        assert!(matches!(err, ExecutorError::InvalidParam("name")));
    }

    // ── LVM validators ────────────────────────────────────────────────────

    #[test]
    fn lvm_name_accepts_valid_and_rejects_injection() {
        assert!(validated_lvm_name("ubuntu-vg", "vg").is_ok());
        assert!(validated_lvm_name("root_lv.0", "lv").is_ok());
        assert!(validated_lvm_name("data+cache", "lv").is_ok());
        // leading dash → option injection
        assert!(validated_lvm_name("-rf", "lv").is_err());
        // reserved / traversal-ish
        assert!(validated_lvm_name(".", "lv").is_err());
        assert!(validated_lvm_name("..", "lv").is_err());
        // slash would forge a vg/lv reference
        assert!(validated_lvm_name("vg/lv", "lv").is_err());
        assert!(validated_lvm_name("", "lv").is_err());
    }

    #[test]
    fn lvm_size_accepts_absolute_relative_decimal() {
        assert!(validated_lvm_size("20G", "size").is_ok());
        assert!(validated_lvm_size("+10G", "size").is_ok());
        assert!(validated_lvm_size("512M", "size").is_ok());
        assert!(validated_lvm_size("1.5T", "size").is_ok());
        assert!(validated_lvm_size("4096", "size").is_ok()); // unit optional
    }

    #[test]
    fn lvm_size_rejects_shrink_and_junk() {
        assert!(validated_lvm_size("-10G", "size").is_err()); // shrink + injection
        assert!(validated_lvm_size("10X", "size").is_err()); // bad unit
        assert!(validated_lvm_size("G", "size").is_err()); // no digits
        assert!(validated_lvm_size("1.2.3G", "size").is_err()); // two dots
        assert!(validated_lvm_size("50%FREE", "size").is_err()); // percent not supported here
    }

    // ── journald validators ───────────────────────────────────────────────

    #[test]
    fn journal_priority_accepts_levels_and_ranges() {
        assert!(validated_journal_priority("err", "priority").is_ok());
        assert!(validated_journal_priority("3", "priority").is_ok());
        assert!(validated_journal_priority("0..3", "priority").is_ok());
        assert!(validated_journal_priority("err..info", "priority").is_ok());
        assert!(validated_journal_priority("8", "priority").is_err());
        assert!(validated_journal_priority("fatal", "priority").is_err());
        assert!(validated_journal_priority("err;info", "priority").is_err());
    }

    #[test]
    fn journal_time_allows_forms_and_rejects_control() {
        assert!(validated_journal_time("2026-07-22 10:00:00", "since").is_ok());
        assert!(validated_journal_time("yesterday", "since").is_ok());
        assert!(validated_journal_time("-1h", "since").is_ok());
        assert!(validated_journal_time("2 days ago", "since").is_ok());
        assert!(validated_journal_time("a\nb", "since").is_err());
        assert!(validated_journal_time("", "since").is_err());
    }

    #[test]
    fn journal_grep_rejects_control_chars() {
        assert!(validated_journal_grep("connection timed out", "grep").is_ok());
        assert!(validated_journal_grep("err.*fatal", "grep").is_ok());
        assert!(validated_journal_grep("bad\nline", "grep").is_err());
        assert!(validated_journal_grep("", "grep").is_err());
    }

    // ── sysctl validators ─────────────────────────────────────────────────

    #[test]
    fn sysctl_key_accepts_dotted_and_rejects_injection() {
        assert!(validated_sysctl_key("net.ipv4.ip_forward", "key").is_ok());
        assert!(validated_sysctl_key("vm.swappiness", "key").is_ok());
        assert!(validated_sysctl_key("kernel.kptr_restrict", "key").is_ok());
        assert!(validated_sysctl_key("-net.ipv4.ip_forward", "key").is_err()); // injection
        assert!(validated_sysctl_key("net/ipv4/ip_forward", "key").is_err()); // slash form
        assert!(validated_sysctl_key("Net.Ipv4", "key").is_err()); // uppercase
        assert!(validated_sysctl_key("", "key").is_err());
    }

    #[test]
    fn sysctl_value_accepts_numbers_and_lists() {
        assert!(validated_sysctl_value("1", "value").is_ok());
        assert!(validated_sysctl_value("4096 87380 6291456", "value").is_ok()); // multi-value
        assert!(validated_sysctl_value("kernel.core", "value").is_ok());
        assert!(validated_sysctl_value("bad\nvalue", "value").is_err());
        assert!(validated_sysctl_value("v$(id)", "value").is_err()); // shell metachar
        assert!(validated_sysctl_value("", "value").is_err());
    }

    // ── systemd resource-limit validators ─────────────────────────────────

    #[test]
    fn memory_limit_accepts_bytes_suffix_infinity() {
        assert!(validated_memory_limit("infinity", "m").is_ok());
        assert!(validated_memory_limit("500M", "m").is_ok());
        assert!(validated_memory_limit("2G", "m").is_ok());
        assert!(validated_memory_limit("1048576", "m").is_ok()); // bare bytes
        assert!(validated_memory_limit("500m", "m").is_err()); // lowercase suffix
        assert!(validated_memory_limit("500MB", "m").is_err()); // two-char suffix
        assert!(validated_memory_limit("-5M", "m").is_err());
        assert!(validated_memory_limit("", "m").is_err());
    }

    #[test]
    fn cpu_quota_requires_percent() {
        assert!(validated_cpu_quota("50%", "q").is_ok());
        assert!(validated_cpu_quota("200%", "q").is_ok()); // >100% = multi-core
        assert!(validated_cpu_quota("50", "q").is_err()); // no percent
        assert!(validated_cpu_quota("%", "q").is_err());
        assert!(validated_cpu_quota("5.5%", "q").is_err());
    }

    #[test]
    fn tasks_max_positive_int_or_infinity() {
        assert!(validated_tasks_max("4096", "t").is_ok());
        assert!(validated_tasks_max("infinity", "t").is_ok());
        assert!(validated_tasks_max("40.5", "t").is_err());
        assert!(validated_tasks_max("-1", "t").is_err());
        assert!(validated_tasks_max("", "t").is_err());
    }

    // ── mount / swap validators ───────────────────────────────────────────

    #[test]
    fn mount_device_accepts_forms_and_rejects_junk() {
        assert!(validated_mount_device("/dev/sdb1", "d").is_ok());
        assert!(validated_mount_device("UUID=1234abcd-5678", "d").is_ok());
        assert!(validated_mount_device("LABEL=data", "d").is_ok());
        assert!(validated_mount_device("//nas/share", "d").is_ok());
        assert!(validated_mount_device("nas.local:/export", "d").is_ok());
        assert!(validated_mount_device("-rf", "d").is_err()); // option injection
        assert!(validated_mount_device("/dev/../etc", "d").is_err()); // traversal
        assert!(validated_mount_device("$(id)", "d").is_err());
    }

    #[test]
    fn mount_point_rejects_critical_and_traversal() {
        assert!(validated_mount_point("/mnt/data", "m").is_ok());
        assert!(validated_mount_point("/srv/backups", "m").is_ok());
        assert!(validated_mount_point("/", "m").is_err()); // critical
        assert!(validated_mount_point("/boot", "m").is_err()); // critical
        assert!(validated_mount_point("/etc", "m").is_err()); // critical
        assert!(validated_mount_point("/mnt/../etc", "m").is_err()); // traversal
        assert!(validated_mount_point("relative", "m").is_err()); // not absolute
    }

    #[test]
    fn fstype_allowlist() {
        assert!(validated_fstype("ext4", "f").is_ok());
        assert!(validated_fstype("xfs", "f").is_ok());
        assert!(validated_fstype("nfs", "f").is_ok());
        assert!(validated_fstype("proc", "f").is_err());
        assert!(validated_fstype("", "f").is_err());
    }

    #[test]
    fn mount_options_and_swap_path() {
        // Every other dangerous-value validator in this file layers a denylist
        // on the charset check. This one did not, so `suid` and `dev` passed.
        // AddMount is High risk and Admin-only, but "mount my USB drive" is an
        // ordinary-sounding request: a setuid-root binary on attacker-supplied
        // media then grants root to whoever runs it, and a device node on it
        // reaches any block device.
        for bad in [
            "suid",
            "dev",
            "ro,suid",
            "suid,noatime",
            "nodev,dev",
            "DEV",
            "SUID",
        ] {
            assert!(
                validated_mount_options(bad, "o").is_err(),
                "mount options {bad:?} were accepted; suid and dev are the two that escalate"
            );
        }
        // The hardening must be added, not merely demanded, so an operator who
        // omits the parameter does not get `defaults` expanding to suid,dev.
        assert_eq!(
            hardened_mount_options(""),
            "nosuid,nodev",
            "an empty option list must still be hardened"
        );
        assert_eq!(
            hardened_mount_options("ro,noatime"),
            "ro,noatime,nosuid,nodev"
        );
        // Already hardened stays as it is rather than repeating itself.
        assert_eq!(hardened_mount_options("nosuid,nodev,ro"), "nosuid,nodev,ro");
        // `exec` is left alone on purpose: running a non-setuid binary from a
        // mounted volume is a legitimate admin need, and nosuid+nodev is what
        // removes the escalation.
        assert!(validated_mount_options("exec,ro", "o").is_ok());
        assert!(validated_mount_options("noatime,ro", "o").is_ok());
        assert!(validated_mount_options("", "o").is_ok()); // helper defaults it
        assert!(validated_mount_options("bad opt", "o").is_err()); // space
        assert!(validated_swap_path("/swapfile", "p").is_ok());
        assert!(validated_swap_path("/var/swap/sk.swap", "p").is_ok());
        assert!(validated_swap_path("swapfile", "p").is_err()); // not absolute
        assert!(validated_swap_path("/../etc/x", "p").is_err()); // traversal
    }

    // ── sudoers validators ────────────────────────────────────────────────

    #[test]
    fn sudoers_name_no_dots_or_tildes() {
        assert!(validated_sudoers_name("deploy-restart", "n").is_ok());
        assert!(validated_sudoers_name("ci_01", "n").is_ok());
        assert!(validated_sudoers_name("bad.name", "n").is_err()); // dot → sudo ignores file
        assert!(validated_sudoers_name("bad~", "n").is_err()); // tilde
        assert!(validated_sudoers_name("-lead", "n").is_err());
        assert!(validated_sudoers_name("", "n").is_err());
    }

    #[test]
    fn sudo_commands_all_or_abs_paths() {
        assert!(validated_sudo_commands("ALL", "c").is_ok());
        assert!(validated_sudo_commands("/usr/bin/systemctl", "c").is_ok());
        assert!(validated_sudo_commands("/usr/bin/systemctl,/usr/sbin/service", "c").is_ok());
        assert!(validated_sudo_commands("systemctl", "c").is_err()); // not absolute
        assert!(validated_sudo_commands("/usr/bin/*", "c").is_err()); // wildcard
        assert!(validated_sudo_commands("/usr/bin/../bin/sh", "c").is_err()); // traversal
        assert!(validated_sudo_commands("/bin/sh; rm -rf /", "c").is_err()); // metachars
    }

    // ── apt-pin validators ────────────────────────────────────────────────

    #[test]
    fn apt_pin_name_package_expr() {
        assert!(validated_apt_pin_name("hold-nginx", "n").is_ok());
        assert!(validated_apt_pin_name("bad.name", "n").is_err()); // dot
        assert!(validated_apt_package("nginx", "p").is_ok());
        assert!(validated_apt_package("libc6*", "p").is_ok()); // glob
        assert!(validated_apt_package("bad pkg", "p").is_err()); // space
        assert!(validated_apt_pin_expr("release a=noble-security", "e").is_ok());
        assert!(validated_apt_pin_expr("version 1.24.*", "e").is_ok());
        assert!(validated_apt_pin_expr("origin\nrepo", "e").is_err()); // newline
        assert!(validated_apt_pin_expr("", "e").is_err());
    }

    // ── logging validators ────────────────────────────────────────────────

    #[test]
    fn log_path_and_syslog_host() {
        assert!(validated_log_path("/var/log/nginx/*.log", "p").is_ok());
        assert!(validated_log_path("/var/log/app.log", "p").is_ok());
        assert!(validated_log_path("relative.log", "p").is_err());
        assert!(validated_log_path("/var/log/../etc/x", "p").is_err());
        assert!(validated_syslog_host("logs.example.com", "h").is_ok());
        assert!(validated_syslog_host("10.0.0.5", "h").is_ok());
        assert!(validated_syslog_host("fe80::1", "h").is_ok());
        assert!(validated_syslog_host("-bad", "h").is_err());
        assert!(validated_syslog_host("bad host", "h").is_err());
    }

    /// The rotation target ends up as the stanza header of a config that root's
    /// logrotate acts on, so anything outside the log root turns a Medium-risk
    /// action into scheduled root-level truncation of an arbitrary file. Mirrors
    /// `valid_log_glob` in `packaging/sysknife-log-edit`.
    #[test]
    fn log_path_is_confined_to_the_log_root() {
        for outside in [
            "/etc/shadow",
            "/etc/*",
            "/boot/*",
            "/root/.ssh/authorized_keys",
            "/usr/lib/sysknife/*",
            "/*",
            "/",
            "/var/lib/*",
            "/var/logs/x", // prefix of a prefix: must not pass a bare match
            "/var/log",    // the directory itself is not a rotation target
            "//var/log/x", // a doubled slash must not launder the prefix
        ] {
            assert!(
                validated_log_path(outside, "p").is_err(),
                "{outside} must not be accepted as a rotation target"
            );
        }
        for inside in [
            "/var/log/nginx/*.log",
            "/var/log/syslog",
            "/var/log/myapp/current.log",
        ] {
            assert!(
                validated_log_path(inside, "p").is_ok(),
                "{inside} is a legitimate log glob"
            );
        }
    }
}