atproto-devtool 0.1.1

A multitool for the atproto developer ecosystem
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
//! Identity resolution primitives for ATProto handles, DIDs, services, and multikey parsing.
//!
//! This module provides a narrow interface over HTTP and DNS resolution,
//! allowing callers to swap real network I/O with recorded fixtures in tests.

use async_trait::async_trait;
use k256::ecdsa::signature::hazmat::PrehashVerifier;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::sync::Arc;
use thiserror::Error;
use url::Url;

use crate::common::APP_USER_AGENT;

/// A DID method identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DidMethod {
    /// `did:plc:` — decentralized identifiers on the PLC directory.
    Plc,
    /// `did:web:` — decentralized identifiers over HTTPS.
    Web,
    /// An unrecognized DID method.
    Other,
}

/// A decentralized identifier (DID), internally stored as a string.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Did(pub String);

impl Did {
    /// Returns the method component of this DID.
    pub fn method(&self) -> DidMethod {
        if self.0.starts_with("did:plc:") {
            DidMethod::Plc
        } else if self.0.starts_with("did:web:") {
            DidMethod::Web
        } else {
            DidMethod::Other
        }
    }
}

impl fmt::Display for Did {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// A verification method (public key) from a DID document.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VerificationMethod {
    /// The identifier for this method, e.g. `"#atproto_labeler"`.
    pub id: String,
    /// The cryptographic type, e.g. `"EcdsaSecp256k1VerificationKey2019"`.
    #[serde(rename = "type")]
    pub type_: String,
    /// The controller DID for this method.
    pub controller: String,
    /// The public key in multibase format.
    #[serde(rename = "publicKeyMultibase", skip_serializing_if = "Option::is_none")]
    pub public_key_multibase: Option<String>,
}

/// A service endpoint from a DID document.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Service {
    /// The identifier for this service, e.g. `"#atproto_labeler"` or `"did:plc:xyz#atproto_labeler"`.
    pub id: String,
    /// The service type, e.g. `"AtprotoLabeler"`.
    #[serde(rename = "type")]
    pub type_: String,
    /// The service endpoint URL or value.
    #[serde(rename = "serviceEndpoint")]
    pub service_endpoint: String,
}

/// A minimal DID document with only the fields we need.
///
/// Per user-global rules, we use explicit field-level `#[serde(rename)]`
/// attributes instead of `#[serde(flatten)]`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DidDocument {
    /// The DID identifier.
    pub id: String,
    /// Aliases for this DID (e.g., handles).
    #[serde(rename = "alsoKnownAs", skip_serializing_if = "Option::is_none")]
    pub also_known_as: Option<Vec<String>>,
    /// Public keys and other verification methods.
    #[serde(rename = "verificationMethod", skip_serializing_if = "Option::is_none")]
    pub verification_method: Option<Vec<VerificationMethod>>,
    /// Service endpoints provided by this DID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service: Option<Vec<Service>>,
}

/// The parsed DID document along with the raw bytes and source name.
///
/// Downstream stages attach the raw bytes to miette diagnostics.
#[derive(Debug, Clone)]
pub struct RawDidDocument {
    /// The parsed DID document.
    pub parsed: DidDocument,
    /// The raw bytes returned by the server.
    pub source_bytes: Arc<[u8]>,
    /// The URL or source name for diagnostics.
    pub source_name: String,
}

/// A public key that may be one of several supported curves.
#[derive(Debug, Clone)]
pub enum AnyVerifyingKey {
    /// secp256k1 verifying key.
    K256(k256::ecdsa::VerifyingKey),
    /// P-256 verifying key.
    P256(p256::ecdsa::VerifyingKey),
}

impl AnyVerifyingKey {
    /// Returns the short curve name for this key ("secp256k1" or "P-256").
    pub fn curve_name(&self) -> &'static str {
        match self {
            AnyVerifyingKey::K256(_) => "secp256k1",
            AnyVerifyingKey::P256(_) => "P-256",
        }
    }

    /// Verifies a prehashed signature against this key.
    ///
    /// The prehash must be a 32-byte SHA-256 digest.
    pub fn verify_prehash(
        &self,
        prehash: &[u8; 32],
        sig: &AnySignature,
    ) -> Result<(), AnySignatureError> {
        match (self, sig) {
            (AnyVerifyingKey::K256(key), AnySignature::K256(sig)) => key
                .verify_prehash(prehash, sig)
                .map_err(AnySignatureError::K256),
            (AnyVerifyingKey::P256(key), AnySignature::P256(sig)) => key
                .verify_prehash(prehash, sig)
                .map_err(AnySignatureError::P256),
            _ => Err(AnySignatureError::CurveMismatch),
        }
    }
}

/// A private signing key that may be one of several supported curves.
///
/// Mirrors `AnyVerifyingKey` for the signing side. Signatures produced by
/// `sign` are always low-s normalized to match the atproto convention
/// already established by `AnySignature`.
#[derive(Debug, Clone)]
pub enum AnySigningKey {
    /// secp256k1 signing key.
    K256(k256::ecdsa::SigningKey),
    /// P-256 signing key.
    P256(p256::ecdsa::SigningKey),
}

impl AnySigningKey {
    /// Returns the corresponding verifying key.
    pub fn verifying_key(&self) -> AnyVerifyingKey {
        match self {
            AnySigningKey::K256(k) => AnyVerifyingKey::K256(*k.verifying_key()),
            AnySigningKey::P256(k) => AnyVerifyingKey::P256(*k.verifying_key()),
        }
    }

    /// Returns the JWT `alg` header identifier for this key's curve
    /// ("ES256K" for secp256k1, "ES256" for P-256).
    pub fn jwt_alg(&self) -> &'static str {
        match self {
            AnySigningKey::K256(_) => "ES256K",
            AnySigningKey::P256(_) => "ES256",
        }
    }

    /// Signs the SHA-256 prehash of `msg` and returns the signature in
    /// low-s normalized form.
    ///
    /// The returned `AnySignature` is guaranteed to satisfy
    /// `AnyVerifyingKey::verify_prehash` against the corresponding
    /// verifying key when given the same prehash bytes.
    pub fn sign(&self, msg: &[u8]) -> AnySignature {
        use sha2::{Digest, Sha256};
        let prehash: [u8; 32] = Sha256::digest(msg).into();
        self.sign_prehash(&prehash)
    }

    /// Signs a precomputed 32-byte SHA-256 prehash directly.
    pub fn sign_prehash(&self, prehash: &[u8; 32]) -> AnySignature {
        use k256::ecdsa::signature::hazmat::PrehashSigner as K256PrehashSigner;
        use p256::ecdsa::signature::hazmat::PrehashSigner as P256PrehashSigner;
        match self {
            AnySigningKey::K256(k) => {
                // k256's sign_prehash already returns a low-s normalized
                // signature (BIP-0062 enforcement is built in). Returns an
                // ecdsa::Signature.
                let sig: k256::ecdsa::Signature = K256PrehashSigner::sign_prehash(k, prehash)
                    .expect("SHA-256 output is always 32 bytes");
                AnySignature::K256(sig)
            }
            AnySigningKey::P256(k) => {
                // p256's sign_prehash may return a high-s signature;
                // normalize explicitly.
                let sig: p256::ecdsa::Signature = P256PrehashSigner::sign_prehash(k, prehash)
                    .expect("SHA-256 output is always 32 bytes");
                let normalized = sig.normalize_s().unwrap_or(sig);
                AnySignature::P256(normalized)
            }
        }
    }
}

/// A signature that may be one of several supported curves.
#[derive(Debug, Clone)]
pub enum AnySignature {
    /// secp256k1 signature.
    K256(k256::ecdsa::Signature),
    /// P-256 signature.
    P256(p256::ecdsa::Signature),
}

impl AnySignature {
    /// Serializes the signature bytes for JWS compact form: raw `r || s`
    /// big-endian concatenation (NOT DER).
    ///
    /// For both ES256 and ES256K this is a 64-byte fixed-length array.
    pub fn to_jws_bytes(&self) -> [u8; 64] {
        match self {
            AnySignature::K256(s) => s.to_bytes().into(),
            AnySignature::P256(s) => s.to_bytes().into(),
        }
    }
}

/// Error from signature verification across multiple curves.
#[derive(Debug, thiserror::Error)]
pub enum AnySignatureError {
    /// secp256k1 signature error.
    #[error("secp256k1 signature verification failed")]
    K256(#[source] k256::ecdsa::Error),
    /// P-256 signature error.
    #[error("P-256 signature verification failed")]
    P256(#[source] p256::ecdsa::Error),
    /// Signature and key use mismatched curves.
    #[error("Signature and key use mismatched curves")]
    CurveMismatch,
}

/// A multikey public key, parsed and ready for signature verification.
#[derive(Debug, Clone)]
pub struct ParsedMultikey {
    /// The verifying key.
    pub verifying_key: AnyVerifyingKey,
}

/// Errors during identity resolution.
#[derive(Debug, Error)]
pub enum IdentityError {
    /// Handle was syntactically invalid.
    #[error("Invalid handle format")]
    InvalidHandle,

    /// Handle could not be resolved via DNS or HTTPS.
    #[error("Handle could not be resolved")]
    HandleUnresolvable {
        /// DNS lookup error (if any).
        dns_error: Option<Box<IdentityError>>,
        /// HTTPS fallback error (if any).
        http_error: Option<Box<IdentityError>>,
    },

    /// DNS lookup failed.
    #[error("DNS lookup failed")]
    DnsLookupFailed {
        /// The underlying DNS error.
        #[source]
        source: Box<IdentityError>,
    },

    /// DNS backend resolver error.
    #[error("DNS backend error")]
    DnsBackend(#[from] hickory_resolver::ResolveError),

    /// HTTPS fallback for handle resolution failed.
    #[error("HTTP fallback for handle resolution failed")]
    HandleHttpFallbackFailed {
        /// The underlying HTTP error.
        #[source]
        source: Box<IdentityError>,
    },

    /// DID method is not supported.
    #[error("Unsupported DID method: {method}")]
    UnsupportedDidMethod { method: String },

    /// DID resolution failed with a non-200 status.
    #[error("DID resolution failed with status {status}")]
    DidResolutionFailed {
        /// The HTTP status code.
        status: u16,
        /// The response body.
        body: String,
    },

    /// DNS record exists but contains no DID entry.
    #[error("DNS record for {handle} has no did= entry")]
    DnsNoDidRecord {
        /// The handle that was queried.
        handle: String,
    },

    /// DID body is invalid or malformed.
    #[error("Invalid DID body: {body}")]
    InvalidDidBody {
        /// The invalid body content.
        body: String,
    },

    /// DID document could not be decoded.
    #[error("DID document decode failed")]
    DidDocumentDecodeFailed {
        /// The source name for diagnostics.
        source_name: String,
        /// The raw bytes for diagnostics.
        source_bytes: Arc<[u8]>,
        /// The JSON parse error.
        #[source]
        cause: serde_json::Error,
    },

    /// Multikey decoding failed.
    #[error("Multikey decoding failed")]
    MultikeyDecodeFailed {
        /// The underlying error.
        #[source]
        source: Box<IdentityError>,
    },

    /// Multibase encoding was not supported.
    #[error("Unsupported multibase encoding")]
    UnsupportedMultibase(String),

    /// Curve is not supported.
    #[error("Unsupported curve")]
    UnsupportedCurve { codec_prefix: Vec<u8> },

    /// Multikey length was invalid.
    #[error("Invalid multikey length")]
    MultikeyLengthInvalid,

    /// HTTP transport error from reqwest.
    #[error("HTTP transport error")]
    HttpTransport(#[from] reqwest::Error),
}

/// Trait for HTTP clients used by identity resolution.
///
/// Narrow interface allowing test fixtures to be injected.
#[async_trait]
pub trait HttpClient: Send + Sync {
    /// Fetches the bytes at the given URL, returning status code and body.
    async fn get_bytes(&self, url: &Url) -> Result<(u16, Vec<u8>), IdentityError>;
}

/// Trait for DNS resolvers used by identity resolution.
///
/// Narrow interface allowing test fixtures to be injected.
#[async_trait]
pub trait DnsResolver: Send + Sync {
    /// Performs a TXT lookup on the given name.
    async fn txt_lookup(&self, name: &str) -> Result<Vec<String>, IdentityError>;
}

/// Real HTTP client using reqwest.
pub struct RealHttpClient {
    inner: reqwest::Client,
}

impl RealHttpClient {
    /// Creates a new HTTP client with a conservative 10-second timeout.
    ///
    /// Uses rustls for TLS (per Cargo.toml `rustls-tls` feature) rather than native-tls
    /// to avoid linking against OpenSSL. Sets a User-Agent header for HTTPS requests.
    pub fn new() -> Result<Self, IdentityError> {
        let client = reqwest::Client::builder()
            .use_rustls_tls()
            .user_agent(APP_USER_AGENT)
            .timeout(std::time::Duration::from_secs(10))
            .build()?;
        Ok(Self { inner: client })
    }

    /// Creates a new HTTP client from an existing reqwest::Client.
    ///
    /// Allows sharing a single client instance across multiple stages.
    pub fn from_client(client: reqwest::Client) -> Self {
        Self { inner: client }
    }
}

#[async_trait]
impl HttpClient for RealHttpClient {
    async fn get_bytes(&self, url: &Url) -> Result<(u16, Vec<u8>), IdentityError> {
        let response = self.inner.get(url.clone()).send().await?;
        let status = response.status().as_u16();
        let bytes = response.bytes().await?;
        Ok((status, bytes.to_vec()))
    }
}

/// Real DNS resolver using hickory-resolver.
pub struct RealDnsResolver {
    inner: hickory_resolver::TokioResolver,
}

impl RealDnsResolver {
    /// Creates a new DNS resolver with system configuration.
    pub fn new() -> Self {
        let resolver = hickory_resolver::Resolver::builder_tokio()
            .expect("failed to build DNS resolver")
            .build();
        Self { inner: resolver }
    }
}

impl Default for RealDnsResolver {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl DnsResolver for RealDnsResolver {
    async fn txt_lookup(&self, name: &str) -> Result<Vec<String>, IdentityError> {
        let lookup = self.inner.txt_lookup(name).await?;
        lookup
            .iter()
            .map(|record| {
                let text = record
                    .iter()
                    .map(|data| {
                        String::from_utf8(data.to_vec()).unwrap_or_else(|_| {
                            tracing::debug!(
                                target = "atproto_devtool::identity",
                                "dropping non-UTF-8 TXT record data"
                            );
                            String::new()
                        })
                    })
                    .collect::<Vec<_>>()
                    .join("");
                Ok(text)
            })
            .collect()
    }
}

/// Resolves an ATProto handle to a DID via DNS or HTTPS fallback.
///
/// Attempts DNS lookup on `_atproto.<handle>` for a `did=...` record,
/// then falls back to HTTPS GET on `https://<handle>/.well-known/atproto-did`.
pub async fn resolve_handle(
    handle: &str,
    http: &dyn HttpClient,
    dns: &dyn DnsResolver,
) -> Result<Did, IdentityError> {
    // Validate handle format: at least one dot, all ASCII, no leading/trailing dot.
    if handle.is_empty()
        || handle.starts_with('.')
        || handle.ends_with('.')
        || !handle.is_ascii()
        || !handle.contains('.')
    {
        return Err(IdentityError::InvalidHandle);
    }

    tracing::debug!(
        target = "atproto_devtool::identity",
        handle = %handle,
        "resolving handle"
    );

    // DNS path: look up _atproto.<handle> for did= records.
    let dns_name = format!("_atproto.{handle}");

    let dns_error_opt = match dns.txt_lookup(&dns_name).await {
        Ok(records) => {
            // Check if any record contains a did= entry.
            for record in records {
                let trimmed = record.trim();
                if let Some(did_str) = trimmed.strip_prefix("did=") {
                    let did = Did(did_str.to_string());
                    tracing::debug!(
                        target = "atproto_devtool::identity",
                        did = %did,
                        "resolved handle via DNS"
                    );
                    return Ok(did);
                }
            }
            // Records exist but no did= entry found; populate error for fallback.
            Some(Box::new(IdentityError::DnsNoDidRecord {
                handle: handle.to_string(),
            }))
        }
        Err(e) => Some(Box::new(e)),
    };

    // HTTPS fallback: GET https://<handle>/.well-known/atproto-did.
    let url = format!("https://{handle}/.well-known/atproto-did");
    let url = url
        .parse::<Url>()
        .map_err(|_| IdentityError::InvalidHandle)?;

    let http_error_opt = match http.get_bytes(&url).await {
        Ok((200, bytes)) => {
            let did_str = String::from_utf8_lossy(&bytes).trim().to_string();
            if !did_str.is_empty() && did_str.starts_with("did:") {
                let did = Did(did_str);
                tracing::debug!(
                    target = "atproto_devtool::identity",
                    did = %did,
                    "resolved handle via HTTPS"
                );
                return Ok(did);
            } else {
                Some(Box::new(IdentityError::HandleHttpFallbackFailed {
                    source: Box::new(IdentityError::InvalidDidBody { body: did_str }),
                }))
            }
        }
        Ok((status, bytes)) => Some(Box::new(IdentityError::HandleHttpFallbackFailed {
            source: Box::new(IdentityError::DidResolutionFailed {
                status,
                body: String::from_utf8_lossy(&bytes).to_string(),
            }),
        })),
        Err(e) => Some(Box::new(IdentityError::HandleHttpFallbackFailed {
            source: Box::new(e),
        })),
    };

    // Both paths failed.
    Err(IdentityError::HandleUnresolvable {
        dns_error: dns_error_opt,
        http_error: http_error_opt,
    })
}

/// Resolves a DID to a parsed DID document with raw bytes.
///
/// Returns both the parsed document and the raw bytes for use in diagnostics.
pub async fn resolve_did(
    did: &Did,
    http: &dyn HttpClient,
) -> Result<RawDidDocument, IdentityError> {
    tracing::debug!(
        target = "atproto_devtool::identity",
        did = %did,
        "resolving DID"
    );

    let (url, source_name) = match did.method() {
        DidMethod::Plc => {
            // did:plc identifiers are base32-like and contain only URL-safe characters.
            // No additional percent-encoding is needed.
            let did_str = &did.0;
            let url_str = format!("https://plc.directory/{did_str}");
            let url = url_str
                .parse::<Url>()
                .map_err(|_| IdentityError::DidResolutionFailed {
                    status: 400,
                    body: "Invalid DID format".to_string(),
                })?;
            (url.clone(), url.to_string())
        }
        DidMethod::Web => {
            // Strip did:web: prefix and URL-decode path segments.
            let rest = did.0.strip_prefix("did:web:").unwrap_or("");
            let parts: Vec<&str> = rest.split(':').collect();

            if parts.is_empty() {
                return Err(IdentityError::DidResolutionFailed {
                    status: 400,
                    body: "Invalid did:web format".to_string(),
                });
            }

            let host = parts[0];
            let path_parts = &parts[1..];

            let url_str = if path_parts.is_empty() {
                format!("https://{host}/.well-known/did.json")
            } else {
                let path = path_parts
                    .iter()
                    .map(|p| percent_decode_str(p).unwrap_or_default())
                    .collect::<Vec<_>>()
                    .join("/");
                format!("https://{host}/{path}/did.json")
            };

            let url = url_str
                .parse::<Url>()
                .map_err(|_| IdentityError::DidResolutionFailed {
                    status: 400,
                    body: "Invalid URL".to_string(),
                })?;
            (url.clone(), url.to_string())
        }
        DidMethod::Other => {
            return Err(IdentityError::UnsupportedDidMethod {
                method: did.0.clone(),
            });
        }
    };

    let (status, bytes) = http.get_bytes(&url).await?;

    if status != 200 {
        return Err(IdentityError::DidResolutionFailed {
            status,
            body: String::from_utf8_lossy(&bytes).to_string(),
        });
    }

    tracing::debug!(
        target = "atproto_devtool::identity",
        bytes_len = bytes.len(),
        "fetched DID document"
    );

    let parsed = serde_json::from_slice::<DidDocument>(&bytes).map_err(|e| {
        IdentityError::DidDocumentDecodeFailed {
            source_name: source_name.clone(),
            source_bytes: Arc::from(bytes.clone()),
            cause: e,
        }
    })?;

    Ok(RawDidDocument {
        parsed,
        source_bytes: Arc::from(bytes),
        source_name,
    })
}

/// Finds a service in a DID document by fragment and type.
///
/// Matches both `"#fragment"` and `"did:..#fragment"` ID forms.
pub fn find_service<'a>(
    doc: &'a DidDocument,
    id_fragment: &str,
    expected_type: &str,
) -> Option<&'a Service> {
    let services = doc.service.as_ref()?;

    for service in services {
        // Extract the fragment after '#', matching both forms:
        // - "#fragment" (short form)
        // - "did:...#fragment" (full form)
        let frag = service.id.rsplit_once('#').map(|(_, f)| f);
        if frag == Some(id_fragment) && service.type_ == expected_type {
            return Some(service);
        }
    }

    None
}

/// Parses a multikey string into a verifying key.
///
/// Accepts either a bare base58btc multibase string (`z…`) or a
/// `did:key:z…` form. The latter is how PLC audit logs and some DID
/// documents surface verification methods, so stripping the prefix here
/// means every caller can stay agnostic to the wire shape.
pub fn parse_multikey(raw: &str) -> Result<ParsedMultikey, IdentityError> {
    tracing::debug!(target = "atproto_devtool::identity", "parsing multikey");

    let multibase_str = raw.strip_prefix("did:key:").unwrap_or(raw);

    let (base, bytes) =
        multibase::decode(multibase_str).map_err(|_| IdentityError::MultikeyDecodeFailed {
            source: Box::new(IdentityError::UnsupportedMultibase(
                "failed to decode multibase".to_string(),
            )),
        })?;

    // Require base58btc encoding.
    if base != multibase::Base::Base58Btc {
        return Err(IdentityError::UnsupportedMultibase(
            "multikey must use base58btc encoding".to_string(),
        ));
    }

    if bytes.len() < 2 {
        return Err(IdentityError::MultikeyLengthInvalid);
    }

    // Parse the varint curve identifier (two bytes for both supported curves).
    let curve_bytes = [bytes[0], bytes[1]];
    let rest = &bytes[2..];

    match curve_bytes {
        // secp256k1-pub (0xe7 0x01)
        [0xe7, 0x01] => {
            if rest.len() != 33 {
                return Err(IdentityError::MultikeyLengthInvalid);
            }
            let key = k256::ecdsa::VerifyingKey::from_sec1_bytes(rest).map_err(|_| {
                IdentityError::MultikeyDecodeFailed {
                    source: Box::new(IdentityError::MultikeyLengthInvalid),
                }
            })?;
            tracing::debug!(
                target = "atproto_devtool::identity",
                curve = "secp256k1",
                "parsed multikey"
            );
            Ok(ParsedMultikey {
                verifying_key: AnyVerifyingKey::K256(key),
            })
        }
        // p256-pub (0x80 0x24)
        [0x80, 0x24] => {
            if rest.len() != 33 {
                return Err(IdentityError::MultikeyLengthInvalid);
            }
            let key = p256::ecdsa::VerifyingKey::from_sec1_bytes(rest).map_err(|_| {
                IdentityError::MultikeyDecodeFailed {
                    source: Box::new(IdentityError::MultikeyLengthInvalid),
                }
            })?;
            tracing::debug!(
                target = "atproto_devtool::identity",
                curve = "p256",
                "parsed multikey"
            );
            Ok(ParsedMultikey {
                verifying_key: AnyVerifyingKey::P256(key),
            })
        }
        _ => Err(IdentityError::UnsupportedCurve {
            codec_prefix: curve_bytes.to_vec(),
        }),
    }
}

/// Encode an `AnyVerifyingKey` as the atproto multibase-multikey format:
/// base58btc multibase prefix `z`, multicodec curve prefix, compressed SEC1
/// public key bytes.
///
/// See <https://atproto.com/specs/cryptography>. The inverse of `parse_multikey`.
pub fn encode_multikey(key: &AnyVerifyingKey) -> String {
    // Multicodec varint prefixes (see https://github.com/multiformats/multicodec).
    const SECP256K1_PUB: &[u8] = &[0xe7, 0x01];
    const P256_PUB: &[u8] = &[0x80, 0x24];

    let (prefix, compressed): (&[u8], Vec<u8>) = match key {
        AnyVerifyingKey::K256(k) => {
            let point = k.to_encoded_point(true);
            (SECP256K1_PUB, point.as_bytes().to_vec())
        }
        AnyVerifyingKey::P256(k) => {
            let point = k.to_encoded_point(true);
            (P256_PUB, point.as_bytes().to_vec())
        }
    };

    let mut buf = Vec::with_capacity(prefix.len() + compressed.len());
    buf.extend_from_slice(prefix);
    buf.extend_from_slice(&compressed);
    multibase::encode(multibase::Base::Base58Btc, &buf)
}

/// A historic key entry from a PLC audit log for a given verification method fragment.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlcHistoricKey {
    /// The multikey string (the raw key material, not a DID fragment).
    pub key_id: String,
    /// The CID of the operation that introduced this key.
    pub operation_cid: String,
    /// ISO8601 timestamp from the operation.
    pub introduced_at: String,
    /// Whether this key was nullified.
    pub nullified: bool,
}

/// Fetches the PLC audit log for a DID and extracts historic keys for a fragment.
///
/// Only valid for `did:plc:` DIDs. Panics in debug for other methods; returns
/// `Err(UnsupportedDidMethod)` in release. Returns keys in chronological order
/// (oldest-first), matching the PLC API wire order. The caller treats the
/// result as a set — iteration order does not affect verification correctness.
///
/// Transport errors are propagated as `HttpTransport`; decode errors as `DidDocumentDecodeFailed`.
pub async fn plc_history_for_fragment(
    did: &Did,
    fragment: &str,
    http: &dyn HttpClient,
) -> Result<Vec<PlcHistoricKey>, IdentityError> {
    debug_assert!(
        did.method() == DidMethod::Plc,
        "plc_history_for_fragment called with non-plc DID: {did}"
    );

    if did.method() != DidMethod::Plc {
        return Err(IdentityError::UnsupportedDidMethod {
            method: format!("{:?}", did.method()),
        });
    }

    // Construct the audit log URL: https://plc.directory/{did}/log/audit
    let audit_url = format!("https://plc.directory/{did}/log/audit");
    let url = Url::parse(&audit_url).map_err(|_| IdentityError::DidResolutionFailed {
        status: 400,
        body: "Invalid PLC audit URL".to_string(),
    })?;

    let (status, bytes) = http.get_bytes(&url).await?;

    if status != 200 {
        return Err(IdentityError::DidResolutionFailed {
            status,
            body: format!("PLC audit log fetch returned status {status}"),
        });
    }

    // Parse the JSON array of operations.
    let operations: Vec<serde_json::Value> =
        serde_json::from_slice(&bytes).map_err(|cause| IdentityError::DidDocumentDecodeFailed {
            source_name: "plc audit log".to_string(),
            source_bytes: Arc::from(bytes.into_boxed_slice()),
            cause,
        })?;

    let mut historic_keys: Vec<PlcHistoricKey> = Vec::new();

    // Walk operations in wire order (oldest-first). Deduplicate by multikey
    // string: PLC audit logs carry one entry per operation, so a single
    // persistent key is repeated on every unrelated rotation. Callers want
    // the set of distinct keys; the dedup keeps the earliest introduction.
    for op in operations {
        // Extract the verificationMethods object from operation.
        let vm = match op
            .get("operation")
            .and_then(|o| o.get("verificationMethods"))
        {
            Some(vm) => vm,
            None => continue,
        };

        // Look for the requested fragment.
        if let Some(multikey_value) = vm.get(fragment) {
            let multikey_str = match multikey_value.as_str() {
                Some(s) => s.to_string(),
                None => continue,
            };

            let operation_cid = op
                .get("cid")
                .and_then(|c| c.as_str())
                .unwrap_or("unknown")
                .to_string();

            // Extract the timestamp from the operation if available.
            let introduced_at = op
                .get("operation")
                .and_then(|o| o.get("createdAt"))
                .and_then(|c| c.as_str())
                .unwrap_or("unknown")
                .to_string();

            let nullified = op
                .get("nullified")
                .and_then(|n| n.as_bool())
                .unwrap_or(false);

            if historic_keys.iter().any(|k| k.key_id == multikey_str) {
                continue;
            }

            historic_keys.push(PlcHistoricKey {
                key_id: multikey_str,
                operation_cid,
                introduced_at,
                nullified,
            });
        }
    }

    Ok(historic_keys)
}

/// Helper to percent-decode a string.
fn percent_decode_str(s: &str) -> Result<String, IdentityError> {
    let decoded = percent_encoding::percent_decode_str(s)
        .decode_utf8()
        .map_err(|_| IdentityError::DidResolutionFailed {
            status: 400,
            body: "Invalid UTF-8 in percent-encoded path".to_string(),
        })?;
    Ok(decoded.to_string())
}

/// Classify a URL's hostname as "locally reachable from the tool's
/// machine" for the purposes of self-mint `did:web` viability.
///
/// Returns `true` when the hostname is one of:
/// - `localhost` (case-insensitive)
/// - `127.0.0.1` (or any IPv4 loopback / `::1`)
/// - Any `.local` mDNS suffix (case-insensitive)
/// - Any RFC 1918 IPv4 private address (10/8, 172.16/12, 192.168/16)
///
/// Returns `false` for all other hostnames. IPv6 private ranges (fc00::/7,
/// link-local) are deliberately NOT classified as local in v1; revisit if
/// users report issues.
pub fn is_local_labeler_hostname(url: &Url) -> bool {
    use url::Host;

    let host = match url.host() {
        Some(h) => h,
        None => return false,
    };

    match host {
        Host::Ipv4(addr) => addr.is_loopback() || addr.is_private(),
        Host::Ipv6(addr) => addr.is_loopback(),
        Host::Domain(domain) => {
            let lower = domain.to_ascii_lowercase();
            if lower == "localhost" {
                return true;
            }
            if lower.ends_with(".local") {
                return true;
            }
            false
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use k256::ecdsa::SigningKey as K256SigningKey;
    use k256::ecdsa::signature::hazmat::PrehashSigner;
    use p256::ecdsa::SigningKey as P256SigningKey;
    use sha2::Digest;
    use std::collections::HashMap;

    /// Response variant for FakeHttpClient.
    #[derive(Clone)]
    enum Response {
        /// HTTP response with status code and body.
        Http(u16, Vec<u8>),
        /// Transport error (network-level failure).
        Transport(String),
    }

    /// Fake HTTP client for testing, built from a map of URL → response.
    struct FakeHttpClient {
        responses: HashMap<String, Response>,
    }

    #[async_trait]
    impl HttpClient for FakeHttpClient {
        async fn get_bytes(&self, url: &Url) -> Result<(u16, Vec<u8>), IdentityError> {
            match self.responses.get(url.as_str()).cloned() {
                Some(Response::Http(status, body)) => Ok((status, body)),
                Some(Response::Transport(message)) => {
                    // Simulate a transport error by returning a synthesized status 0.
                    // We cannot construct a real reqwest::Error in unit tests, so the
                    // message is threaded into the body so assertions can inspect it.
                    Err(IdentityError::DidResolutionFailed {
                        status: 0,
                        body: format!("Transport error: {message}"),
                    })
                }
                None => Err(IdentityError::DidResolutionFailed {
                    status: 404,
                    body: "Not found".to_string(),
                }),
            }
        }
    }

    /// Fake DNS resolver for testing, built from a map of name → records.
    struct FakeDnsResolver {
        records: HashMap<String, Vec<String>>,
    }

    #[async_trait]
    impl DnsResolver for FakeDnsResolver {
        async fn txt_lookup(&self, name: &str) -> Result<Vec<String>, IdentityError> {
            self.records
                .get(name)
                .cloned()
                .ok_or_else(|| IdentityError::DnsLookupFailed {
                    source: Box::new(IdentityError::InvalidHandle),
                })
        }
    }

    #[tokio::test]
    async fn resolve_handle_via_dns() {
        let mut records = HashMap::new();
        records.insert(
            "_atproto.alice.example".to_string(),
            vec!["did=did:plc:abc123".to_string()],
        );
        let dns = FakeDnsResolver { records };
        let http = FakeHttpClient {
            responses: HashMap::new(),
        };

        let result = resolve_handle("alice.example", &http, &dns).await;

        assert!(result.is_ok());
        let did = result.unwrap();
        assert_eq!(did.0, "did:plc:abc123");
    }

    #[tokio::test]
    async fn resolve_handle_via_https_fallback() {
        let dns = FakeDnsResolver {
            records: HashMap::new(),
        };
        let mut responses = HashMap::new();
        responses.insert(
            "https://alice.example/.well-known/atproto-did".to_string(),
            Response::Http(200, b"did:plc:abc123\n".to_vec()),
        );
        let http = FakeHttpClient { responses };

        let result = resolve_handle("alice.example", &http, &dns).await;

        assert!(result.is_ok());
        let did = result.unwrap();
        assert_eq!(did.0, "did:plc:abc123");
    }

    #[tokio::test]
    async fn resolve_handle_both_paths_fail() {
        let dns = FakeDnsResolver {
            records: HashMap::new(),
        };
        let http = FakeHttpClient {
            responses: HashMap::new(),
        };

        let result = resolve_handle("alice.example", &http, &dns).await;

        assert!(result.is_err());
        match result.unwrap_err() {
            IdentityError::HandleUnresolvable {
                dns_error,
                http_error,
            } => {
                assert!(dns_error.is_some());
                assert!(http_error.is_some());
            }
            _ => panic!("Expected HandleUnresolvable error"),
        }
    }

    #[tokio::test]
    async fn resolve_did_plc_success() {
        let plc_doc = include_bytes!("../../tests/fixtures/identity/plc_bsky_labeler.json");
        let mut responses = HashMap::new();
        responses.insert(
            "https://plc.directory/did:plc:test-labeler".to_string(),
            Response::Http(200, plc_doc.to_vec()),
        );
        let http = FakeHttpClient { responses };

        let did = Did("did:plc:test-labeler".to_string());
        let raw_doc = resolve_did(&did, &http).await.expect("resolve_did");
        assert_eq!(raw_doc.parsed.id, "did:plc:test-labeler");
        assert!(raw_doc.source_bytes.as_ref() == plc_doc);
        assert_eq!(
            raw_doc.source_name,
            "https://plc.directory/did:plc:test-labeler"
        );

        // Verify both services are present.
        let services = raw_doc.parsed.service.as_ref().expect("services");
        assert!(
            services.iter().any(|s| s.type_ == "AtprotoLabeler"),
            "fixture must contain a labeler service"
        );
        assert!(
            services
                .iter()
                .any(|s| s.type_ == "AtprotoPersonalDataServer"),
            "fixture must contain a PDS service"
        );

        // Verify both verification methods are present.
        let vms = raw_doc
            .parsed
            .verification_method
            .as_ref()
            .expect("verificationMethod");
        assert!(
            vms.iter().any(|vm| vm.id == "#atproto"),
            "fixture must contain a repo signing key"
        );
        assert!(
            vms.iter().any(|vm| vm.id == "#atproto_label"),
            "fixture must contain a label signing key"
        );
    }

    #[tokio::test]
    async fn resolve_did_web_success() {
        let web_doc = include_bytes!("../../tests/fixtures/identity/web_example.json");
        let mut responses = HashMap::new();
        responses.insert(
            "https://example.com/.well-known/did.json".to_string(),
            Response::Http(200, web_doc.to_vec()),
        );
        let http = FakeHttpClient { responses };

        let did = Did("did:web:example.com".to_string());
        let result = resolve_did(&did, &http).await;

        assert!(result.is_ok());
        let raw_doc = result.unwrap();
        assert_eq!(raw_doc.parsed.id, "did:web:example.com");
        assert_eq!(
            raw_doc.source_name,
            "https://example.com/.well-known/did.json"
        );
    }

    #[tokio::test]
    async fn resolve_did_decode_failure_preserves_bytes() {
        let bad_json = b"not valid json";
        let mut responses = HashMap::new();
        responses.insert(
            "https://plc.directory/did:plc:bad".to_string(),
            Response::Http(200, bad_json.to_vec()),
        );
        let http = FakeHttpClient { responses };

        let did = Did("did:plc:bad".to_string());
        let result = resolve_did(&did, &http).await;

        assert!(result.is_err());
        match result.unwrap_err() {
            IdentityError::DidDocumentDecodeFailed {
                source_name: _,
                source_bytes,
                cause: _,
            } => {
                assert_eq!(source_bytes.as_ref(), bad_json);
            }
            _ => panic!("Expected DidDocumentDecodeFailed error"),
        }
    }

    #[test]
    fn find_service_matches_both_id_forms() {
        let doc = DidDocument {
            id: "did:plc:abc".to_string(),
            also_known_as: None,
            verification_method: None,
            service: Some(vec![
                Service {
                    id: "did:plc:abc#atproto_labeler".to_string(),
                    type_: "AtprotoLabeler".to_string(),
                    service_endpoint: "https://example.com/labeler".to_string(),
                },
                Service {
                    id: "#atproto_pds".to_string(),
                    type_: "AtprotoPersonalDataServer".to_string(),
                    service_endpoint: "https://example.com/pds".to_string(),
                },
                // Service with a name that contains the search fragment as a substring.
                Service {
                    id: "#xatproto_labeler".to_string(),
                    type_: "OtherType".to_string(),
                    service_endpoint: "https://example.com/other".to_string(),
                },
            ]),
        };

        let labeler = find_service(&doc, "atproto_labeler", "AtprotoLabeler");
        assert!(labeler.is_some());
        let labeler = labeler.unwrap();
        assert_eq!(labeler.id, "did:plc:abc#atproto_labeler");

        let pds = find_service(&doc, "atproto_pds", "AtprotoPersonalDataServer");
        assert!(pds.is_some());
        let pds = pds.unwrap();
        assert_eq!(pds.id, "#atproto_pds");

        // Ensure false-positive on substring is not matched.
        let wrong = find_service(&doc, "atproto_labeler", "OtherType");
        assert!(wrong.is_none());
    }

    #[test]
    fn find_service_type_mismatch_returns_none() {
        let doc = DidDocument {
            id: "did:plc:abc".to_string(),
            also_known_as: None,
            verification_method: None,
            service: Some(vec![Service {
                id: "#atproto_labeler".to_string(),
                type_: "AtprotoLabeler".to_string(),
                service_endpoint: "https://example.com/labeler".to_string(),
            }]),
        };

        let result = find_service(&doc, "atproto_labeler", "WrongType");
        assert!(result.is_none());
    }

    #[test]
    fn parse_multikey_k256() {
        // Generated from an ephemeral k256 keypair.
        // These keys are not production keys; they are synthetic fixtures for testing.
        let multikey = include_str!("../../tests/fixtures/identity/multikey_k256.txt").trim();

        let result = parse_multikey(multikey);
        assert!(result.is_ok());

        let parsed = result.unwrap();

        // Verify the key can be extracted and its bytes match the expected value.
        match &parsed.verifying_key {
            AnyVerifyingKey::K256(key) => {
                let sec1_bytes = key.to_sec1_bytes();
                assert_eq!(sec1_bytes.len(), 33); // Compressed form is 33 bytes.
                // Expected bytes derived from the multikey fixture.
                // zQ3shVc2UkAfJCdc1TR8E66J85h48P43r93q8jGPkPpjF9Ef9 decodes to:
                // [0xe7, 0x01] (k256 prefix) + 33-byte SEC1 point.
                let expected_hex =
                    "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798";
                let actual_hex = sec1_bytes.iter().fold(String::new(), |mut s, b| {
                    use std::fmt::Write;
                    let _ = write!(s, "{b:02x}");
                    s
                });
                assert_eq!(actual_hex, expected_hex);
            }
            _ => panic!("Expected K256 verifying key"),
        }
    }

    #[test]
    fn parse_multikey_p256() {
        // Generated from an ephemeral p256 keypair.
        // These keys are not production keys; they are synthetic fixtures for testing.
        let multikey = include_str!("../../tests/fixtures/identity/multikey_p256.txt").trim();

        let result = parse_multikey(multikey);
        assert!(result.is_ok());

        let parsed = result.unwrap();

        // Verify the key can be extracted and is the correct type.
        match &parsed.verifying_key {
            AnyVerifyingKey::P256(key) => {
                // Force compressed form for consistent testing.
                let sec1_bytes = key.to_encoded_point(true).as_bytes().to_vec();
                assert_eq!(sec1_bytes.len(), 33);
                // Expected bytes derived from the multikey fixture.
                let expected_hex =
                    "026b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296";
                let actual_hex = sec1_bytes.iter().fold(String::new(), |mut s, b| {
                    use std::fmt::Write;
                    let _ = write!(s, "{b:02x}");
                    s
                });
                assert_eq!(actual_hex, expected_hex);
            }
            _ => panic!("Expected P256 verifying key"),
        }
    }

    #[test]
    fn parse_multikey_unsupported_curve() {
        // Build a multikey with an unsupported curve prefix (0x01 0x00).
        let mut unsupported_bytes = vec![0x01, 0x00];
        unsupported_bytes.extend_from_slice(&[0; 33]); // Fake 33-byte key.
        // multibase::encode already returns the z-prefixed string for Base58Btc.
        let multikey = multibase::encode(multibase::Base::Base58Btc, unsupported_bytes);

        let result = parse_multikey(&multikey);
        assert!(result.is_err());

        match result.unwrap_err() {
            IdentityError::UnsupportedCurve { codec_prefix: _ } => {}
            _ => panic!("Expected UnsupportedCurve error"),
        }
    }

    #[test]
    fn parse_multikey_not_base58btc() {
        // Use base16 encoding instead of base58btc.
        let mut key_bytes = vec![0xe7, 0x01];
        key_bytes.extend_from_slice(&[0; 33]);
        // Manually create base16 multibase string (f prefix).
        let hex_str = key_bytes.iter().fold(String::new(), |mut s, b| {
            use std::fmt::Write;
            let _ = write!(s, "{b:02x}");
            s
        });
        let multikey = format!("f{hex_str}");

        let result = parse_multikey(&multikey);
        assert!(result.is_err());

        match result.unwrap_err() {
            IdentityError::UnsupportedMultibase(_) => {}
            _ => panic!("Expected UnsupportedMultibase error"),
        }
    }

    #[test]
    fn parse_multikey_accepts_did_key_prefix() {
        // The bare multikey parses, and prepending "did:key:" must be equivalent.
        // PLC audit logs store verificationMethods values in the did:key form,
        // so this path is load-bearing for the crypto stage's history fallback.
        let bare = include_str!("../../tests/fixtures/identity/multikey_k256.txt").trim();
        let did_key = format!("did:key:{bare}");

        let from_bare = parse_multikey(bare).expect("bare multikey should parse");
        let from_did_key = parse_multikey(&did_key).expect("did:key multikey should parse");

        assert!(matches!(from_bare.verifying_key, AnyVerifyingKey::K256(_)));
        assert!(matches!(
            from_did_key.verifying_key,
            AnyVerifyingKey::K256(_)
        ));
    }

    #[test]
    fn parse_multikey_wrong_length() {
        // Build a multikey with a 10-byte body instead of 33.
        let mut wrong_len_bytes = vec![0x80, 0x24]; // p256 prefix
        wrong_len_bytes.extend_from_slice(&[0; 10]); // Only 10 bytes instead of 33

        // multibase::encode already returns the z-prefixed string for Base58Btc.
        let multikey = multibase::encode(multibase::Base::Base58Btc, &wrong_len_bytes);

        let result = parse_multikey(&multikey);
        assert!(result.is_err());

        // Must strictly assert MultikeyLengthInvalid.
        match result.unwrap_err() {
            IdentityError::MultikeyLengthInvalid => {
                // Correct error variant.
            }
            e => panic!("Expected MultikeyLengthInvalid, got {e:?}"),
        }
    }

    #[test]
    fn verify_prehash_k256_valid() {
        // Create an ephemeral k256 keypair for testing.
        let signing_key = K256SigningKey::random(&mut k256::elliptic_curve::rand_core::OsRng);
        let verifying_key = signing_key.verifying_key();

        // Create a test prehash (32 bytes).
        let prehash = *b"01234567890123456789012345678901";

        // Sign the prehash.
        let signature = signing_key.sign_prehash(&prehash).expect("signing failed");

        // Wrap in our generic types.
        let any_key = AnyVerifyingKey::K256(*verifying_key);
        let any_sig = AnySignature::K256(signature);

        // Verify should succeed.
        assert!(any_key.verify_prehash(&prehash, &any_sig).is_ok());
    }

    #[test]
    fn verify_prehash_p256_valid() {
        // Create an ephemeral p256 keypair for testing.
        let signing_key = P256SigningKey::random(&mut p256::elliptic_curve::rand_core::OsRng);
        let verifying_key = signing_key.verifying_key();

        // Create a test prehash (32 bytes).
        let prehash = *b"01234567890123456789012345678901";

        // Sign the prehash.
        let signature = signing_key.sign_prehash(&prehash).expect("signing failed");

        // Wrap in our generic types.
        let any_key = AnyVerifyingKey::P256(*verifying_key);
        let any_sig = AnySignature::P256(signature);

        // Verify should succeed.
        assert!(any_key.verify_prehash(&prehash, &any_sig).is_ok());
    }

    #[test]
    fn verify_prehash_curve_mismatch() {
        // Test k256 key with p256 signature (should fail).
        let k256_signing_key = K256SigningKey::random(&mut k256::elliptic_curve::rand_core::OsRng);
        let k256_key = AnyVerifyingKey::K256(*k256_signing_key.verifying_key());

        let p256_signing_key = P256SigningKey::random(&mut p256::elliptic_curve::rand_core::OsRng);
        let prehash = *b"01234567890123456789012345678901";
        let p256_sig = p256_signing_key
            .sign_prehash(&prehash)
            .expect("signing failed");
        let p256_any_sig = AnySignature::P256(p256_sig);

        // Verify should fail due to curve mismatch.
        assert!(k256_key.verify_prehash(&prehash, &p256_any_sig).is_err());

        // Test p256 key with k256 signature (symmetric case).
        let p256_signing_key_2 =
            P256SigningKey::random(&mut p256::elliptic_curve::rand_core::OsRng);
        let p256_key = AnyVerifyingKey::P256(*p256_signing_key_2.verifying_key());

        let k256_signing_key_2 =
            K256SigningKey::random(&mut k256::elliptic_curve::rand_core::OsRng);
        let k256_sig = k256_signing_key_2
            .sign_prehash(&prehash)
            .expect("signing failed");
        let k256_any_sig = AnySignature::K256(k256_sig);

        // Verify should fail due to curve mismatch.
        assert!(p256_key.verify_prehash(&prehash, &k256_any_sig).is_err());
    }

    #[tokio::test]
    async fn plc_history_parses_rotation_fixture() {
        // Load the fixture with one key rotation.
        let fixture_bytes =
            include_bytes!("../../tests/fixtures/identity/plc_audit_log_with_rotation.json");
        let mut responses = HashMap::new();
        responses.insert(
            "https://plc.directory/did:plc:test/log/audit".to_string(),
            Response::Http(200, fixture_bytes.to_vec()),
        );
        let http = FakeHttpClient { responses };

        let did = Did("did:plc:test".to_string());
        let result = plc_history_for_fragment(&did, "atproto_label", &http)
            .await
            .expect("plc_history should succeed");

        // Expect two distinct keys from the fixture, in chronological order.
        assert_eq!(result.len(), 2);
        assert_eq!(
            result[0].key_id,
            "z3u1HhU9Dn1R1TDe8kSmEMCrJ5B8t9K7c7N2L3xX7y"
        );
        assert!(!result[0].nullified);
        assert_eq!(
            result[1].key_id,
            "z3u1HhU9Dn1R1TDe8kSmEMCrJ5B8t9K7c7N2L3xX7z"
        );
        assert!(!result[1].nullified);
    }

    #[tokio::test]
    async fn plc_history_dedupes_repeated_key() {
        // Craft an audit log where the same atproto_label multikey appears
        // across several operations (e.g. because only unrelated signing
        // keys rotated). The caller wants the set of distinct historic keys.
        let key = "did:key:zQ3shw6eSipD1cnrmmokVWvKCuE6Yc9j2jAjWJ9nWpuF4yQKV";
        let log = serde_json::json!([
            {"cid": "op3", "operation": {"verificationMethods": {"atproto_label": key}}},
            {"cid": "op2", "operation": {"verificationMethods": {"atproto_label": key}}},
            {"cid": "op1", "operation": {"verificationMethods": {"atproto_label": key}}},
        ]);
        let mut responses = HashMap::new();
        responses.insert(
            "https://plc.directory/did:plc:dedupe/log/audit".to_string(),
            Response::Http(200, serde_json::to_vec(&log).unwrap()),
        );
        let http = FakeHttpClient { responses };

        let did = Did("did:plc:dedupe".to_string());
        let result = plc_history_for_fragment(&did, "atproto_label", &http)
            .await
            .expect("plc_history should succeed");

        assert_eq!(result.len(), 1);
        assert_eq!(result[0].key_id, key);
        // Newest entry wins on dedupe.
        assert_eq!(result[0].operation_cid, "op3");
    }

    #[tokio::test]
    #[should_panic(expected = "plc_history_for_fragment called with non-plc DID")]
    async fn plc_history_unsupported_method_errors() {
        // did:web should panic in debug (due to debug_assert).
        // In release, it would return Err(UnsupportedDidMethod).
        let mut responses = HashMap::new();
        responses.insert(
            "https://plc.directory/did:web:example.com/log/audit".to_string(),
            Response::Http(200, b"[]".to_vec()),
        );
        let http = FakeHttpClient { responses };

        let did = Did("did:web:example.com".to_string());
        let _result = plc_history_for_fragment(&did, "atproto_label", &http).await;
    }

    #[tokio::test]
    async fn plc_history_transport_error_propagates() {
        // FakeHttpClient returning a transport error (represented as status 0).
        let mut responses = HashMap::new();
        responses.insert(
            "https://plc.directory/did:plc:test/log/audit".to_string(),
            Response::Transport("connection refused".to_string()),
        );
        let http = FakeHttpClient { responses };

        let did = Did("did:plc:test".to_string());
        let result = plc_history_for_fragment(&did, "atproto_label", &http).await;

        assert!(result.is_err());
        // The error should be DidResolutionFailed with status 0 (transport error).
        match result.unwrap_err() {
            IdentityError::DidResolutionFailed { status, body } => {
                assert_eq!(status, 0);
                assert_eq!(body, "Transport error: connection refused");
            }
            e => panic!("Expected DidResolutionFailed with status 0, got {e:?}"),
        }
    }

    #[test]
    fn any_signing_key_k256_round_trip() {
        let key = AnySigningKey::K256(K256SigningKey::from_slice(&[1u8; 32]).expect("valid seed"));
        let vkey = key.verifying_key();
        let msg = b"test message";
        let sig = key.sign(msg);
        assert!(vkey.verify_prehash(&[0u8; 32], &sig).is_err()); // Wrong prehash should fail.

        // Sign the same message and verify.
        let sig2 = key.sign(msg);
        let hash: [u8; 32] = sha2::Sha256::digest(msg).into();
        assert!(vkey.verify_prehash(&hash, &sig2).is_ok());
    }

    #[test]
    fn any_signing_key_p256_round_trip() {
        let key = AnySigningKey::P256(P256SigningKey::from_slice(&[2u8; 32]).expect("valid seed"));
        let vkey = key.verifying_key();
        let msg = b"test message";
        let sig = key.sign(msg);
        let hash: [u8; 32] = sha2::Sha256::digest(msg).into();
        assert!(vkey.verify_prehash(&hash, &sig).is_ok());
    }

    #[test]
    fn any_signing_key_jwt_alg() {
        let k256_key =
            AnySigningKey::K256(K256SigningKey::from_slice(&[1u8; 32]).expect("valid seed"));
        let p256_key =
            AnySigningKey::P256(P256SigningKey::from_slice(&[2u8; 32]).expect("valid seed"));

        assert_eq!(k256_key.jwt_alg(), "ES256K");
        assert_eq!(p256_key.jwt_alg(), "ES256");
    }

    #[test]
    fn any_signature_to_jws_bytes() {
        let key = AnySigningKey::K256(K256SigningKey::from_slice(&[1u8; 32]).expect("valid seed"));
        let msg = b"test";
        let sig = key.sign(msg);
        let jws_bytes = sig.to_jws_bytes();
        assert_eq!(jws_bytes.len(), 64);
    }

    #[test]
    fn any_signing_key_p256_signature_is_normalized() {
        // Test that P256 signatures produced by AnySigningKey::sign are normalized to low-s.
        let key = AnySigningKey::P256(P256SigningKey::from_slice(&[3u8; 32]).expect("valid seed"));
        let msg = b"test message for normalization";
        let vkey = key.verifying_key();

        // Sign and get the signature.
        let sig = key.sign(msg);

        // Explicitly verify that the signature is low-s (normalized).
        if let AnySignature::P256(sig_p256) = &sig {
            assert!(
                sig_p256.normalize_s().is_none(),
                "signature should already be low-s (further normalization should return None)"
            );
        } else {
            unreachable!("signing with P256 key must produce P256 signature");
        }

        // Also verify that signature verifies correctly.
        use sha2::Digest as _;
        let hash: [u8; 32] = sha2::Sha256::digest(msg).into();
        assert!(
            vkey.verify_prehash(&hash, &sig).is_ok(),
            "P256 signature should verify after normalization"
        );

        // Also verify that to_jws_bytes produces a 64-byte result.
        let sig_bytes = sig.to_jws_bytes();
        assert_eq!(
            sig_bytes.len(),
            64,
            "P256 signature should be 64 bytes after JWS serialization"
        );
    }

    #[test]
    fn is_local_labeler_hostname_classifies_expected_hosts() {
        let cases: &[(&str, bool)] = &[
            // Positive: localhost variants.
            ("http://localhost/", true),
            ("https://LOCALHOST:8080/foo", true),
            ("http://127.0.0.1/", true),
            ("http://127.1.2.3/", true),
            ("http://[::1]/", true),
            // Positive: .local mDNS.
            ("http://mybox.local/", true),
            ("https://mybox.LOCAL:8443/", true),
            // Positive: RFC 1918.
            ("http://10.0.0.1/", true),
            ("http://172.16.0.1/", true),
            ("http://172.31.255.255/", true),
            ("http://192.168.1.100/", true),
            // Negative: public.
            ("https://labeler.example.com/", false),
            ("http://8.8.8.8/", false),
            ("http://172.15.0.1/", false), // outside 172.16/12
            ("http://172.32.0.1/", false), // outside 172.16/12
            ("http://11.0.0.1/", false),   // outside 10/8 once we pass 10.x
            ("http://172.17.1.1/", true),  // inside 172.16/12
        ];
        for (url, expected) in cases {
            let parsed = Url::parse(url).expect("test URLs are valid");
            assert_eq!(
                is_local_labeler_hostname(&parsed),
                *expected,
                "classification mismatch for {url}"
            );
        }
    }

    #[test]
    fn encode_multikey_round_trip_k256() {
        // Create a random k256 signing key, encode its public key, then
        // decode it back and verify the keys match.
        let signing_key = AnySigningKey::K256(k256::ecdsa::SigningKey::random(
            &mut k256::elliptic_curve::rand_core::OsRng,
        ));
        let original_verifying = signing_key.verifying_key();

        // Encode to multikey format.
        let encoded = encode_multikey(&original_verifying);
        assert!(
            encoded.starts_with('z'),
            "multikey should start with 'z' (base58btc)"
        );

        // Decode back and verify.
        let parsed = parse_multikey(&encoded).expect("encoded multikey should parse");
        match (&original_verifying, &parsed.verifying_key) {
            (AnyVerifyingKey::K256(original), AnyVerifyingKey::K256(decoded)) => {
                let orig_bytes = original.to_sec1_bytes();
                let decoded_bytes = decoded.to_sec1_bytes();
                assert_eq!(
                    orig_bytes, decoded_bytes,
                    "k256 keys should match after round-trip"
                );
            }
            _ => panic!("Expected K256 keys"),
        }
    }

    #[test]
    fn encode_multikey_round_trip_p256() {
        // Create a random p256 signing key, encode its public key, then
        // decode it back and verify the keys match.
        let signing_key = AnySigningKey::P256(p256::ecdsa::SigningKey::random(
            &mut p256::elliptic_curve::rand_core::OsRng,
        ));
        let original_verifying = signing_key.verifying_key();

        // Encode to multikey format.
        let encoded = encode_multikey(&original_verifying);
        assert!(
            encoded.starts_with('z'),
            "multikey should start with 'z' (base58btc)"
        );

        // Decode back and verify.
        let parsed = parse_multikey(&encoded).expect("encoded multikey should parse");
        match (&original_verifying, &parsed.verifying_key) {
            (AnyVerifyingKey::P256(original), AnyVerifyingKey::P256(decoded)) => {
                let orig_bytes = original.to_encoded_point(true).as_bytes().to_vec();
                let decoded_bytes = decoded.to_encoded_point(true).as_bytes().to_vec();
                assert_eq!(
                    orig_bytes, decoded_bytes,
                    "p256 keys should match after round-trip"
                );
            }
            _ => panic!("Expected P256 keys"),
        }
    }
}