domain-check-lib 1.0.2

A fast, robust library for checking domain availability using RDAP and WHOIS protocols
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
//! RDAP (Registration Data Access Protocol) implementation.
//!
//! This module provides functionality to check domain availability using the RDAP protocol,
//! which is the modern replacement for WHOIS. RDAP provides structured JSON responses
//! with standardized data formats.

use crate::error::DomainCheckError;
use crate::protocols::registry::{extract_tld, get_rdap_endpoint};
use crate::types::{CheckMethod, DomainInfo, DomainResult};
use reqwest::StatusCode;
use std::time::{Duration, Instant};

/// RDAP client for checking domain availability.
///
/// This client handles RDAP protocol communication, including endpoint discovery,
/// request formatting, response parsing, and error handling.
#[derive(Clone)]
pub struct RdapClient {
    /// HTTP client for making RDAP requests
    http_client: reqwest::Client,
    /// Timeout for RDAP requests
    timeout: Duration,
    /// Whether to use IANA bootstrap for unknown TLDs
    use_bootstrap: bool,
}

impl RdapClient {
    /// Create a new RDAP client with default settings.
    pub fn new() -> Result<Self, DomainCheckError> {
        let http_client = reqwest::Client::builder()
            .timeout(Duration::from_secs(5))
            .build()
            .map_err(|e| {
                DomainCheckError::network_with_source(
                    "Failed to create RDAP HTTP client",
                    e.to_string(),
                )
            })?;

        Ok(Self {
            http_client,
            timeout: Duration::from_secs(3),
            use_bootstrap: false,
        })
    }

    /// Create a new RDAP client with custom settings.
    pub fn with_config(timeout: Duration, use_bootstrap: bool) -> Result<Self, DomainCheckError> {
        let http_client = reqwest::Client::builder()
            .timeout(timeout + Duration::from_secs(2)) // Add buffer for HTTP timeout
            .build()
            .map_err(|e| {
                DomainCheckError::network_with_source(
                    "Failed to create RDAP HTTP client",
                    e.to_string(),
                )
            })?;

        Ok(Self {
            http_client,
            timeout,
            use_bootstrap,
        })
    }

    /// Check domain availability using RDAP.
    ///
    /// # Arguments
    ///
    /// * `domain` - The domain name to check (e.g., "example.com")
    ///
    /// # Returns
    ///
    /// A `DomainResult` with availability status and optional registration details.
    ///
    /// # Errors
    ///
    /// Returns `DomainCheckError` if:
    /// - The domain format is invalid
    /// - No RDAP endpoint is available for the TLD
    /// - Network errors occur
    /// - The RDAP response cannot be parsed
    pub async fn check_domain(&self, domain: &str) -> Result<DomainResult, DomainCheckError> {
        let start_time = Instant::now();

        // Extract TLD and get RDAP endpoint
        let tld = extract_tld(domain)?;
        let endpoint = get_rdap_endpoint(&tld, self.use_bootstrap).await?;

        // Build RDAP URL
        let rdap_url = format!("{}{}", endpoint, domain);

        // 🔍 DEBUG: Log the URL being requested
        if std::env::var("DOMAIN_CHECK_DEBUG_RDAP").is_ok() {
            println!("🔍 Attempting RDAP request to: {}", rdap_url);
        }

        // Make RDAP request with timeout
        let result =
            tokio::time::timeout(self.timeout, self.make_rdap_request(&rdap_url, domain)).await;

        let check_duration = start_time.elapsed();

        match result {
            Ok(Ok((available, info))) => Ok(DomainResult {
                domain: domain.to_string(),
                available: Some(available),
                info,
                check_duration: Some(check_duration),
                method_used: if self.use_bootstrap {
                    CheckMethod::Bootstrap
                } else {
                    CheckMethod::Rdap
                },
                error_message: None,
            }),
            Ok(Err(e)) => {
                // 🔍 DEBUG: Log RDAP errors
                if std::env::var("DOMAIN_CHECK_DEBUG_RDAP").is_ok() {
                    println!("🔍 RDAP Error for {}: {}", domain, e);
                }

                // Propagate all errors (including 404) to checker.rs so it can
                // try WHOIS fallback before concluding availability.
                Err(e)
            }
            Err(_) => {
                // 🔍 DEBUG: Log timeout
                if std::env::var("DOMAIN_CHECK_DEBUG_RDAP").is_ok() {
                    println!("🔍 RDAP Timeout for {} after {:?}", domain, self.timeout);
                }

                Err(DomainCheckError::timeout("RDAP request", self.timeout))
            }
        }
    }

    /// Make an RDAP request to the specified URL.
    /// Make an RDAP request to the specified URL.
    async fn make_rdap_request(
        &self,
        rdap_url: &str,
        domain: &str,
    ) -> Result<(bool, Option<DomainInfo>), DomainCheckError> {
        // First attempt
        let response = self.http_client.get(rdap_url).send().await.map_err(|e| {
            // 🔍 DEBUG: Log request errors
            if std::env::var("DOMAIN_CHECK_DEBUG_RDAP").is_ok() {
                println!("🔍 HTTP Request failed for {}: {}", rdap_url, e);
                if e.is_timeout() {
                    println!("   └─ Timeout error");
                } else if e.is_connect() {
                    println!("   └─ Connection error");
                } else if e.is_request() {
                    println!("   └─ Request error");
                }
            }
            DomainCheckError::rdap(domain, format!("Request failed: {}", e))
        })?;

        // 🔍 DEBUG: Log response status
        if std::env::var("DOMAIN_CHECK_DEBUG_RDAP").is_ok() {
            println!("🔍 HTTP Response for {}: {}", domain, response.status());
        }

        match response.status() {
            StatusCode::OK => {
                // Domain exists, parse the response
                let json = response.json::<serde_json::Value>().await.map_err(|e| {
                    DomainCheckError::rdap(domain, format!("Failed to parse JSON: {}", e))
                })?;

                // 🔍 DEBUG: Print the actual JSON response for analysis
                if std::env::var("DOMAIN_CHECK_DEBUG_RDAP").is_ok() {
                    println!("🔍 RDAP Response for {}:", domain);
                    println!(
                        "{}",
                        serde_json::to_string_pretty(&json).unwrap_or_default()
                    );
                    println!("--- End RDAP Response ---\n");
                }

                let domain_info = extract_domain_info(&json);

                // 🔍 DEBUG: Print extracted info
                if std::env::var("DOMAIN_CHECK_DEBUG_RDAP").is_ok() {
                    println!("🔍 Extracted Info for {}:", domain);
                    println!("  Registrar: {:?}", domain_info.registrar);
                    println!("  Created: {:?}", domain_info.creation_date);
                    println!("  Expires: {:?}", domain_info.expiration_date);
                    println!("  Status: {:?}", domain_info.status);
                    println!("--- End Extracted Info ---\n");
                }

                Ok((false, Some(domain_info)))
            }
            StatusCode::NOT_FOUND => {
                // RDAP 404 is inconclusive — some registries return 404 for
                // registered domains without NS delegation (e.g. .moe).
                // Defer to WHOIS for verification instead of assuming available.
                if std::env::var("DOMAIN_CHECK_DEBUG_RDAP").is_ok() {
                    println!(
                        "🔍 RDAP 404 for {} — deferring to WHOIS for verification",
                        domain
                    );
                }
                Err(DomainCheckError::rdap_with_status(
                    domain,
                    "RDAP returned 404 (domain may or may not be registered)",
                    404,
                ))
            }
            StatusCode::TOO_MANY_REQUESTS => {
                // Rate limited, try once more after a short delay
                if std::env::var("DOMAIN_CHECK_DEBUG_RDAP").is_ok() {
                    println!("🔍 Rate limited for {}, retrying after 500ms...", domain);
                }

                tokio::time::sleep(Duration::from_millis(500)).await;

                let retry_response = self.http_client.get(rdap_url).send().await.map_err(|e| {
                    DomainCheckError::rdap(domain, format!("Retry request failed: {}", e))
                })?;

                match retry_response.status() {
                    StatusCode::OK => {
                        let json =
                            retry_response
                                .json::<serde_json::Value>()
                                .await
                                .map_err(|e| {
                                    DomainCheckError::rdap(
                                        domain,
                                        format!("Failed to parse retry JSON: {}", e),
                                    )
                                })?;

                        let domain_info = extract_domain_info(&json);
                        Ok((false, Some(domain_info)))
                    }
                    StatusCode::NOT_FOUND => Err(DomainCheckError::rdap_with_status(
                        domain,
                        "RDAP returned 404 after retry (domain may or may not be registered)",
                        404,
                    )),
                    code => {
                        if std::env::var("DOMAIN_CHECK_DEBUG_RDAP").is_ok() {
                            println!("🔍 Retry failed for {} with status: {}", domain, code);
                        }
                        Err(DomainCheckError::rdap_with_status(
                            domain,
                            format!("RDAP server error after retry: {}", code),
                            code.as_u16(),
                        ))
                    }
                }
            }
            code => {
                if std::env::var("DOMAIN_CHECK_DEBUG_RDAP").is_ok() {
                    println!("🔍 RDAP server error for {} with status: {}", domain, code);
                }
                Err(DomainCheckError::rdap_with_status(
                    domain,
                    format!("RDAP server returned error: {}", code),
                    code.as_u16(),
                ))
            }
        }
    }
}

impl Default for RdapClient {
    fn default() -> Self {
        Self::new().expect("Failed to create default RDAP client")
    }
}

/// Extract domain information from an RDAP JSON response.
///
/// This function parses the standardized RDAP JSON format and extracts
/// relevant domain registration details.
///
/// # Arguments
///
/// * `json` - The RDAP JSON response
///
/// # Returns
///
/// A `DomainInfo` struct with extracted registration details.
pub fn extract_domain_info(json: &serde_json::Value) -> DomainInfo {
    let mut info = DomainInfo::default();

    // Extract registrar information from entities
    if let Some(entities) = json.get("entities").and_then(|e| e.as_array()) {
        for entity in entities {
            if let Some(roles) = entity.get("roles").and_then(|r| r.as_array()) {
                let is_registrar = roles.iter().any(|role| role.as_str() == Some("registrar"));

                if is_registrar {
                    // Try to get registrar name from vcardArray
                    if let Some(name) = extract_vcard_name(entity) {
                        info.registrar = Some(name);
                        break;
                    }
                    // Fallback to publicIds or handle
                    else if let Some(name) = extract_entity_identifier(entity) {
                        info.registrar = Some(name);
                        break;
                    }
                }
            }
        }
    }

    // Extract dates from events
    if let Some(events) = json.get("events").and_then(|e| e.as_array()) {
        for event in events {
            if let (Some(event_action), Some(event_date)) = (
                event.get("eventAction").and_then(|a| a.as_str()),
                event.get("eventDate").and_then(|d| d.as_str()),
            ) {
                match event_action {
                    "registration" => info.creation_date = Some(event_date.to_string()),
                    "expiration" => info.expiration_date = Some(event_date.to_string()),
                    "last update of RDAP database" | "last changed" => {
                        info.updated_date = Some(event_date.to_string())
                    }
                    _ => {}
                }
            }
        }
    }

    // Extract status codes
    if let Some(statuses) = json.get("status").and_then(|s| s.as_array()) {
        for status in statuses {
            if let Some(status_str) = status.as_str() {
                info.status.push(status_str.to_string());
            }
        }
    }

    // Extract nameservers
    if let Some(nameservers) = json.get("nameservers").and_then(|ns| ns.as_array()) {
        for nameserver in nameservers {
            if let Some(ldh_name) = nameserver.get("ldhName").and_then(|name| name.as_str()) {
                info.nameservers.push(ldh_name.to_string());
            }
        }
    }

    info
}

/// Extract organization name from vCard format in RDAP entity.
fn extract_vcard_name(entity: &serde_json::Value) -> Option<String> {
    entity
        .get("vcardArray")
        .and_then(|v| v.as_array())
        .and_then(|a| a.get(1))
        .and_then(|a| a.as_array())
        .and_then(|items| {
            for item in items {
                if let Some(item_array) = item.as_array() {
                    if item_array.len() >= 4 {
                        if let Some(first) = item_array.first().and_then(|f| f.as_str()) {
                            if first == "fn" {
                                return item_array
                                    .get(3)
                                    .and_then(|n| n.as_str())
                                    .map(String::from);
                            }
                        }
                    }
                }
            }
            None
        })
}

/// Extract entity identifier from publicIds or handle.
fn extract_entity_identifier(entity: &serde_json::Value) -> Option<String> {
    // Try publicIds first
    if let Some(public_ids) = entity.get("publicIds").and_then(|p| p.as_array()) {
        if let Some(id) = public_ids
            .first()
            .and_then(|id| id.get("identifier"))
            .and_then(|i| i.as_str())
        {
            return Some(id.to_string());
        }
    }

    // Fallback to handle
    if let Some(handle) = entity.get("handle").and_then(|h| h.as_str()) {
        return Some(handle.to_string());
    }

    // Fallback to name
    entity
        .get("name")
        .and_then(|n| n.as_str())
        .map(String::from)
}

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

    // ── RdapClient creation ─────────────────────────────────────────────

    #[tokio::test]
    async fn test_rdap_client_new() {
        let client = RdapClient::new();
        assert!(client.is_ok());
        let client = client.unwrap();
        assert_eq!(client.timeout, Duration::from_secs(3));
        assert!(!client.use_bootstrap);
    }

    #[tokio::test]
    async fn test_rdap_client_with_config() {
        let client = RdapClient::with_config(Duration::from_secs(10), true).unwrap();
        assert_eq!(client.timeout, Duration::from_secs(10));
        assert!(client.use_bootstrap);
    }

    #[test]
    fn test_rdap_client_default() {
        let client = RdapClient::default();
        assert_eq!(client.timeout, Duration::from_secs(3));
    }

    // ── extract_domain_info ─────────────────────────────────────────────

    #[test]
    fn test_extract_domain_info_dates_and_status() {
        let json = serde_json::json!({
            "events": [
                {"eventAction": "registration", "eventDate": "1995-08-14T04:00:00Z"},
                {"eventAction": "expiration", "eventDate": "2025-08-13T04:00:00Z"}
            ],
            "status": ["client delete prohibited", "client transfer prohibited"]
        });

        let info = extract_domain_info(&json);
        assert_eq!(info.creation_date, Some("1995-08-14T04:00:00Z".to_string()));
        assert_eq!(
            info.expiration_date,
            Some("2025-08-13T04:00:00Z".to_string())
        );
        assert_eq!(info.status.len(), 2);
        assert!(info
            .status
            .contains(&"client delete prohibited".to_string()));
    }

    #[test]
    fn test_extract_domain_info_updated_date() {
        let json = serde_json::json!({
            "events": [
                {"eventAction": "last changed", "eventDate": "2024-01-01T00:00:00Z"}
            ]
        });
        let info = extract_domain_info(&json);
        assert_eq!(info.updated_date, Some("2024-01-01T00:00:00Z".to_string()));
    }

    #[test]
    fn test_extract_domain_info_rdap_database_update() {
        let json = serde_json::json!({
            "events": [
                {"eventAction": "last update of RDAP database", "eventDate": "2024-06-15T00:00:00Z"}
            ]
        });
        let info = extract_domain_info(&json);
        assert_eq!(info.updated_date, Some("2024-06-15T00:00:00Z".to_string()));
    }

    #[test]
    fn test_extract_domain_info_unknown_event_ignored() {
        let json = serde_json::json!({
            "events": [
                {"eventAction": "transfer", "eventDate": "2024-01-01T00:00:00Z"}
            ]
        });
        let info = extract_domain_info(&json);
        assert!(info.creation_date.is_none());
        assert!(info.expiration_date.is_none());
        assert!(info.updated_date.is_none());
    }

    #[test]
    fn test_extract_domain_info_nameservers() {
        let json = serde_json::json!({
            "nameservers": [
                {"ldhName": "ns1.example.com"},
                {"ldhName": "ns2.example.com"}
            ]
        });
        let info = extract_domain_info(&json);
        assert_eq!(info.nameservers.len(), 2);
        assert!(info.nameservers.contains(&"ns1.example.com".to_string()));
        assert!(info.nameservers.contains(&"ns2.example.com".to_string()));
    }

    #[test]
    fn test_extract_domain_info_registrar_from_vcard() {
        let json = serde_json::json!({
            "entities": [{
                "roles": ["registrar"],
                "vcardArray": ["vcard", [
                    ["fn", {}, "text", "GoDaddy LLC"]
                ]]
            }]
        });
        let info = extract_domain_info(&json);
        assert_eq!(info.registrar, Some("GoDaddy LLC".to_string()));
    }

    #[test]
    fn test_extract_domain_info_registrar_from_public_id() {
        let json = serde_json::json!({
            "entities": [{
                "roles": ["registrar"],
                "publicIds": [{"identifier": "292", "type": "IANA Registrar ID"}]
            }]
        });
        let info = extract_domain_info(&json);
        assert_eq!(info.registrar, Some("292".to_string()));
    }

    #[test]
    fn test_extract_domain_info_registrar_from_handle() {
        let json = serde_json::json!({
            "entities": [{
                "roles": ["registrar"],
                "handle": "REG-123"
            }]
        });
        let info = extract_domain_info(&json);
        assert_eq!(info.registrar, Some("REG-123".to_string()));
    }

    #[test]
    fn test_extract_domain_info_non_registrar_entity_skipped() {
        let json = serde_json::json!({
            "entities": [{
                "roles": ["technical"],
                "vcardArray": ["vcard", [["fn", {}, "text", "Tech Contact"]]]
            }]
        });
        let info = extract_domain_info(&json);
        assert!(info.registrar.is_none());
    }

    #[test]
    fn test_extract_domain_info_empty_json() {
        let json = serde_json::json!({});
        let info = extract_domain_info(&json);
        assert!(info.registrar.is_none());
        assert!(info.creation_date.is_none());
        assert!(info.expiration_date.is_none());
        assert!(info.status.is_empty());
        assert!(info.nameservers.is_empty());
    }

    #[test]
    fn test_extract_domain_info_full_response() {
        let json = serde_json::json!({
            "entities": [{
                "roles": ["registrar"],
                "vcardArray": ["vcard", [["fn", {}, "text", "MarkMonitor Inc."]]]
            }],
            "events": [
                {"eventAction": "registration", "eventDate": "1997-09-15T04:00:00Z"},
                {"eventAction": "expiration", "eventDate": "2028-09-14T04:00:00Z"},
                {"eventAction": "last changed", "eventDate": "2024-01-15T00:00:00Z"}
            ],
            "status": ["client delete prohibited", "server transfer prohibited"],
            "nameservers": [
                {"ldhName": "ns1.google.com"},
                {"ldhName": "ns2.google.com"},
                {"ldhName": "ns3.google.com"}
            ]
        });
        let info = extract_domain_info(&json);
        assert_eq!(info.registrar, Some("MarkMonitor Inc.".to_string()));
        assert_eq!(info.creation_date, Some("1997-09-15T04:00:00Z".to_string()));
        assert_eq!(
            info.expiration_date,
            Some("2028-09-14T04:00:00Z".to_string())
        );
        assert_eq!(info.updated_date, Some("2024-01-15T00:00:00Z".to_string()));
        assert_eq!(info.status.len(), 2);
        assert_eq!(info.nameservers.len(), 3);
    }

    // ── extract_vcard_name ──────────────────────────────────────────────

    #[test]
    fn test_extract_vcard_name_standard() {
        let entity = serde_json::json!({
            "vcardArray": ["vcard", [["fn", {}, "text", "Example Registrar Inc."]]]
        });
        assert_eq!(
            extract_vcard_name(&entity),
            Some("Example Registrar Inc.".to_string())
        );
    }

    #[test]
    fn test_extract_vcard_name_no_fn_field() {
        let entity = serde_json::json!({
            "vcardArray": ["vcard", [["org", {}, "text", "Some Org"]]]
        });
        assert_eq!(extract_vcard_name(&entity), None);
    }

    #[test]
    fn test_extract_vcard_name_no_vcard() {
        let entity = serde_json::json!({"handle": "test"});
        assert_eq!(extract_vcard_name(&entity), None);
    }

    #[test]
    fn test_extract_vcard_name_empty_vcard_array() {
        let entity = serde_json::json!({"vcardArray": ["vcard", []]});
        assert_eq!(extract_vcard_name(&entity), None);
    }

    #[test]
    fn test_extract_vcard_name_short_item_array() {
        let entity = serde_json::json!({
            "vcardArray": ["vcard", [["fn", {}]]]
        });
        assert_eq!(extract_vcard_name(&entity), None);
    }

    // ── extract_entity_identifier ───────────────────────────────────────

    #[test]
    fn test_extract_entity_identifier_public_id() {
        let entity = serde_json::json!({
            "publicIds": [{"identifier": "292", "type": "IANA Registrar ID"}]
        });
        assert_eq!(extract_entity_identifier(&entity), Some("292".to_string()));
    }

    #[test]
    fn test_extract_entity_identifier_handle_fallback() {
        let entity = serde_json::json!({"handle": "REG-123"});
        assert_eq!(
            extract_entity_identifier(&entity),
            Some("REG-123".to_string())
        );
    }

    #[test]
    fn test_extract_entity_identifier_name_fallback() {
        let entity = serde_json::json!({"name": "Some Registrar"});
        assert_eq!(
            extract_entity_identifier(&entity),
            Some("Some Registrar".to_string())
        );
    }

    #[test]
    fn test_extract_entity_identifier_precedence() {
        // publicIds should be preferred over handle
        let entity = serde_json::json!({
            "publicIds": [{"identifier": "292"}],
            "handle": "REG-123",
            "name": "Some Registrar"
        });
        assert_eq!(extract_entity_identifier(&entity), Some("292".to_string()));
    }

    #[test]
    fn test_extract_entity_identifier_none() {
        let entity = serde_json::json!({"roles": ["registrar"]});
        assert_eq!(extract_entity_identifier(&entity), None);
    }

    #[test]
    fn test_extract_entity_identifier_empty_public_ids() {
        let entity = serde_json::json!({
            "publicIds": [],
            "handle": "FALLBACK"
        });
        assert_eq!(
            extract_entity_identifier(&entity),
            Some("FALLBACK".to_string())
        );
    }
}