monovm-whois-rust 1.0.0

Domain WHOIS and RDAP lookups with availability detection, structured record parsing, referral chasing, caching and rate limiting.
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
//! The rules, in the order the engine applies them.
//!
//! Each rule is a small type with one job, and each either reaches a conclusion or
//! abstains. The order they run in is the whole design: the response `Status: not
//! available` contains the substring `available`, so a rule that looks for
//! availability must never run before the rules that look for the opposite.
//!
//! Reading order top to bottom is also priority order:
//!
//! 1. [`WrongServerRule`] — we are asking the wrong server; nothing it says counts
//! 2. [`RefusalRule`] — it declined to answer; nothing it says counts either
//! 3. [`RdapRule`] — structured JSON, so the answer is a fact rather than a guess
//! 4. [`RegistryMarkerRule`] — this registry's own documented wording
//! 5. [`WithheldRule`] — reserved, restricted or premium
//! 6. [`RegisteredRule`] — a record exists
//! 7. [`NotFoundRule`] — generic "no such domain" wording
//! 8. [`TldPatternRule`] — per-suffix wording the generic table misses
//! 9. [`RecordlessRule`] — no record at all, where the registry says that means free

use serde_json::Value;

use crate::detect::{patterns, AvailabilityRule, Confidence, Evidence, Judgement};
use crate::domain::Availability;
use crate::error::Refusal;

/// Minimum number of distinct registration fields that make a response a record.
///
/// Two rather than three: a thin `.com` answer for a domain whose registrar has
/// gone quiet can be as short as `Domain Name:` plus `Registrar:`, and the
/// fields are anchored to line starts, so a false positive from prose is not
/// the risk it would otherwise be.
const MIN_REGISTRATION_FIELDS: usize = 2;

/// Longest response that can still be called "no record at all".
const RECORDLESS_MAX_LEN: usize = 400;

/// Rejects answers from a server that does not serve this suffix.
///
/// Runs first because such an answer is not evidence of anything. A stale mapping
/// that sends a `.example` query to an IP registry gets `no entries found` back,
/// which every availability table matches — this is the rule that stops a whole
/// suffix being reported as free.
#[derive(Debug, Default, Clone, Copy)]
pub struct WrongServerRule;

impl AvailabilityRule for WrongServerRule {
    fn name(&self) -> &'static str {
        "wrong-server"
    }

    fn evaluate(&self, evidence: &Evidence<'_>) -> Judgement {
        // "This server does not serve that TLD" can be said anywhere in a response.
        if let Some(matched) = patterns::wrong_server().first_match(evidence.lowercase()) {
            return Judgement::WrongServer {
                because: format!("response matched {matched:?}"),
            };
        }

        // An IP registry's self-identification, on the other hand, is only meaningful
        // at the top. JPRS closes its `.jp` banner with a list of every regional
        // registry's WHOIS host, and reading that as identification made every `.jp`
        // lookup conclude it had reached ARIN.
        let banner = evidence.head(patterns::BANNER_LINES);
        match patterns::rir_banner().first_match(&banner) {
            Some(matched) => Judgement::WrongServer {
                because: format!("the server identified itself with {matched:?}"),
            },
            None => Judgement::Abstain,
        }
    }
}

/// Rejects answers where the server declined the query.
///
/// Rate limiting, a blocked client, a retired port 43 service. Classifying any
/// of these as availability would mean a rate-limited registry reports its
/// entire zone as free to register.
#[derive(Debug, Default, Clone, Copy)]
pub struct RefusalRule;

impl AvailabilityRule for RefusalRule {
    fn name(&self) -> &'static str {
        "refusal"
    }

    fn evaluate(&self, evidence: &Evidence<'_>) -> Judgement {
        let text = evidence.lowercase();

        /// A table of function pointers rather than closures: closures would be
        /// temporaries whose references cannot outlive the array literal.
        type Match = fn(&str) -> Option<&'static str>;

        // Most specific first. A retired service and a rate limit are both
        // "declined", but only one of them is worth retrying.
        const CHECKS: [(Match, Refusal); 5] = [
            (
                |text| patterns::port_retired().first_match(text),
                Refusal::PortRetired,
            ),
            (
                |text| patterns::rate_limited().first_match(text),
                Refusal::RateLimited,
            ),
            (
                |text| patterns::blocked().first_match(text),
                Refusal::Blocked,
            ),
            (
                |text| patterns::access_restricted().first_match(text),
                Refusal::AccessRestricted,
            ),
            (
                |text| patterns::unavailable().first_match(text),
                Refusal::Unavailable,
            ),
        ];

        for (check, reason) in CHECKS {
            let Some(matched) = check(text) else { continue };

            // A record that happens to mention one of these phrases is still a
            // record — a registrant called "Try Again Later Ltd" should not make a
            // lookup fail. Only treat it as a refusal when there is nothing else in
            // the response.
            if looks_like_a_record(evidence) {
                continue;
            }

            return Judgement::Refused {
                reason,
                because: format!("response matched {matched:?}"),
            };
        }

        Judgement::Abstain
    }
}

/// Reads an RDAP JSON answer, which says outright what WHOIS only implies.
///
/// RFC 9083 gives availability a machine-readable form: a domain that does not
/// exist is an error object with `errorCode` 404, and one that does is a domain
/// object with `objectClassName` and an `ldhName`. No wording to interpret.
#[derive(Debug, Default, Clone, Copy)]
pub struct RdapRule;

impl AvailabilityRule for RdapRule {
    fn name(&self) -> &'static str {
        "rdap"
    }

    fn evaluate(&self, evidence: &Evidence<'_>) -> Judgement {
        if !evidence.is_rdap() {
            return Judgement::Abstain;
        }

        let Ok(json) = serde_json::from_str::<Value>(evidence.text()) else {
            // Not JSON despite the endpoint claiming RDAP. Let the text rules try;
            // some registries answer with an HTML error page.
            return Judgement::Abstain;
        };

        if let Some(code) = json.get("errorCode").and_then(Value::as_u64) {
            return match code {
                404 => Judgement::decided(
                    Availability::Available,
                    Confidence::Definitive,
                    "RDAP errorCode 404: the domain object does not exist",
                ),
                429 => Judgement::Refused {
                    reason: Refusal::RateLimited,
                    because: "RDAP errorCode 429".to_string(),
                },
                401 | 403 => Judgement::Refused {
                    reason: Refusal::AccessRestricted,
                    because: format!("RDAP errorCode {code}"),
                },
                _ => Judgement::Abstain,
            };
        }

        let is_domain_object = json
            .get("objectClassName")
            .and_then(Value::as_str)
            .is_some_and(|class| class.eq_ignore_ascii_case("domain"));
        let has_name = json.get("ldhName").and_then(Value::as_str).is_some();

        if is_domain_object || has_name {
            // Some registries publish a domain object for a name they have merely
            // reserved, flagged through an RDAP status value.
            let statuses = rdap_statuses(&json);
            if statuses
                .iter()
                .any(|status| status.contains("reserved") || status.contains("blocked"))
            {
                return Judgement::decided(
                    Availability::Reserved,
                    Confidence::Definitive,
                    format!("RDAP domain object with status {statuses:?}"),
                );
            }

            return Judgement::decided(
                Availability::Registered,
                Confidence::Definitive,
                "RDAP returned a domain object",
            );
        }

        Judgement::Abstain
    }
}

/// Applies the availability wording curated for this specific registry.
///
/// The strongest text signal there is. A generic pattern is a guess about how
/// registries phrase things in general; a marker was written by reading what one
/// server actually says, which is why it runs before every generic table.
#[derive(Debug, Default, Clone, Copy)]
pub struct RegistryMarkerRule;

impl AvailabilityRule for RegistryMarkerRule {
    fn name(&self) -> &'static str {
        "registry-marker"
    }

    fn evaluate(&self, evidence: &Evidence<'_>) -> Judgement {
        let Some(registry) = evidence.registry() else {
            return Judgement::Abstain;
        };

        for marker in registry.premium_markers() {
            if !marker.is_empty() && evidence.contains(&marker.to_lowercase()) {
                return Judgement::decided(
                    Availability::Premium,
                    Confidence::High,
                    format!("registry premium marker {marker:?}"),
                );
            }
        }

        // Matched against significant lines, so a marker that happens to appear in a
        // disclaimer does not count. Joined once, because registries wrap sentences
        // and a marker may straddle two lines.
        let significant = evidence.significant_text();

        for marker in registry.available_markers() {
            if marker.is_empty() {
                continue;
            }
            if significant.contains(&marker.to_lowercase()) {
                return Judgement::decided(
                    Availability::Available,
                    Confidence::High,
                    format!("registry availability marker {marker:?}"),
                );
            }
        }

        Judgement::Abstain
    }
}

/// Recognises names the registry is holding back.
///
/// Reserved and premium names are neither registered nor available, and a checkout
/// page that treats them as available quotes a price that does not exist. Runs
/// before [`RegisteredRule`] because a reservation notice carries no fields for
/// that rule to count, and before the availability rules because it usually
/// carries none of their wording either.
#[derive(Debug, Default, Clone, Copy)]
pub struct WithheldRule;

impl AvailabilityRule for WithheldRule {
    fn name(&self) -> &'static str {
        "withheld"
    }

    fn evaluate(&self, evidence: &Evidence<'_>) -> Judgement {
        let text = evidence.lowercase();

        if let Some(matched) = patterns::premium().first_match(text) {
            return Judgement::decided(
                Availability::Premium,
                Confidence::Medium,
                format!("response matched {matched:?}"),
            );
        }

        if let Some(matched) = patterns::reserved().first_match(text) {
            return Judgement::decided(
                Availability::Reserved,
                Confidence::Medium,
                format!("response matched {matched:?}"),
            );
        }

        Judgement::Abstain
    }
}

/// Recognises a response that is a record.
///
/// Three independent signals, any of which is enough: a status value only a
/// registered name can hold, a sentence saying so, or simply enough distinct
/// registration fields to be a record. Runs before the availability rules so that
/// `Status: not available` cannot be read as `available`.
#[derive(Debug, Clone, Copy)]
pub struct RegisteredRule {
    min_fields: usize,
}

impl RegisteredRule {
    /// With the default field threshold.
    pub fn new() -> Self {
        RegisteredRule {
            min_fields: MIN_REGISTRATION_FIELDS,
        }
    }

    /// With an explicit field threshold.
    pub fn with_min_fields(min_fields: usize) -> Self {
        RegisteredRule {
            min_fields: min_fields.max(1),
        }
    }
}

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

impl AvailabilityRule for RegisteredRule {
    fn name(&self) -> &'static str {
        "registered"
    }

    fn evaluate(&self, evidence: &Evidence<'_>) -> Judgement {
        let significant = evidence.significant_text();

        if let Some(matched) = patterns::registered_status().first_match(&significant) {
            return Judgement::decided(
                Availability::Registered,
                Confidence::High,
                format!("status field matched {matched:?}"),
            );
        }

        if let Some(matched) = patterns::registered_phrase().first_match(&significant) {
            return Judgement::decided(
                Availability::Registered,
                Confidence::High,
                format!("response matched {matched:?}"),
            );
        }

        // Field counting runs against the response itself, not the joined
        // significant lines, because the patterns are anchored to line starts.
        let fields = patterns::registration_fields().match_count(evidence.lowercase());
        if fields >= self.min_fields {
            return Judgement::decided(
                Availability::Registered,
                Confidence::Medium,
                format!("{fields} distinct registration fields present"),
            );
        }

        Judgement::Abstain
    }
}

/// Recognises the generic ways registries say "no such domain".
#[derive(Debug, Default, Clone, Copy)]
pub struct NotFoundRule;

impl AvailabilityRule for NotFoundRule {
    fn name(&self) -> &'static str {
        "not-found"
    }

    fn evaluate(&self, evidence: &Evidence<'_>) -> Judgement {
        // Significant lines only: registries print "available" in their advertising,
        // and "not found" in their explanations of what a lookup failure means.
        if let Some(matched) = patterns::not_found().first_match(&evidence.significant_text()) {
            return Judgement::decided(
                Availability::Available,
                Confidence::Medium,
                format!("response matched {matched:?}"),
            );
        }

        // Some registries put the verdict in a comment, where the filtering above
        // hides it. Only the anchored comment table is consulted here, never the
        // general wording — see `patterns::comment_answer`.
        for line in evidence.comment_lines() {
            if let Some(matched) = patterns::comment_answer().first_match(line) {
                return Judgement::decided(
                    Availability::Available,
                    Confidence::Medium,
                    format!("comment line {line:?} matched {matched:?}"),
                );
            }
        }

        Judgement::Abstain
    }
}

/// Applies wording specific to one suffix.
///
/// The last resort before giving up, for registries whose phrasing the general
/// tables cannot safely carry — Nominet's `Registered on:`, JPRS's `No match!!`.
#[derive(Debug, Default, Clone, Copy)]
pub struct TldPatternRule;

impl AvailabilityRule for TldPatternRule {
    fn name(&self) -> &'static str {
        "tld-pattern"
    }

    fn evaluate(&self, evidence: &Evidence<'_>) -> Judgement {
        let tld = evidence.tld().ascii();
        let significant = evidence.significant_text();

        // Registered before available, for the same reason as everywhere else.
        if let Some(table) = patterns::tld_registered(tld) {
            if let Some(matched) = table.first_match(&significant) {
                return Judgement::decided(
                    Availability::Registered,
                    Confidence::Medium,
                    format!(".{tld} registered pattern {matched:?}"),
                );
            }
        }

        if let Some(table) = patterns::tld_not_found(tld) {
            if let Some(matched) = table.first_match(&significant) {
                return Judgement::decided(
                    Availability::Available,
                    Confidence::Medium,
                    format!(".{tld} availability pattern {matched:?}"),
                );
            }
        }

        Judgement::Abstain
    }
}

/// Reads "no record at all" as availability, for the registries that mean it.
///
/// A few registries answer an unregistered name with nothing but their banner —
/// NIC Monaco is one — so the absence of a record is the only signal available.
/// That inference is only sound when the server clearly did answer and simply had
/// nothing to say, and only for registries known to behave this way, which is why
/// it is opt-in per registry through
/// [`Registry::available_when_empty`](crate::registry::Registry::available_when_empty)
/// and never a global fallback.
#[derive(Debug, Default, Clone, Copy)]
pub struct RecordlessRule;

impl AvailabilityRule for RecordlessRule {
    fn name(&self) -> &'static str {
        "recordless"
    }

    fn evaluate(&self, evidence: &Evidence<'_>) -> Judgement {
        let opted_in = evidence
            .registry()
            .is_some_and(|registry| registry.available_when_empty());
        if !opted_in {
            return Judgement::Abstain;
        }

        // An error notice has no registration fields either, and reading one as a
        // free domain is exactly the mistake this rule is one step away from.
        if patterns::error_notice().matches(evidence.lowercase()) {
            return Judgement::Abstain;
        }

        let fields = patterns::registration_fields().match_count(evidence.lowercase());
        if fields > 0 {
            return Judgement::Abstain;
        }
        if evidence.len() > RECORDLESS_MAX_LEN {
            return Judgement::Abstain;
        }

        Judgement::decided(
            Availability::Available,
            Confidence::Low,
            "no record, and this registry answers unregistered names with a banner only",
        )
    }
}

/// Whether a response looks like an actual record rather than a notice.
///
/// Used by [`RefusalRule`] to avoid discarding a real record that happens to
/// mention one of its phrases — a registrant whose organisation is called
/// "Try Again Later Ltd" should not make a lookup fail.
fn looks_like_a_record(evidence: &Evidence<'_>) -> bool {
    patterns::registration_fields().match_count(evidence.lowercase()) >= MIN_REGISTRATION_FIELDS
}

/// The RDAP `status` array, lower-cased.
fn rdap_statuses(json: &Value) -> Vec<String> {
    json.get("status")
        .and_then(Value::as_array)
        .map(|values| {
            values
                .iter()
                .filter_map(Value::as_str)
                .map(str::to_lowercase)
                .collect()
        })
        .unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::Tld;
    use crate::registry::Registry;
    use crate::transport::ResponseKind;

    fn whois<'a>(text: &'a str, tld: &'a Tld) -> Evidence<'a> {
        Evidence::new(text, ResponseKind::WhoisText, tld, None)
    }

    fn rdap<'a>(json: &'a str, tld: &'a Tld) -> Evidence<'a> {
        Evidence::new(json, ResponseKind::RdapJson, tld, None)
    }

    // ---------------------------------------------------------------- wrong server

    #[test]
    fn a_rir_banner_is_not_an_answer() {
        let tld = Tld::parse("example").unwrap();
        let response = "% This is the RIPE Database query service.\n%ERROR:101: no entries found\n";

        // The generic availability table matches this, which is the trap.
        assert!(patterns::not_found().matches(response));
        assert!(matches!(
            WrongServerRule.evaluate(&whois(response, &tld)),
            Judgement::WrongServer { .. }
        ));
    }

    #[test]
    fn wrong_server_abstains_on_a_normal_record() {
        let tld = Tld::parse("com").unwrap();
        let evidence = whois("Domain Name: EXAMPLE.COM\nRegistrar: Example\n", &tld);
        assert!(matches!(
            WrongServerRule.evaluate(&evidence),
            Judgement::Abstain
        ));
    }

    // -------------------------------------------------------------------- refusal

    #[test]
    fn refusals_are_classified_by_kind() {
        let tld = Tld::parse("com").unwrap();
        let cases = [
            ("%% queries limit exceeded", Refusal::RateLimited),
            (
                "Requests of this client are not permitted",
                Refusal::Blocked,
            ),
            ("The WHOIS service has been retired", Refusal::PortRetired),
            (
                "Server is busy, please try again later",
                Refusal::Unavailable,
            ),
        ];

        for (response, expected) in cases {
            match RefusalRule.evaluate(&whois(response, &tld)) {
                Judgement::Refused { reason, .. } => {
                    assert_eq!(reason, expected, "for {response:?}")
                }
                other => panic!("expected a refusal for {response:?}, got {other:?}"),
            }
        }
    }

    #[test]
    fn a_real_record_survives_an_unlucky_phrase() {
        let tld = Tld::parse("com").unwrap();
        let record = "Domain Name: EXAMPLE.COM\n\
                      Registrant Organization: Try Again Later Ltd\n\
                      Registrar: Example LLC\n";

        assert!(
            matches!(
                RefusalRule.evaluate(&whois(record, &tld)),
                Judgement::Abstain
            ),
            "a record was discarded because of one phrase in a field value"
        );
    }

    // ----------------------------------------------------------------------- rdap

    #[test]
    fn rdap_404_is_definitive_availability() {
        let tld = Tld::parse("com").unwrap();
        let json = r#"{"errorCode":404,"title":"Not Found"}"#;

        match RdapRule.evaluate(&rdap(json, &tld)) {
            Judgement::Decided {
                availability,
                confidence,
                ..
            } => {
                assert_eq!(availability, Availability::Available);
                assert_eq!(confidence, Confidence::Definitive);
            }
            other => panic!("got {other:?}"),
        }
    }

    #[test]
    fn an_rdap_domain_object_is_definitive_registration() {
        let tld = Tld::parse("com").unwrap();
        let json = r#"{"objectClassName":"domain","ldhName":"example.com","status":["active"]}"#;

        match RdapRule.evaluate(&rdap(json, &tld)) {
            Judgement::Decided { availability, .. } => {
                assert_eq!(availability, Availability::Registered)
            }
            other => panic!("got {other:?}"),
        }
    }

    #[test]
    fn an_rdap_reserved_status_is_neither() {
        let tld = Tld::parse("com").unwrap();
        let json = r#"{"objectClassName":"domain","ldhName":"a.com","status":["reserved"]}"#;

        match RdapRule.evaluate(&rdap(json, &tld)) {
            Judgement::Decided { availability, .. } => {
                assert_eq!(availability, Availability::Reserved)
            }
            other => panic!("got {other:?}"),
        }
    }

    #[test]
    fn rdap_rate_limiting_is_a_refusal_not_availability() {
        let tld = Tld::parse("com").unwrap();
        let json = r#"{"errorCode":429,"title":"Too Many Requests"}"#;

        match RdapRule.evaluate(&rdap(json, &tld)) {
            Judgement::Refused { reason, .. } => assert_eq!(reason, Refusal::RateLimited),
            other => panic!("got {other:?}"),
        }
    }

    #[test]
    fn rdap_rule_ignores_whois_text_and_broken_json() {
        let tld = Tld::parse("com").unwrap();
        assert!(matches!(
            RdapRule.evaluate(&whois(r#"{"errorCode":404}"#, &tld)),
            Judgement::Abstain
        ));
        assert!(matches!(
            RdapRule.evaluate(&rdap("<html>error</html>", &tld)),
            Judgement::Abstain
        ));
    }

    // ------------------------------------------------------------ registry marker

    #[test]
    fn a_curated_marker_decides_with_high_confidence() {
        let tld = Tld::parse("com").unwrap();
        let registry = Registry::builder([tld.clone()])
            .available_marker("No match for")
            .build();
        let evidence = Evidence::new(
            "No match for \"NOTHERE.COM\"",
            ResponseKind::WhoisText,
            &tld,
            Some(&registry),
        );

        match RegistryMarkerRule.evaluate(&evidence) {
            Judgement::Decided {
                availability,
                confidence,
                ..
            } => {
                assert_eq!(availability, Availability::Available);
                assert_eq!(confidence, Confidence::High);
            }
            other => panic!("got {other:?}"),
        }
    }

    #[test]
    fn a_marker_in_a_banner_does_not_count() {
        let tld = Tld::parse("example").unwrap();
        let registry = Registry::builder([tld.clone()])
            .available_marker("not found")
            .build();
        // The phrase appears only inside a comment explaining the service.
        let response = "% If a domain is not found, this server says so.\n\
                        Domain Name: TAKEN.EXAMPLE\n\
                        Registrar: Someone\n";
        let evidence = Evidence::new(response, ResponseKind::WhoisText, &tld, Some(&registry));

        assert!(matches!(
            RegistryMarkerRule.evaluate(&evidence),
            Judgement::Abstain
        ));
    }

    #[test]
    fn marker_rule_abstains_without_a_registry() {
        let tld = Tld::parse("com").unwrap();
        assert!(matches!(
            RegistryMarkerRule.evaluate(&whois("No match for x", &tld)),
            Judgement::Abstain
        ));
    }

    // -------------------------------------------------------------------- withheld

    #[test]
    fn restriction_notices_are_neither_registered_nor_available() {
        let tld = Tld::parse("sx").unwrap();
        let response = "Error code: 01044\nThis domain name has usage restrictions applied.\n";

        match WithheldRule.evaluate(&whois(response, &tld)) {
            Judgement::Decided { availability, .. } => {
                assert_eq!(availability, Availability::Reserved)
            }
            other => panic!("got {other:?}"),
        }
    }

    // ------------------------------------------------------------------ registered

    #[test]
    fn an_epp_status_decides_registration() {
        let tld = Tld::parse("com").unwrap();
        let response = "Domain Status: clientTransferProhibited\n";
        match RegisteredRule::new().evaluate(&whois(response, &tld)) {
            Judgement::Decided {
                availability,
                confidence,
                ..
            } => {
                assert_eq!(availability, Availability::Registered);
                assert_eq!(confidence, Confidence::High);
            }
            other => panic!("got {other:?}"),
        }
    }

    #[test]
    fn enough_fields_decide_registration() {
        let tld = Tld::parse("com").unwrap();
        let response =
            "Domain Name: EXAMPLE.COM\nRegistrar: Example LLC\nName Server: ns1.example\n";

        match RegisteredRule::new().evaluate(&whois(response, &tld)) {
            Judgement::Decided { availability, .. } => {
                assert_eq!(availability, Availability::Registered)
            }
            other => panic!("got {other:?}"),
        }
    }

    #[test]
    fn a_no_match_response_has_no_fields_to_count() {
        let tld = Tld::parse("com").unwrap();
        let response = "No match for \"NOTHERE.COM\".\n\
                        >>> Last update of whois database: 2026-01-01 <<<\n";

        assert!(
            matches!(
                RegisteredRule::new().evaluate(&whois(response, &tld)),
                Judgement::Abstain
            ),
            "an availability response was read as a record"
        );
    }

    #[test]
    fn nominets_availability_banner_is_not_a_record() {
        let tld = Tld::parse("co.uk").unwrap();
        // Nominet's real "free" answer: prose, and the word Registrar in it.
        let response = "\
    No match for \"NOTREGISTERED.CO.UK\".

    This domain name has not been registered.

    WHOIS lookup made at 10:00:00 01-Jan-2026
--
This WHOIS information is provided for free by Nominet UK. You may contact a
Registrar to register this domain name.
";
        assert!(
            matches!(
                RegisteredRule::new().evaluate(&whois(response, &tld)),
                Judgement::Abstain
            ),
            "prose mentioning a registrar was counted as a registration field"
        );
    }

    #[test]
    fn status_not_available_is_registration_not_availability() {
        let tld = Tld::parse("example").unwrap();
        let response = "Status: not available\n";

        match RegisteredRule::new().evaluate(&whois(response, &tld)) {
            Judgement::Decided { availability, .. } => {
                assert_eq!(availability, Availability::Registered)
            }
            other => panic!("got {other:?}"),
        }
    }

    // ------------------------------------------------------------------- not found

    #[test]
    fn generic_wordings_are_recognised() {
        let tld = Tld::parse("com").unwrap();
        for response in [
            "Domain not found",
            "NOT FOUND",
            "No entries found",
            "Status: AVAILABLE",
        ] {
            match NotFoundRule.evaluate(&whois(response, &tld)) {
                Judgement::Decided { availability, .. } => {
                    assert_eq!(availability, Availability::Available, "for {response:?}")
                }
                other => panic!("for {response:?}: got {other:?}"),
            }
        }
    }

    #[test]
    fn a_disclaimer_mentioning_free_is_not_availability() {
        let tld = Tld::parse("co.uk").unwrap();
        let response = "\
    Domain name:
        example.co.uk

    Registrar:
        Example Ltd
--
This WHOIS information is provided for free by Nominet.
";
        assert!(matches!(
            NotFoundRule.evaluate(&whois(response, &tld)),
            Judgement::Abstain
        ));
    }

    // ----------------------------------------------------------------- tld pattern

    #[test]
    fn per_suffix_wording_is_applied() {
        let jp = Tld::parse("jp").unwrap();
        match TldPatternRule.evaluate(&whois("No match!!", &jp)) {
            Judgement::Decided { availability, .. } => {
                assert_eq!(availability, Availability::Available)
            }
            other => panic!("got {other:?}"),
        }

        let de = Tld::parse("de").unwrap();
        match TldPatternRule.evaluate(&whois("Status: connect", &de)) {
            Judgement::Decided { availability, .. } => {
                assert_eq!(availability, Availability::Registered)
            }
            other => panic!("got {other:?}"),
        }
    }

    #[test]
    fn tld_rule_abstains_for_suffixes_with_no_table() {
        let tld = Tld::parse("com").unwrap();
        assert!(matches!(
            TldPatternRule.evaluate(&whois("something unusual", &tld)),
            Judgement::Abstain
        ));
    }

    // ------------------------------------------------------------------ recordless

    #[test]
    fn recordless_needs_the_registry_to_opt_in() {
        let tld = Tld::parse("mc").unwrap();
        let banner = "% NIC Monaco whois server\n";

        // Without the flag, silence proves nothing.
        assert!(matches!(
            RecordlessRule.evaluate(&whois(banner, &tld)),
            Judgement::Abstain
        ));

        let registry = Registry::builder([tld.clone()])
            .available_when_empty(true)
            .build();
        let evidence = Evidence::new(banner, ResponseKind::WhoisText, &tld, Some(&registry));

        match RecordlessRule.evaluate(&evidence) {
            Judgement::Decided {
                availability,
                confidence,
                ..
            } => {
                assert_eq!(availability, Availability::Available);
                assert_eq!(
                    confidence,
                    Confidence::Low,
                    "a guess must not claim confidence"
                );
            }
            other => panic!("got {other:?}"),
        }
    }

    #[test]
    fn recordless_never_fires_through_an_error_notice() {
        let tld = Tld::parse("mc").unwrap();
        let registry = Registry::builder([tld.clone()])
            .available_when_empty(true)
            .build();
        let notice = "Error code: 500\nAccess denied.\n";
        let evidence = Evidence::new(notice, ResponseKind::WhoisText, &tld, Some(&registry));

        assert!(matches!(
            RecordlessRule.evaluate(&evidence),
            Judgement::Abstain
        ));
    }

    #[test]
    fn recordless_declines_a_long_response() {
        let tld = Tld::parse("mc").unwrap();
        let registry = Registry::builder([tld.clone()])
            .available_when_empty(true)
            .build();
        let long = "% banner line\n".repeat(60);
        let evidence = Evidence::new(&long, ResponseKind::WhoisText, &tld, Some(&registry));

        assert!(matches!(
            RecordlessRule.evaluate(&evidence),
            Judgement::Abstain
        ));
    }
}