didwebvh-rs 0.4.1

Implementation of the did:webvh method in Rust
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
use crate::DIDWebVHError;
use chrono::{DateTime, FixedOffset};
use std::fmt::{Display, Formatter};
use std::net::IpAddr;
use url::Url;

type QueryPairs = (Option<String>, Option<DateTime<FixedOffset>>, Option<u32>);

/// Distinguishes the type of resource a WebVH URL points to.
#[derive(Clone, Debug, PartialEq)]
pub enum URLType {
    /// Regular DID Documentation lookup
    DIDDoc,

    /// WebVH Whois lookup
    WhoIs,
}

/// Breakdown of a WebVH URL into its components
#[derive(Clone)]
pub struct WebVHURL {
    /// What type of URL is this?
    pub type_: URLType,

    /// Initial full URL
    pub did_url: String,

    /// Self Certifying IDentifier (SCID)
    pub scid: String,

    /// Domain name for this DID
    pub domain: String,

    /// Custom port if specified
    pub port: Option<u16>,

    /// URL Path component
    /// Always has a trailing slash
    /// i.e. /.well-known/
    /// i.e. /custom/path/
    pub path: String,

    /// URL fragment
    pub fragment: Option<String>,

    /// URL Query
    pub query: Option<String>,

    /// file_name
    pub file_name: Option<String>,

    /// WebVH supports query options to resolve a specific version or which LogEntry was active at
    /// a particuliar time
    /// Helper pointing to versionId
    pub query_version_id: Option<String>,

    /// Helper pointing to versionTime
    pub query_version_time: Option<DateTime<FixedOffset>>,

    /// Helper pointing to versionNumber
    pub query_version_number: Option<u32>,
}

impl WebVHURL {
    /// Parses a WebVH URL and returns a WebVHURL struct
    pub fn parse_did_url(url: &str) -> Result<WebVHURL, DIDWebVHError> {
        // may already have the did prefix stripped
        let url = if let Some(prefix) = url.strip_prefix("did:webvh:") {
            prefix
        } else if url.starts_with("did:") {
            return Err(DIDWebVHError::UnsupportedMethod(format!(
                "Expected did:webvh, got: {}",
                url.split(':').take(3).collect::<Vec<_>>().join(":")
            )));
        } else {
            url
        };

        // split fragment from the rest of the URL
        let (prefix, fragment) = match url.split_once('#') {
            Some((prefix, fragment)) => (prefix, Some(fragment.to_string())),
            None => (url, None),
        };

        // split query from the rest of the URL
        let (prefix, query) = match prefix.split_once('?') {
            Some((prefix, query)) => (prefix, Some(query.to_string())),
            None => (url, None),
        };

        let (query_version_id, query_version_time, query_version_number) =
            Self::parse_query(query.as_deref())?;

        // Expect minimum of two parts (SCID, domain)
        // May contain three parts (SCID, domain, path)
        let parts = prefix.split(':').collect::<Vec<_>>();

        if parts.len() < 2 {
            return Err(DIDWebVHError::InvalidMethodIdentifier(
                "Invalid URL: Must contain SCID and domain".to_string(),
            ));
        }

        let scid = parts[0].to_string();

        let (domain, port) = match parts[1].split_once("%3A") {
            Some((domain, port)) => {
                let port = match port.parse::<u16>() {
                    Ok(port) => port,
                    Err(err) => {
                        return Err(DIDWebVHError::InvalidMethodIdentifier(format!(
                            "Invalid URL: Port ({port}) must be a number: {err}",
                        )));
                    }
                };
                (domain.to_string(), Some(port))
            }
            None => (parts[1].to_string(), None),
        };

        Self::reject_ip_address(&domain)?;

        let mut path = String::new();
        let mut file_name = String::new();
        for part in parts[2..].iter() {
            if part != &"whois" {
                path.push('/');
                path.push_str(part);
            }
        }
        if path.is_empty() {
            path = "/.well-known/".to_string();
        } else {
            // add a trailing slash to the path
            path.push('/');
        }

        let type_ = if parts.len() > 2 && parts[parts.len() - 1] == "whois" {
            if path == "/.well-known/" {
                path = "/".to_string()
            }
            file_name.push_str("whois.vp");
            URLType::WhoIs
        } else {
            file_name.push_str("did.jsonl");
            URLType::DIDDoc
        };

        Ok(WebVHURL {
            type_,
            did_url: url.to_string(),
            scid,
            domain,
            port,
            path,
            fragment,
            query,
            file_name: Some(file_name),
            query_version_id,
            query_version_time,
            query_version_number,
        })
    }

    /// Parses a http URL and returns a WebVHURL struct
    pub fn parse_url(url: &Url) -> Result<WebVHURL, DIDWebVHError> {
        if url.scheme() != "http" && url.scheme() != "https" {
            return Err(DIDWebVHError::InvalidMethodIdentifier(
                "Invalid URL: Must be http or https".to_string(),
            ));
        }

        let fragment = url.fragment();
        let (query_version_id, query_version_time, query_version_number) =
            Self::parse_query(url.query())?;

        let Some(domain) = url.domain() else {
            // url::Url::domain() returns None for IP addresses — provide a specific error
            if let Some(host) = url.host_str() {
                return Err(DIDWebVHError::InvalidMethodIdentifier(format!(
                    "Invalid URL: IP addresses are not allowed, use a domain name instead: {host}",
                )));
            }
            return Err(DIDWebVHError::InvalidMethodIdentifier(
                "Invalid URL: Must contain domain".to_string(),
            ));
        };
        let port = url.port();

        // Defense-in-depth: reject IP addresses even if they somehow pass domain()
        Self::reject_ip_address(domain)?;

        let (type_, path, file_name) = if url.path() == "/" {
            (
                URLType::DIDDoc,
                "/.well-known/".to_string(),
                Some("did.jsonl".to_string()),
            )
        } else if url.path().ends_with("/whois") {
            (URLType::WhoIs, "/whois.vp".to_string(), None)
        } else if url.path().ends_with("/did.jsonl") {
            (
                URLType::DIDDoc,
                url.path()
                    .to_string()
                    .trim_end_matches("did.jsonl")
                    .to_string(),
                Some("did.jsonl".to_string()),
            )
        } else {
            (
                URLType::DIDDoc,
                if url.path().ends_with('/') {
                    url.path().to_string()
                } else {
                    format!("{}/", url.path())
                },
                Some("did.jsonl".to_string()),
            )
        };

        Ok(WebVHURL {
            type_,
            did_url: url.to_string(),
            scid: "{SCID}".to_string(),
            domain: domain.to_string(),
            port,
            path,
            fragment: fragment.map(|s| s.to_string()),
            query: url.query().map(|s| s.to_string()),
            file_name,
            query_version_id,
            query_version_time,
            query_version_number,
        })
    }

    /// Rejects IP addresses (both IPv4 and IPv6) as the domain component.
    /// The did:webvh spec requires domain names, not IP addresses.
    fn reject_ip_address(domain: &str) -> Result<(), DIDWebVHError> {
        // Strip brackets for IPv6 (e.g., "[::1]" -> "::1")
        let bare = domain
            .strip_prefix('[')
            .and_then(|s| s.strip_suffix(']'))
            .unwrap_or(domain);
        if bare.parse::<IpAddr>().is_ok() {
            return Err(DIDWebVHError::InvalidMethodIdentifier(format!(
                "Invalid URL: IP addresses are not allowed, use a domain name instead: {domain}",
            )));
        }
        Ok(())
    }

    /// Parses URL query parameters and returns:
    /// Error if versionTime or VersionId are invalid parameters
    /// None if there is no valid qauery
    /// (versionId, versionTime, versionNumber) if valid query parameters exist
    fn parse_query(
        // Example query string = "versionId=1-test&versionTime=1996-12-19T16:39:57-08:00"
        query: Option<&str>,
    ) -> Result<QueryPairs, DIDWebVHError> {
        if let Some(query) = query {
            let mut version_id = None;
            let mut version_time = None;
            let mut version_number = None;
            for parameter in query.split('&') {
                if let Some((key, value)) = parameter.split_once('=') {
                    if key == "versionId" {
                        version_id = Some(value.to_string());
                    } else if key == "versionTime" {
                        version_time = Some(DateTime::parse_from_rfc3339(value)
                            .map_err(|e| {
                                DIDWebVHError::DIDError(format!("DID Query parameter (versionTime) is invalid. Must be RFC 3339 compliant: {e}"
                                ))
                            })?);
                    } else if key == "versionNumber" {
                        version_number = Some(str::parse(value).map_err(|e| {
                            DIDWebVHError::DIDError(format!("DID Query parameter (versionNumber) is invalid. Must be a positive integer: {e}"
                            ))
                        })?);
                    }
                } else {
                    return Err(DIDWebVHError::DIDError(format!(
                        "DID Query parameter ({parameter}) is invalid. Must be in the format key=value."
                    )));
                }
            }
            // Only one of versionId, versionTime, or versionNumber may be specified
            let count = [
                version_id.is_some(),
                version_time.is_some(),
                version_number.is_some(),
            ]
            .iter()
            .filter(|&&v| v)
            .count();
            if count > 1 {
                return Err(DIDWebVHError::DIDError(
                    "Only one of versionId, versionTime, or versionNumber may be specified"
                        .to_string(),
                ));
            }

            Ok((version_id, version_time, version_number))
        } else {
            Ok((None, None, None))
        }
    }

    // Returns the base HTTP URL without any path or file name
    fn get_http_base_url(&self) -> String {
        let mut url_string = String::new();

        if self.domain == "localhost" {
            url_string.push_str("http://");
        } else {
            url_string.push_str("https://");
        }

        url_string.push_str(&self.domain);

        if let Some(port) = self.port {
            url_string.push_str(&format!(":{port}",));
        }

        url_string
    }

    /// Creates a HTTP URL from webvh DID
    /// Can specify a file_name depending on the operation
    /// If None, then the default file_name will be used
    pub fn get_http_url(&self, file_name: Option<&str>) -> Result<Url, DIDWebVHError> {
        let mut url_string = self.get_http_base_url();

        url_string.push_str(&self.path);
        if let Some(file_name) = file_name {
            url_string.push_str(file_name);
        } else if let Some(file_name) = &self.file_name {
            url_string.push_str(file_name);
        }

        if let Some(query) = &self.query {
            url_string.push_str(&format!("?{query}",));
        }
        if let Some(fragment) = &self.fragment {
            url_string.push_str(&format!("#{fragment}",));
        }

        match Url::parse(&url_string) {
            Ok(url) => Ok(url),
            Err(err) => Err(DIDWebVHError::InvalidMethodIdentifier(format!(
                "Invalid URL: {err}",
            ))),
        }
    }

    /// Returns the URL for a whois.vp file location
    /// NOTE: This will strip out /.well-known if it exists
    pub fn get_http_whois_url(&self) -> Result<Url, DIDWebVHError> {
        let mut url_string = self.get_http_base_url();

        if self.path == "/.well-known/" {
            // Strip the /.well-known/ path if it exists
            url_string.push_str("/whois.vp");
        } else {
            url_string.push_str(&self.path);
            url_string.push_str("whois.vp");
        }

        match Url::parse(&url_string) {
            Ok(url) => Ok(url),
            Err(err) => Err(DIDWebVHError::InvalidMethodIdentifier(format!(
                "Invalid URL: {err}",
            ))),
        }
    }

    /// Returns the URL for the #files service URL
    /// NOTE: This will strip out /.well-known if it exists
    pub fn get_http_files_url(&self) -> Result<Url, DIDWebVHError> {
        let mut url_string = self.get_http_base_url();

        if self.path == "/.well-known/" {
            // Strip the /.well-known/ path if it exists
            url_string.push('/');
        } else {
            url_string.push_str(&self.path);
        }

        match Url::parse(&url_string) {
            Ok(url) => Ok(url),
            Err(err) => Err(DIDWebVHError::InvalidMethodIdentifier(format!(
                "Invalid URL: {err}",
            ))),
        }
    }
}

impl WebVHURL {
    /// Returns the base DID string (without query parameters or fragment).
    /// This is the format expected as the top-level `id` in a DID Document.
    pub fn to_did_base(&self) -> String {
        let mut url_string = String::from("did:webvh:");
        url_string.push_str(&self.scid);
        url_string.push(':');
        url_string.push_str(&self.domain);
        if let Some(port) = self.port {
            url_string.push_str(&format!("%3A{port}"));
        }
        if self.path != "/.well-known/" {
            url_string.push_str(&self.path.trim_end_matches("/").replace('/', ":"));
        }
        url_string
    }
}

impl Display for WebVHURL {
    /// Handles converting a WebVHURL to a WebVH DID representation
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let mut url_string = String::new();
        url_string.push_str("did:webvh:");
        url_string.push_str(&self.scid);
        url_string.push(':');
        url_string.push_str(&self.domain);
        if let Some(port) = self.port {
            url_string.push_str(&format!("%3A{port}",));
        }

        if self.path != "/.well-known/" {
            url_string.push_str(&self.path.trim_end_matches("/").replace('/', ":"));
        }

        if let Some(query) = &self.query {
            url_string.push('?');
            url_string.push_str(query);
        }
        if let Some(fragment) = &self.fragment {
            url_string.push('#');
            url_string.push_str(fragment);
        }
        write!(f, "{url_string}",)
    }
}

#[cfg(test)]
mod tests {
    use url::Url;

    use crate::{
        DIDWebVHError,
        url::{URLType, WebVHURL},
    };

    #[test]
    fn wrong_method() {
        assert!(WebVHURL::parse_did_url("did:wrong:method").is_err())
    }

    #[test]
    fn url_with_fragment() {
        let parsed = match WebVHURL::parse_did_url("did:webvh:scid:example.com#key-fragment") {
            Ok(parsed) => parsed,
            Err(_) => panic!("Failed to parse URL"),
        };

        assert_eq!(parsed.fragment, Some("key-fragment".to_string()));
    }

    #[test]
    fn url_with_query() {
        let parsed = match WebVHURL::parse_did_url("did:webvh:scid:example.com?versionId=1-xyz") {
            Ok(parsed) => parsed,
            Err(_) => panic!("Failed to parse URL"),
        };

        assert_eq!(parsed.query, Some("versionId=1-xyz".to_string()));
    }

    #[test]
    fn url_with_query_version_number() {
        let parsed = match WebVHURL::parse_did_url("did:webvh:scid:example.com?versionNumber=13") {
            Ok(parsed) => parsed,
            Err(_) => panic!("Failed to parse URL"),
        };

        assert_eq!(parsed.query_version_number, Some(13));
    }

    #[test]
    fn missing_parts() {
        assert!(WebVHURL::parse_did_url("did:webvh:domain").is_err());
        assert!(WebVHURL::parse_did_url("did:webvh:domain#test").is_err());
    }

    #[test]
    fn url_with_port() {
        assert!(WebVHURL::parse_did_url("did:webvh:scid:domain%3A8000").is_ok());
    }

    #[test]
    fn url_with_bad_port() {
        assert!(WebVHURL::parse_did_url("did:webvh:scid:domain%3A8bad").is_err());
        assert!(WebVHURL::parse_did_url("did:webvh:scid:domain%3A999999").is_err());
    }

    #[test]
    fn url_with_whois() -> Result<(), DIDWebVHError> {
        let result = WebVHURL::parse_did_url("did:webvh:scid:domain%3A8000:whois")?;
        assert_eq!(result.type_, URLType::WhoIs);
        assert_eq!(result.path, "/");
        assert_eq!(result.file_name, Some("whois.vp".to_string()));
        Ok(())
    }

    #[test]
    fn url_with_whois_path() -> Result<(), DIDWebVHError> {
        let result = WebVHURL::parse_did_url("did:webvh:scid:domain%3A8000:custom:path:whois")?;
        assert_eq!(result.type_, URLType::WhoIs);
        assert_eq!(result.path, "/custom/path/");
        assert_eq!(result.file_name, Some("whois.vp".to_string()));
        assert_eq!(
            result.get_http_whois_url()?.to_string().as_str(),
            "https://domain:8000/custom/path/whois.vp"
        );
        Ok(())
    }

    #[test]
    fn url_with_default_path() -> Result<(), DIDWebVHError> {
        let result = WebVHURL::parse_did_url("did:webvh:scid:domain%3A8000")?;
        assert_eq!(result.type_, URLType::DIDDoc);
        assert_eq!(result.path, "/.well-known/");
        assert_eq!(result.file_name, Some("did.jsonl".to_string()));
        Ok(())
    }

    #[test]
    fn url_with_custom_path() -> Result<(), DIDWebVHError> {
        let result = WebVHURL::parse_did_url("did:webvh:scid:domain%3A8000:custom:path")?;
        assert_eq!(result.type_, URLType::DIDDoc);
        assert_eq!(result.path, "/custom/path/");
        assert_eq!(result.file_name, Some("did.jsonl".to_string()));
        Ok(())
    }

    #[test]
    fn to_url_from_basic() -> Result<(), DIDWebVHError> {
        let webvh = WebVHURL::parse_did_url("did:webvh:scid:example.com")?;
        assert_eq!(
            webvh.get_http_url(None)?.to_string().as_str(),
            "https://example.com/.well-known/did.jsonl"
        );
        Ok(())
    }

    #[test]
    fn to_url_from_basic_whois() -> Result<(), DIDWebVHError> {
        let webvh = WebVHURL::parse_did_url("did:webvh:scid:example.com:whois")?;
        assert_eq!(
            webvh.get_http_url(None)?.to_string().as_str(),
            "https://example.com/whois.vp"
        );
        assert_eq!(
            webvh.get_http_whois_url()?.to_string().as_str(),
            "https://example.com/whois.vp"
        );
        Ok(())
    }

    #[test]
    fn to_url_from_complex() -> Result<(), DIDWebVHError> {
        let webvh = WebVHURL::parse_did_url(
            "did:webvh:scid:example.com%3A8080:custom:path?versionId=1-xyz#fragment",
        )?;
        assert_eq!(
            webvh.get_http_url(None)?.to_string().as_str(),
            "https://example.com:8080/custom/path/did.jsonl?versionId=1-xyz#fragment"
        );
        Ok(())
    }

    #[test]
    fn to_did_from_url() -> Result<(), DIDWebVHError> {
        let webvh = WebVHURL::parse_url(&Url::parse("http://localhost:8000/").unwrap())?;
        assert_eq!(webvh.to_string(), "did:webvh:{SCID}:localhost%3A8000");
        Ok(())
    }

    #[test]
    fn to_did_from_url_trailing_slash() -> Result<(), DIDWebVHError> {
        let webvh = WebVHURL::parse_url(&Url::parse("https://localhost:8000/test/").unwrap())?;
        assert_eq!(webvh.to_string(), "did:webvh:{SCID}:localhost%3A8000:test");
        assert_eq!(
            webvh.get_http_url(None)?.to_string().as_str(),
            "http://localhost:8000/test/did.jsonl"
        );
        Ok(())
    }

    #[test]
    fn to_http_whois_url_default() -> Result<(), DIDWebVHError> {
        let webvh = WebVHURL::parse_url(&Url::parse("https://localhost/").unwrap())?;

        let result = webvh.get_http_whois_url()?;

        assert_eq!(result.as_str(), "http://localhost/whois.vp");
        Ok(())
    }

    #[test]
    fn to_http_whois_url_path() -> Result<(), DIDWebVHError> {
        let webvh = WebVHURL::parse_url(&Url::parse("https://localhost/test/path").unwrap())?;

        let result = webvh.get_http_whois_url()?;

        assert_eq!(result.as_str(), "http://localhost/test/path/whois.vp");
        Ok(())
    }

    #[test]
    fn to_http_whois_url_path_trailing_slash() -> Result<(), DIDWebVHError> {
        let webvh = WebVHURL::parse_url(&Url::parse("https://localhost/test/path/").unwrap())?;

        let result = webvh.get_http_whois_url()?;

        assert_eq!(result.as_str(), "http://localhost/test/path/whois.vp");
        Ok(())
    }

    #[test]
    fn to_http_whois_files_default() -> Result<(), DIDWebVHError> {
        let webvh = WebVHURL::parse_url(&Url::parse("https://localhost/").unwrap())?;

        let result = webvh.get_http_files_url()?;

        assert_eq!(result.as_str(), "http://localhost/");
        Ok(())
    }

    #[test]
    fn to_http_whois_files_path() -> Result<(), DIDWebVHError> {
        let webvh = WebVHURL::parse_url(&Url::parse("https://localhost/test/path").unwrap())?;

        let result = webvh.get_http_files_url()?;

        assert_eq!(result.as_str(), "http://localhost/test/path/");
        Ok(())
    }

    #[test]
    fn to_http_whois_files_path_trailing_slash() -> Result<(), DIDWebVHError> {
        let webvh = WebVHURL::parse_url(&Url::parse("https://localhost/test/path/").unwrap())?;

        let result = webvh.get_http_files_url()?;

        assert_eq!(result.as_str(), "http://localhost/test/path/");
        Ok(())
    }

    #[test]
    fn to_did_base_simple() -> Result<(), DIDWebVHError> {
        let webvh = WebVHURL::parse_did_url("did:webvh:scid:example.com")?;
        assert_eq!(webvh.to_did_base(), "did:webvh:scid:example.com");
        Ok(())
    }

    #[test]
    fn to_did_base_with_port() -> Result<(), DIDWebVHError> {
        let webvh = WebVHURL::parse_did_url("did:webvh:scid:example.com%3A8080")?;
        assert_eq!(webvh.to_did_base(), "did:webvh:scid:example.com%3A8080");
        Ok(())
    }

    #[test]
    fn to_did_base_with_path() -> Result<(), DIDWebVHError> {
        let webvh = WebVHURL::parse_did_url("did:webvh:scid:example.com:custom:path")?;
        assert_eq!(
            webvh.to_did_base(),
            "did:webvh:scid:example.com:custom:path"
        );
        Ok(())
    }

    #[test]
    fn parse_query_version_id_and_version_time_rejects() {
        let result = WebVHURL::parse_did_url(
            "did:webvh:scid:example.com?versionId=1-xyz&versionTime=2024-01-01T00:00:00Z",
        );
        let err = result.err().expect("expected error");
        assert!(
            err.to_string()
                .contains("Only one of versionId, versionTime, or versionNumber")
        );
    }

    #[test]
    fn parse_query_version_id_and_version_number_rejects() {
        let result =
            WebVHURL::parse_did_url("did:webvh:scid:example.com?versionId=1-xyz&versionNumber=5");
        let err = result.err().expect("expected error");
        assert!(
            err.to_string()
                .contains("Only one of versionId, versionTime, or versionNumber")
        );
    }

    #[test]
    fn parse_query_version_time_and_version_number_rejects() {
        let result = WebVHURL::parse_did_url(
            "did:webvh:scid:example.com?versionTime=2024-01-01T00:00:00Z&versionNumber=5",
        );
        let err = result.err().expect("expected error");
        assert!(
            err.to_string()
                .contains("Only one of versionId, versionTime, or versionNumber")
        );
    }

    #[test]
    fn parse_query_all_three_rejects() {
        let result = WebVHURL::parse_did_url(
            "did:webvh:scid:example.com?versionId=1-xyz&versionTime=2024-01-01T00:00:00Z&versionNumber=5",
        );
        let err = result.err().expect("expected error");
        assert!(
            err.to_string()
                .contains("Only one of versionId, versionTime, or versionNumber")
        );
    }

    #[test]
    fn to_did_base_strips_query_and_fragment() -> Result<(), DIDWebVHError> {
        let webvh = WebVHURL::parse_did_url(
            "did:webvh:scid:example.com%3A8080:custom:path?versionId=1-xyz#fragment",
        )?;
        assert_eq!(
            webvh.to_did_base(),
            "did:webvh:scid:example.com%3A8080:custom:path"
        );
        Ok(())
    }

    // --- IP address rejection tests for parse_did_url ---

    #[test]
    fn parse_did_url_rejects_ipv4() {
        let result = WebVHURL::parse_did_url("did:webvh:scid:192.168.1.1");
        let err = result.err().expect("expected error for IPv4 address");
        assert!(err.to_string().contains("IP addresses are not allowed"));
    }

    #[test]
    fn parse_did_url_rejects_ipv4_loopback() {
        let result = WebVHURL::parse_did_url("did:webvh:scid:127.0.0.1");
        let err = result.err().expect("expected error for IPv4 loopback");
        assert!(err.to_string().contains("IP addresses are not allowed"));
    }

    #[test]
    fn parse_did_url_rejects_ipv4_with_port() {
        let result = WebVHURL::parse_did_url("did:webvh:scid:192.168.1.1%3A8080");
        let err = result.err().expect("expected error for IPv4 with port");
        assert!(err.to_string().contains("IP addresses are not allowed"));
    }

    #[test]
    fn parse_did_url_allows_localhost() {
        assert!(WebVHURL::parse_did_url("did:webvh:scid:localhost").is_ok());
    }

    #[test]
    fn parse_did_url_allows_fqdn() {
        assert!(WebVHURL::parse_did_url("did:webvh:scid:example.com").is_ok());
    }

    // --- IP address rejection tests for parse_url ---

    #[test]
    fn parse_url_rejects_ipv4() {
        let url = Url::parse("https://192.168.1.1/").unwrap();
        let result = WebVHURL::parse_url(&url);
        let err = result.err().expect("expected error for IPv4 address");
        assert!(err.to_string().contains("IP addresses are not allowed"));
    }

    #[test]
    fn parse_url_rejects_ipv6() {
        let url = Url::parse("https://[::1]/").unwrap();
        let result = WebVHURL::parse_url(&url);
        let err = result.err().expect("expected error for IPv6 address");
        assert!(err.to_string().contains("IP addresses are not allowed"));
    }

    #[test]
    fn parse_url_allows_localhost() -> Result<(), DIDWebVHError> {
        let url = Url::parse("http://localhost:8000/").unwrap();
        let result = WebVHURL::parse_url(&url)?;
        assert_eq!(result.domain, "localhost");
        Ok(())
    }

    #[test]
    fn parse_url_allows_fqdn() -> Result<(), DIDWebVHError> {
        let url = Url::parse("https://example.com/").unwrap();
        let result = WebVHURL::parse_url(&url)?;
        assert_eq!(result.domain, "example.com");
        Ok(())
    }
}