hb46pp 0.1.3

Client library for the HTTP-Based IPv4 over IPv6 Provisioning Protocol
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
use std::{collections::BTreeMap, fmt, str::FromStr};

use serde::de::DeserializeOwned;
use serde_json::{Map, Value};
use thiserror::Error;
use url::{Host, Url};

const V6MIG_SPEC: &str = "v6mig-1";
const MAX_TTL_SECS: u64 = 604_800;

#[derive(Debug, Error)]
#[non_exhaustive]
/// Errors returned when parsing and validating a [`Bootstrap`] record.
pub enum BootstrapError {
    /// The provisioning endpoint is not a supported HTTP or HTTPS URL.
    #[error("url: {0}, err: {1}")]
    InvalidUrl(String, String),
    /// The bootstrap record contains an unsupported `t` value.
    #[error("extracting tls policy : {0}")]
    InvalidTlsPolicy(String),
    /// A bootstrap field does not have its required `key=value` form or order.
    #[error("parsing field, expected: '{0}', got: '{1}'")]
    MalformedField(String, String),
    /// A required bootstrap field is absent.
    #[error("missing field: {0}")]
    MissingField(&'static str),
    /// The bootstrap record declares an unsupported protocol version.
    #[error("unsupported spec version: {0}")]
    UnsupportedVersion(String),
    /// Certificate validation was requested for an HTTP endpoint.
    #[error("tls policy set to validate for http scheme")]
    InvalidTlsForHttp,
    /// The provisioning URL does not contain a host.
    #[error("provisioning URL must contain a host")]
    MissingUrlHost,
    /// The record contains fields beyond the three fields defined by HB46PP.
    #[error("record contain data beyond spec fields, record: {0}")]
    InvalidRecord(String),
    /// The provisioning endpoint uses an IPv4 address instead of IPv6.
    #[error("provisioning URL cannot use an IPv4 address")]
    Ipv4EndpointNotAllowed,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
/// An IPv4-over-IPv6 method recognized by HB46PP.
pub enum Capability {
    /// 464XLAT.
    Xlat464,
    /// Dual-Stack Lite.
    DsLite,
    /// An RFC 2473 IP-in-IP tunnel.
    IpIp,
    /// Lightweight 4over6.
    Lw4o6,
    /// Mapping of Address and Port with Encapsulation.
    MapE,
    /// Mapping of Address and Port using Translation.
    MapT,
}

impl Capability {
    const ALL: [Self; 6] = [
        Self::Xlat464,
        Self::DsLite,
        Self::IpIp,
        Self::Lw4o6,
        Self::MapE,
        Self::MapT,
    ];

    /// Returns the capability name used in HB46PP requests and responses.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Xlat464 => "464xlat",
            Self::DsLite => "dslite",
            Self::IpIp => "ipip",
            Self::Lw4o6 => "lw4o6",
            Self::MapE => "map_e",
            Self::MapT => "map_t",
        }
    }
}

#[derive(Debug, Error, PartialEq, Eq)]
/// Errors returned when parsing a [`Capability`] name.
pub enum CapabilityError {
    /// The name is not one of the capabilities defined by HB46PP.
    #[error("unsupported HB46PP capability: {0}")]
    UnsupportedName(String),
}

impl FromStr for Capability {
    type Err = CapabilityError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::ALL
            .into_iter()
            .find(|capability| capability.as_str() == value)
            .ok_or_else(|| CapabilityError::UnsupportedName(value.to_string()))
    }
}

#[derive(Debug, Error, PartialEq, Eq)]
/// Errors returned when constructing a provisioning [`Ttl`].
pub enum TtlError {
    /// The lifetime exceeds the protocol maximum of seven days.
    #[error("TTL must be at most {MAX_TTL_SECS} seconds")]
    TooLarge,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// The validated lifetime of provisioning data, in seconds.
///
/// HB46PP limits this value to seven days.
pub struct Ttl(u32);

impl Ttl {
    /// Returns the provisioning lifetime in seconds.
    pub fn as_secs(self) -> u32 {
        self.0
    }
}

impl TryFrom<u64> for Ttl {
    type Error = TtlError;

    fn try_from(value: u64) -> Result<Self, Self::Error> {
        if value > MAX_TTL_SECS {
            return Err(TtlError::TooLarge);
        }

        Ok(Self(value as u32))
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// The result of user/password authentication reported by the server.
pub enum AuthStatus {
    /// Credentials were absent, but providing them may yield more parameters.
    Required,
    /// Credentials were provided but authentication failed.
    Rejected,
    /// Credentials were provided and authentication succeeded.
    Accepted,
}

impl AuthStatus {
    /// Returns the authentication status value used in an HB46PP response.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Required => "req",
            Self::Rejected => "bad",
            Self::Accepted => "ok",
        }
    }
}

#[derive(Debug, Error, PartialEq, Eq)]
/// Errors returned when parsing an [`AuthStatus`].
pub enum AuthStatusError {
    /// The value is not an authentication status defined by HB46PP.
    #[error("unsupported HB46PP auth status: {0}")]
    UnsupportedStatus(String),
}

impl FromStr for AuthStatus {
    type Err = AuthStatusError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value {
            "req" => Ok(Self::Required),
            "bad" => Ok(Self::Rejected),
            "ok" => Ok(Self::Accepted),
            _ => Err(AuthStatusError::UnsupportedStatus(value.to_string())),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Informational names identifying the provisioned service and its providers.
///
/// These names are intended for display. They distinguish the network operator
/// enabling IPv4-over-IPv6 connectivity, that operator's service, and an
/// Internet provider's service offered to customers when all three are supplied.
pub struct ProviderInfo {
    enabler_name: String,
    service_name: Option<String>,
    isp_name: Option<String>,
}

impl ProviderInfo {
    /// Returns the name of the operator enabling IPv4-over-IPv6 connectivity.
    pub fn enabler_name(&self) -> &str {
        &self.enabler_name
    }

    /// Returns that operator's name for the IPv4-over-IPv6 service, if supplied.
    pub fn service_name(&self) -> Option<&str> {
        self.service_name.as_deref()
    }

    /// Returns the Internet provider's service name, if supplied.
    pub fn isp_name(&self) -> Option<&str> {
        self.isp_name.as_deref()
    }
}

/// An offer supported by the caller and selected using the server's preference order.
pub struct SelectedOffer<'a> {
    capability: Capability,
    parameters: &'a serde_json::Value,
}

impl SelectedOffer<'_> {
    /// Returns the IPv4-over-IPv6 method selected for this offer.
    pub fn capability(&self) -> Capability {
        self.capability
    }

    /// Returns the method parameters without interpreting their contents.
    ///
    /// Parameters are a JSON object for every capability except `ipip`, whose
    /// parameters are an array containing one JSON object for each tunnel.
    pub fn parameters(&self) -> &serde_json::Value {
        self.parameters
    }
}

#[derive(Debug, Error)]
#[non_exhaustive]
/// Errors returned when parsing and validating [`ProvisioningData`].
pub enum ProvisioningDataError {
    /// The outer JSON value is not an object.
    #[error("response is not a JSON object")]
    NotObject,
    /// A required field is absent from the response.
    #[error("missing required response field: {0}")]
    MissingField(&'static str),
    /// A field is present with `null` instead of its expected value.
    #[error("response field must not be null: {0}")]
    NullField(&'static str),
    /// A field cannot be decoded as its expected JSON type.
    #[error("invalid response field {field}: {source}")]
    InvalidField {
        /// The name of the invalid response field.
        field: &'static str,
        /// The JSON decoding error for the field.
        #[source]
        source: serde_json::Error,
    },
    /// An informational name is too large after JSON encoding.
    #[error("response field exceeds 256 bytes including quotes: {0}")]
    InformationalNameTooLong(&'static str),
    /// The response contains an invalid provisioning lifetime.
    #[error(transparent)]
    Ttl(#[from] TtlError),
    /// The response contains an invalid token.
    #[error(transparent)]
    Token(#[from] TokenError),
    /// The response contains an unsupported authentication status.
    #[error(transparent)]
    AuthStatus(#[from] AuthStatusError),
    /// The response names an unsupported capability.
    #[error(transparent)]
    Capability(#[from] CapabilityError),
    /// A capability appears more than once in the server preference order.
    #[error("duplicate capability in response order: {0:?}")]
    DuplicateOrder(Capability),
    /// The preference order names a capability without providing its parameters.
    #[error("response order lists a method without its provisioning payload: {0:?}")]
    MissingOffer(Capability),
    /// A capability's parameters are not in the JSON shape required by HB46PP.
    #[error("invalid provisioning payload shape for capability: {0:?}")]
    InvalidOfferShape(Capability),
}

#[derive(Debug, Clone)]
/// Validated provisioning data returned by an HB46PP server.
///
/// The type validates the shared response fields and retains each method's
/// parameters as JSON for interpretation by the application implementing that
/// method. Unknown fields in the outer object are ignored.
pub struct ProvisioningData {
    provider_info: ProviderInfo,
    ttl: Option<Ttl>,
    token: Option<Token>,
    auth: Option<AuthStatus>,
    order: Vec<Capability>,
    ipv6_mostly: Option<bool>,
    offers: BTreeMap<Capability, Value>,
}

impl ProvisioningData {
    /// Parses and validates an HB46PP provisioning JSON object.
    pub fn parse(input: &str) -> Result<Self, ProvisioningDataError> {
        let value =
            serde_json::from_str(input).map_err(|source| ProvisioningDataError::InvalidField {
                field: "response",
                source,
            })?;
        let mut fields = match value {
            Value::Object(fields) => fields,
            _ => return Err(ProvisioningDataError::NotObject),
        };

        let enabler_name = take_required::<String>(&mut fields, "enabler_name")?;
        validate_informational_name("enabler_name", &enabler_name)?;
        let service_name = take_optional::<String>(&mut fields, "service_name")?;
        if let Some(service_name) = &service_name {
            validate_informational_name("service_name", service_name)?;
        }
        let isp_name = take_optional::<String>(&mut fields, "isp_name")?;
        if let Some(isp_name) = &isp_name {
            validate_informational_name("isp_name", isp_name)?;
        }

        let ttl = take_optional::<u64>(&mut fields, "ttl")
            .map(|ttl| ttl.map(Ttl::try_from).transpose())??;
        let token = take_optional::<String>(&mut fields, "token")
            .map(|token| token.map(|token| token.parse()).transpose())??;
        let auth = take_optional::<String>(&mut fields, "auth")
            .map(|auth| auth.map(|auth| auth.parse()).transpose())??;
        let order_names = take_required::<Vec<String>>(&mut fields, "order")?;
        let ipv6_mostly = take_optional::<bool>(&mut fields, "ipv6_mostly")?;

        let mut order = Vec::with_capacity(order_names.len());
        for name in order_names {
            let capability = name.parse()?;
            if order.contains(&capability) {
                return Err(ProvisioningDataError::DuplicateOrder(capability));
            }
            order.push(capability);
        }

        let mut offers = BTreeMap::new();
        for capability in Capability::ALL {
            let Some(parameters) = take_optional::<Value>(&mut fields, capability.as_str())? else {
                continue;
            };

            let has_valid_shape = match capability {
                Capability::IpIp => parameters
                    .as_array()
                    .is_some_and(|tunnels| tunnels.iter().all(Value::is_object)),
                _ => parameters.is_object(),
            };

            if !has_valid_shape {
                return Err(ProvisioningDataError::InvalidOfferShape(capability));
            }

            offers.insert(capability, parameters);
        }
        for capability in &order {
            if !offers.contains_key(capability) {
                return Err(ProvisioningDataError::MissingOffer(*capability));
            }
        }

        Ok(Self {
            provider_info: ProviderInfo {
                enabler_name,
                service_name,
                isp_name,
            },
            ttl,
            token,
            auth,
            order,
            ipv6_mostly,
            offers,
        })
    }

    /// Selects the first supported offer in the server's preference order.
    ///
    /// The order of `supported` does not affect selection. If none of the
    /// server's ordered offers are supported, this returns `None`.
    pub fn select(&self, supported: &[Capability]) -> Option<SelectedOffer<'_>> {
        for &capability in self.order() {
            if !supported.contains(&capability) {
                continue;
            }

            let Some(parameters) = self.offer(capability) else {
                continue;
            };

            return Some(SelectedOffer {
                capability,
                parameters,
            });
        }

        None
    }

    /// Returns the informational service and provider names.
    pub fn provider_info(&self) -> &ProviderInfo {
        &self.provider_info
    }

    /// Returns how long the provisioning data remains valid, if supplied.
    pub fn ttl(&self) -> Option<Ttl> {
        self.ttl
    }

    /// Returns the opaque token for a later provisioning request, if supplied.
    ///
    /// The token is sensitive and should not be logged. It must not be
    /// persisted when the HTTP response prohibits storage.
    pub fn token(&self) -> Option<&Token> {
        self.token.as_ref()
    }

    /// Returns the server's user/password authentication result, if supplied.
    pub fn auth(&self) -> Option<AuthStatus> {
        self.auth
    }

    /// Returns the server's capability preference order.
    pub fn order(&self) -> &[Capability] {
        &self.order
    }

    /// Returns whether the router should provide an IPv6-Mostly local network.
    ///
    /// In this mode, local devices primarily use IPv6 and obtain IPv4
    /// connectivity through 464XLAT. When this is `Some(true)`, the `464xlat`
    /// offer supplies the NAT64 prefix to advertise to the local network even
    /// if `464xlat` is absent from the preference order.
    pub fn ipv6_mostly(&self) -> Option<bool> {
        self.ipv6_mostly
    }

    /// Returns the uninterpreted parameters offered for a capability.
    ///
    /// An offer may be present even when the capability is not listed in the
    /// server preference order, as required for IPv6-Mostly provisioning.
    pub fn offer(&self, capability: Capability) -> Option<&Value> {
        self.offers.get(&capability)
    }
}

fn take_required<T>(
    fields: &mut Map<String, Value>,
    field: &'static str,
) -> Result<T, ProvisioningDataError>
where
    T: DeserializeOwned,
{
    let value = fields
        .remove(field)
        .ok_or(ProvisioningDataError::MissingField(field))?;
    if value.is_null() {
        return Err(ProvisioningDataError::NullField(field));
    }

    serde_json::from_value(value)
        .map_err(|source| ProvisioningDataError::InvalidField { field, source })
}

fn take_optional<T>(
    fields: &mut Map<String, Value>,
    field: &'static str,
) -> Result<Option<T>, ProvisioningDataError>
where
    T: DeserializeOwned,
{
    let Some(value) = fields.remove(field) else {
        return Ok(None);
    };
    if value.is_null() {
        return Err(ProvisioningDataError::NullField(field));
    }

    serde_json::from_value(value)
        .map(Some)
        .map_err(|source| ProvisioningDataError::InvalidField { field, source })
}

fn validate_informational_name(
    field: &'static str,
    value: &str,
) -> Result<(), ProvisioningDataError> {
    if value.len() + 2 > 256 {
        return Err(ProvisioningDataError::InformationalNameTooLong(field));
    }

    Ok(())
}

#[derive(Debug, Error, PartialEq, Eq)]
/// Errors returned when constructing a [`ProvisioningRequest`].
pub enum ProvisioningRequestError {
    /// No supported IPv4-over-IPv6 capability was supplied.
    #[error("at least one capability is required")]
    EmptyCapabilities,
    /// The supplied capability list contains the same capability more than once.
    #[error("capabilities must not contain duplicates")]
    DuplicateCapability,
}

#[derive(Debug, Error, PartialEq, Eq)]
/// Errors returned when parsing a [`VendorId`].
pub enum VendorIdError {
    /// The value does not follow the HB46PP vendor identifier format.
    #[error("vendor ID must be 6 ASCII hex digits with an optional 1..24 character suffix")]
    InvalidFormat,
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// A validated value for the HB46PP `vendorid` request parameter.
///
/// The value starts with the vendor's 24-bit IEEE organization identifier,
/// written as six hexadecimal digits. It may have a suffix of 1 to 24 ASCII
/// letters, digits, or underscores separated by `-`.
pub struct VendorId(String);

impl VendorId {
    /// Returns the validated vendor identifier.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl FromStr for VendorId {
    type Err = VendorIdError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let (oui, suffix) = match value.split_once('-') {
            Some((oui, suffix)) => (oui, Some(suffix)),
            None => (value, None),
        };

        if oui.len() != 6
            || !oui.chars().all(|c| c.is_ascii_hexdigit())
            || suffix.is_some_and(|suffix| {
                suffix.is_empty()
                    || suffix.len() > 24
                    || !suffix
                        .chars()
                        .all(|c| c.is_ascii_alphanumeric() || c == '_')
            })
        {
            return Err(VendorIdError::InvalidFormat);
        }

        Ok(Self(value.to_string()))
    }
}

#[derive(Debug, Error, PartialEq, Eq)]
/// Errors returned when parsing a [`Product`].
pub enum ProductError {
    /// The value does not follow the HB46PP product identifier format.
    #[error("product must be 1..32 ASCII letters, digits, '_' or '-'")]
    InvalidFormat,
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// A validated value for the HB46PP `product` request parameter.
pub struct Product(String);

impl Product {
    /// Returns the validated product identifier.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl FromStr for Product {
    type Err = ProductError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        if value.is_empty()
            || value.len() > 32
            || !value
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
        {
            return Err(ProductError::InvalidFormat);
        }

        Ok(Self(value.to_string()))
    }
}

#[derive(Debug, Error, PartialEq, Eq)]
/// Errors returned when parsing a [`FirmwareVersion`].
pub enum FirmwareVersionError {
    /// The value does not follow the HB46PP firmware version format.
    #[error("firmware version must be 1..32 ASCII digits or '_'")]
    InvalidFormat,
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// A validated value for the HB46PP `version` request parameter.
///
/// Versions contain only ASCII digits and underscores. A dotted software
/// version such as `1.2.0` must therefore be supplied as `1_2_0`.
pub struct FirmwareVersion(String);

impl FirmwareVersion {
    /// Returns the validated firmware version.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl FromStr for FirmwareVersion {
    type Err = FirmwareVersionError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        if value.is_empty()
            || value.len() > 32
            || !value.chars().all(|c| c.is_ascii_digit() || c == '_')
        {
            return Err(FirmwareVersionError::InvalidFormat);
        }

        Ok(Self(value.to_string()))
    }
}

#[derive(Debug, Error, PartialEq, Eq)]
/// Errors returned when constructing [`Credentials`].
pub enum CredentialsError {
    /// The user name does not follow the HB46PP credential format.
    #[error("user must be at most 32 ASCII letters, digits, '_' or '-'")]
    InvalidUser,
    /// The password does not follow the HB46PP credential format.
    #[error("password must be at most 32 ASCII letters, digits, '_' or '-'")]
    InvalidPassword,
    /// The server name cannot be parsed as a URL host.
    #[error("expected server name is not a valid URL host")]
    InvalidExpectedServerName,
}

#[derive(Clone)]
/// Optional user name and password sent with a provisioning request.
///
/// The custom [`Debug`](fmt::Debug) implementation redacts the password.
pub struct Credentials {
    user: String,
    password: String,
    expected_server_name: Option<Host<String>>,
}

impl Credentials {
    /// Creates credentials restricted to one validated HTTPS server.
    ///
    /// The credentials can only be added to a request when certificate
    /// validation is enabled and the request URL host matches
    /// `expected_server_name`.
    pub fn for_server(
        user: String,
        password: String,
        expected_server_name: String,
    ) -> Result<Self, CredentialsError> {
        validate_credentials(&user, &password)?;

        let expected_server_name = Host::parse(&expected_server_name)
            .map_err(|_| CredentialsError::InvalidExpectedServerName)?;

        Ok(Self {
            user,
            password,
            expected_server_name: Some(expected_server_name),
        })
    }

    /// Creates credentials that may be sent to any provisioning endpoint.
    ///
    /// HB46PP permits this when the user did not provide an expected server
    /// name. This includes endpoints using HTTP, unvalidated HTTPS, and hosts
    /// reached through redirects, so callers must choose this explicitly.
    pub fn unrestricted(user: String, password: String) -> Result<Self, CredentialsError> {
        validate_credentials(&user, &password)?;

        Ok(Self {
            user,
            password,
            expected_server_name: None,
        })
    }

    /// Returns the user name.
    pub fn user(&self) -> &str {
        &self.user
    }

    /// Returns the password.
    ///
    /// The returned value is sensitive and should not be logged or persisted
    /// without appropriate protection.
    pub fn password(&self) -> &str {
        &self.password
    }
}

impl fmt::Debug for Credentials {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Credentials")
            .field("user", &self.user)
            .field("password", &"[redacted]")
            .field("expected_server_name", &self.expected_server_name)
            .finish()
    }
}

fn validate_credentials(user: &str, password: &str) -> Result<(), CredentialsError> {
    if !valid_credential_component(user) {
        return Err(CredentialsError::InvalidUser);
    }
    if !valid_credential_component(password) {
        return Err(CredentialsError::InvalidPassword);
    }

    Ok(())
}

fn valid_credential_component(value: &str) -> bool {
    value.len() <= 32
        && value
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
}

#[derive(Debug, Error, PartialEq, Eq)]
/// Errors returned when parsing a [`Token`].
pub enum TokenError {
    /// The value is not exactly 64 lowercase hexadecimal characters.
    #[error("token must be lowercase ASCII hexadecimal only, 64 characters long")]
    InvalidFormat,
}

#[derive(Clone, PartialEq, Eq)]
/// An opaque token returned by a provisioning server for a later request.
///
/// The custom [`Debug`](fmt::Debug) implementation redacts the token.
pub struct Token(String);

impl Token {
    /// Returns the token value.
    ///
    /// The returned value is sensitive and should not be logged. It must not
    /// be persisted when the provisioning response prohibits storage.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

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

impl FromStr for Token {
    type Err = TokenError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        if value.len() != 64 || !value.chars().all(|c| matches!(c, '0'..='9' | 'a'..='f')) {
            return Err(TokenError::InvalidFormat);
        }

        Ok(Self(value.to_string()))
    }
}

#[derive(Debug, Error, PartialEq, Eq)]
/// Errors returned when adding restricted credentials to a provisioning URL.
pub enum ProvisioningUrlError {
    /// Restricted credentials would be sent over a connection without HTTPS.
    #[error("credentials with an expected server name require HTTPS")]
    CredentialsRequireHttps,
    /// Restricted credentials would be sent without certificate validation.
    #[error("credentials with an expected server name require certificate validation")]
    CredentialsRequireCertificateValidation,
    /// The endpoint host does not match the host associated with the credentials.
    #[error("provisioning URL host does not match the expected server name")]
    UnexpectedProvisioningHost,
}

#[derive(Clone)]
/// Validated parameters used to request HB46PP provisioning data.
///
/// The request identifies the device, declares its supported capabilities,
/// and may carry a token or credentials. Its custom [`Debug`](fmt::Debug)
/// implementation redacts those sensitive values.
pub struct ProvisioningRequest {
    vendor_id: VendorId,
    product: Product,
    version: FirmwareVersion,
    capabilities: Vec<Capability>,
    token: Option<Token>,
    credentials: Option<Credentials>,
}

impl ProvisioningRequest {
    /// Creates a provisioning request.
    ///
    /// At least one capability is required, and each capability may appear
    /// only once. The order does not control offer selection; the server's
    /// response order does.
    pub fn new(
        vendor_id: VendorId,
        product: Product,
        version: FirmwareVersion,
        capabilities: Vec<Capability>,
        token: Option<Token>,
        credentials: Option<Credentials>,
    ) -> Result<Self, ProvisioningRequestError> {
        if capabilities.is_empty() {
            return Err(ProvisioningRequestError::EmptyCapabilities);
        }
        if capabilities
            .iter()
            .enumerate()
            .any(|(index, capability)| capabilities[..index].contains(capability))
        {
            return Err(ProvisioningRequestError::DuplicateCapability);
        }

        Ok(Self {
            vendor_id,
            product,
            version,
            capabilities,
            token,
            credentials,
        })
    }

    /// Returns the device vendor identifier.
    pub fn vendor_id(&self) -> &VendorId {
        &self.vendor_id
    }

    /// Returns the device product identifier.
    pub fn product(&self) -> &Product {
        &self.product
    }

    /// Returns the device firmware version.
    pub fn version(&self) -> &FirmwareVersion {
        &self.version
    }

    /// Returns the capabilities declared by the device.
    pub fn capabilities(&self) -> &[Capability] {
        &self.capabilities
    }

    /// Returns the token to send with this request, if present.
    ///
    /// The returned value is sensitive and should not be logged.
    pub fn token(&self) -> Option<&str> {
        self.token.as_ref().map(Token::as_str)
    }

    /// Sets the token sent with subsequent provisioning requests.
    ///
    /// Passing `None` stops sending the current token.
    pub fn set_token(&mut self, token: Option<Token>) {
        self.token = token;
    }

    /// Returns the credentials to send with this request, if present.
    pub fn credentials(&self) -> Option<&Credentials> {
        self.credentials.as_ref()
    }
}

impl fmt::Debug for ProvisioningRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ProvisioningRequest")
            .field("vendor_id", &self.vendor_id)
            .field("product", &self.product)
            .field("version", &self.version)
            .field("capabilities", &self.capabilities)
            .field("token", &self.token)
            .field("credentials", &self.credentials)
            .finish()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// The certificate validation policy declared by an HB46PP bootstrap record.
pub enum TlsPolicy {
    /// Bootstrap field `t=a`: certificate validation is not required.
    NoCertificateValidation, // t=a
    /// Bootstrap field `t=b`: validate the HTTPS server certificate.
    ValidateCertificate, // t=b
}

#[derive(Debug)]
/// A validated HB46PP bootstrap record.
///
/// It contains the provisioning endpoint and TLS policy obtained from a DNS
/// TXT record.
pub struct Bootstrap {
    url: Url,
    tls_policy: TlsPolicy,
}

impl Bootstrap {
    /// Parses and validates an HB46PP bootstrap TXT record.
    pub fn parse(txt: &str) -> Result<Self, BootstrapError> {
        let mut iter = txt.split(' ');

        let version_field = iter.next().ok_or(BootstrapError::MissingField("v"))?;
        let version_value = parse_field(version_field, "v")?;
        if version_value != V6MIG_SPEC {
            return Err(BootstrapError::UnsupportedVersion(
                version_value.to_string(),
            ));
        }

        let url_field = iter.next().ok_or(BootstrapError::MissingField("url"))?;
        let url_value = parse_field(url_field, "url")?;

        let tls_field = iter.next().ok_or(BootstrapError::MissingField("t"))?;
        let tls_value = parse_field(tls_field, "t")?;

        if iter.next().is_some() {
            return Err(BootstrapError::InvalidRecord(txt.to_string()));
        };

        let tls_policy = match tls_value {
            "a" => TlsPolicy::NoCertificateValidation,
            "b" => TlsPolicy::ValidateCertificate,
            _ => {
                return Err(BootstrapError::InvalidTlsPolicy(format!(
                    "invalid tls policy value: {tls_value}, expected '<a|b>'"
                )));
            }
        };

        let url = Url::parse(url_value)
            .map_err(|e| BootstrapError::InvalidUrl(url_value.to_string(), e.to_string()))?;

        if url.scheme() != "http" && url.scheme() != "https" {
            return Err(BootstrapError::InvalidUrl(
                url_value.to_string(),
                format!(
                    "unsuported url scheme: {}, supported: <http|https>",
                    url.scheme(),
                ),
            ));
        };

        if url.scheme() == "http" && tls_policy == TlsPolicy::ValidateCertificate {
            return Err(BootstrapError::InvalidTlsForHttp);
        }

        match url.host() {
            Some(Host::Ipv4(_)) => return Err(BootstrapError::Ipv4EndpointNotAllowed),
            Some(_) => {}
            None => return Err(BootstrapError::MissingUrlHost),
        }

        Ok(Bootstrap { url, tls_policy })
    }

    /// Builds the provisioning URL for the initial bootstrap endpoint.
    ///
    /// The returned URL preserves endpoint query parameters and adds the
    /// request's HB46PP query parameters.
    pub fn provisioning_url(
        &self,
        request: &ProvisioningRequest,
    ) -> Result<Url, ProvisioningUrlError> {
        self.provisioning_url_for(self.url.clone(), request)
    }

    pub(crate) fn provisioning_url_for(
        &self,
        endpoint: Url,
        request: &ProvisioningRequest,
    ) -> Result<Url, ProvisioningUrlError> {
        if let Some(credentials) = request.credentials() {
            self.validate_credentials(&endpoint, credentials)?;
        }
        let mut request_url = endpoint;
        let capabilities = request
            .capabilities()
            .iter()
            .map(|c| c.as_str())
            .collect::<Vec<_>>()
            .join(",");
        {
            let mut query = request_url.query_pairs_mut();
            query.append_pair("vendorid", request.vendor_id().as_str());
            query.append_pair("product", request.product().as_str());
            query.append_pair("version", request.version().as_str());
            query.append_pair("capability", &capabilities);
            if let Some(token) = request.token() {
                query.append_pair("token", token);
            }
            if let Some(credentials) = request.credentials() {
                query.append_pair("user", credentials.user());
                query.append_pair("pass", credentials.password());
            }
        }
        Ok(request_url)
    }

    fn validate_credentials(
        &self,
        endpoint: &Url,
        credentials: &Credentials,
    ) -> Result<(), ProvisioningUrlError> {
        let Some(expected_server_name) = &credentials.expected_server_name else {
            return Ok(());
        };

        if endpoint.scheme() != "https" {
            return Err(ProvisioningUrlError::CredentialsRequireHttps);
        }
        if self.tls_policy != TlsPolicy::ValidateCertificate {
            return Err(ProvisioningUrlError::CredentialsRequireCertificateValidation);
        }

        let endpoint_host = endpoint.host().map(|host| host.to_owned());
        if endpoint_host.as_ref() != Some(expected_server_name) {
            return Err(ProvisioningUrlError::UnexpectedProvisioningHost);
        }

        Ok(())
    }

    /// Returns the TLS policy declared by the bootstrap record.
    pub fn tls_policy(&self) -> TlsPolicy {
        self.tls_policy
    }

    /// Returns the provisioning endpoint from the bootstrap record.
    pub fn endpoint(&self) -> &Url {
        &self.url
    }
}

fn parse_field<'a>(field: &'a str, expected_key: &'static str) -> Result<&'a str, BootstrapError> {
    let (key, value) = field.split_once('=').ok_or(BootstrapError::MalformedField(
        format!("{expected_key}=<value>"),
        field.to_string(),
    ))?;

    if key != expected_key {
        return Err(BootstrapError::MalformedField(
            expected_key.to_string(),
            key.to_string(),
        ));
    };
    Ok(value)
}

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

    const V6CONNECT_BOOTSTRAP: &str =
        "v=v6mig-1 url=https://prod.v6mig.v6connect.net/cpe/v1/config t=b";
    const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";

    fn vendor_id() -> VendorId {
        "000000".parse().unwrap()
    }

    fn product() -> Product {
        "dslite-b4".parse().unwrap()
    }

    fn version() -> FirmwareVersion {
        "0_1_0".parse().unwrap()
    }

    fn credentials_for_server(expected_server_name: &str) -> Credentials {
        Credentials::for_server(
            "user".to_string(),
            "pass".to_string(),
            expected_server_name.to_string(),
        )
        .unwrap()
    }

    fn valid_request() -> ProvisioningRequest {
        ProvisioningRequest::new(
            vendor_id(),
            product(),
            version(),
            vec![Capability::DsLite],
            None,
            None,
        )
        .unwrap()
    }

    #[test]
    fn serializes_capabilities_to_hb46pp_wire_names() {
        let names: Vec<_> = Capability::ALL
            .into_iter()
            .map(Capability::as_str)
            .collect();

        assert_eq!(
            names,
            ["464xlat", "dslite", "ipip", "lw4o6", "map_e", "map_t"]
        );
    }

    #[test]
    fn parses_hb46pp_capability_wire_names() {
        for capability in Capability::ALL {
            assert_eq!(capability.as_str().parse(), Ok(capability));
        }
    }

    #[test]
    fn rejects_unknown_capability_wire_names() {
        for name in ["DS-Lite", "wireguard"] {
            let error = name.parse::<Capability>().unwrap_err();

            assert_eq!(error, CapabilityError::UnsupportedName(name.to_string()));
        }
    }

    #[test]
    fn accepts_ttl_at_the_specification_limit() {
        let ttl = Ttl::try_from(604_800).unwrap();

        assert_eq!(ttl.as_secs(), 604_800);
    }

    #[test]
    fn rejects_ttl_above_the_specification_limit() {
        let error = Ttl::try_from(604_801).unwrap_err();

        assert_eq!(error, TtlError::TooLarge);
    }

    #[test]
    fn parses_hb46pp_auth_statuses() {
        for (wire_name, status) in [
            ("req", AuthStatus::Required),
            ("bad", AuthStatus::Rejected),
            ("ok", AuthStatus::Accepted),
        ] {
            assert_eq!(wire_name.parse(), Ok(status));
            assert_eq!(status.as_str(), wire_name);
        }
    }

    #[test]
    fn rejects_unknown_hb46pp_auth_status() {
        let error = "required".parse::<AuthStatus>().unwrap_err();

        assert_eq!(
            error,
            AuthStatusError::UnsupportedStatus("required".to_string())
        );
    }

    #[test]
    fn parses_v6connect_response_shape() {
        let response = ProvisioningData::parse(&format!(
            r#"{{
                "ttl": 86400,
                "token": "{TOKEN}",
                "service_name": "v6 コネクト",
                "enabler_name": "v6 コネクト",
                "dslite": {{"aftr": "dslite.v6connect.net"}},
                "order": ["dslite"],
                "future_extension": {{"ignored": true}}
            }}"#
        ))
        .unwrap();

        assert_eq!(response.provider_info().enabler_name(), "v6 コネクト");
        assert_eq!(response.provider_info().service_name(), Some("v6 コネクト"));
        assert_eq!(response.provider_info().isp_name(), None);
        assert_eq!(response.ttl().unwrap().as_secs(), 86_400);
        assert_eq!(response.token().unwrap().as_str(), TOKEN);
        assert_eq!(response.auth(), None);
        assert_eq!(response.order(), [Capability::DsLite]);
        assert_eq!(
            response.offer(Capability::DsLite),
            Some(&serde_json::json!({"aftr": "dslite.v6connect.net"}))
        );
    }

    #[test]
    fn retains_ipv6_mostly_xlat_offer_outside_activation_order() {
        let response = ProvisioningData::parse(
            r#"{
                "enabler_name": "example",
                "order": ["dslite"],
                "ipv6_mostly": true,
                "dslite": {"aftr": "dslite.example"},
                "464xlat": {"nat64prefix": "64:ff9b::/96"}
            }"#,
        )
        .unwrap();

        assert_eq!(response.order(), [Capability::DsLite]);
        assert_eq!(response.ipv6_mostly(), Some(true));
        assert_eq!(
            response.offer(Capability::Xlat464),
            Some(&serde_json::json!({"nat64prefix": "64:ff9b::/96"}))
        );
    }

    #[test]
    fn selects_the_first_server_ordered_supported_offer() {
        let response = ProvisioningData::parse(
            r#"{
                "enabler_name": "example",
                "order": ["map_e", "dslite"],
                "map_e": {"br": "2001:db8::1", "rules": []},
                "dslite": {"aftr": "dslite.example"}
            }"#,
        )
        .unwrap();

        let selected = response
            .select(&[Capability::DsLite, Capability::MapE])
            .unwrap();

        assert_eq!(selected.capability(), Capability::MapE);
        assert_eq!(
            selected.parameters(),
            &serde_json::json!({"br": "2001:db8::1", "rules": []})
        );
    }

    #[test]
    fn selects_a_later_offer_when_higher_priority_offers_are_unsupported() {
        let response = ProvisioningData::parse(
            r#"{
                "enabler_name": "example",
                "order": ["map_e", "dslite"],
                "map_e": {"br": "2001:db8::1", "rules": []},
                "dslite": {"aftr": "dslite.example"}
            }"#,
        )
        .unwrap();

        let selected = response.select(&[Capability::DsLite]).unwrap();

        assert_eq!(selected.capability(), Capability::DsLite);
        assert_eq!(
            selected.parameters(),
            &serde_json::json!({"aftr": "dslite.example"})
        );
    }

    #[test]
    fn selects_nothing_when_no_ordered_offer_is_supported() {
        let response = ProvisioningData::parse(
            r#"{
                "enabler_name": "example",
                "order": ["map_e"],
                "map_e": {"br": "2001:db8::1", "rules": []}
            }"#,
        )
        .unwrap();

        assert!(response.select(&[Capability::DsLite]).is_none());
    }

    #[test]
    fn rejects_null_for_an_optional_response_field() {
        let error = ProvisioningData::parse(
            r#"{
                "enabler_name": "example",
                "token": null,
                "order": []
            }"#,
        )
        .unwrap_err();

        assert!(matches!(error, ProvisioningDataError::NullField("token")));
    }

    #[test]
    fn rejects_non_object_method_payload() {
        let error = ProvisioningData::parse(
            r#"{
                "enabler_name": "example",
                "order": ["dslite"],
                "dslite": "invalid"
            }"#,
        )
        .unwrap_err();

        assert!(matches!(
            error,
            ProvisioningDataError::InvalidOfferShape(Capability::DsLite)
        ));
    }

    #[test]
    fn accepts_ipip_array_payload() {
        let response = ProvisioningData::parse(
            r#"{
                "enabler_name": "example",
                "order": ["ipip"],
                "ipip": [{
                    "ipv6_local": "2001:db8:1::1",
                    "ipv6_remote": "2001:db8:2::1",
                    "ipv4": "192.0.2.0/29"
                }]
            }"#,
        )
        .unwrap();

        assert_eq!(
            response.offer(Capability::IpIp),
            Some(&serde_json::json!([{
                "ipv6_local": "2001:db8:1::1",
                "ipv6_remote": "2001:db8:2::1",
                "ipv4": "192.0.2.0/29"
            }]))
        );
    }

    #[test]
    fn rejects_ipip_object_payload() {
        let error = ProvisioningData::parse(
            r#"{
                "enabler_name": "example",
                "order": ["ipip"],
                "ipip": {"ipv6_remote": "2001:db8:2::1"}
            }"#,
        )
        .unwrap_err();

        assert!(matches!(
            error,
            ProvisioningDataError::InvalidOfferShape(Capability::IpIp)
        ));
    }

    #[test]
    fn rejects_non_object_entry_in_ipip_array() {
        let error = ProvisioningData::parse(
            r#"{
                "enabler_name": "example",
                "order": ["ipip"],
                "ipip": ["invalid"]
            }"#,
        )
        .unwrap_err();

        assert!(matches!(
            error,
            ProvisioningDataError::InvalidOfferShape(Capability::IpIp)
        ));
    }

    #[test]
    fn rejects_an_ordered_capability_without_a_payload() {
        let error = ProvisioningData::parse(
            r#"{
                "enabler_name": "example",
                "order": ["dslite"]
            }"#,
        )
        .unwrap_err();

        assert!(matches!(
            error,
            ProvisioningDataError::MissingOffer(Capability::DsLite)
        ));
    }

    #[test]
    fn validates_ttl_and_token_in_a_response() {
        let ttl_error = ProvisioningData::parse(
            r#"{
                "enabler_name": "example",
                "ttl": 604801,
                "order": []
            }"#,
        )
        .unwrap_err();
        let token_error = ProvisioningData::parse(
            r#"{
                "enabler_name": "example",
                "token": "not-a-token",
                "order": []
            }"#,
        )
        .unwrap_err();

        assert!(matches!(ttl_error, ProvisioningDataError::Ttl(_)));
        assert!(matches!(token_error, ProvisioningDataError::Token(_)));
    }

    #[test]
    fn builds_valid_provisioning_request() {
        let request = valid_request();

        assert_eq!(request.vendor_id().as_str(), "000000");
        assert_eq!(request.product().as_str(), "dslite-b4");
        assert_eq!(request.version().as_str(), "0_1_0");
        assert_eq!(request.capabilities(), [Capability::DsLite]);
        assert_eq!(request.token(), None);
    }

    #[test]
    fn accepts_multiple_capabilities_and_a_token() {
        let request = ProvisioningRequest::new(
            "acde48-v6pc_swg_hgw".parse().unwrap(),
            "V6MIG-ROUTER".parse().unwrap(),
            "1_32".parse().unwrap(),
            vec![Capability::MapE, Capability::DsLite, Capability::Lw4o6],
            Some(TOKEN.parse().unwrap()),
            None,
        )
        .unwrap();

        assert_eq!(
            request.capabilities(),
            [Capability::MapE, Capability::DsLite, Capability::Lw4o6]
        );
        assert_eq!(request.token(), Some(TOKEN));
    }

    #[test]
    fn parses_valid_token() {
        let token: Token = TOKEN.parse().unwrap();

        assert_eq!(token.as_str(), TOKEN);
    }

    #[test]
    fn rejects_invalid_token_formats() {
        let invalid_tokens = [
            "0".repeat(63),
            "0".repeat(65),
            format!("A{}", "0".repeat(63)),
            format!("g{}", "0".repeat(63)),
        ];

        for token in invalid_tokens {
            let error = token.parse::<Token>().unwrap_err();

            assert_eq!(error, TokenError::InvalidFormat);
        }
    }

    #[test]
    fn redacts_tokens_in_debug_output() {
        let token: Token = TOKEN.parse().unwrap();

        let debug = format!("{token:?}");

        assert_eq!(debug, "Token([redacted])");
    }

    #[test]
    fn rejects_invalid_credentials() {
        let invalid_user =
            Credentials::unrestricted("user!".to_string(), "pass".to_string()).unwrap_err();
        let invalid_password =
            Credentials::unrestricted("user".to_string(), "pass!".to_string()).unwrap_err();
        let invalid_server_name = Credentials::for_server(
            "user".to_string(),
            "pass".to_string(),
            "[2001:db8::1".to_string(),
        )
        .unwrap_err();

        assert_eq!(invalid_user, CredentialsError::InvalidUser);
        assert_eq!(invalid_password, CredentialsError::InvalidPassword);
        assert_eq!(
            invalid_server_name,
            CredentialsError::InvalidExpectedServerName
        );
    }

    #[test]
    fn rejects_invalid_vendor_id() {
        let error = "not-an-oui".parse::<VendorId>().unwrap_err();

        assert_eq!(error, VendorIdError::InvalidFormat);
    }

    #[test]
    fn rejects_invalid_product() {
        let error = "dslite b4".parse::<Product>().unwrap_err();

        assert_eq!(error, ProductError::InvalidFormat);
    }

    #[test]
    fn rejects_invalid_version() {
        let error = "0.1.0".parse::<FirmwareVersion>().unwrap_err();

        assert_eq!(error, FirmwareVersionError::InvalidFormat);
    }

    #[test]
    fn rejects_empty_capabilities() {
        let error =
            ProvisioningRequest::new(vendor_id(), product(), version(), Vec::new(), None, None)
                .unwrap_err();

        assert_eq!(error, ProvisioningRequestError::EmptyCapabilities);
    }

    #[test]
    fn rejects_duplicate_capabilities() {
        let error = ProvisioningRequest::new(
            vendor_id(),
            product(),
            version(),
            vec![Capability::DsLite, Capability::DsLite],
            None,
            None,
        )
        .unwrap_err();

        assert_eq!(error, ProvisioningRequestError::DuplicateCapability);
    }

    #[test]
    fn parses_v6connect_bootstrap_record() {
        let bootstrap = Bootstrap::parse(V6CONNECT_BOOTSTRAP).unwrap();

        assert_eq!(
            bootstrap.endpoint().as_str(),
            "https://prod.v6mig.v6connect.net/cpe/v1/config"
        );
        assert_eq!(bootstrap.tls_policy(), TlsPolicy::ValidateCertificate);
    }

    #[test]
    fn accepts_http_without_tls_validation() {
        let bootstrap = Bootstrap::parse("v=v6mig-1 url=http://vne.example/rule.cgi t=a").unwrap();

        assert_eq!(bootstrap.endpoint().scheme(), "http");
        assert_eq!(bootstrap.tls_policy(), TlsPolicy::NoCertificateValidation);
    }

    #[test]
    fn builds_provisioning_url() {
        let bootstrap = Bootstrap::parse(V6CONNECT_BOOTSTRAP).unwrap();
        let request = valid_request();

        let pairs: Vec<_> = bootstrap
            .provisioning_url(&request)
            .unwrap()
            .query_pairs()
            .into_owned()
            .collect();

        assert_eq!(
            pairs,
            [
                ("vendorid".to_string(), "000000".to_string()),
                ("product".to_string(), "dslite-b4".to_string()),
                ("version".to_string(), "0_1_0".to_string()),
                ("capability".to_string(), "dslite".to_string()),
            ]
        );
    }

    #[test]
    fn preserves_existing_query_pairs_and_appends_token() {
        let bootstrap =
            Bootstrap::parse("v=v6mig-1 url=https://vne.example/rule.cgi?provider=example t=b")
                .unwrap();
        let request = ProvisioningRequest::new(
            vendor_id(),
            product(),
            version(),
            vec![Capability::MapE, Capability::DsLite],
            Some(TOKEN.parse().unwrap()),
            None,
        )
        .unwrap();

        let pairs: Vec<_> = bootstrap
            .provisioning_url(&request)
            .unwrap()
            .query_pairs()
            .into_owned()
            .collect();

        assert_eq!(
            pairs,
            [
                ("provider".to_string(), "example".to_string()),
                ("vendorid".to_string(), "000000".to_string()),
                ("product".to_string(), "dslite-b4".to_string()),
                ("version".to_string(), "0_1_0".to_string()),
                ("capability".to_string(), "map_e,dslite".to_string()),
                ("token".to_string(), TOKEN.to_string()),
            ]
        );
    }

    #[test]
    fn sends_credentials_without_expected_server_name() {
        let bootstrap = Bootstrap::parse(V6CONNECT_BOOTSTRAP).unwrap();
        let request = ProvisioningRequest::new(
            vendor_id(),
            product(),
            version(),
            vec![Capability::DsLite],
            None,
            Some(Credentials::unrestricted("user".to_string(), "pass".to_string()).unwrap()),
        )
        .unwrap();

        let pairs: Vec<_> = bootstrap
            .provisioning_url(&request)
            .unwrap()
            .query_pairs()
            .into_owned()
            .collect();

        assert!(pairs.contains(&("user".to_string(), "user".to_string())));
        assert!(pairs.contains(&("pass".to_string(), "pass".to_string())));
    }

    #[test]
    fn sends_credentials_when_expected_server_name_matches_validated_https() {
        let bootstrap = Bootstrap::parse(V6CONNECT_BOOTSTRAP).unwrap();
        let request = ProvisioningRequest::new(
            vendor_id(),
            product(),
            version(),
            vec![Capability::DsLite],
            None,
            Some(credentials_for_server("prod.v6mig.v6connect.net")),
        )
        .unwrap();

        assert!(bootstrap.provisioning_url(&request).is_ok());
    }

    #[test]
    fn rejects_credentials_for_unvalidated_or_unexpected_bootstrap() {
        let request_with_expected_server = ProvisioningRequest::new(
            vendor_id(),
            product(),
            version(),
            vec![Capability::DsLite],
            None,
            Some(credentials_for_server("provision.example")),
        )
        .unwrap();
        let http = Bootstrap::parse("v=v6mig-1 url=http://provision.example/rule.cgi t=a").unwrap();
        let unvalidated_https =
            Bootstrap::parse("v=v6mig-1 url=https://provision.example/rule.cgi t=a").unwrap();
        let unexpected_host =
            Bootstrap::parse("v=v6mig-1 url=https://other.example/rule.cgi t=b").unwrap();

        assert_eq!(
            http.provisioning_url(&request_with_expected_server),
            Err(ProvisioningUrlError::CredentialsRequireHttps)
        );
        assert_eq!(
            unvalidated_https.provisioning_url(&request_with_expected_server),
            Err(ProvisioningUrlError::CredentialsRequireCertificateValidation)
        );
        assert_eq!(
            unexpected_host.provisioning_url(&request_with_expected_server),
            Err(ProvisioningUrlError::UnexpectedProvisioningHost)
        );
    }

    #[test]
    fn rejects_missing_url_field() {
        let error = Bootstrap::parse("v=v6mig-1").unwrap_err();

        assert!(matches!(error, BootstrapError::MissingField(_)));
    }

    #[test]
    fn rejects_fields_out_of_order() {
        let error = Bootstrap::parse("url=https://vne.example/rule.cgi v=v6mig-1 t=b").unwrap_err();

        assert!(matches!(error, BootstrapError::MalformedField(_, _)));
    }

    #[test]
    fn rejects_unsupported_version() {
        let error = Bootstrap::parse("v=v6mig-2 url=https://vne.example/rule.cgi t=b").unwrap_err();

        assert!(matches!(error, BootstrapError::UnsupportedVersion(_)));
    }

    #[test]
    fn rejects_non_http_url_scheme() {
        let error = Bootstrap::parse("v=v6mig-1 url=ftp://vne.example/rule.cgi t=a").unwrap_err();

        assert!(matches!(error, BootstrapError::InvalidUrl(_, _)));
    }

    #[test]
    fn rejects_http_with_tls_validation() {
        let error = Bootstrap::parse("v=v6mig-1 url=http://vne.example/rule.cgi t=b").unwrap_err();

        assert!(matches!(error, BootstrapError::InvalidTlsForHttp));
    }

    #[test]
    fn rejects_extra_fields() {
        let error = Bootstrap::parse("v=v6mig-1 url=https://vne.example/rule.cgi t=b extra=value")
            .unwrap_err();

        assert!(matches!(error, BootstrapError::InvalidRecord(_)));
    }

    #[test]
    fn rejects_ipv4_literal_provisioning_url() {
        let error = Bootstrap::parse("v=v6mig-1 url=https://192.0.2.1/provision t=b").unwrap_err();

        assert!(matches!(error, BootstrapError::Ipv4EndpointNotAllowed));
    }

    #[test]
    fn sets_and_clears_provisioning_request_token() {
        let mut request = valid_request();
        assert_eq!(request.token(), None);

        request.set_token(Some(TOKEN.parse().unwrap()));
        assert_eq!(request.token(), Some(TOKEN));

        request.set_token(None);
        assert_eq!(request.token(), None);
    }
}