s2-kit 0.4.0

The S2 energy flexibility standard (EN 50491-12-2) in Rust: the S2 JSON data model, a semantic validator, sans-IO Resource Manager and Customer Energy Manager session engines, and S2 Connect
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
//! Pairing as a state machine that refuses to advance when a rule is broken.
//!
//! The exchange is a **two-way** challenge–response, and the two directions are not
//! symmetrical in time: the client challenges first and the server answers in the same
//! round trip, then the server's challenge is answered one request later. Getting that
//! order wrong produces something that looks like authentication and proves nothing.
//!
//! ```text
//!   HTTPS client                                      HTTPS server
//!   ────────────                                      ────────────
//!   1. generate C_c
//!      POST /v1/requestPairing ───────────────────▶   2. R_c = HMAC(C_c, T ‖ binding)
//!         clientNodeDescription, C_c,                    (rate-limited, ≥ 1 s delay)
//!         versions, protocols, algorithms                generate C_s, attempt id
//!   4. check R_c                ◀───────────────────3. pairingAttemptId, R_c, C_s,
//!   5. R_s = HMAC(C_s, T ‖ binding)                     serverNodeDescription
//!   6A. POST /v1/requestConnectionDetails ───────▶   7A. check R_s
//!          R_s                  ◀───────────────────    ConnectionDetails
//!    or
//!   6B. POST /v1/postConnectionDetails ──────────▶   7B. check R_s
//!          R_s, ConnectionDetails
//!   8. POST /v1/finalizePairing {success} ───────▶   both sides store the pairing
//! ```
//!
//! Which of 6A and 6B applies is decided by [`Deployment::communication_server`], not by
//! preference: the side that will be the *communication* server is the side that has
//! connection details to give.
//!
//! `R_c` proves the server holds the pairing token **and** that the TLS identity answering
//! is the one the token was meant for — its leaf-certificate fingerprint in a LAN, its
//! domain name otherwise. `R_s` proves the client holds the token. Steps 2 through 8 are
//! authenticated by the `pairingAttemptId` the server issues, which is a bearer token.

use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec::Vec;

use serde::{Deserialize, Serialize};
use zeroize::{Zeroize, ZeroizeOnDrop};

use crate::types::{Duration, ProtocolVersion, Timestamp};

use super::{
    AccessToken, ChallengeResponse, CommunicationProtocol, ConnectError, Deployment,
    EndpointDescription, HmacBinding, HmacHashingAlgorithm, NodeDescription, NodeId, NodeIdAlias,
    PairingToken, Role,
};

/// How long a whole pairing attempt may take.
///
/// `S2C §Pairing`: "the pairing attempt must be finished within 15 seconds". Each side
/// keeps its own budget, because each side can only see its own clock.
pub const PAIRING_BUDGET: Duration = Duration::from_secs(15);

/// The delay the server must insert before answering `requestPairing`.
///
/// `S2C §2. Calculate clientHmacChallengeResponse`: "To mitigate brute-force attacks, the
/// server **must** enforce a mandatory delay of one second before sending its response to
/// the client. For any given node at the server, pairing attempts **must** be handled
/// sequentially, such that each second only one pairing attempt can be processed for a
/// node."
pub const MINIMUM_SERVER_DELAY: Duration = Duration::from_secs(1);

// ---------------------------------------------------------------------------
// Wire types — `s2-connect-pairing.yml`
// ---------------------------------------------------------------------------

/// The bearer token that authenticates steps 6 through 8 of one pairing attempt.
///
/// `S2C-OAS pairing/PairingAttemptId`: "a random string with a minimal length of 32
/// characters… generated by a cryptographically secure pseudorandom number generator. The
/// recommended method is to generate 24 random bytes and Base64 encode them."
#[derive(Clone, Zeroize, ZeroizeOnDrop, Serialize, Deserialize)]
#[serde(transparent)]
pub struct PairingAttemptId(String);

impl PairingAttemptId {
    /// The fewest characters the specification allows.
    pub const MIN_LEN: usize = 32;

    /// Wrap an identifier received from a peer.
    #[must_use]
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    /// Generate one from the recommended 24 bytes of entropy.
    pub fn from_entropy(bytes: &[u8]) -> Result<Self, ConnectError> {
        // 24 bytes Base64-encode to exactly the 32 characters the minimum requires.
        if bytes.len() < 24 {
            return Err(ConnectError::WeakSecret {
                got: bytes.len(),
                need: 24,
            });
        }
        Ok(Self(super::base64_encode(bytes)))
    }

    /// The string, which is what travels in `Authorization: Bearer …`.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Whether a presented identifier is this one, compared in constant time.
    #[must_use]
    pub fn verify(&self, presented: &str) -> bool {
        use subtle::ConstantTimeEq as _;
        self.0.len() == presented.len() && bool::from(self.0.as_bytes().ct_eq(presented.as_bytes()))
    }
}

impl core::fmt::Debug for PairingAttemptId {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str("PairingAttemptId(<redacted>)")
    }
}

/// The body of `POST /v1/requestPairing`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PairingRequest {
    /// Who the client is.
    pub client_node_description: NodeDescription,
    /// Where the client's endpoint runs.
    pub client_endpoint_description: EndpointDescription,
    /// Which node at the endpoint, when the client knows its identifier.
    ///
    /// `S2C-OAS pairing/requestPairing`: "The (optional) properties nodeId and nodeIdAlias
    /// may never be used at the same time." [`PairingClient`] cannot set both.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub node_id: Option<NodeId>,
    /// Which node at the endpoint, when the client only has the alias from the code.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub node_id_alias: Option<NodeIdAlias>,
    /// How the client can carry S2 messages afterwards.
    pub supported_communication_protocols: Vec<CommunicationProtocol>,
    /// **S2 JSON** message versions — the same versions the `Handshake` negotiates,
    /// spelled the way `S2C` spells them (E25).
    pub supported_s2_message_versions: Vec<ProtocolVersion>,
    /// The hash functions the client accepts; SHA-256 "**must** be present".
    pub supported_hmac_hashing_algorithms: Vec<HmacHashingAlgorithm>,
    /// `C_c`: a nonce of at least 32 bytes, Base64.
    pub client_hmac_challenge: String,
    /// Pair anyway, even with no S2 message version in common.
    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
    pub force_pairing: bool,
}

/// The `200` body of `requestPairing`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PairingAccepted {
    /// The bearer for the rest of the attempt.
    pub pairing_attempt_id: PairingAttemptId,
    /// Who the server is.
    pub server_node_description: NodeDescription,
    /// Where the server's endpoint runs.
    pub server_endpoint_description: EndpointDescription,
    /// The hash function the server chose from the client's list.
    pub selected_hmac_hashing_algorithm: HmacHashingAlgorithm,
    /// `R_c`: the server's answer to the client's challenge.
    pub client_hmac_challenge_response: String,
    /// `C_s`: the server's own nonce.
    pub server_hmac_challenge: String,
}

/// Why a pairing was refused. `S2C-OAS pairing/PairingResponseErrorMessage`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum PairingErrorMessage {
    /// Two CEMs, or two RMs.
    InvalidCombinationOfRoles,
    /// No S2 JSON message version in common.
    IncompatibleS2MessageVersions,
    /// No hash function in common.
    IncompatibleHmacHashingAlgorithms,
    /// No transport in common.
    IncompatibleCommunicationProtocols,
    /// The alias or identifier names no node here.
    NodeNotFound,
    /// The endpoint hosts more than one node and the client named none.
    NoNodeIdProvided,
    /// No pairing token is active for that node.
    NoValidPairingTokenOnPairingServer,
    /// The body was not understood.
    ParsingError,
    /// Anything else.
    Other,
}

/// The `400` body of `requestPairing`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PairingRefused {
    /// Which of the enumerated reasons.
    pub error_message: PairingErrorMessage,
    /// Free text, for a log.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub additional_info: Option<String>,
}

/// Where a communication client should connect, and with what.
///
/// `S2C-OAS pairing/ConnectionDetails`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConnectionDetails {
    /// The base URL of the session-initiation API.
    pub initiate_session_url: String,
    /// The first access token, which session initiation will rotate.
    pub access_token: AccessToken,
    /// Fingerprints of the **CA** certificate the communication server uses, by hashing
    /// algorithm; `SHA256` is always present.
    ///
    /// Note that this is the *CA*, whereas the HMAC binding uses the **leaf**
    /// (`S2C §Challenge response process`). They are different certificates and the
    /// specification names them differently in the two places; conflating them produces a
    /// pairing that verifies and a connection that does not.
    ///
    /// "Mandatory when the pairing client will become the communication server."
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub certificate_fingerprint: BTreeMap<String, String>,
}

impl ConnectionDetails {
    /// The key `S2C` requires in [`certificate_fingerprint`](Self::certificate_fingerprint).
    ///
    /// (The OpenAPI's description spells it `"SHA265"`; the prose and every
    /// implementation spell it `SHA256` — erratum E31.)
    pub const SHA256: &'static str = "SHA256";

    /// Details with no fingerprint: what a communication server hands out in 7A, where the
    /// client pins the CA it saw during pairing instead.
    #[must_use]
    pub fn new(initiate_session_url: impl Into<String>, access_token: AccessToken) -> Self {
        Self {
            initiate_session_url: initiate_session_url.into(),
            access_token,
            certificate_fingerprint: BTreeMap::new(),
        }
    }

    /// Add the SHA-256 fingerprint of the CA, written the way `S2C` encodes it: plain
    /// lowercase hexadecimal.
    ///
    /// Mandatory in 6B ("when the pairing client will become the communication server"),
    /// harmless in 7A.
    #[must_use]
    pub fn with_ca_fingerprint(mut self, sha256: &[u8; 32]) -> Self {
        use core::fmt::Write as _;
        let mut hex = String::with_capacity(64);
        for b in sha256 {
            let _ = write!(hex, "{b:02x}");
        }
        self.certificate_fingerprint
            .insert(String::from(Self::SHA256), hex);
        self
    }

    /// The SHA-256 fingerprint of the CA, if one was given and it is 32 bytes of hex —
    /// either case, with or without colons.
    #[must_use]
    pub fn ca_fingerprint(&self) -> Option<[u8; 32]> {
        let hex = self.certificate_fingerprint.get(Self::SHA256)?;
        match super::HmacBinding::from_hex_fingerprint(hex).ok()? {
            super::HmacBinding::LeafFingerprint(bytes) => bytes.try_into().ok(),
            super::HmacBinding::DomainName(_) => None,
        }
    }
}

/// The body of `requestConnectionDetails` (6A).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConnectionDetailsRequest {
    /// `R_s`: the client's answer to the server's challenge.
    pub server_hmac_challenge_response: String,
}

/// The body of `postConnectionDetails` (6B).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConnectionDetailsPost {
    /// `R_s`: the client's answer to the server's challenge.
    pub server_hmac_challenge_response: String,
    /// What the client, as the future communication server, is offering.
    pub connection_details: ConnectionDetails,
}

/// The body of `finalizePairing` (8).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct FinalizePairing {
    /// Whether the client is satisfied and has stored the pairing.
    pub success: bool,
}

/// A completed pairing, ready to be stored.
#[derive(Debug, Clone)]
pub struct Pairing {
    /// This node.
    pub local: NodeId,
    /// The node paired with.
    pub remote: NodeDescription,
    /// The remote endpoint.
    pub remote_endpoint: EndpointDescription,
    /// Where to initiate sessions, and with what.
    pub details: ConnectionDetails,
    /// Which side will be the communication server.
    pub communication_server: Role,
    /// The S2 JSON message versions both sides offered, newest first — what a later
    /// `Handshake` or `initiateSession` negotiates from.
    pub s2_message_versions: Vec<ProtocolVersion>,
}

// ---------------------------------------------------------------------------
// The client
// ---------------------------------------------------------------------------

/// How far a pairing attempt has got.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PairingStep {
    /// Nothing has been sent.
    Start,
    /// `requestPairing` has been sent; the server's answer has not arrived.
    AwaitingAcceptance,
    /// `R_c` is verified; connection details have not been exchanged.
    Authenticated,
    /// Connection details are known; `finalizePairing` has not been sent.
    DetailsExchanged,
    /// The pairing is complete and may be stored.
    Paired,
    /// The attempt failed and may not be resumed.
    Failed,
}

impl PairingStep {
    const fn name(self) -> &'static str {
        match self {
            PairingStep::Start => "the start of pairing",
            PairingStep::AwaitingAcceptance => "the server's acceptance",
            PairingStep::Authenticated => "connection details",
            PairingStep::DetailsExchanged => "finalization",
            PairingStep::Paired => "a completed pairing",
            PairingStep::Failed => "a failed pairing",
        }
    }
}

/// Which of steps 6A and 6B the client must take next.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NextStep {
    /// 6A — the pairing server will be the communication server, so ask it for details.
    RequestConnectionDetails,
    /// 6B — the pairing *client* will be the communication server, so send details.
    PostConnectionDetails,
}

/// The pairing client: the side that types in the code and makes the HTTPS requests.
///
/// ```
/// # use s2_kit::connect::proto::*;
/// # use s2_kit::types::Timestamp;
/// # fn me() -> NodeDescription { NodeDescription {
/// #   id: NodeId::parse("cem-1").unwrap(), brand: "Acme".into(), logo_url: None,
/// #   kind: "CEM".into(), model_name: "Hub".into(), user_defined_name: None,
/// #   role: Role::Cem } }
/// let code = PairingCode::parse("evse7-A1b2C3", TokenKind::Static)?;
/// let now = Timestamp::from_unix(1_700_000_000, 0);
///
/// let mut client = PairingClient::start(me(), EndpointDescription::default(), code, now);
/// let body = client.request_pairing(&[0xA5; 32])?;
/// assert_eq!(client.step(), PairingStep::AwaitingAcceptance);
/// // The alias from the code names the node; `nodeId` stays unset, as the spec requires.
/// assert!(body.node_id.is_none());
/// assert_eq!(body.node_id_alias.as_ref().unwrap().0, "evse7");
/// # Ok::<(), Box<dyn core::error::Error>>(())
/// ```
#[derive(Debug)]
pub struct PairingClient {
    local: NodeDescription,
    local_endpoint: EndpointDescription,
    code: super::PairingCode,
    /// Known only once the server has presented a certificate, which is why it arrives
    /// with [`PairingClient::accept`] rather than at the start.
    binding: Option<HmacBinding>,
    started: Timestamp,
    step: PairingStep,
    /// `C_c`, kept so the server's `R_c` can be checked against it in step 4.
    challenge: Option<Vec<u8>>,
    s2_message_versions: Vec<ProtocolVersion>,
    protocols: Vec<CommunicationProtocol>,
    force: bool,
    accepted: Option<PairingAccepted>,
    /// The server's handle on the attempt, remembered **before** anything about the
    /// server's answer is judged.
    ///
    /// It is not ours: it names a slot the server is holding open for us, and the server's
    /// rate limit is one attempt per node per second, so an attempt left in flight refuses
    /// every retry with `503` for the whole fifteen-second budget. A client that decides
    /// the server failed its challenge still has to give the slot back, and cannot if it
    /// only kept the id on the success path.
    attempt_id: Option<PairingAttemptId>,
    details: Option<ConnectionDetails>,
    communication_server: Option<Role>,
}

impl PairingClient {
    /// Begin an attempt. The fifteen-second clock starts here.
    #[must_use]
    pub fn start(
        local: NodeDescription,
        local_endpoint: EndpointDescription,
        code: super::PairingCode,
        now: Timestamp,
    ) -> Self {
        Self {
            local,
            local_endpoint,
            code,
            binding: None,
            started: now,
            step: PairingStep::Start,
            challenge: None,
            // Both, newest first — the deployed ecosystem still negotiates the beta.
            s2_message_versions: alloc::vec![
                crate::types::WireProfile::V1_0_0.connect_version(),
                crate::types::WireProfile::V0_0_2Beta.connect_version(),
            ],
            protocols: alloc::vec![CommunicationProtocol::WebSocket],
            force: false,
            accepted: None,
            attempt_id: None,
            details: None,
            communication_server: None,
        }
    }

    /// Offer a different set of S2 JSON message versions, newest first.
    #[must_use]
    pub fn with_s2_message_versions(mut self, versions: Vec<ProtocolVersion>) -> Self {
        self.s2_message_versions = versions;
        self
    }

    /// Pair even with no S2 message version in common.
    ///
    /// The two nodes will not be able to talk until one of them is updated, which is
    /// exactly what the flag is for: `S2C-OAS pairing` calls it out as something "could
    /// later be solved through a software update".
    #[must_use]
    pub fn forcing(mut self) -> Self {
        self.force = true;
        self
    }

    /// How far the attempt has got.
    #[must_use]
    pub const fn step(&self) -> PairingStep {
        self.step
    }

    /// The bearer for steps 6 through 8, once the server has issued one.
    #[must_use]
    pub fn attempt_id(&self) -> Option<&PairingAttemptId> {
        self.attempt_id.as_ref()
    }

    /// Step 1: build `requestPairing` from 32 bytes of cryptographically secure
    /// randomness.
    ///
    /// The randomness is a parameter because this layer has no business drawing it: a
    /// test needs it pinned, and a driver knows where the system's entropy lives.
    pub fn request_pairing(&mut self, challenge: &[u8]) -> Result<PairingRequest, ConnectError> {
        self.expect(PairingStep::Start)?;
        if challenge.len() < 32 {
            self.step = PairingStep::Failed;
            return Err(ConnectError::WeakSecret {
                got: challenge.len(),
                need: 32,
            });
        }
        self.challenge = Some(challenge.to_vec());
        self.step = PairingStep::AwaitingAcceptance;
        Ok(PairingRequest {
            client_node_description: self.local.clone(),
            client_endpoint_description: self.local_endpoint.clone(),
            // "may never be used at the same time" — the alias wins, because it is what
            // the user typed.
            node_id: None,
            node_id_alias: self.code.alias.clone(),
            supported_communication_protocols: self.protocols.clone(),
            supported_s2_message_versions: self.s2_message_versions.clone(),
            supported_hmac_hashing_algorithms: alloc::vec![HmacHashingAlgorithm::Sha256],
            client_hmac_challenge: super::base64_encode(challenge),
            force_pairing: self.force,
        })
    }

    /// Step 4: check `clientHmacChallengeResponse`, and decide which of 6A and 6B follows.
    ///
    /// This is the moment the client learns it is talking to something that holds the same
    /// pairing token *and* is the TLS identity the token was meant for. A man in the
    /// middle who terminates TLS with his own certificate computes a different `R_c` and
    /// is refused here.
    ///
    /// `S2C §4`: "in case of a local server, the TLS certificate fingerprint is part of
    /// the challenge. So if the challenge succeeds, the certificate fingerprint is
    /// correct, and the certificate can be trusted. The client **must** pin the
    /// self-signed CA (root) certificate."
    ///
    /// `server_deployment` is how the server was reached — [`Deployment::Lan`] for a
    /// `.local` endpoint, [`Deployment::Wan`] for one verified against the public PKI —
    /// and is used only when the server's endpoint description omits its own. This
    /// node's deployment is the one its own [`EndpointDescription`] states, LAN when it
    /// states none.
    pub fn accept(
        &mut self,
        accepted: PairingAccepted,
        binding: HmacBinding,
        server_deployment: Deployment,
        now: Timestamp,
    ) -> Result<NextStep, ConnectError> {
        self.expect(PairingStep::AwaitingAcceptance)?;
        // Before anything can refuse: whatever the verdict below, the server is holding an
        // attempt for us and this is the only way to hand it back.
        self.attempt_id = Some(accepted.pairing_attempt_id.clone());
        self.within_budget(now)?;
        self.binding = Some(binding);

        if !self
            .local
            .role
            .can_pair_with(accepted.server_node_description.role)
        {
            self.step = PairingStep::Failed;
            return Err(ConnectError::SameRole(self.local.role));
        }

        let challenge = self.challenge.as_ref().ok_or(ConnectError::OutOfOrder {
            got: "the server's acceptance",
            expected: "the start of pairing",
        })?;
        let binding = self.binding.as_ref().ok_or(ConnectError::ChallengeFailed)?;
        let expected = ChallengeResponse::compute(challenge, &self.code.token, binding)?;
        if !expected.verify(&accepted.client_hmac_challenge_response) {
            self.step = PairingStep::Failed;
            return Err(ConnectError::ChallengeFailed);
        }

        // Which side is the communication server is decided by the two deployments and
        // the two roles, never by preference.
        let server_deployment = accepted
            .server_endpoint_description
            .deployment
            .unwrap_or(server_deployment);
        let local_deployment = self.local_endpoint.deployment.unwrap_or(Deployment::Lan);
        let (cem, rm) = if self.local.role == Role::Cem {
            (local_deployment, server_deployment)
        } else {
            (server_deployment, local_deployment)
        };
        let communication_server = Deployment::communication_server(cem, rm);
        self.communication_server = Some(communication_server);

        self.accepted = Some(accepted);
        self.step = PairingStep::Authenticated;
        Ok(if communication_server == self.local.role {
            NextStep::PostConnectionDetails
        } else {
            NextStep::RequestConnectionDetails
        })
    }

    /// Step 5: `R_s`, the answer to the server's challenge, Base64.
    ///
    /// Goes in the body of whichever of 6A and 6B [`Self::accept`] selected.
    pub fn server_challenge_response(&self) -> Result<String, ConnectError> {
        let accepted = self.accepted.as_ref().ok_or(ConnectError::OutOfOrder {
            got: "a challenge response",
            expected: "the server's acceptance",
        })?;
        let binding = self.binding.as_ref().ok_or(ConnectError::OutOfOrder {
            got: "a challenge response",
            expected: "the server's acceptance",
        })?;
        let challenge = super::base64_decode(&accepted.server_hmac_challenge)
            .ok_or(ConnectError::ChallengeFailed)?;
        Ok(ChallengeResponse::compute(&challenge, &self.code.token, binding)?.as_base64())
    }

    /// Step 6A: the body to send when the pairing server is the communication server.
    pub fn request_connection_details(&self) -> Result<ConnectionDetailsRequest, ConnectError> {
        Ok(ConnectionDetailsRequest {
            server_hmac_challenge_response: self.server_challenge_response()?,
        })
    }

    /// Step 6B: the body to send when *this* node is the communication server.
    pub fn post_connection_details(
        &mut self,
        details: ConnectionDetails,
        now: Timestamp,
    ) -> Result<ConnectionDetailsPost, ConnectError> {
        // "The key `SHA256` must always be provided": without it the pairing server, which
        // is about to become our communication client, has nothing to pin.
        if details.ca_fingerprint().is_none() {
            return Err(ConnectError::OutOfOrder {
                got: "connection details without a SHA256 CA fingerprint",
                expected: "certificateFingerprint.SHA256",
            });
        }
        let response = self.server_challenge_response()?;
        self.connection_details(details.clone(), now)?;
        Ok(ConnectionDetailsPost {
            server_hmac_challenge_response: response,
            connection_details: details,
        })
    }

    /// Record the connection details, however they arrived.
    pub fn connection_details(
        &mut self,
        details: ConnectionDetails,
        now: Timestamp,
    ) -> Result<(), ConnectError> {
        self.expect(PairingStep::Authenticated)?;
        self.within_budget(now)?;
        self.details = Some(details);
        self.step = PairingStep::DetailsExchanged;
        Ok(())
    }

    /// Step 8: the body of `finalizePairing`, and the pairing to store.
    pub fn finalize(&mut self, now: Timestamp) -> Result<(FinalizePairing, Pairing), ConnectError> {
        self.expect(PairingStep::DetailsExchanged)?;
        self.within_budget(now)?;
        let accepted = self.accepted.take().ok_or(ConnectError::OutOfOrder {
            got: "finalization",
            expected: "the server's acceptance",
        })?;
        let details = self.details.take().ok_or(ConnectError::OutOfOrder {
            got: "finalization",
            expected: "connection details",
        })?;
        self.step = PairingStep::Paired;
        Ok((
            FinalizePairing { success: true },
            Pairing {
                local: self.local.id,
                remote: accepted.server_node_description,
                remote_endpoint: accepted.server_endpoint_description,
                details,
                communication_server: self.communication_server.unwrap_or(Role::Cem),
                s2_message_versions: self.s2_message_versions.clone(),
            },
        ))
    }

    /// Give up, telling the server so. `S2C §8`: the client may finalize with
    /// `success: false` "to let the server know it was not satisfied".
    pub fn abandon(&mut self) -> FinalizePairing {
        self.step = PairingStep::Failed;
        FinalizePairing { success: false }
    }

    fn expect(&mut self, step: PairingStep) -> Result<(), ConnectError> {
        if self.step == step {
            return Ok(());
        }
        let got = self.step.name();
        self.step = PairingStep::Failed;
        Err(ConnectError::OutOfOrder {
            got,
            expected: step.name(),
        })
    }

    fn within_budget(&mut self, now: Timestamp) -> Result<(), ConnectError> {
        if now.saturating_duration_since(self.started) > PAIRING_BUDGET {
            self.step = PairingStep::Failed;
            return Err(ConnectError::Expired {
                what: "pairing",
                limit: PAIRING_BUDGET,
            });
        }
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// The server
// ---------------------------------------------------------------------------

/// The pairing server: the side that holds the token and answers.
///
/// It carries the two rules a request handler tends to lose — one attempt per node per
/// second, and a response delayed by at least a second — as state rather than as
/// discipline. `s2energy`'s S2 Connect layer has exactly these as an open issue.
#[derive(Debug)]
pub struct PairingServer {
    local: NodeDescription,
    local_endpoint: EndpointDescription,
    binding: HmacBinding,
    s2_message_versions: Vec<ProtocolVersion>,
    protocols: Vec<CommunicationProtocol>,
    /// The attempt currently in flight, if any.
    attempt: Option<Attempt>,
    /// When the last attempt for this node finished, for the rate limit.
    last_finished: Option<Timestamp>,
    /// The answer we owe the client, held until the mandatory second has elapsed.
    pending: Option<(Timestamp, PairingAccepted)>,
}

#[derive(Debug)]
struct Attempt {
    id: PairingAttemptId,
    started: Timestamp,
    /// `C_s`, kept so the client's `R_s` can be checked against it.
    expected_response: ChallengeResponse,
    client: NodeDescription,
    client_endpoint: EndpointDescription,
    s2_message_versions: Vec<ProtocolVersion>,
    details: Option<ConnectionDetails>,
    verified: bool,
    /// Whether the *client* will be the communication server — 6B — rather than this
    /// node — 6A. Decided from the two deployments when the attempt starts, so a client
    /// that takes the other branch is refused rather than obeyed.
    client_is_communication_server: bool,
}

impl PairingServer {
    /// A server for one node, bound to the identity clients will verify against.
    #[must_use]
    pub fn new(
        local: NodeDescription,
        local_endpoint: EndpointDescription,
        binding: HmacBinding,
    ) -> Self {
        Self {
            local,
            local_endpoint,
            binding,
            s2_message_versions: alloc::vec![
                crate::types::WireProfile::V1_0_0.connect_version(),
                crate::types::WireProfile::V0_0_2Beta.connect_version(),
            ],
            protocols: alloc::vec![CommunicationProtocol::WebSocket],
            attempt: None,
            last_finished: None,
            pending: None,
        }
    }

    /// Offer a different set of S2 JSON message versions, newest first.
    #[must_use]
    pub fn with_s2_message_versions(mut self, versions: Vec<ProtocolVersion>) -> Self {
        self.s2_message_versions = versions;
        self
    }

    /// Steps 2 and 3: handle `requestPairing`.
    ///
    /// Returns the `200` body **and the instant before which it may not be sent**. The
    /// delay is not advisory: with a four-character token there are 14.7 million
    /// possibilities, and one guess per second is the difference between a brute force
    /// taking months and taking an afternoon.
    ///
    /// A refusal consumes the rate-limit slot just as a success does, which is what makes
    /// the limit worth anything.
    ///
    /// # Errors
    ///
    /// [`ConnectError::RateLimited`] should become `503`; a [`PairingRefused`] carried in
    /// [`ConnectError::Refused`] should become `400` with that body.
    pub fn request_pairing(
        &mut self,
        request: &PairingRequest,
        token: &PairingToken,
        server_challenge: &[u8],
        attempt_id: PairingAttemptId,
        now: Timestamp,
    ) -> Result<(Timestamp, PairingAccepted), ConnectError> {
        if let Some(attempt) = &self.attempt
            && now.saturating_duration_since(attempt.started) <= PAIRING_BUDGET
        {
            return Err(ConnectError::RateLimited);
        }
        if let Some(finished) = self.last_finished
            && now.saturating_duration_since(finished) < MINIMUM_SERVER_DELAY
        {
            return Err(ConnectError::RateLimited);
        }

        let result = self.answer(request, token, server_challenge, attempt_id, now);
        if result.is_err() {
            self.last_finished = Some(now);
            self.attempt = None;
        }
        result
    }

    fn answer(
        &mut self,
        request: &PairingRequest,
        token: &PairingToken,
        server_challenge: &[u8],
        attempt_id: PairingAttemptId,
        now: Timestamp,
    ) -> Result<(Timestamp, PairingAccepted), ConnectError> {
        use PairingErrorMessage as E;

        // The checks in the order `S2C §1. Request pairing` tabulates them.
        if !self
            .local
            .role
            .can_pair_with(request.client_node_description.role)
        {
            return Err(refused(E::InvalidCombinationOfRoles));
        }
        if !request
            .supported_hmac_hashing_algorithms
            .contains(&HmacHashingAlgorithm::Sha256)
        {
            return Err(refused(E::IncompatibleHmacHashingAlgorithms));
        }
        if !request
            .supported_communication_protocols
            .iter()
            .any(|p| self.protocols.contains(p))
        {
            return Err(refused(E::IncompatibleCommunicationProtocols));
        }
        // A version mismatch is refusable, but `forcePairing` overrides it: the nodes
        // pair now and talk after a software update.
        let common = request
            .supported_s2_message_versions
            .iter()
            .filter(|v| self.s2_message_versions.iter().any(|ours| ours.matches(v)))
            .cloned()
            .collect::<Vec<_>>();
        if common.is_empty() && !request.force_pairing {
            return Err(refused(E::IncompatibleS2MessageVersions));
        }
        if request.node_id.is_some() && request.node_id_alias.is_some() {
            return Err(refused(E::ParsingError));
        }

        let client_challenge = super::base64_decode(&request.client_hmac_challenge)
            .ok_or_else(|| refused(E::ParsingError))?;
        // `R_c`: prove to the client that we hold the token and are the identity it
        // reached.
        let client_response = ChallengeResponse::compute(&client_challenge, token, &self.binding)?;
        // `C_s` / the response we will expect back in step 6.
        let expected_response = ChallengeResponse::compute(server_challenge, token, &self.binding)?;

        let accepted = PairingAccepted {
            pairing_attempt_id: attempt_id.clone(),
            server_node_description: self.local.clone(),
            server_endpoint_description: self.local_endpoint.clone(),
            selected_hmac_hashing_algorithm: HmacHashingAlgorithm::Sha256,
            client_hmac_challenge_response: client_response.as_base64(),
            server_hmac_challenge: super::base64_encode(server_challenge),
        };

        let client_deployment = request
            .client_endpoint_description
            .deployment
            .unwrap_or(Deployment::Lan);
        let own_deployment = self.local_endpoint.deployment.unwrap_or(Deployment::Lan);
        let (cem, rm) = if self.local.role == Role::Cem {
            (own_deployment, client_deployment)
        } else {
            (client_deployment, own_deployment)
        };
        let client_is_communication_server =
            Deployment::communication_server(cem, rm) == request.client_node_description.role;

        self.attempt = Some(Attempt {
            id: attempt_id,
            started: now,
            expected_response,
            client: request.client_node_description.clone(),
            client_endpoint: request.client_endpoint_description.clone(),
            s2_message_versions: common,
            details: None,
            verified: false,
            client_is_communication_server,
        });
        let send_after = now.checked_add(MINIMUM_SERVER_DELAY).unwrap_or(now);
        self.pending = Some((send_after, accepted.clone()));
        Ok((send_after, accepted))
    }

    /// When the driver should next do something: the moment the delayed answer becomes
    /// sendable, or the moment the attempt's budget runs out.
    #[must_use]
    pub fn poll_timeout(&self) -> Option<Timestamp> {
        self.pending.as_ref().map(|(at, _)| *at).or_else(|| {
            self.attempt
                .as_ref()
                .map(|a| a.started.checked_add(PAIRING_BUDGET).unwrap_or(a.started))
        })
    }

    /// Take the delayed answer, if the mandatory second has elapsed.
    ///
    /// Returning `None` early is the point: a driver that loops on this cannot answer
    /// sooner than the specification allows, however tempting it is to.
    pub fn poll_response(&mut self, now: Timestamp) -> Option<PairingAccepted> {
        let (at, _) = self.pending.as_ref()?;
        if now < *at {
            return None;
        }
        self.pending.take().map(|(_, accepted)| accepted)
    }

    /// Authenticate a step-6-or-later request by its bearer.
    ///
    /// A `false` here is a `401`, and `S2C-OAS` says the client "may restart the pairing
    /// process by calling /requestPairing again" — so it must not fail the attempt.
    #[must_use]
    pub fn authenticates(&self, bearer: &str) -> bool {
        self.attempt.as_ref().is_some_and(|a| a.id.verify(bearer))
    }

    /// Steps 7A and 7B: check `serverHmacChallengeResponse`.
    ///
    /// A `false` here is a `403`: `S2C-OAS` — "The PairingAttempt has failed and cannot
    /// proceed", so the attempt is dropped rather than merely refused.
    pub fn verify_client(&mut self, response: &str, now: Timestamp) -> Result<(), ConnectError> {
        let Some(attempt) = self.attempt.as_mut() else {
            return Err(ConnectError::OutOfOrder {
                got: "a challenge response",
                expected: "the start of pairing",
            });
        };
        if now.saturating_duration_since(attempt.started) > PAIRING_BUDGET {
            self.fail(now);
            return Err(ConnectError::Expired {
                what: "pairing",
                limit: PAIRING_BUDGET,
            });
        }
        if !attempt.expected_response.verify(response) {
            self.fail(now);
            return Err(ConnectError::ChallengeFailed);
        }
        attempt.verified = true;
        Ok(())
    }

    /// Whether this attempt's client is to be the communication server (6B), if an
    /// attempt is in flight.
    #[must_use]
    pub fn client_is_communication_server(&self) -> Option<bool> {
        self.attempt
            .as_ref()
            .map(|a| a.client_is_communication_server)
    }

    /// Step 7A: what to answer `requestConnectionDetails` with, once verified.
    ///
    /// Refused — and the attempt failed — when the client is the one that should be the
    /// communication server: `S2C §Invalid interactions`, "If the server receives a wrong
    /// HTTPS request (e.g. `/postConnectionDetails` while it was expecting
    /// `/requestConnectionDetails`) … it **must** respond with a status 400 and consider
    /// the pairing attempt as failed."
    pub fn connection_details(
        &mut self,
        details: ConnectionDetails,
        now: Timestamp,
    ) -> Result<ConnectionDetails, ConnectError> {
        self.record_details(details, false, now)
    }

    /// Step 7B: record the details the client posted, once verified.
    ///
    /// Refused — and the attempt failed — when this node should be the communication
    /// server, or when the details carry no `SHA256` CA fingerprint to pin.
    pub fn accept_connection_details(
        &mut self,
        details: ConnectionDetails,
        now: Timestamp,
    ) -> Result<(), ConnectError> {
        if details.ca_fingerprint().is_none() {
            self.fail(now);
            return Err(refused(PairingErrorMessage::ParsingError));
        }
        self.record_details(details, true, now).map(|_| ())
    }

    fn record_details(
        &mut self,
        details: ConnectionDetails,
        posted_by_client: bool,
        now: Timestamp,
    ) -> Result<ConnectionDetails, ConnectError> {
        let (verified, client_is_server) = self
            .attempt
            .as_ref()
            .map(|a| (a.verified, a.client_is_communication_server))
            .ok_or(ConnectError::OutOfOrder {
                got: "connection details",
                expected: "the start of pairing",
            })?;
        if !verified {
            return Err(ConnectError::ChallengeFailed);
        }
        if client_is_server != posted_by_client {
            let (got, expected) = if posted_by_client {
                ("postConnectionDetails", "requestConnectionDetails")
            } else {
                ("requestConnectionDetails", "postConnectionDetails")
            };
            self.fail(now);
            return Err(ConnectError::OutOfOrder { got, expected });
        }
        if let Some(attempt) = self.attempt.as_mut() {
            attempt.details = Some(details.clone());
        }
        Ok(details)
    }

    /// Step 8: handle `finalizePairing`, yielding the pairing to store.
    ///
    /// A `success: false` is not an error — it is the client saying it could not proceed —
    /// but it yields no pairing.
    pub fn finalize(
        &mut self,
        body: FinalizePairing,
        now: Timestamp,
    ) -> Result<Option<Pairing>, ConnectError> {
        let Some(attempt) = self.attempt.take() else {
            return Err(ConnectError::OutOfOrder {
                got: "finalization",
                expected: "the start of pairing",
            });
        };
        self.last_finished = Some(now);
        self.pending = None;

        if now.saturating_duration_since(attempt.started) > PAIRING_BUDGET {
            return Err(ConnectError::Expired {
                what: "pairing",
                limit: PAIRING_BUDGET,
            });
        }
        if !body.success {
            return Ok(None);
        }
        if !attempt.verified {
            return Err(ConnectError::ChallengeFailed);
        }
        let details = attempt.details.ok_or(ConnectError::OutOfOrder {
            got: "finalization",
            expected: "connection details",
        })?;
        let client_deployment = attempt
            .client_endpoint
            .deployment
            .unwrap_or(Deployment::Lan);
        let own_deployment = self.local_endpoint.deployment.unwrap_or(Deployment::Lan);
        let (cem, rm) = if self.local.role == Role::Cem {
            (own_deployment, client_deployment)
        } else {
            (client_deployment, own_deployment)
        };
        Ok(Some(Pairing {
            local: self.local.id,
            remote: attempt.client,
            remote_endpoint: attempt.client_endpoint,
            details,
            communication_server: Deployment::communication_server(cem, rm),
            s2_message_versions: attempt.s2_message_versions,
        }))
    }

    fn fail(&mut self, now: Timestamp) {
        self.attempt = None;
        self.pending = None;
        self.last_finished = Some(now);
    }
}

fn refused(message: PairingErrorMessage) -> ConnectError {
    ConnectError::Refused(PairingRefused {
        error_message: message,
        additional_info: None,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::connect::proto::{PairingCode, TokenKind};
    // Explicit because the crate is `no_std`: without `std` there is no prelude to take
    // `.to_string()` from, and `cargo test --lib --no-default-features` is a CI job.
    use alloc::string::ToString;

    const CLIENT_CHALLENGE: [u8; 32] = [0xA5; 32];
    const SERVER_CHALLENGE: [u8; 32] = [0x5A; 32];
    const ATTEMPT: [u8; 24] = [0x33; 24];

    fn binding() -> HmacBinding {
        HmacBinding::DomainName("pairing.example.com".to_string())
    }

    fn code() -> PairingCode {
        PairingCode::parse("evse7-A1b2C3", TokenKind::Static).expect("a legal code")
    }

    fn node(id: &str, role: Role) -> NodeDescription {
        NodeDescription {
            id: NodeId::parse(id).expect("a legal id"),
            brand: "Acme".to_string(),
            logo_url: None,
            kind: if role == Role::Cem { "CEM" } else { "EVSE" }.to_string(),
            model_name: "Charger 9000".to_string(),
            user_defined_name: None,
            role,
        }
    }

    fn endpoint(deployment: Deployment) -> EndpointDescription {
        EndpointDescription {
            name: Some("Test endpoint".to_string()),
            logo_url: None,
            deployment: Some(deployment),
        }
    }

    fn details() -> ConnectionDetails {
        ConnectionDetails::new(
            "https://pairing.example.com/",
            AccessToken::from_entropy(&[1u8; 32]).expect("32 bytes"),
        )
        .with_ca_fingerprint(&[0xCA; 32])
    }

    fn t(secs: i64) -> Timestamp {
        Timestamp::from_unix(1_700_000_000 + secs, 0)
    }

    fn attempt_id() -> PairingAttemptId {
        PairingAttemptId::from_entropy(&ATTEMPT).expect("24 bytes")
    }

    /// Both sides, driven end to end the way a real pairing runs: a WAN CEM as the
    /// pairing client, a LAN RM as the pairing server, so the RM is the pairing server
    /// and the CEM the communication server (6B).
    struct Run {
        client: PairingClient,
        server: PairingServer,
    }

    fn setup(
        client_role: Role,
        client_deployment: Deployment,
        server_deployment: Deployment,
    ) -> Run {
        Run {
            client: PairingClient::start(
                node("cem-1", client_role),
                endpoint(client_deployment),
                code(),
                t(0),
            ),
            server: PairingServer::new(
                node("rm-1", client_role.other()),
                endpoint(server_deployment),
                binding(),
            ),
        }
    }

    #[test]
    fn a_pairing_runs_to_completion_and_both_sides_agree() {
        let Run {
            mut client,
            mut server,
        } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);

        // 1–3.
        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
        let (send_after, accepted) = server
            .request_pairing(
                &request,
                &code().token,
                &SERVER_CHALLENGE,
                attempt_id(),
                t(0),
            )
            .unwrap();
        assert_eq!(send_after, t(1));
        let accepted = {
            assert!(server.poll_response(t(0)).is_none());
            server.poll_response(t(1)).unwrap_or(accepted)
        };

        // 4–5. Both LAN, so the CEM is the communication server: the client posts.
        let next = client
            .accept(accepted, binding(), Deployment::Lan, t(1))
            .unwrap();
        assert_eq!(next, NextStep::PostConnectionDetails);

        // 6B–7B.
        let post = client.post_connection_details(details(), t(1)).unwrap();
        assert!(server.authenticates(client.attempt_id().unwrap().as_str()));
        server
            .verify_client(&post.server_hmac_challenge_response, t(1))
            .unwrap();
        server
            .accept_connection_details(post.connection_details, t(1))
            .unwrap();

        // 8.
        let (body, mine) = client.finalize(t(2)).unwrap();
        assert!(body.success);
        let theirs = server.finalize(body, t(2)).unwrap().expect("a pairing");

        assert_eq!(client.step(), PairingStep::Paired);
        assert_eq!(mine.remote.id, theirs.local);
        assert_eq!(theirs.remote.id, mine.local);
        assert_eq!(mine.communication_server, Role::Cem);
        assert_eq!(theirs.communication_server, Role::Cem);
    }

    #[test]
    fn a_wan_pairing_server_supplies_the_details_instead() {
        // The RM is in the WAN, so it is the communication server and the client asks.
        let Run {
            mut client,
            mut server,
        } = setup(Role::Cem, Deployment::Lan, Deployment::Wan);

        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
        let (_, accepted) = server
            .request_pairing(
                &request,
                &code().token,
                &SERVER_CHALLENGE,
                attempt_id(),
                t(0),
            )
            .unwrap();
        let next = client
            .accept(accepted, binding(), Deployment::Lan, t(1))
            .unwrap();
        assert_eq!(next, NextStep::RequestConnectionDetails);

        let ask = client.request_connection_details().unwrap();
        server
            .verify_client(&ask.server_hmac_challenge_response, t(1))
            .unwrap();
        let given = server.connection_details(details(), t(1)).unwrap();
        client.connection_details(given, t(1)).unwrap();
        let (body, pairing) = client.finalize(t(2)).unwrap();
        assert_eq!(pairing.communication_server, Role::Rm);
        assert!(server.finalize(body, t(2)).unwrap().is_some());
    }

    #[test]
    fn a_server_that_omits_its_deployment_is_taken_to_be_where_it_was_reached() {
        // A LAN CEM pairing with a WAN RM that leaves `deployment` out. Defaulting the
        // absent value to LAN made the CEM the communication server and the client posted
        // details the server never asked for — the WAN node is the server
        // (`S2C §Mapping`), and the client reached it as one.
        let outcome = |reached: Deployment| {
            let Run {
                mut client,
                mut server,
            } = setup(Role::Cem, Deployment::Lan, Deployment::Wan);
            let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
            let (_, mut accepted) = server
                .request_pairing(
                    &request,
                    &code().token,
                    &SERVER_CHALLENGE,
                    attempt_id(),
                    t(0),
                )
                .unwrap();
            accepted.server_endpoint_description.deployment = None;
            client.accept(accepted, binding(), reached, t(1)).unwrap()
        };
        assert_eq!(outcome(Deployment::Wan), NextStep::RequestConnectionDetails);
        assert_eq!(outcome(Deployment::Lan), NextStep::PostConnectionDetails);
    }

    #[test]
    fn the_wrong_branch_of_step_six_fails_the_attempt() {
        // `S2C §Invalid interactions`: "/postConnectionDetails while it was expecting
        // /requestConnectionDetails … must respond with a status 400 and consider the
        // pairing attempt as failed." Here the server is the WAN RM, so 6A is expected and
        // a client that posts its own details instead is refused, and the attempt is over.
        let Run {
            mut client,
            mut server,
        } = setup(Role::Cem, Deployment::Lan, Deployment::Wan);
        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
        let (_, accepted) = server
            .request_pairing(
                &request,
                &code().token,
                &SERVER_CHALLENGE,
                attempt_id(),
                t(0),
            )
            .unwrap();
        client
            .accept(accepted, binding(), Deployment::Lan, t(1))
            .unwrap();
        let ask = client.request_connection_details().unwrap();
        server
            .verify_client(&ask.server_hmac_challenge_response, t(1))
            .unwrap();
        assert_eq!(server.client_is_communication_server(), Some(false));
        assert!(matches!(
            server.accept_connection_details(details(), t(1)),
            Err(ConnectError::OutOfOrder { .. })
        ));
        assert!(
            server.client_is_communication_server().is_none(),
            "the attempt is failed, not merely refused"
        );
    }

    #[test]
    fn posted_details_without_a_ca_fingerprint_are_refused() {
        // "The key `SHA256` must always be provided": without it the pairing server has
        // nothing to pin when it becomes the communication client.
        let bare = ConnectionDetails::new("https://cem.local/", AccessToken::new("x".repeat(43)));
        assert!(bare.ca_fingerprint().is_none());
        let pinned = bare.clone().with_ca_fingerprint(&[0xAB; 32]);
        assert_eq!(pinned.ca_fingerprint(), Some([0xAB; 32]));
        assert_eq!(
            pinned
                .certificate_fingerprint
                .get("SHA256")
                .map(String::as_str),
            Some("ab".repeat(32).as_str()),
            "plain lowercase hexadecimal on the wire"
        );
        // Colons and capitals are still read.
        let mut colons = bare;
        colons
            .certificate_fingerprint
            .insert("SHA256".to_string(), alloc::vec!["AB"; 32].join(":"));
        assert_eq!(colons.ca_fingerprint(), Some([0xAB; 32]));
    }

    #[test]
    fn the_response_may_not_be_sent_before_the_mandatory_second() {
        let Run {
            mut client,
            mut server,
        } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
        server
            .request_pairing(
                &request,
                &code().token,
                &SERVER_CHALLENGE,
                attempt_id(),
                t(0),
            )
            .unwrap();

        assert_eq!(server.poll_timeout(), Some(t(1)));
        assert!(server.poll_response(t(0)).is_none());
        assert!(
            server
                .poll_response(Timestamp::from_unix(1_700_000_000, 999_000_000))
                .is_none()
        );
        assert!(server.poll_response(t(1)).is_some());
        // And it is delivered once.
        assert!(server.poll_response(t(2)).is_none());
    }

    #[test]
    fn a_second_attempt_for_the_same_node_is_refused() {
        let Run {
            mut client,
            mut server,
        } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
        server
            .request_pairing(
                &request,
                &code().token,
                &SERVER_CHALLENGE,
                attempt_id(),
                t(0),
            )
            .unwrap();

        assert!(matches!(
            server.request_pairing(
                &request,
                &code().token,
                &SERVER_CHALLENGE,
                attempt_id(),
                t(1)
            ),
            Err(ConnectError::RateLimited)
        ));
        // Once its budget has run out, the slot frees.
        assert!(
            server
                .request_pairing(
                    &request,
                    &code().token,
                    &SERVER_CHALLENGE,
                    attempt_id(),
                    t(16)
                )
                .is_ok()
        );
    }

    #[test]
    fn a_wrong_token_costs_the_attacker_a_second_too() {
        let Run {
            mut client,
            mut server,
        } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();

        // The server answers with *its* token; a client holding the wrong one fails in
        // step 4, not here — so the interesting failure is the reverse direction.
        let wrong = PairingToken::parse("Z9y8X7", TokenKind::Static).unwrap();
        let (_, accepted) = server
            .request_pairing(&request, &wrong, &SERVER_CHALLENGE, attempt_id(), t(0))
            .unwrap();
        assert!(matches!(
            client.accept(accepted, binding(), Deployment::Lan, t(1)),
            Err(ConnectError::ChallengeFailed)
        ));

        // And a client that guesses wrong at step 6 kills the attempt outright.
        let Run {
            mut client,
            mut server,
        } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
        let (_, accepted) = server
            .request_pairing(
                &request,
                &code().token,
                &SERVER_CHALLENGE,
                attempt_id(),
                t(0),
            )
            .unwrap();
        client
            .accept(accepted, binding(), Deployment::Lan, t(1))
            .unwrap();
        let forged = ChallengeResponse::compute(&SERVER_CHALLENGE, &wrong, &binding())
            .unwrap()
            .as_base64();
        assert!(matches!(
            server.verify_client(&forged, t(1)),
            Err(ConnectError::ChallengeFailed)
        ));
        // "The PairingAttempt has failed and cannot proceed."
        assert!(!server.authenticates(attempt_id().as_str()));
    }

    #[test]
    fn a_man_in_the_middle_cannot_relay_the_exchange() {
        // The attacker terminates TLS with his own certificate, so his binding differs.
        let attacker = HmacBinding::DomainName("pairing.example.com.evil.test".to_string());
        let mut client = PairingClient::start(
            node("cem-1", Role::Cem),
            endpoint(Deployment::Lan),
            code(),
            t(0),
        );
        let mut server =
            PairingServer::new(node("rm-1", Role::Rm), endpoint(Deployment::Lan), attacker);

        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
        // He can relay the request and compute a response — but under his own name.
        let (_, accepted) = server
            .request_pairing(
                &request,
                &code().token,
                &SERVER_CHALLENGE,
                attempt_id(),
                t(0),
            )
            .unwrap();
        // The client, which binds to the name it *believes* it reached, refuses it.
        assert!(matches!(
            client.accept(accepted, binding(), Deployment::Lan, t(1)),
            Err(ConnectError::ChallengeFailed)
        ));
        assert_eq!(client.step(), PairingStep::Failed);
    }

    #[test]
    fn the_fifteen_second_budget_is_enforced_on_both_sides() {
        let Run {
            mut client,
            mut server,
        } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
        let (_, accepted) = server
            .request_pairing(
                &request,
                &code().token,
                &SERVER_CHALLENGE,
                attempt_id(),
                t(0),
            )
            .unwrap();

        assert!(matches!(
            client.accept(accepted, binding(), Deployment::Lan, t(16)),
            Err(ConnectError::Expired { .. })
        ));
        assert!(matches!(
            server.verify_client("anything", t(16)),
            Err(ConnectError::Expired { .. })
        ));
    }

    #[test]
    fn the_steps_cannot_be_taken_out_of_order() {
        let Run { mut client, .. } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
        assert!(matches!(
            client.finalize(t(0)),
            Err(ConnectError::OutOfOrder { .. })
        ));
        // And the attempt is now dead, not merely unhappy.
        assert_eq!(client.step(), PairingStep::Failed);
        assert!(client.request_pairing(&CLIENT_CHALLENGE).is_err());
    }

    #[test]
    fn two_nodes_of_the_same_role_are_refused_by_both_sides() {
        // The server refuses in step 1, with the enumerated reason.
        let mut client = PairingClient::start(
            node("cem-1", Role::Cem),
            endpoint(Deployment::Lan),
            code(),
            t(0),
        );
        let mut server = PairingServer::new(
            node("cem-2", Role::Cem),
            endpoint(Deployment::Lan),
            binding(),
        );
        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
        let err = server
            .request_pairing(
                &request,
                &code().token,
                &SERVER_CHALLENGE,
                attempt_id(),
                t(0),
            )
            .unwrap_err();
        assert!(matches!(
            err,
            ConnectError::Refused(PairingRefused {
                error_message: PairingErrorMessage::InvalidCombinationOfRoles,
                ..
            })
        ));
    }

    #[test]
    fn incompatible_versions_are_refused_unless_forced() {
        let mut client = PairingClient::start(
            node("cem-1", Role::Cem),
            endpoint(Deployment::Lan),
            code(),
            t(0),
        )
        .with_s2_message_versions(alloc::vec![crate::types::ProtocolVersion::new("9.9.9")]);
        let mut server =
            PairingServer::new(node("rm-1", Role::Rm), endpoint(Deployment::Lan), binding());
        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
        assert!(matches!(
            server.request_pairing(
                &request,
                &code().token,
                &SERVER_CHALLENGE,
                attempt_id(),
                t(0)
            ),
            Err(ConnectError::Refused(PairingRefused {
                error_message: PairingErrorMessage::IncompatibleS2MessageVersions,
                ..
            }))
        ));

        // Forced, it pairs anyway — the nodes cannot talk until one is updated, which is
        // what the flag is for.
        let mut client = PairingClient::start(
            node("cem-1", Role::Cem),
            endpoint(Deployment::Lan),
            code(),
            t(0),
        )
        .with_s2_message_versions(alloc::vec![crate::types::ProtocolVersion::new("9.9.9")])
        .forcing();
        let mut server =
            PairingServer::new(node("rm-1", Role::Rm), endpoint(Deployment::Lan), binding());
        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
        assert!(
            server
                .request_pairing(
                    &request,
                    &code().token,
                    &SERVER_CHALLENGE,
                    attempt_id(),
                    t(16)
                )
                .is_ok()
        );
    }

    #[test]
    fn a_client_without_sha256_is_refused() {
        let Run {
            mut client,
            mut server,
        } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
        let mut request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
        request.supported_hmac_hashing_algorithms.clear();
        assert!(matches!(
            server.request_pairing(
                &request,
                &code().token,
                &SERVER_CHALLENGE,
                attempt_id(),
                t(0)
            ),
            Err(ConnectError::Refused(PairingRefused {
                error_message: PairingErrorMessage::IncompatibleHmacHashingAlgorithms,
                ..
            }))
        ));
    }

    #[test]
    fn a_short_challenge_never_reaches_the_wire() {
        let Run { mut client, .. } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
        assert!(matches!(
            client.request_pairing(&[0u8; 16]),
            Err(ConnectError::WeakSecret { need: 32, .. })
        ));
    }

    #[test]
    fn the_attempt_id_is_a_bearer_and_is_compared_in_constant_time() {
        let Run {
            mut client,
            mut server,
        } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
        server
            .request_pairing(
                &request,
                &code().token,
                &SERVER_CHALLENGE,
                attempt_id(),
                t(0),
            )
            .unwrap();

        assert!(server.authenticates(attempt_id().as_str()));
        assert!(!server.authenticates("something else entirely"));
        assert!(!server.authenticates(""));
        // 24 bytes Base64-encode to the 32 characters the specification requires.
        assert_eq!(attempt_id().as_str().len(), PairingAttemptId::MIN_LEN);
        assert!(PairingAttemptId::from_entropy(&[0u8; 23]).is_err());
        // And it never prints itself.
        assert_eq!(
            alloc::format!("{:?}", attempt_id()),
            "PairingAttemptId(<redacted>)"
        );
    }

    #[test]
    fn a_client_that_gives_up_says_so_and_no_pairing_is_stored() {
        let Run {
            mut client,
            mut server,
        } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
        let (_, accepted) = server
            .request_pairing(
                &request,
                &code().token,
                &SERVER_CHALLENGE,
                attempt_id(),
                t(0),
            )
            .unwrap();
        client
            .accept(accepted, binding(), Deployment::Lan, t(1))
            .unwrap();

        let body = client.abandon();
        assert!(!body.success);
        assert!(server.finalize(body, t(2)).unwrap().is_none());
    }

    #[test]
    fn the_request_body_is_the_shape_the_openapi_defines() {
        let Run { mut client, .. } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
        let json = serde_json::to_value(&request).expect("serializable");
        for key in [
            "clientNodeDescription",
            "clientEndpointDescription",
            "supportedCommunicationProtocols",
            "supportedS2MessageVersions",
            "supportedHmacHashingAlgorithms",
            "clientHmacChallenge",
        ] {
            assert!(json.get(key).is_some(), "missing required property {key}");
        }
        // "may never be used at the same time" — and `forcePairing` defaults to absent.
        assert!(json.get("nodeId").is_none());
        assert!(json.get("nodeIdAlias").is_some());
        assert!(json.get("forcePairing").is_none());
        assert_eq!(
            json["clientNodeDescription"]["role"].as_str(),
            Some("CEM"),
            "the role enum is spelled as the schema spells it"
        );
    }
}