draupnir 0.1.9

Draupnir — the nordisk boot/provisioning library: fire up a runtime from one BootSpec across three backends (KVM via tunnr · OCI container · Redfish bare-metal virtual-media) and drive its power lifecycle. Odin's ring that drips eight identical copies → boot a fleet of identical machines from one ISO.
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
//! **Draupnir's own BMC** — a pure-Rust **Redfish server** that fronts KVM.
//!
//! `src/redfish.rs` is the Redfish **client**: it drives a real iDRAC / iLO /
//! OpenBMC. This is the other end — a Redfish **service** that answers the same
//! endpoints and, instead of a baseboard controller wired to a motherboard, drives
//! a QEMU/KVM guest through draupnir's own [`Boot`] / [`Lifecycle`] seam.
//!
//! # Why it exists
//!
//! Two reasons, and the second is the durable one.
//!
//! 1. A Redfish burn needs a **BMC**: the always-on management controller a real
//!    server has and a developer box does not. Without one the `iso-metal` proof is
//!    a human with a USB stick, which is not a matrix row. This gives the wire half
//!    of that proof a service to run against.
//! 2. A Rust Redfish server fronting KVM turns **any Linux box into a
//!    Redfish-controllable machine**. That is squarely this crate's charter (kvm and
//!    container, low level), and it is useful far outside a test harness: a lab, a
//!    CI fleet, a nested-virt pool can all be addressed with the same out-of-band
//!    vocabulary as the metal they stand in for.
//!
//! # What it does NOT prove — read this before believing a green
//!
//! **An emulator proves the wire, never the hardware.** draupnir's client talking to
//! draupnir's server is a mirror: both ends can be wrong in the same way and every
//! round trip still passes. A loopback green on its own is evidence of
//! self-consistency and of nothing else.
//!
//! Two things are done about that, and neither is optional:
//!
//! * **The shapes are anchored outside this repo.** `tests/redfish_server_conformance.rs`
//!   checks every response against **DMTF's own published JSON Schema, message
//!   registry and mockup** (vendored under `tests/fixtures/dmtf/`, provenance and
//!   hashes in `PROVENANCE.md`). Required properties, `@odata.type` versions,
//!   `@Redfish.AllowableValues` subsets and the `error` payload are all read out of
//!   DMTF's files, not out of ours.
//! * **The result is recorded as `iso-redfish-sim`, never `iso-metal`.** Recording an
//!   emulator's green in the cell a real-hardware green would occupy is exactly the
//!   false green the form split exists to prevent. `iso-metal` stays Absent.
//!
//! # The translation
//!
//! Every Redfish verb lands on vocabulary this crate already had — nothing new was
//! invented for the server side:
//!
//! | Redfish | draupnir |
//! |---|---|
//! | `VirtualMedia.InsertMedia` | [`BootSpec::medium`] |
//! | `Boot.BootSourceOverrideTarget` | [`BootOrder`] (via [`BootOrder::from_redfish_target`]) |
//! | `ComputerSystem.Reset` | [`Boot::boot`] / [`Lifecycle::power_off`] |
//! | `ComputerSystem.PowerState` | [`Lifecycle::status`] |
//!
//! and the URLs, property names and enum tokens come from [`crate::redfish::wire`],
//! the **one** module both ends read. The client composes `host + path()`; the
//! server routes on `path()`. They agree by construction.
//!
//! # Security posture
//!
//! draupnir's client **pins** the BMC certificate, so this server needs a real TLS
//! identity to be pinned. It mints a genuine self-signed X.509 with SANs per run
//! (`rcgen` over `ring` — the same crate, features and call shape as Skidbladnir's
//! `pki::issue_leaf`) and holds the key **in memory only**: nothing is written to
//! disk, so there is no `.key`/`.pem`/`.der` that could be committed. The cert PEM is
//! handed out through [`RedfishKvmServer::cert_pem`] for the client to pin.
//!
//! Everything except the protocol-version probe and the service root requires HTTP
//! Basic auth, which is what DSP0266 permits an unauthenticated client to reach.
//!
//! # Example
//!
//! ```no_run
//! use draupnir::redfish_server::{NodeConfig, RedfishKvmServer};
//! use draupnir::redfish::RedfishBoot;
//! use draupnir::{Boot, BootSpec};
//!
//! // A BMC in front of this box's KVM.
//! let server = RedfishKvmServer::start(
//!     NodeConfig::new("System.Embedded.1")
//!         .credentials("admin", "secret")
//!         .local_disk("/var/lib/node.qcow2"),
//! )?;
//!
//! // ...driven by draupnir's ordinary Redfish CLIENT, cert pinned.
//! let backend = RedfishBoot::new()
//!     .with_password("secret")
//!     .pin_cert_pem(server.cert_pem().as_bytes().to_vec());
//! let spec = BootSpec::iso_boot("burn", "/images/appliance.iso")
//!     .on_metal(server.bmc_endpoint());
//! let machine = backend.boot(&spec)?;
//! # Ok::<(), draupnir::Error>(())
//! ```

use std::collections::BTreeMap;
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use serde_json::{json, Value};

use crate::kvm::KvmBoot;
use crate::redfish::wire::{self, prop};
use crate::{
    BmcEndpoint, Boot, BootOrder, BootSpec, BootTarget, Error, Lifecycle, Machine, PowerState,
    Result, Seen,
};

// ===========================================================================
// DMTF message registry — the error vocabulary, transcribed and then CHECKED
// ===========================================================================

/// The DMTF **Base** message registry this service reports `MessageId`s from.
///
/// Every `MessageId` it emits is `{BASE_REGISTRY}.{Id}`, and every message body is
/// the registry's own template with `MessageArgs` substituted. The conformance test
/// loads `tests/fixtures/dmtf/registries/Base.1.19.0.json` and asserts that each
/// [`Message`] below matches the registry's `Message`, `MessageSeverity`,
/// `NumberOfArgs` and `Resolution` **exactly** — so a hand-typed error string that
/// merely *sounds* like Redfish cannot survive here.
pub const BASE_REGISTRY: &str = "Base.1.19.0";

/// One entry of the DMTF Base registry, as this service reports it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Message {
    /// The registry entry's `Id` (the part after the registry name in a `MessageId`).
    pub id: &'static str,
    /// The registry's `Message` template, with `%1`..`%N` placeholders.
    pub template: &'static str,
    /// The registry's `MessageSeverity`.
    pub severity: &'static str,
    /// The registry's `Resolution`.
    pub resolution: &'static str,
    /// The registry's `NumberOfArgs`.
    pub nargs: usize,
    /// The HTTP status this service answers with when it reports this message.
    pub status: u16,
}

impl Message {
    /// The full `MessageId`, e.g. `Base.1.19.0.ActionParameterValueNotInList`.
    pub fn message_id(&self) -> String {
        format!("{BASE_REGISTRY}.{}", self.id)
    }

    /// Render the registry template with `args` substituted for `%1`..`%N`.
    ///
    /// A wrong arity is a **programming** error in this crate, not a client error, so
    /// it is caught by a debug assertion and then rendered honestly (the unfilled
    /// placeholder stays visible) rather than papered over.
    pub fn render(&self, args: &[&str]) -> String {
        debug_assert_eq!(
            args.len(),
            self.nargs,
            "{} takes {} args, got {}",
            self.id,
            self.nargs,
            args.len()
        );
        let mut out = self.template.to_string();
        // Descending index, so `%10` (were the registry ever to grow one) is not
        // eaten by `%1`.
        for (i, a) in args.iter().enumerate().rev() {
            out = out.replace(&format!("%{}", i + 1), a);
        }
        out
    }
}

/// `The value '%1' for the parameter %2 in the action %3 is not in the list of
/// acceptable values.` — a bad `ResetType`.
pub const ACTION_PARAMETER_VALUE_NOT_IN_LIST: Message = Message {
    id: "ActionParameterValueNotInList",
    template: "The value '%1' for the parameter %2 in the action %3 is not in the list of acceptable values.",
    severity: "Warning",
    resolution: "Choose a value from the enumeration list that the implementation can support and resubmit the request if the operation failed.",
    nargs: 3,
    status: 400,
};

/// `The action %1 requires the parameter %2 to be present in the request body.`
pub const ACTION_PARAMETER_MISSING: Message = Message {
    id: "ActionParameterMissing",
    template: "The action %1 requires the parameter %2 to be present in the request body.",
    severity: "Critical",
    resolution: "Supply the action with the required parameter in the request body when the request is resubmitted.",
    nargs: 2,
    status: 400,
};

/// `The value '%1' for the property %2 is not in the list of acceptable values.` —
/// a `BootSourceOverrideTarget` this node cannot honour.
pub const PROPERTY_VALUE_NOT_IN_LIST: Message = Message {
    id: "PropertyValueNotInList",
    template: "The value '%1' for the property %2 is not in the list of acceptable values.",
    severity: "Warning",
    resolution: "Choose a value from the enumeration list that the implementation can support and resubmit the request if the operation failed.",
    nargs: 2,
    status: 400,
};

/// `The resource at the URI '%1' was not found.` — an `InsertMedia` pointing at an
/// image that is not there. THE red control: a media URI nobody built must be
/// refused **by name**, not mounted as an empty tray.
pub const RESOURCE_MISSING_AT_URI: Message = Message {
    id: "ResourceMissingAtURI",
    template: "The resource at the URI '%1' was not found.",
    severity: "Critical",
    resolution: "Place a valid resource at the URI or correct the URI and resubmit the request.",
    nargs: 1,
    status: 400,
};

/// `The requested resource of type %1 named '%2' was not found.`
pub const RESOURCE_NOT_FOUND: Message = Message {
    id: "ResourceNotFound",
    template: "The requested resource of type %1 named '%2' was not found.",
    severity: "Critical",
    resolution: "Provide a valid resource identifier and resubmit the request.",
    nargs: 2,
    status: 404,
};

/// `There is no valid session established with the implementation.` — no (or bad)
/// credentials.
pub const NO_VALID_SESSION: Message = Message {
    id: "NoValidSession",
    template: "There is no valid session established with the implementation.",
    severity: "Critical",
    resolution: "Establish a session before attempting any operations.",
    nargs: 0,
    status: 401,
};

/// `The action %1 is not supported by the resource.`
pub const ACTION_NOT_SUPPORTED: Message = Message {
    id: "ActionNotSupported",
    template: "The action %1 is not supported by the resource.",
    severity: "Critical",
    resolution: "Check the Actions property in the resource for the supported actions.",
    nargs: 1,
    status: 400,
};

/// `The request body submitted was malformed JSON and could not be parsed by the
/// receiving service.`
pub const MALFORMED_JSON: Message = Message {
    id: "MalformedJSON",
    template: "The request body submitted was malformed JSON and could not be parsed by the receiving service.",
    severity: "Critical",
    resolution: "Ensure that the request body is valid JSON and resubmit the request.",
    nargs: 0,
    status: 400,
};

/// `A general error has occurred.  See Resolution for information on how to resolve
/// the error, or @Message.ExtendedInfo if Resolution is not provided.` — the
/// catch-all for a backend that refused (QEMU would not start, no medium inserted,
/// no local disk configured). The **detail always names what happened**, in the
/// `Resolution`-shaped second sentence of the extended info.
pub const GENERAL_ERROR: Message = Message {
    id: "GeneralError",
    template: "A general error has occurred.  See Resolution for information on how to resolve the error, or @Message.ExtendedInfo if Resolution is not provided.",
    severity: "Critical",
    resolution: "None.",
    nargs: 0,
    status: 500,
};

/// Every message this service can emit — the list the conformance test walks when it
/// checks each one against DMTF's registry. A new message added below and forgotten
/// here is a message nothing checks, so this array is the gate.
pub const ALL_MESSAGES: &[Message] = &[
    ACTION_PARAMETER_VALUE_NOT_IN_LIST,
    ACTION_PARAMETER_MISSING,
    PROPERTY_VALUE_NOT_IN_LIST,
    RESOURCE_MISSING_AT_URI,
    RESOURCE_NOT_FOUND,
    NO_VALID_SESSION,
    ACTION_NOT_SUPPORTED,
    MALFORMED_JSON,
    GENERAL_ERROR,
];

/// The `@odata.type` values this service reports, one per resource. Pinned as
/// constants because the conformance test resolves each against the matching DMTF
/// schema file and fails if the named version does not define the named type.
mod odata_type {
    /// `ServiceRoot`.
    pub const SERVICE_ROOT: &str = "#ServiceRoot.v1_16_1.ServiceRoot";
    /// `ComputerSystemCollection` (collections are unversioned).
    pub const SYSTEM_COLLECTION: &str = "#ComputerSystemCollection.ComputerSystemCollection";
    /// `ComputerSystem`.
    pub const SYSTEM: &str = "#ComputerSystem.v1_22_0.ComputerSystem";
    /// `VirtualMediaCollection` (unversioned).
    pub const VIRTUAL_MEDIA_COLLECTION: &str = "#VirtualMediaCollection.VirtualMediaCollection";
    /// `VirtualMedia`.
    pub const VIRTUAL_MEDIA: &str = "#VirtualMedia.v1_6_3.VirtualMedia";
    /// `SessionCollection` (unversioned).
    pub const SESSION_COLLECTION: &str = "#SessionCollection.SessionCollection";
}

/// The Redfish protocol version this service reports as `ServiceRoot.RedfishVersion`.
const REDFISH_VERSION: &str = "1.15.0";

// ===========================================================================
// Configuration
// ===========================================================================

/// **The node this BMC fronts** — what the emulated `ComputerSystem` looks like and
/// which local resources it actually drives.
#[derive(Debug, Clone)]
pub struct NodeConfig {
    /// The Redfish `ComputerSystem` id — the `{system_id}` in every URL, and what a
    /// [`BmcEndpoint`] carries. Choose the same spelling a real BMC of the fleet
    /// would use (`System.Embedded.1` for iDRAC, `1` for iLO) so a spec written
    /// against the emulator is byte-identical against the metal.
    pub system_id: String,
    /// The `VirtualMedia` slot id the ISO is inserted into. Defaults to
    /// [`crate::redfish::DEFAULT_MEDIA_ID`] (`"CD"`) — the slot draupnir's own client
    /// targets when nothing else is said. (DMTF's mockup happens to call its slot
    /// `CD1`, and iLO calls it `1`: the id is an instance detail, never spec-fixed.)
    pub media_slot: String,
    /// The Redfish account username.
    pub username: String,
    /// The Redfish account password.
    pub password: String,
    /// The address to bind. `127.0.0.1:0` (the default) takes an ephemeral port;
    /// read the real one back with [`RedfishKvmServer::addr`].
    pub bind: SocketAddr,
    /// **The node's local disk** — what a `BootSourceOverrideTarget: "Hdd"` actually
    /// boots. `None` means this node has no disk, and an `Hdd` override is then
    /// refused by name rather than silently falling through to the medium (which is
    /// precisely how a boot override gets "accepted" without ever being applied).
    pub local_disk: Option<String>,
    /// Guest RAM in MiB for the VM this BMC boots.
    pub mem_mb: u32,
    /// vCPU count for the VM this BMC boots.
    pub cores: u32,
    /// `ComputerSystem.Name`.
    pub system_name: String,
    /// `ComputerSystem.Manufacturer`.
    pub manufacturer: String,
    /// `ComputerSystem.Model`.
    pub model: String,
    /// `ComputerSystem.UUID` / `ServiceRoot.UUID`.
    pub uuid: String,
    /// Extra TLS SANs beyond `localhost` / `127.0.0.1` — set when the BMC is reached
    /// by a name other than loopback.
    pub extra_sans: Vec<String>,
}

impl NodeConfig {
    /// A node with `system_id`, bound to an ephemeral loopback port, `admin` with no
    /// password, no local disk, 1024 MiB / 2 cores.
    pub fn new(system_id: impl Into<String>) -> Self {
        Self {
            system_id: system_id.into(),
            media_slot: crate::redfish::DEFAULT_MEDIA_ID.to_string(),
            username: "admin".into(),
            password: String::new(),
            bind: SocketAddr::from(([127, 0, 0, 1], 0)),
            local_disk: None,
            mem_mb: 1024,
            cores: 2,
            system_name: "draupnir-node".into(),
            manufacturer: "nordisk".into(),
            model: "draupnir Redfish/KVM".into(),
            uuid: "1f0d3a26-4c5b-4e77-9a2c-6b1e0d7a55f1".into(),
            extra_sans: Vec::new(),
        }
    }

    /// Set the Redfish account (builder style).
    pub fn credentials(mut self, username: impl Into<String>, password: impl Into<String>) -> Self {
        self.username = username.into();
        self.password = password.into();
        self
    }

    /// Set the address to bind (builder style).
    pub fn bind(mut self, bind: SocketAddr) -> Self {
        self.bind = bind;
        self
    }

    /// Set the `VirtualMedia` slot id (builder style).
    pub fn media_slot(mut self, slot: impl Into<String>) -> Self {
        self.media_slot = slot.into();
        self
    }

    /// Give the node a local disk — what an `Hdd` boot override boots (builder style).
    pub fn local_disk(mut self, disk: impl Into<String>) -> Self {
        self.local_disk = Some(disk.into());
        self
    }

    /// Size the VM this BMC boots (builder style).
    pub fn sized(mut self, mem_mb: u32, cores: u32) -> Self {
        self.mem_mb = mem_mb;
        self.cores = cores;
        self
    }

    /// Add TLS SANs (builder style).
    pub fn extra_sans<I, S>(mut self, sans: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.extra_sans.extend(sans.into_iter().map(Into::into));
        self
    }
}

// ===========================================================================
// The node's state
// ===========================================================================

/// The mutable state of the emulated node — everything the six endpoints read and
/// write. One `Mutex` guards it all: this is a control plane answering a handful of
/// requests, not a data path, and a single lock is the shape that cannot deadlock.
#[derive(Debug, Default)]
struct NodeState {
    /// The media URI exactly as the client named it (`VirtualMedia.Image`).
    image_uri: Option<String>,
    /// The local file that URI resolved to — what a boot actually attaches.
    image_path: Option<String>,
    /// `VirtualMedia.Inserted`.
    inserted: bool,
    /// `VirtualMedia.WriteProtected`.
    write_protected: bool,
    /// `Boot.BootSourceOverrideEnabled`.
    override_enabled: String,
    /// `Boot.BootSourceOverrideTarget`, once mapped.
    override_target: Option<BootTarget>,
    /// The machine the last successful power-on produced.
    machine: Option<Machine>,
    /// The [`BootSpec`] the last power-on actually handed the backend — the applied
    /// output, readable by a caller that wants to prove *what* was booted rather than
    /// that something was.
    last_spec: Option<BootSpec>,
    /// The last `ResetType` accepted.
    last_reset: Option<String>,
}

impl NodeState {
    fn fresh() -> Self {
        Self {
            override_enabled: wire::OVERRIDE_DISABLED.to_string(),
            ..Default::default()
        }
    }
}

// ===========================================================================
// The backend seam
// ===========================================================================

/// What this BMC can drive: anything that can be [`Boot`]ed and has a
/// [`Lifecycle`].
///
/// [`KvmBoot`] is the real one. The seam is a trait so the conformance suite can
/// front a **recording** backend that launches nothing — the wire shapes must be
/// provable on a box with no `/dev/kvm`, and a conformance test that needed a real
/// VM would be a conformance test nobody ran.
pub trait NodeBackend: Boot + Lifecycle + Send + Sync {}
impl<T: Boot + Lifecycle + Send + Sync> NodeBackend for T {}

// ===========================================================================
// The server
// ===========================================================================

/// A running Redfish service in front of a KVM host.
///
/// Started with [`start`](RedfishKvmServer::start) (real KVM) or
/// [`start_with`](RedfishKvmServer::start_with) (any [`NodeBackend`]). It listens on
/// its own background thread — a [`gatling::background::Job`], the constellation's
/// sanctioned home for a raw thread — until [`shutdown`](RedfishKvmServer::shutdown)
/// or drop.
pub struct RedfishKvmServer {
    cfg: NodeConfig,
    addr: SocketAddr,
    cert_pem: String,
    state: Arc<Mutex<NodeState>>,
    stop: Arc<AtomicBool>,
    /// The accept loop. `Option` so `shutdown` can take and join it.
    job: Option<gatling::background::Job<()>>,
    /// Kept typed (not just as a `NodeBackend`) so the serial console of the guest
    /// this BMC booted is readable — the applied output a caller needs to prove the
    /// override was honoured, rather than merely acknowledged.
    kvm: Option<Arc<KvmBoot>>,
}

impl std::fmt::Debug for RedfishKvmServer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RedfishKvmServer")
            .field("addr", &self.addr)
            .field("system_id", &self.cfg.system_id)
            .field("media_slot", &self.cfg.media_slot)
            // Never the password, and never the private key (which is not held here
            // at all — only the public cert PEM).
            .field("cert_pem", &format_args!("<{} bytes>", self.cert_pem.len()))
            .finish_non_exhaustive()
    }
}

impl RedfishKvmServer {
    /// Start a BMC in front of **this box's KVM** ([`KvmBoot`]).
    pub fn start(cfg: NodeConfig) -> Result<Self> {
        let kvm = Arc::new(KvmBoot::new());
        let backend: Arc<dyn NodeBackend> = kvm.clone();
        let mut me = Self::start_with(cfg, backend)?;
        me.kvm = Some(kvm);
        Ok(me)
    }

    /// Start a BMC in front of an arbitrary [`NodeBackend`] — the seam the
    /// conformance suite uses to prove the wire with no VM anywhere.
    pub fn start_with(cfg: NodeConfig, backend: Arc<dyn NodeBackend>) -> Result<Self> {
        let (tls_config, cert_pem) = tls_identity(&cfg)?;
        let listener = TcpListener::bind(cfg.bind)
            .map_err(|e| Error::Backend(format!("redfish server bind {}: {e}", cfg.bind)))?;
        let addr = listener
            .local_addr()
            .map_err(|e| Error::Backend(format!("redfish server local_addr: {e}")))?;
        // Non-blocking accept + a short poll is what lets `shutdown` be prompt
        // without a self-connect trick; the accepted socket is put back into
        // blocking mode before the TLS handshake, which needs it.
        listener
            .set_nonblocking(true)
            .map_err(|e| Error::Backend(format!("redfish server set_nonblocking: {e}")))?;

        let state = Arc::new(Mutex::new(NodeState::fresh()));
        let stop = Arc::new(AtomicBool::new(false));

        let service = Service {
            routes: Routes::for_node(&cfg),
            cfg: cfg.clone(),
            state: state.clone(),
            backend,
        };
        let loop_stop = stop.clone();
        let job = gatling::background::Job::spawn(move || {
            accept_loop(listener, tls_config, service, loop_stop)
        });

        crate::functional_status(
            "draupnir/redfish-server",
            "start",
            true,
            &format!(
                "BMC for system `{}` listening on https://{addr} (slot `{}`)",
                cfg.system_id, cfg.media_slot
            ),
        );

        Ok(Self {
            cfg,
            addr,
            cert_pem,
            state,
            stop,
            job: Some(job),
            kvm: None,
        })
    }

    /// The address it is listening on (the real port when `bind` asked for `:0`).
    pub fn addr(&self) -> SocketAddr {
        self.addr
    }

    /// The service base URL, e.g. `https://127.0.0.1:41234`.
    pub fn base_url(&self) -> String {
        format!("https://{}", self.addr)
    }

    /// The **PEM certificate to pin** — feed it to
    /// [`RedfishBoot::pin_cert_pem`](crate::redfish::RedfishBoot::pin_cert_pem) so the
    /// client keeps full TLS verification on with this cert as its sole trusted root.
    pub fn cert_pem(&self) -> &str {
        &self.cert_pem
    }

    /// A [`BmcEndpoint`] addressing this server — what a spec's
    /// [`on_metal`](BootSpec::on_metal) takes.
    pub fn bmc_endpoint(&self) -> BmcEndpoint {
        BmcEndpoint {
            host: self.base_url(),
            username: self.cfg.username.clone(),
            system_id: self.cfg.system_id.clone(),
        }
    }

    /// The machine the last accepted power-on produced, if any.
    pub fn machine(&self) -> Option<Machine> {
        self.state.lock().unwrap().machine.clone()
    }

    /// **The [`BootSpec`] the BMC actually handed its backend** on the last power-on.
    ///
    /// This is the applied output at the spec level: it says *what* the node was told
    /// to boot, so a test can prove a boot override was honoured rather than merely
    /// acknowledged with a `204`.
    pub fn last_boot_spec(&self) -> Option<BootSpec> {
        self.state.lock().unwrap().last_spec.clone()
    }

    /// The media URI currently inserted (`VirtualMedia.Image`), if any.
    pub fn inserted_image(&self) -> Option<String> {
        let s = self.state.lock().unwrap();
        s.inserted.then(|| s.image_uri.clone()).flatten()
    }

    /// **The serial console of the guest this BMC booted** — the applied output at
    /// the machine level. `None` unless the server was started with
    /// [`start`](RedfishKvmServer::start) (a real [`KvmBoot`]) and a VM is live.
    ///
    /// Redfish itself has no "give me the console" GET, so this is deliberately a
    /// *host-side* accessor rather than an invented endpoint: an emulator that grew a
    /// non-standard resource would be a worse emulator.
    pub fn serial_log(&self) -> Option<String> {
        let kvm = self.kvm.as_ref()?;
        let machine = self.machine()?;
        kvm.serial_log(&machine)
    }

    /// Wait for a named line on the booted guest's console, or a deadline — the same
    /// [`Seen`] observation shape [`KvmBoot::await_serial_marker`] returns, because it
    /// *is* that call. `Err` when this server never booted a KVM guest.
    pub fn await_serial_marker(
        &self,
        marker: &str,
        budget: Duration,
        poll: Duration,
    ) -> Result<Seen> {
        let kvm = self.kvm.as_ref().ok_or_else(|| {
            Error::Backend(
                "this Redfish server does not front a KVM backend (started with start_with)".into(),
            )
        })?;
        let machine = self
            .machine()
            .ok_or_else(|| Error::Backend("no machine has been powered on yet".into()))?;
        kvm.await_serial_marker(&machine, marker, budget, poll)
    }

    /// Stop the listener and join its thread.
    pub fn shutdown(&mut self) {
        self.stop.store(true, Ordering::SeqCst);
        if let Some(job) = self.job.take() {
            let _ = job.join();
        }
    }
}

impl Drop for RedfishKvmServer {
    fn drop(&mut self) {
        self.shutdown();
        // A BMC that "powered off" by exiting would leave a QEMU process on the box.
        if let (Some(kvm), Some(machine)) = (self.kvm.as_ref(), self.machine()) {
            let _ = kvm.power_off(&machine);
        }
    }
}

// ===========================================================================
// TLS identity
// ===========================================================================

/// Mint the server's TLS identity and build a `rustls` config from it.
///
/// A genuine self-signed X.509 with `localhost`, `127.0.0.1`, the bound IP and any
/// [`NodeConfig::extra_sans`] as SANs. The private key never leaves this function's
/// return value — it goes straight into the `rustls` config and is never serialized
/// to disk, so no key material can be left behind or committed.
#[allow(clippy::type_complexity)]
fn tls_identity(cfg: &NodeConfig) -> Result<(Arc<rustls::ServerConfig>, String)> {
    let mut sans: Vec<String> = vec![
        "localhost".into(),
        "127.0.0.1".into(),
        "::1".into(),
        cfg.bind.ip().to_string(),
    ];
    sans.extend(cfg.extra_sans.iter().cloned());
    sans.sort();
    sans.dedup();

    let mut params = rcgen::CertificateParams::new(sans)
        .map_err(|e| Error::Backend(format!("redfish server cert params: {e}")))?;
    params.distinguished_name = {
        let mut dn = rcgen::DistinguishedName::new();
        dn.push(
            rcgen::DnType::CommonName,
            format!("draupnir BMC {}", cfg.system_id),
        );
        dn.push(rcgen::DnType::OrganizationName, "nordisk");
        dn
    };
    let key = rcgen::KeyPair::generate()
        .map_err(|e| Error::Backend(format!("redfish server keypair: {e}")))?;
    let cert = params
        .self_signed(&key)
        .map_err(|e| Error::Backend(format!("redfish server self-sign: {e}")))?;
    let cert_pem = cert.pem();

    let cert_der = rustls::pki_types::CertificateDer::from(cert.der().to_vec());
    let key_der = rustls::pki_types::PrivateKeyDer::try_from(key.serialize_der())
        .map_err(|e| Error::Backend(format!("redfish server key DER: {e}")))?;

    let provider = Arc::new(rustls::crypto::ring::default_provider());
    let tls = rustls::ServerConfig::builder_with_provider(provider)
        .with_safe_default_protocol_versions()
        .map_err(|e| Error::Backend(format!("redfish server tls versions: {e}")))?
        .with_no_client_auth()
        .with_single_cert(vec![cert_der], key_der)
        .map_err(|e| Error::Backend(format!("redfish server tls cert: {e}")))?;

    Ok((Arc::new(tls), cert_pem))
}

// ===========================================================================
// The accept loop
// ===========================================================================

/// How long a single connection may take to deliver its request / read its response.
/// A BMC exchange is a few hundred bytes; a peer that stalls longer than this is
/// wedged, and holding the (deliberately serial) control plane for it would be worse
/// than dropping it.
const CONNECTION_TIMEOUT: Duration = Duration::from_secs(30);

/// The idle poll between `accept` attempts — what makes shutdown prompt.
const ACCEPT_POLL: Duration = Duration::from_millis(5);

fn accept_loop(
    listener: TcpListener,
    tls: Arc<rustls::ServerConfig>,
    service: Service,
    stop: Arc<AtomicBool>,
) {
    while !stop.load(Ordering::SeqCst) {
        match listener.accept() {
            Ok((sock, _peer)) => {
                if sock.set_nonblocking(false).is_err() {
                    continue;
                }
                let _ = sock.set_read_timeout(Some(CONNECTION_TIMEOUT));
                let _ = sock.set_write_timeout(Some(CONNECTION_TIMEOUT));
                serve_connection(sock, &tls, &service);
            }
            Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                std::thread::sleep(ACCEPT_POLL);
            }
            Err(_) => break,
        }
    }
}

/// Serve **one** request on one TLS connection, then close it gracefully.
///
/// # Why one request per connection, and not keep-alive
///
/// This was keep-alive first, and it produced a real, reproducible flake: measured on
/// this box 2026-08-15, **3 failures in 28** full runs of `cargo test --features
/// redfish-server,backend-redfish --test redfish_server_conformance`, each an
/// `ECONNRESET` raised by the client. Instrumenting the accept loop showed the classic
/// HTTP/1.1 **idle-close race**: the server had answered two requests on a pooled
/// connection, the client's pool retired it, and the client's next request went out on
/// the socket the server was already closing. After this change: **0 failures in 40**
/// consecutive runs.
///
/// The race is inherent to keep-alive and every client is supposed to retry through
/// it. A flaky proof is worse than a slow one, so this service does the thing a
/// server is always allowed to do: answer one request, say `Connection: close`, and
/// shut the connection down cleanly. Plenty of real BMCs behave exactly this way. The
/// cost is a TLS handshake per request — about a millisecond on loopback, for a
/// control plane that makes single-digit numbers of calls per boot.
///
/// It also removes a second defect keep-alive had: the accept loop is deliberately
/// **serial** (a BMC is not a data path), so a connection parked in `read` waiting for
/// a follow-up request that never came would hold the whole service — and would make
/// [`RedfishKvmServer::shutdown`] block for the full [`CONNECTION_TIMEOUT`].
fn serve_connection(sock: TcpStream, tls: &Arc<rustls::ServerConfig>, service: &Service) {
    let Ok(conn) = rustls::ServerConnection::new(tls.clone()) else {
        return;
    };
    let mut stream = rustls::StreamOwned::new(conn, sock);
    let mut buf: Vec<u8> = Vec::with_capacity(2048);
    match read_request(&mut stream, &mut buf) {
        // A clean close, or a peer that went away mid-request: nothing to answer.
        Ok(None) => {}
        Ok(Some(request)) => {
            let response = service
                .dispatch(&request)
                .with_header("Connection", "close");
            let _ = write_response(&mut stream, &response);
        }
        Err(resp) => {
            let _ = write_response(&mut stream, &resp.with_header("Connection", "close"));
        }
    }
    graceful_close(stream);
}

/// Close a TLS connection so the peer sees a clean shutdown rather than a reset.
///
/// Three steps, each load-bearing: send the TLS `close_notify` (so the client's TLS
/// layer sees an orderly end of stream, not a truncation), `shutdown(Write)` to send
/// the FIN, and then **drain** whatever the peer still had in flight. That last one is
/// the reset: the kernel emits RST instead of FIN when a socket is closed with unread
/// data in its receive queue, which is precisely how a well-behaved client ends up
/// reporting "connection reset by peer" against a server that did nothing wrong.
fn graceful_close(mut stream: rustls::StreamOwned<rustls::ServerConnection, TcpStream>) {
    stream.conn.send_close_notify();
    let _ = stream.flush();
    let _ = stream.sock.shutdown(std::net::Shutdown::Write);
    let _ = stream
        .sock
        .set_read_timeout(Some(Duration::from_millis(250)));
    let mut sink = [0u8; 1024];
    // Bounded: drain what is there, then stop. An endless drain would be a new way
    // for one peer to hold the serial accept loop.
    for _ in 0..16 {
        match stream.sock.read(&mut sink) {
            Ok(0) | Err(_) => break,
            Ok(_) => continue,
        }
    }
}

// ===========================================================================
// Minimal HTTP/1.1 — pure std, no framework
// ===========================================================================

/// The largest request head this service will read. A Redfish request head is a few
/// hundred bytes; anything past this is not a BMC client.
const MAX_HEAD: usize = 16 * 1024;
/// The largest request body. The biggest legitimate body here is an `InsertMedia`
/// with a long URI.
const MAX_BODY: usize = 1024 * 1024;

/// A parsed HTTP request.
struct Request {
    method: String,
    /// The percent-decoded path, without the query string.
    path: String,
    headers: BTreeMap<String, String>,
    body: Vec<u8>,
}

impl Request {
    fn header(&self, name: &str) -> Option<&str> {
        self.headers.get(&name.to_ascii_lowercase()).map(String::as_str)
    }
}

/// A response to write.
struct Response {
    status: u16,
    headers: Vec<(String, String)>,
    body: Vec<u8>,
}

impl Response {
    fn new(status: u16) -> Self {
        Self {
            status,
            headers: Vec::new(),
            body: Vec::new(),
        }
    }

    fn with_header(mut self, name: &str, value: impl Into<String>) -> Self {
        self.headers.push((name.to_string(), value.into()));
        self
    }

    /// A JSON resource body.
    fn json(status: u16, value: &Value) -> Self {
        let mut r = Self::new(status);
        r.body = serde_json::to_vec(value).unwrap_or_else(|_| b"{}".to_vec());
        r.headers.push((
            "Content-Type".into(),
            "application/json;charset=utf-8".into(),
        ));
        r
    }

    /// `204 No Content` — what a successful Redfish action or PATCH returns.
    fn no_content() -> Self {
        Self::new(204)
    }

    /// A DMTF-shaped `error` payload (`redfish-error.v1_0_2`): `error.code`,
    /// `error.message`, and one `@Message.ExtendedInfo` entry carrying the registry
    /// `MessageId`, the rendered `Message`, its `MessageArgs`, `MessageSeverity` and
    /// `Resolution`.
    ///
    /// `detail`, when given, is appended to the extended info's `Resolution` — so a
    /// refusal always **names the thing it refused** even where DMTF's registry
    /// template has no argument for it.
    fn error(msg: Message, args: &[&str], detail: Option<&str>) -> Self {
        let rendered = msg.render(args);
        let resolution = match detail {
            Some(d) => format!("{} {d}", msg.resolution),
            None => msg.resolution.to_string(),
        };
        let mut info = json!({
            "@odata.type": "#Message.v1_1_2.Message",
            "MessageId": msg.message_id(),
            "Message": rendered,
            "MessageSeverity": msg.severity,
            "Resolution": resolution,
        });
        if !args.is_empty() {
            info["MessageArgs"] = json!(args);
        }
        Response::json(
            msg.status,
            &json!({
                "error": {
                    "code": msg.message_id(),
                    "message": rendered,
                    "@Message.ExtendedInfo": [info],
                }
            }),
        )
    }

    /// `405 Method Not Allowed` with the mandatory `Allow` header — DSP0266 requires
    /// the header, and a client that reads it can discover the right verb.
    fn method_not_allowed(allow: &str) -> Self {
        Response::error(
            ACTION_NOT_SUPPORTED,
            &["the requested method"],
            Some(&format!("Allowed methods: {allow}.")),
        )
        .with_status(405)
        .with_header("Allow", allow)
    }

    fn with_status(mut self, status: u16) -> Self {
        self.status = status;
        self
    }
}

fn reason(status: u16) -> &'static str {
    match status {
        200 => "OK",
        201 => "Created",
        204 => "No Content",
        400 => "Bad Request",
        401 => "Unauthorized",
        404 => "Not Found",
        405 => "Method Not Allowed",
        413 => "Payload Too Large",
        500 => "Internal Server Error",
        501 => "Not Implemented",
        _ => "Status",
    }
}

/// Read one request off `stream`, buffering leftovers for the next keep-alive round.
///
/// `Ok(None)` is a clean close. `Err(response)` is a request this service will not
/// even parse (too large, unreadable) and carries what to answer with.
fn read_request<S: Read>(stream: &mut S, buf: &mut Vec<u8>) -> std::result::Result<Option<Request>, Response> {
    // 1. Head — read until CRLFCRLF.
    let head_end = loop {
        if let Some(p) = find_subsequence(buf, b"\r\n\r\n") {
            break p;
        }
        if buf.len() > MAX_HEAD {
            return Err(Response::error(
                MALFORMED_JSON,
                &[],
                Some("The request head exceeded this service's limit."),
            )
            .with_status(413));
        }
        let mut chunk = [0u8; 1024];
        match stream.read(&mut chunk) {
            Ok(0) => return Ok(None),
            Ok(n) => buf.extend_from_slice(&chunk[..n]),
            Err(_) => return Ok(None),
        }
    };

    let head = String::from_utf8_lossy(&buf[..head_end]).into_owned();
    let mut lines = head.split("\r\n");
    let request_line = lines.next().unwrap_or_default();
    let mut parts = request_line.split_whitespace();
    let method = parts.next().unwrap_or_default().to_string();
    let raw_target = parts.next().unwrap_or_default();
    if method.is_empty() || raw_target.is_empty() {
        return Ok(None);
    }
    let path_part = raw_target.split('?').next().unwrap_or(raw_target);
    let path = percent_decode(path_part);

    let mut headers = BTreeMap::new();
    for line in lines {
        if let Some((k, v)) = line.split_once(':') {
            headers.insert(k.trim().to_ascii_lowercase(), v.trim().to_string());
        }
    }

    // 2. Body — Content-Length only. Redfish clients do not chunk their action
    //    bodies, and a service that guessed at a chunked body would be guessing.
    let len: usize = headers
        .get("content-length")
        .and_then(|v| v.parse().ok())
        .unwrap_or(0);
    if len > MAX_BODY {
        return Err(Response::error(
            MALFORMED_JSON,
            &[],
            Some("The request body exceeded this service's limit."),
        )
        .with_status(413));
    }
    let body_start = head_end + 4;
    while buf.len() < body_start + len {
        let mut chunk = [0u8; 4096];
        match stream.read(&mut chunk) {
            Ok(0) => return Ok(None),
            Ok(n) => buf.extend_from_slice(&chunk[..n]),
            Err(_) => return Ok(None),
        }
    }
    let body = buf[body_start..body_start + len].to_vec();
    // Keep whatever the peer pipelined behind this request.
    buf.drain(..body_start + len);

    Ok(Some(Request {
        method,
        path,
        headers,
        body,
    }))
}

fn write_response<S: Write>(stream: &mut S, resp: &Response) -> std::io::Result<()> {
    let mut out = Vec::with_capacity(256 + resp.body.len());
    out.extend_from_slice(
        format!("HTTP/1.1 {} {}\r\n", resp.status, reason(resp.status)).as_bytes(),
    );
    // Redfish requires OData-Version on every response.
    out.extend_from_slice(b"OData-Version: 4.0\r\n");
    out.extend_from_slice(b"Cache-Control: no-cache\r\n");
    for (k, v) in &resp.headers {
        out.extend_from_slice(format!("{k}: {v}\r\n").as_bytes());
    }
    out.extend_from_slice(format!("Content-Length: {}\r\n\r\n", resp.body.len()).as_bytes());
    out.extend_from_slice(&resp.body);
    stream.write_all(&out)?;
    stream.flush()
}

fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    haystack
        .windows(needle.len())
        .position(|w| w == needle)
}

/// Percent-decode a URL path segment sequence. Invalid escapes are left verbatim
/// rather than dropped, so a path this service does not recognise fails as
/// "not found at *that* URI" and names the URI the client actually sent.
fn percent_decode(s: &str) -> String {
    let bytes = s.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok();
            if let Some(b) = hex.and_then(|h| u8::from_str_radix(h, 16).ok()) {
                out.push(b);
                i += 3;
                continue;
            }
        }
        out.push(bytes[i]);
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

// ===========================================================================
// Routing
// ===========================================================================

/// The service's routing table — every path built from [`crate::redfish::wire`], the
/// same module the CLIENT builds its URLs from. This is the whole of the anti-mirror
/// discipline at the URL level: there is no second spelling to drift from.
#[derive(Debug, Clone)]
struct Routes {
    system: String,
    reset: String,
    vm_collection: String,
    vm: String,
    vm_insert: String,
    vm_eject: String,
}

impl Routes {
    fn for_node(cfg: &NodeConfig) -> Self {
        let id = &cfg.system_id;
        let slot = &cfg.media_slot;
        Self {
            system: wire::system_path(id),
            reset: wire::reset_path(id),
            vm_collection: wire::virtual_media_collection_path(id),
            vm: wire::virtual_media_path(id, slot),
            vm_insert: wire::virtual_media_action_path(id, slot, wire::INSERT_MEDIA),
            vm_eject: wire::virtual_media_action_path(id, slot, wire::EJECT_MEDIA),
        }
    }
}

/// Everything a request needs: the routes, the node config, its state, its backend.
struct Service {
    routes: Routes,
    cfg: NodeConfig,
    state: Arc<Mutex<NodeState>>,
    backend: Arc<dyn NodeBackend>,
}

impl Service {
    fn dispatch(&self, req: &Request) -> Response {
        let path = req.path.as_str();
        let m = req.method.as_str();

        // The two unauthenticated URIs DSP0266 allows: the protocol-version probe
        // and the service root.
        if path == wire::PROTOCOL_VERSION_PATH {
            return match m {
                "GET" | "HEAD" => Response::json(200, &json!({ "v1": wire::SERVICE_ROOT_PATH })),
                _ => Response::method_not_allowed("GET"),
            };
        }
        if path == wire::SERVICE_ROOT_PATH || path == wire::SERVICE_ROOT_PATH_BARE {
            return match m {
                "GET" | "HEAD" => Response::json(200, &self.service_root()),
                _ => Response::method_not_allowed("GET"),
            };
        }

        if let Some(unauthorized) = self.check_auth(req) {
            return unauthorized;
        }

        let r = &self.routes;
        if path == wire::SYSTEMS_PATH {
            return match m {
                "GET" | "HEAD" => Response::json(200, &self.system_collection()),
                _ => Response::method_not_allowed("GET"),
            };
        }
        if path == wire::SESSIONS_PATH {
            return match m {
                "GET" | "HEAD" => Response::json(200, &self.session_collection()),
                _ => Response::method_not_allowed("GET"),
            };
        }
        if path == r.system {
            return match m {
                "GET" | "HEAD" => Response::json(200, &self.computer_system()),
                "PATCH" => self.patch_system(req),
                _ => Response::method_not_allowed("GET, PATCH"),
            };
        }
        if path == r.reset {
            return match m {
                "POST" => self.post_reset(req),
                _ => Response::method_not_allowed("POST"),
            };
        }
        if path == r.vm_collection {
            return match m {
                "GET" | "HEAD" => Response::json(200, &self.virtual_media_collection()),
                _ => Response::method_not_allowed("GET"),
            };
        }
        if path == r.vm {
            return match m {
                "GET" | "HEAD" => Response::json(200, &self.virtual_media()),
                _ => Response::method_not_allowed("GET"),
            };
        }
        if path == r.vm_insert {
            return match m {
                "POST" => self.post_insert_media(req),
                _ => Response::method_not_allowed("POST"),
            };
        }
        if path == r.vm_eject {
            return match m {
                "POST" => self.post_eject_media(),
                _ => Response::method_not_allowed("POST"),
            };
        }

        Response::error(RESOURCE_NOT_FOUND, &["Resource", path], None)
    }

    /// `None` when the request is authorized. Everything below the service root
    /// needs a Basic credential matching the configured account.
    fn check_auth(&self, req: &Request) -> Option<Response> {
        let ok = req
            .header("authorization")
            .and_then(wire::parse_basic_auth)
            .is_some_and(|(u, p)| u == self.cfg.username && p == self.cfg.password);
        if ok {
            return None;
        }
        Some(
            Response::error(NO_VALID_SESSION, &[], None)
                .with_header("WWW-Authenticate", "Basic realm=\"RedfishService\""),
        )
    }

    // ── resources ───────────────────────────────────────────────────────────

    fn service_root(&self) -> Value {
        json!({
            "@odata.id": wire::SERVICE_ROOT_PATH,
            "@odata.type": odata_type::SERVICE_ROOT,
            "Id": "RootService",
            "Name": "Root Service",
            "RedfishVersion": REDFISH_VERSION,
            "UUID": self.cfg.uuid,
            "Product": "draupnir",
            "Vendor": "nordisk",
            "Systems": { "@odata.id": wire::SYSTEMS_PATH },
            // REQUIRED by the ServiceRoot schema, and it must resolve — hence the
            // (read-only, empty) SessionCollection this service also answers.
            "Links": { "Sessions": { "@odata.id": wire::SESSIONS_PATH } },
        })
    }

    fn system_collection(&self) -> Value {
        json!({
            "@odata.id": wire::SYSTEMS_PATH,
            "@odata.type": odata_type::SYSTEM_COLLECTION,
            "Name": "Computer System Collection",
            "Members": [ { "@odata.id": self.routes.system } ],
            "Members@odata.count": 1,
        })
    }

    /// An EMPTY session collection.
    ///
    /// It exists because `ServiceRoot.Links.Sessions` is a **required** property whose
    /// pointer must resolve; it is empty because this service authenticates with HTTP
    /// Basic only. Session *creation* is a named gap, not a silent one: a `POST` here
    /// is answered `405` with `Allow: GET`, so a client that needs session auth is
    /// told so instead of being handed a plausible-looking token.
    fn session_collection(&self) -> Value {
        json!({
            "@odata.id": wire::SESSIONS_PATH,
            "@odata.type": odata_type::SESSION_COLLECTION,
            "Name": "Session Collection",
            "Members": [],
            "Members@odata.count": 0,
        })
    }

    fn computer_system(&self) -> Value {
        let s = self.state.lock().unwrap();
        let power = self.observe_power(&s);
        let target = s
            .override_target
            .map_or(wire::BOOT_TARGET_NONE, wire::target_str);
        json!({
            "@odata.id": self.routes.system,
            "@odata.type": odata_type::SYSTEM,
            "Id": self.cfg.system_id,
            "Name": self.cfg.system_name,
            "SystemType": "Physical",
            "Manufacturer": self.cfg.manufacturer,
            "Model": self.cfg.model,
            "UUID": self.cfg.uuid,
            "PowerState": power_state_str(power),
            "Status": { "State": "Enabled", "Health": "OK" },
            "Boot": {
                prop::BOOT_SOURCE_OVERRIDE_ENABLED: s.override_enabled,
                prop::BOOT_SOURCE_OVERRIDE_TARGET: target,
                prop::BOOT_SOURCE_OVERRIDE_MODE: "UEFI",
                wire::allowable_values_key(prop::BOOT_SOURCE_OVERRIDE_TARGET):
                    wire::BOOT_TARGET_ALLOWABLE,
            },
            "MemorySummary": { "TotalSystemMemoryGiB": self.cfg.mem_mb as f64 / 1024.0 },
            "ProcessorSummary": { "Count": self.cfg.cores },
            "VirtualMedia": { "@odata.id": self.routes.vm_collection },
            "Actions": {
                wire::ACTION_RESET: {
                    prop::TARGET: self.routes.reset,
                    wire::allowable_values_key(prop::RESET_TYPE): wire::RESET_TYPE_ALLOWABLE,
                }
            },
        })
    }

    fn virtual_media_collection(&self) -> Value {
        json!({
            "@odata.id": self.routes.vm_collection,
            "@odata.type": odata_type::VIRTUAL_MEDIA_COLLECTION,
            "Name": "Virtual Media Services",
            "Members": [ { "@odata.id": self.routes.vm } ],
            "Members@odata.count": 1,
        })
    }

    fn virtual_media(&self) -> Value {
        let s = self.state.lock().unwrap();
        json!({
            "@odata.id": self.routes.vm,
            "@odata.type": odata_type::VIRTUAL_MEDIA,
            "Id": self.cfg.media_slot,
            "Name": "Virtual CD",
            "MediaTypes": ["CD", "DVD"],
            "ConnectedVia": if s.inserted { "URI" } else { "NotConnected" },
            prop::IMAGE: s.image_uri,
            prop::IMAGE_NAME: s.image_uri.as_deref().and_then(basename),
            prop::INSERTED: s.inserted,
            prop::WRITE_PROTECTED: s.write_protected,
            "Actions": {
                wire::ACTION_INSERT_MEDIA: { prop::TARGET: self.routes.vm_insert },
                wire::ACTION_EJECT_MEDIA:  { prop::TARGET: self.routes.vm_eject },
            },
        })
    }

    // ── actions ─────────────────────────────────────────────────────────────

    fn body_json(&self, req: &Request) -> std::result::Result<Value, Response> {
        if req.body.is_empty() {
            return Ok(json!({}));
        }
        serde_json::from_slice(&req.body)
            .map_err(|e| Response::error(MALFORMED_JSON, &[], Some(&format!("Parser said: {e}."))))
    }

    /// `POST .../VirtualMedia/{slot}/Actions/VirtualMedia.InsertMedia`
    fn post_insert_media(&self, req: &Request) -> Response {
        let body = match self.body_json(req) {
            Ok(b) => b,
            Err(r) => return r,
        };
        let insert = match wire::read_insert_media_body(&body) {
            Ok(i) => i,
            Err(missing) => {
                return Response::error(
                    ACTION_PARAMETER_MISSING,
                    &[wire::ACTION_INSERT_MEDIA, missing],
                    None,
                )
            }
        };
        // RED CONTROL: a media URI that resolves to nothing on this host is refused
        // BY NAME, before anything is mounted. An emulator that accepted it would
        // hand a later boot an empty tray and report the failure as "the appliance
        // did not come up" — a different bug with a different owner.
        let path = match resolve_media(&insert.image) {
            Ok(p) => p,
            Err(why) => {
                return Response::error(
                    RESOURCE_MISSING_AT_URI,
                    &[&insert.image],
                    Some(&why),
                )
            }
        };
        let mut s = self.state.lock().unwrap();
        s.image_uri = Some(insert.image.clone());
        s.image_path = Some(path.clone());
        s.inserted = insert.inserted;
        s.write_protected = insert.write_protected;
        drop(s);
        crate::functional_status(
            "draupnir/redfish-server",
            "InsertMedia",
            true,
            &format!("`{}` mounted from `{path}`", insert.image),
        );
        Response::no_content()
    }

    /// `POST .../VirtualMedia/{slot}/Actions/VirtualMedia.EjectMedia`
    fn post_eject_media(&self) -> Response {
        let mut s = self.state.lock().unwrap();
        s.image_uri = None;
        s.image_path = None;
        s.inserted = false;
        s.write_protected = false;
        Response::no_content()
    }

    /// `PATCH /redfish/v1/Systems/{id}` — the one-time boot override.
    fn patch_system(&self, req: &Request) -> Response {
        let body = match self.body_json(req) {
            Ok(b) => b,
            Err(r) => return r,
        };
        let Some(ovr) = wire::read_boot_override_body(&body) else {
            // A PATCH that names nothing this service owns changes nothing. It is not
            // an error (Redfish PATCH is a partial update), and it must not be
            // reported as one.
            return Response::no_content();
        };

        let mut s = self.state.lock().unwrap();
        if let Some(enabled) = &ovr.enabled {
            if !wire::OVERRIDE_ENABLED_ALLOWABLE.contains(&enabled.as_str()) {
                return Response::error(
                    PROPERTY_VALUE_NOT_IN_LIST,
                    &[enabled, prop::BOOT_SOURCE_OVERRIDE_ENABLED],
                    Some(&format!(
                        "Acceptable values: {}.",
                        wire::OVERRIDE_ENABLED_ALLOWABLE.join(", ")
                    )),
                );
            }
            s.override_enabled = enabled.clone();
        }
        if let Some(raw) = &ovr.target {
            if raw == wire::BOOT_TARGET_NONE {
                s.override_target = None;
            } else {
                // A target this node cannot actually honour is REFUSED, never quietly
                // coerced into one it can. `Pxe`/`BiosSetup` are legal DMTF tokens
                // that this KVM front end has nothing to do with, and answering 204
                // for them would be the exact "accepted but not applied" lie.
                match wire::target_from_str(raw)
                    .and_then(|t| BootOrder::from_redfish_target(Some(t)).map(|_| t))
                {
                    Some(t) => s.override_target = Some(t),
                    None => {
                        return Response::error(
                            PROPERTY_VALUE_NOT_IN_LIST,
                            &[raw, prop::BOOT_SOURCE_OVERRIDE_TARGET],
                            Some(&format!(
                                "This node honours: {}.",
                                boot_targets_this_node_honours().join(", ")
                            )),
                        )
                    }
                }
            }
        }
        let applied = format!(
            "{}/{}",
            s.override_enabled,
            s.override_target.map_or(wire::BOOT_TARGET_NONE, wire::target_str)
        );
        drop(s);
        crate::functional_status(
            "draupnir/redfish-server",
            "BootOverride",
            true,
            &format!("boot override set to {applied}"),
        );
        Response::no_content()
    }

    /// `POST /redfish/v1/Systems/{id}/Actions/ComputerSystem.Reset`
    fn post_reset(&self, req: &Request) -> Response {
        let body = match self.body_json(req) {
            Ok(b) => b,
            Err(r) => return r,
        };
        let reset_type = match wire::read_reset_body(&body) {
            Ok(t) => t,
            Err(missing) => {
                return Response::error(
                    ACTION_PARAMETER_MISSING,
                    &[wire::ACTION_RESET, missing],
                    None,
                )
            }
        };
        // RED CONTROL: a ResetType outside the advertised list is refused BY NAME,
        // quoting the value, the parameter and the action — DMTF's own
        // ActionParameterValueNotInList.
        if !wire::is_allowable_reset_type(&reset_type) {
            return Response::error(
                ACTION_PARAMETER_VALUE_NOT_IN_LIST,
                &[&reset_type, prop::RESET_TYPE, wire::ACTION_RESET],
                Some(&format!(
                    "Acceptable values: {}.",
                    wire::RESET_TYPE_ALLOWABLE.join(", ")
                )),
            );
        }

        match reset_type.as_str() {
            wire::RESET_ON | wire::RESET_FORCE_ON => self.power_up(&reset_type),
            wire::RESET_FORCE_OFF | wire::RESET_GRACEFUL_SHUTDOWN => self.power_down(&reset_type),
            wire::RESET_FORCE_RESTART | wire::RESET_GRACEFUL_RESTART => {
                self.power_down(&reset_type);
                self.power_up(&reset_type)
            }
            // Unreachable while RESET_TYPE_ALLOWABLE and this match agree; if they
            // ever stop agreeing, say so instead of pretending to act.
            other => Response::error(
                ACTION_PARAMETER_VALUE_NOT_IN_LIST,
                &[other, prop::RESET_TYPE, wire::ACTION_RESET],
                Some("This service advertises the value but does not implement it."),
            ),
        }
    }

    /// Power the node on: build the [`BootSpec`] the current state describes and hand
    /// it to the backend. **This is where the override becomes applied output** — the
    /// spec that leaves here is the machine that gets booted.
    fn power_up(&self, reset_type: &str) -> Response {
        let spec = {
            let s = self.state.lock().unwrap();
            match self.spec_for(&s) {
                Ok(spec) => spec,
                Err(why) => {
                    crate::functional_status(
                        "draupnir/redfish-server",
                        "Reset",
                        false,
                        &format!("{reset_type} refused: {why}"),
                    );
                    return Response::error(GENERAL_ERROR, &[], Some(&why));
                }
            }
        };
        match self.backend.boot(&spec) {
            Ok(machine) => {
                let mut s = self.state.lock().unwrap();
                s.machine = Some(machine);
                s.last_spec = Some(spec.clone());
                s.last_reset = Some(reset_type.to_string());
                // A ONE-TIME override is CONSUMED by the boot it applied to — DSP0266
                // says the service resets it to Disabled/None. Modelling that is what
                // stops a stale `Once` from silently steering a later boot.
                if s.override_enabled == wire::OVERRIDE_ONCE {
                    s.override_enabled = wire::OVERRIDE_DISABLED.to_string();
                    s.override_target = None;
                }
                drop(s);
                crate::functional_status(
                    "draupnir/redfish-server",
                    "Reset",
                    true,
                    &format!(
                        "{reset_type}: booted `{}` (order {:?}, medium {:?})",
                        spec.name,
                        spec.boot_order,
                        spec.medium_path()
                    ),
                );
                Response::no_content()
            }
            Err(e) => {
                crate::functional_status(
                    "draupnir/redfish-server",
                    "Reset",
                    false,
                    &format!("{reset_type} failed: {e}"),
                );
                Response::error(GENERAL_ERROR, &[], Some(&format!("The node's backend refused to start: {e}")))
            }
        }
    }

    fn power_down(&self, reset_type: &str) -> Response {
        let machine = self.state.lock().unwrap().machine.clone();
        let Some(machine) = machine else {
            // Powering off an already-off node is a no-op, not a fault.
            return Response::no_content();
        };
        match self.backend.power_off(&machine) {
            Ok(()) => {
                let mut s = self.state.lock().unwrap();
                s.machine = None;
                s.last_reset = Some(reset_type.to_string());
                Response::no_content()
            }
            Err(e) => Response::error(
                GENERAL_ERROR,
                &[],
                Some(&format!("The node's backend refused to power off: {e}")),
            ),
        }
    }

    /// **The translation, in one function.** Redfish state → a draupnir [`BootSpec`].
    ///
    /// The boot order comes from [`BootOrder::from_redfish_target`] — the inverse of
    /// the mapping the CLIENT uses — and then each order selects the constructor that
    /// already expresses it:
    ///
    /// * [`BootOrder::Medium`] → [`BootSpec::iso_boot`] (the inserted media is the
    ///   whole payload; `-cdrom` + `-boot d`).
    /// * [`BootOrder::Disk`] → [`BootSpec::kvm_boot_installed_disk`], which by
    ///   construction carries **no medium at all** ([`BootSpec::validate`] refuses
    ///   `Disk` + a medium). That is what makes an `Hdd` override *applied* rather
    ///   than merely acknowledged: the ISO is not attached to the machine.
    /// * [`BootOrder::Auto`] → the node's own order: the medium if a tray is loaded,
    ///   else the local disk.
    ///
    /// Every refusal names what was missing, because "the appliance did not come up"
    /// and "you never inserted an ISO" are different failures with different owners.
    fn spec_for(&self, s: &NodeState) -> std::result::Result<BootSpec, String> {
        let effective_target = if s.override_enabled == wire::OVERRIDE_DISABLED {
            None
        } else {
            s.override_target
        };
        let order = BootOrder::from_redfish_target(effective_target).ok_or_else(|| {
            format!(
                "boot override target {:?} is not a boot order this node can apply",
                effective_target
            )
        })?;

        let name = format!("redfish-{}", self.cfg.system_id);
        let medium = s.inserted.then(|| s.image_path.clone()).flatten();

        let mut spec = match order {
            BootOrder::Medium => {
                let iso = medium.ok_or_else(|| {
                    format!(
                        "the boot override asks for {} but no virtual media is inserted in slot `{}`",
                        wire::target_str(BootTarget::Cd),
                        self.cfg.media_slot
                    )
                })?;
                BootSpec::iso_boot(name, iso)
            }
            BootOrder::Disk => {
                let disk = self.cfg.local_disk.clone().ok_or_else(|| {
                    format!(
                        "the boot override asks for {} but this node has no local disk configured \
                         (NodeConfig::local_disk)",
                        wire::target_str(BootTarget::Hdd)
                    )
                })?;
                BootSpec::kvm_boot_installed_disk(name, disk)
            }
            BootOrder::Auto => match (medium, self.cfg.local_disk.clone()) {
                (Some(iso), _) => BootSpec::iso_boot(name, iso),
                (None, Some(disk)) => BootSpec::kvm_boot_installed_disk(name, disk),
                (None, None) => {
                    return Err(
                        "this node has neither virtual media inserted nor a local disk to boot"
                            .into(),
                    )
                }
            },
        };
        spec.mem_mb = self.cfg.mem_mb;
        spec.cores = self.cfg.cores;
        // Validate here, so a spec this service could not have booted is refused with
        // draupnir's own reason rather than QEMU's, from inside the Redfish action.
        spec.validate().map_err(|e| e.to_string())?;
        Ok(spec)
    }

    /// The node's power state, read from the backend when there is a machine.
    fn observe_power(&self, s: &NodeState) -> PowerState {
        match &s.machine {
            None => PowerState::Off,
            Some(m) => self.backend.status(m).unwrap_or(PowerState::Unknown),
        }
    }
}

/// The `BootSourceOverrideTarget` tokens this node will actually apply — the subset
/// of [`wire::BOOT_TARGET_ALLOWABLE`] that maps onto a [`BootOrder`].
fn boot_targets_this_node_honours() -> Vec<&'static str> {
    wire::BOOT_TARGET_ALLOWABLE
        .iter()
        .copied()
        .filter(|t| {
            wire::target_from_str(t)
                .and_then(|bt| BootOrder::from_redfish_target(Some(bt)))
                .is_some()
        })
        .chain(std::iter::once(wire::BOOT_TARGET_NONE))
        .collect()
}

/// The Redfish `PowerState` token for a draupnir [`PowerState`].
fn power_state_str(p: PowerState) -> &'static str {
    match p {
        PowerState::On => "On",
        PowerState::Off => "Off",
        // DMTF has no "unknown" PowerState token; the honest report for a node whose
        // state cannot be observed is to omit the claim, and `Off` would be a claim.
        PowerState::Unknown => "Paused",
    }
}

/// The last path segment of a media URI, for `VirtualMedia.ImageName`.
fn basename(uri: &str) -> Option<String> {
    uri.rsplit(['/', '\\']).next().map(str::to_string).filter(|s| !s.is_empty())
}

/// **Resolve a Redfish media URI onto a local file.**
///
/// A real BMC *pulls* the image over http(s)/NFS/CIFS. This service fronts local
/// KVM, so it resolves a `file://` URI or an absolute path and **refuses a remote
/// scheme by name** rather than pretending to have fetched it. That limitation is a
/// property of the emulator, not of the protocol: draupnir's client is unchanged and
/// still sends whatever URI a real BMC would be given.
fn resolve_media(uri: &str) -> std::result::Result<String, String> {
    let path = if let Some(rest) = uri.strip_prefix("file://") {
        // `file:///abs/path` — the authority is empty for a local file.
        let rest = rest.strip_prefix("localhost").unwrap_or(rest);
        if !rest.starts_with('/') {
            return Err(format!(
                "This service resolves `file://` URIs with an absolute path; `{uri}` has none."
            ));
        }
        percent_decode(rest)
    } else if uri.starts_with('/') {
        uri.to_string()
    } else {
        let scheme = uri.split_once("://").map(|(s, _)| s).unwrap_or("<none>");
        return Err(format!(
            "This BMC fronts local KVM and mounts only `file://` URIs or absolute paths; \
             it does not fetch `{scheme}` media. A real BMC would."
        ));
    };
    if std::path::Path::new(&path).is_file() {
        Ok(path)
    } else {
        Err(format!(
            "No file exists at `{path}` on the host running this service."
        ))
    }
}

// ===========================================================================
// Unit tests — the PURE halves. The wire conformance lives in
// tests/redfish_server_conformance.rs, anchored to DMTF's own fixtures.
// ===========================================================================

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

    /// The registry templates render with their arguments substituted — the check
    /// that a `MessageArgs` array and the `Message` string actually agree.
    #[test]
    fn registry_messages_render_their_arguments() {
        assert_eq!(
            ACTION_PARAMETER_VALUE_NOT_IN_LIST.render(&[
                "Reboot",
                prop::RESET_TYPE,
                wire::ACTION_RESET
            ]),
            "The value 'Reboot' for the parameter ResetType in the action \
             #ComputerSystem.Reset is not in the list of acceptable values."
        );
        assert_eq!(
            RESOURCE_MISSING_AT_URI.render(&["file:///nope.iso"]),
            "The resource at the URI 'file:///nope.iso' was not found."
        );
        // A zero-arg message renders verbatim.
        assert_eq!(NO_VALID_SESSION.render(&[]), NO_VALID_SESSION.template);
        // No `%N` may survive a full substitution.
        for m in ALL_MESSAGES {
            let args: Vec<&str> = (0..m.nargs).map(|_| "X").collect();
            let out = m.render(&args);
            assert!(!out.contains('%'), "{} left a placeholder: {out}", m.id);
        }
    }

    #[test]
    fn message_ids_are_registry_qualified() {
        assert_eq!(
            RESOURCE_MISSING_AT_URI.message_id(),
            "Base.1.19.0.ResourceMissingAtURI"
        );
        for m in ALL_MESSAGES {
            assert!(
                m.message_id().starts_with("Base.1.19.0."),
                "{} is unqualified",
                m.id
            );
        }
    }

    /// The routing table is built from the same `wire` functions the client builds
    /// its URLs from. RED-when-broken: hand-type any route and this fails.
    #[test]
    fn every_route_is_the_path_the_client_would_ask_for() {
        let cfg = NodeConfig::new("System.Embedded.1").media_slot("CD");
        let r = Routes::for_node(&cfg);
        assert_eq!(r.system, "/redfish/v1/Systems/System.Embedded.1");
        assert_eq!(
            r.reset,
            "/redfish/v1/Systems/System.Embedded.1/Actions/ComputerSystem.Reset"
        );
        assert_eq!(
            r.vm_insert,
            "/redfish/v1/Systems/System.Embedded.1/VirtualMedia/CD/Actions/VirtualMedia.InsertMedia"
        );
        assert_eq!(
            r.vm_eject,
            "/redfish/v1/Systems/System.Embedded.1/VirtualMedia/CD/Actions/VirtualMedia.EjectMedia"
        );
        assert_eq!(r.vm, "/redfish/v1/Systems/System.Embedded.1/VirtualMedia/CD");
        assert_eq!(
            r.vm_collection,
            "/redfish/v1/Systems/System.Embedded.1/VirtualMedia"
        );
    }

    #[test]
    fn media_resolution_refuses_by_name() {
        // A remote scheme is named, not silently swallowed.
        let e = resolve_media("https://depot/x.iso").unwrap_err();
        assert!(e.contains("https"), "names the scheme: {e}");
        // A path that is not there is named.
        let e = resolve_media("/nonexistent/never-built.iso").unwrap_err();
        assert!(e.contains("/nonexistent/never-built.iso"), "{e}");
        // A directory is not a medium.
        assert!(resolve_media("/tmp").is_err());
        // A real file resolves, by path and by file:// URI.
        let real = std::env::current_exe().unwrap();
        let real = real.to_string_lossy().into_owned();
        assert_eq!(resolve_media(&real).unwrap(), real);
        assert_eq!(resolve_media(&format!("file://{real}")).unwrap(), real);
        // Percent-encoding is DECODED, so a media path with a space or a non-ASCII
        // character (this box keeps its ISOs under `Hämtningar`) resolves.
        let odd = std::env::temp_dir().join(format!("draupnir rf-server å-{}.iso", std::process::id()));
        std::fs::write(&odd, b"medium").unwrap();
        let encoded = odd
            .to_string_lossy()
            .replace(' ', "%20")
            .replace('å', "%C3%A5");
        assert_eq!(
            resolve_media(&format!("file://{encoded}")).unwrap(),
            odd.to_string_lossy()
        );
        let _ = std::fs::remove_file(&odd);
    }

    #[test]
    fn percent_decode_handles_utf8_and_leaves_junk_alone() {
        assert_eq!(percent_decode("/H%C3%A4mtningar"), "/Hämtningar");
        assert_eq!(percent_decode("/a%zz"), "/a%zz", "invalid escape survives");
        assert_eq!(percent_decode("/plain"), "/plain");
    }

    #[test]
    fn basename_is_the_last_segment() {
        assert_eq!(basename("file:///a/b/c.iso").as_deref(), Some("c.iso"));
        assert_eq!(basename("x.iso").as_deref(), Some("x.iso"));
        assert_eq!(basename("/a/b/").as_deref(), None);
    }

    /// The node advertises exactly the targets it can apply, plus `None`. A token in
    /// `BOOT_TARGET_ALLOWABLE` that maps to no `BootOrder` must not appear here.
    #[test]
    fn the_node_honours_only_the_targets_it_can_actually_apply() {
        let honoured = boot_targets_this_node_honours();
        assert!(honoured.contains(&"Cd"));
        assert!(honoured.contains(&"Hdd"));
        assert!(honoured.contains(&"None"));
        assert!(!honoured.contains(&"Pxe"), "no PXE on a KVM front end");
        assert!(!honoured.contains(&"BiosSetup"));
    }

    /// A backend that records the spec it was handed and never launches anything —
    /// the same shape the conformance suite uses.
    #[derive(Default)]
    struct Recorder {
        specs: Mutex<Vec<BootSpec>>,
    }
    impl Boot for Recorder {
        fn boot(&self, spec: &BootSpec) -> Result<Machine> {
            self.specs.lock().unwrap().push(spec.clone());
            Ok(Machine::started(format!("rec-{}", spec.name), spec))
        }
    }
    impl Lifecycle for Recorder {
        fn power_on(&self, _m: &Machine) -> Result<()> {
            Ok(())
        }
        fn power_off(&self, _m: &Machine) -> Result<()> {
            Ok(())
        }
        fn status(&self, _m: &Machine) -> Result<PowerState> {
            Ok(PowerState::On)
        }
    }

    fn service_with(cfg: NodeConfig) -> Service {
        Service {
            routes: Routes::for_node(&cfg),
            cfg,
            state: Arc::new(Mutex::new(NodeState::fresh())),
            backend: Arc::new(Recorder::default()),
        }
    }

    /// **The translation, proven at the spec level.** A `Cd` override with media in
    /// the tray produces a spec that boots OFF the medium; an `Hdd` override produces
    /// one that carries NO medium at all.
    #[test]
    fn the_boot_override_selects_which_spec_the_node_boots() {
        let iso = std::env::current_exe().unwrap().to_string_lossy().into_owned();
        let svc = service_with(
            NodeConfig::new("s1")
                .local_disk("/var/lib/node.qcow2")
                .sized(2048, 4),
        );
        {
            let mut s = svc.state.lock().unwrap();
            s.image_uri = Some(iso.clone());
            s.image_path = Some(iso.clone());
            s.inserted = true;
            s.override_enabled = wire::OVERRIDE_ONCE.into();
            s.override_target = Some(BootTarget::Cd);
        }
        let spec = svc.spec_for(&svc.state.lock().unwrap()).unwrap();
        assert_eq!(spec.boot_order, BootOrder::Medium);
        assert_eq!(spec.medium_path(), Some(iso.as_str()));
        assert_eq!(spec.mem_mb, 2048);
        assert_eq!(spec.cores, 4);

        // Flip ONLY the override. The media stays in the tray, exactly as it would on
        // a real machine — and the spec must still stop naming it.
        svc.state.lock().unwrap().override_target = Some(BootTarget::Hdd);
        let spec = svc.spec_for(&svc.state.lock().unwrap()).unwrap();
        assert_eq!(spec.boot_order, BootOrder::Disk);
        assert_eq!(
            spec.medium_path(),
            None,
            "an Hdd override must not leave the installer medium attached — that is \
             how a boot override gets accepted without ever being applied"
        );
    }

    #[test]
    fn an_override_the_node_cannot_apply_is_refused_by_name_not_coerced() {
        let svc = service_with(NodeConfig::new("s1"));
        let req = Request {
            method: "PATCH".into(),
            path: wire::system_path("s1"),
            headers: BTreeMap::new(),
            body: serde_json::to_vec(&json!({
                "Boot": { "BootSourceOverrideTarget": "Pxe" }
            }))
            .unwrap(),
        };
        let resp = svc.patch_system(&req);
        assert_eq!(resp.status, 400);
        let v: Value = serde_json::from_slice(&resp.body).unwrap();
        assert_eq!(v["error"]["code"], "Base.1.19.0.PropertyValueNotInList");
        assert!(
            v["error"]["message"].as_str().unwrap().contains("Pxe"),
            "the refusal quotes the value: {v}"
        );
        // ...and nothing was applied.
        assert_eq!(svc.state.lock().unwrap().override_target, None);
    }

    #[test]
    fn a_cd_override_with_an_empty_tray_refuses_instead_of_booting_something_else() {
        let svc = service_with(NodeConfig::new("s1").local_disk("/var/lib/node.qcow2"));
        {
            let mut s = svc.state.lock().unwrap();
            s.override_enabled = wire::OVERRIDE_ONCE.into();
            s.override_target = Some(BootTarget::Cd);
        }
        let err = svc.spec_for(&svc.state.lock().unwrap()).unwrap_err();
        assert!(err.contains("no virtual media is inserted"), "{err}");
        // The configured disk is NOT quietly substituted.
        assert!(!err.contains("qcow2"), "{err}");
    }

    #[test]
    fn a_hdd_override_on_a_diskless_node_refuses_instead_of_falling_back_to_the_medium() {
        let iso = std::env::current_exe().unwrap().to_string_lossy().into_owned();
        let svc = service_with(NodeConfig::new("s1")); // no local disk
        {
            let mut s = svc.state.lock().unwrap();
            s.image_path = Some(iso);
            s.inserted = true;
            s.override_enabled = wire::OVERRIDE_ONCE.into();
            s.override_target = Some(BootTarget::Hdd);
        }
        let err = svc.spec_for(&svc.state.lock().unwrap()).unwrap_err();
        assert!(err.contains("no local disk"), "{err}");
    }

    /// A one-time override is CONSUMED by the boot that applied it.
    #[test]
    fn a_once_override_does_not_steer_the_next_boot_too() {
        let iso = std::env::current_exe().unwrap().to_string_lossy().into_owned();
        let svc = service_with(NodeConfig::new("s1"));
        {
            let mut s = svc.state.lock().unwrap();
            s.image_uri = Some(iso.clone());
            s.image_path = Some(iso);
            s.inserted = true;
            s.override_enabled = wire::OVERRIDE_ONCE.into();
            s.override_target = Some(BootTarget::Cd);
        }
        assert_eq!(svc.power_up(wire::RESET_ON).status, 204);
        let s = svc.state.lock().unwrap();
        assert_eq!(s.override_enabled, wire::OVERRIDE_DISABLED);
        assert_eq!(s.override_target, None);
        assert_eq!(s.last_spec.as_ref().unwrap().boot_order, BootOrder::Medium);
    }

    #[test]
    fn a_bad_reset_type_is_refused_and_nothing_boots() {
        let svc = service_with(NodeConfig::new("s1"));
        let req = Request {
            method: "POST".into(),
            path: wire::reset_path("s1"),
            headers: BTreeMap::new(),
            body: serde_json::to_vec(&json!({ "ResetType": "Reboot" })).unwrap(),
        };
        let resp = svc.post_reset(&req);
        assert_eq!(resp.status, 400);
        let v: Value = serde_json::from_slice(&resp.body).unwrap();
        assert_eq!(
            v["error"]["code"],
            "Base.1.19.0.ActionParameterValueNotInList"
        );
        assert_eq!(v["error"]["@Message.ExtendedInfo"][0]["MessageArgs"][0], "Reboot");
        assert!(svc.state.lock().unwrap().machine.is_none(), "nothing booted");
    }

    #[test]
    fn a_reset_with_no_reset_type_names_the_missing_parameter() {
        let svc = service_with(NodeConfig::new("s1"));
        let req = Request {
            method: "POST".into(),
            path: wire::reset_path("s1"),
            headers: BTreeMap::new(),
            body: b"{}".to_vec(),
        };
        let resp = svc.post_reset(&req);
        assert_eq!(resp.status, 400);
        let v: Value = serde_json::from_slice(&resp.body).unwrap();
        assert_eq!(v["error"]["code"], "Base.1.19.0.ActionParameterMissing");
        assert!(v["error"]["message"].as_str().unwrap().contains("ResetType"));
    }

    #[test]
    fn insert_media_pointing_at_nothing_is_refused_by_name() {
        let svc = service_with(NodeConfig::new("s1"));
        let req = Request {
            method: "POST".into(),
            path: svc.routes.vm_insert.clone(),
            headers: BTreeMap::new(),
            body: serde_json::to_vec(&wire::insert_media_body("/nonexistent/never-built.iso"))
                .unwrap(),
        };
        let resp = svc.post_insert_media(&req);
        assert_eq!(resp.status, 400);
        let v: Value = serde_json::from_slice(&resp.body).unwrap();
        assert_eq!(v["error"]["code"], "Base.1.19.0.ResourceMissingAtURI");
        assert!(v["error"]["message"]
            .as_str()
            .unwrap()
            .contains("/nonexistent/never-built.iso"));
        // Nothing was mounted.
        assert!(!svc.state.lock().unwrap().inserted);
    }

    #[test]
    fn a_method_the_resource_does_not_take_answers_405_with_allow() {
        let svc = service_with(NodeConfig::new("s1").credentials("admin", "pw"));
        let auth = wire::basic_auth_header("admin", "pw");
        let mut headers = BTreeMap::new();
        headers.insert("authorization".to_string(), auth);
        // GET on an action target.
        let req = Request {
            method: "GET".into(),
            path: wire::reset_path("s1"),
            headers: headers.clone(),
            body: Vec::new(),
        };
        let resp = svc.dispatch(&req);
        assert_eq!(resp.status, 405);
        assert!(resp
            .headers
            .iter()
            .any(|(k, v)| k == "Allow" && v == "POST"));
        // POST on the ComputerSystem.
        let req = Request {
            method: "POST".into(),
            path: wire::system_path("s1"),
            headers,
            body: Vec::new(),
        };
        let resp = svc.dispatch(&req);
        assert_eq!(resp.status, 405);
        assert!(resp
            .headers
            .iter()
            .any(|(k, v)| k == "Allow" && v == "GET, PATCH"));
    }

    #[test]
    fn everything_below_the_service_root_needs_a_credential() {
        let svc = service_with(NodeConfig::new("s1").credentials("admin", "pw"));
        let unauth = |path: &str| Request {
            method: "GET".into(),
            path: path.into(),
            headers: BTreeMap::new(),
            body: Vec::new(),
        };
        // The two DSP0266 unauthenticated URIs are reachable...
        assert_eq!(svc.dispatch(&unauth(wire::PROTOCOL_VERSION_PATH)).status, 200);
        assert_eq!(svc.dispatch(&unauth(wire::SERVICE_ROOT_PATH)).status, 200);
        // ...and nothing else is.
        for p in [
            wire::SYSTEMS_PATH,
            &wire::system_path("s1"),
            &wire::virtual_media_path("s1", "CD"),
        ] {
            let r = svc.dispatch(&unauth(p));
            assert_eq!(r.status, 401, "{p}");
            assert!(r.headers.iter().any(|(k, _)| k == "WWW-Authenticate"), "{p}");
        }
        // A WRONG password is not a credential either.
        let mut headers = BTreeMap::new();
        headers.insert(
            "authorization".into(),
            wire::basic_auth_header("admin", "wrong"),
        );
        let req = Request {
            method: "GET".into(),
            path: wire::system_path("s1"),
            headers,
            body: Vec::new(),
        };
        assert_eq!(svc.dispatch(&req).status, 401);
    }

    #[test]
    fn an_unknown_uri_is_a_dmtf_shaped_404_naming_the_uri() {
        let svc = service_with(NodeConfig::new("s1").credentials("admin", ""));
        let mut headers = BTreeMap::new();
        headers.insert("authorization".into(), wire::basic_auth_header("admin", ""));
        let req = Request {
            method: "GET".into(),
            path: "/redfish/v1/Systems/other".into(),
            headers,
            body: Vec::new(),
        };
        let resp = svc.dispatch(&req);
        assert_eq!(resp.status, 404);
        let v: Value = serde_json::from_slice(&resp.body).unwrap();
        assert_eq!(v["error"]["code"], "Base.1.19.0.ResourceNotFound");
        assert!(v["error"]["message"]
            .as_str()
            .unwrap()
            .contains("/redfish/v1/Systems/other"));
    }

    #[test]
    fn malformed_json_is_reported_as_malformed_json() {
        let svc = service_with(NodeConfig::new("s1"));
        let req = Request {
            method: "POST".into(),
            path: wire::reset_path("s1"),
            headers: BTreeMap::new(),
            body: b"{not json".to_vec(),
        };
        let resp = svc.post_reset(&req);
        assert_eq!(resp.status, 400);
        let v: Value = serde_json::from_slice(&resp.body).unwrap();
        assert_eq!(v["error"]["code"], "Base.1.19.0.MalformedJSON");
    }

    #[test]
    fn a_freshly_started_node_reports_itself_off_with_an_empty_tray() {
        let svc = service_with(NodeConfig::new("s1"));
        let sys = svc.computer_system();
        assert_eq!(sys["PowerState"], "Off");
        assert_eq!(sys["Boot"]["BootSourceOverrideEnabled"], "Disabled");
        assert_eq!(sys["Boot"]["BootSourceOverrideTarget"], "None");
        let vm = svc.virtual_media();
        assert_eq!(vm["Inserted"], false);
        assert!(vm["Image"].is_null());
    }
}