acme-proxy-protocol 0.6.0

The ACME (RFC 8555) services, extractors, handlers and routers of acme-proxy (internal crate, no semver promise)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
//! What a request may ask for, as checks over the values themselves.
//!
//! No database, no HTTP: an identifier's shape, a contact's, a CSR's agreement
//! with its order, a datetime's format. The `acme::*` services call these
//! before anything is written, and the job handlers call the same functions on
//! the same values, so one rule has one implementation.
//!
//! **The CSR checks are the security boundary for `custom` and `relay`.**
//! Neither backend can check a CSR against the order — one hands it to an
//! operator's script, the other to an upstream CA that never saw the
//! authorizations — so whatever passes here is what those backends sign. Read
//! [`check_csr_matches_order`] before changing any of it, and keep it reading
//! the DER rather than a re-serialisation of it.

use rcgen::{CertificateSigningRequestParams, DnType, DnValue, SanType};
use rustls_pki_types::CertificateSigningRequestDer;
use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339;
use tracing::warn;

use acme_proxy_core::error::Problem;
use acme_proxy_core::identifier::Identifier;

/// Parses a PKCS#10 CSR, which also verifies its own self-signature.
///
/// Separated from [`csr_identifiers`] because `OrderService::finalize` performs two checks
/// on the same CSR: parsing it once avoids reparsing it.
pub(crate) fn parse_csr(csr_der: &[u8]) -> Result<CertificateSigningRequestParams, Problem> {
    let der = CertificateSigningRequestDer::from(csr_der.to_vec());
    CertificateSigningRequestParams::from_der(&der).map_err(|error| {
        warn!(event = "csr_parse_failed", outcome = "failure", error = %error);
        Problem::bad_csr("CSR is unparsable")
    })
}

/// RFC 8555 §7.4: "The CSR MUST indicate the exact same set of requested
/// identifiers as the initial newOrder request."
///
/// This check lives **here**, in the handler, and not in a backend.
/// `LocalCa::issue` has always done it, but it is the only backend doing so:
/// `custom` passes the CSR to an operator script which is not told to verify it,
/// and `relay` relays it to an upstream CA which only sees *this* server's
/// account and doesn't know which names the local client has proven.
/// With either of them, an account authorized for one name could get a certificate
/// for any other name. The backend check remains as defense in depth — a backend
/// is a unit others build tests against, and must be safe when asked to sign
/// directly — but this check makes the guarantee independent of the backend.
///
/// Raw comparison, without renormalizing the CSR side: the order identifiers
/// have already been normalized by `OrderService::new_order`, and normalizing here
/// would allow signing a leaf bearing `EXAMPLE.COM.` when the check compared
/// `example.com`. This is also what keeps this check and the one in `LocalCa::issue`
/// in agreement byte for byte.
pub(crate) fn check_csr_matches_order(
    csr: &CertificateSigningRequestParams,
    csr_der: &[u8],
    identifiers: &[Identifier],
) -> Result<(), Problem> {
    // A SAN that is not a DNS name would not be seen by the set comparison
    // below, and would therefore travel uninspected all the way into the
    // signed leaf.
    if let Some(other) = csr
        .params
        .subject_alt_names
        .iter()
        .find(|san| !matches!(san, SanType::DnsName(_)))
    {
        warn!(event = "csr_non_dns_san", outcome = "failure", san = ?other);
        return Err(Problem::bad_csr(
            "CSR carries a subject alternative name that is not a DNS name",
        ));
    }

    let csr_dns: std::collections::BTreeSet<&str> = csr
        .params
        .subject_alt_names
        .iter()
        .filter_map(|san| match san {
            SanType::DnsName(name) => Some(name.as_str()),
            _ => None,
        })
        .collect();
    let want_dns: std::collections::BTreeSet<&str> = identifiers
        .iter()
        .filter(|id| id.typ == "dns")
        .map(|id| id.value.as_str())
        .collect();

    if csr_dns != want_dns {
        warn!(event = "csr_identifier_mismatch", outcome = "failure", csr = ?csr_dns, order = ?want_dns);
        return Err(Problem::bad_csr(
            "CSR does not request the order's identifiers",
        ));
    }

    // `CertificateSigningRequestParams::from_der` copies the entire distinguished name
    // from the CSR into `params`, and `signed_by` writes it into the leaf: a CN
    // naming a domain the order never authorized ends up asserted by
    // a certificate that this CA signed. Verifiers ignore the CN since
    // RFC 2818 was replaced, but "ignored by most" is not "unasserted".
    //
    // Only CNs *shaped like a DNS name* are checked. A CN is also, very
    // ordinarily, a human label — rcgen puts "rcgen self signed
    // cert" by default — and this is exactly why `filter::identifiers`
    // already excludes `cn` from its `allow` rules (`SUBJECT_ONLY_TYPES`) while
    // leaving it reachable by `deny`. Refusing any label would break legitimate
    // clients without protecting anything: what is dangerous is a CN
    // that an old verifier could read as a hostname.
    //
    // `LocalCa::issue` goes further and empties the whole distinguished name; this check
    // is what covers backends which transmit the CSR as-is
    // (`custom`, `relay`).
    //
    // Read from the **DER**, not from `csr.params`: rcgen's distinguished name
    // is a map keyed by type, so of two `CommonName` attributes it keeps only
    // the last, and it exposes a BMPString or UniversalString value as neither
    // text nor bytes. Either shape is a CN this check would never see, while
    // the raw CSR — the thing a `custom` script or an upstream CA is handed —
    // still carries it.
    // A CN with no dot is prose here ("ACME client"), unless the order itself
    // deals in single-label names — which this server allows — in which case a
    // CN shaped like one is a name being asserted like any other.
    let single_label_order = want_dns.iter().any(|name| !name.contains('.'));
    for common_name in subject_common_names(csr_der)? {
        let candidate = normalize_dns_name(&common_name);
        let asserted = looks_like_dns_name(&candidate)
            || (single_label_order
                && well_formed_name(&candidate)
                && !candidate.chars().any(|c| c.is_ascii_whitespace()));
        if asserted && !want_dns.contains(candidate.as_str()) {
            warn!(event = "csr_common_name_mismatch", outcome = "failure", common_name = %candidate);
            return Err(Problem::bad_csr(
                "CSR common name is a domain the order does not cover",
            ));
        }
    }

    Ok(())
}

/// Every `CommonName` of the CSR's subject, in the order the DER carries them.
///
/// Fails closed: a CN whose string encoding this cannot read is refused rather
/// than skipped, since the check above is the only thing standing between a
/// `custom` script or an upstream CA and a CN naming a domain the order never
/// authorized. Reading the DER twice — rcgen has already parsed it — costs one
/// parse of a few hundred bytes on the finalize path.
fn subject_common_names(csr_der: &[u8]) -> Result<Vec<String>, Problem> {
    use x509_parser::prelude::FromDer;

    let (_, request) = x509_parser::certification_request::X509CertificationRequest::from_der(
        csr_der,
    )
    .map_err(|error| {
        warn!(event = "csr_parse_failed", outcome = "failure", error = %error);
        Problem::bad_csr("CSR is unparsable")
    })?;

    request
        .certification_request_info
        .subject
        .iter_common_name()
        .map(|attribute| {
            attribute.as_str().map(str::to_string).map_err(|_| {
                warn!(event = "csr_common_name_unreadable", outcome = "failure");
                Problem::bad_csr("CSR common name is not a readable string")
            })
        })
        .collect()
}

/// Whether a subject `CommonName` reads as a host name rather than a human
/// label — the distinction [`check_csr_matches_order`] uses to decide whether a
/// CN is a name being asserted or just descriptive text.
fn looks_like_dns_name(value: &str) -> bool {
    !value.is_empty()
        && value.contains('.')
        && !value.chars().any(|c| c.is_ascii_whitespace())
        && well_formed_name(value)
}

/// Projects everything a CSR asks to have certified into the shared
/// [`Identifier`] shape, so one policy list covers all of it.
pub(crate) fn csr_identifiers(csr: &CertificateSigningRequestParams) -> Vec<Identifier> {
    let mut identifiers: Vec<Identifier> = csr
        .params
        .subject_alt_names
        .iter()
        .map(|san| match san {
            SanType::DnsName(name) => Identifier::dns(normalize_dns_name(name.as_str())),
            SanType::IpAddress(ip) => Identifier::new("ip", ip.to_canonical().to_string()),
            SanType::Rfc822Name(name) => Identifier::new("email", name.as_str().to_string()),
            SanType::URI(uri) => Identifier::new("uri", uri.as_str().to_string()),
            other => Identifier::new("other", format!("{other:?}")),
        })
        .collect();

    if let Some(common_name) = csr.params.distinguished_name.get(&DnType::CommonName) {
        identifiers.push(match dn_text(common_name) {
            Some(value) => Identifier::new("cn", normalize_dns_name(&value)),
            None => Identifier::new("other", format!("{common_name:?}")),
        });
    }

    identifiers
}

/// Canonicalizes a DNS name for comparison: lowercased, with one trailing dot
/// removed.
#[must_use]
pub fn normalize_dns_name(value: &str) -> String {
    let trimmed = value.strip_suffix('.').unwrap_or(value);
    trimmed.to_ascii_lowercase()
}

/// Whether an identifier names every host under a domain (RFC 8555 §7.1.3).
#[must_use]
pub fn is_wildcard(value: &str) -> bool {
    value.starts_with("*.")
}

/// The longest a DNS name may be, in presentation form (RFC 1035 §2.3.4's
/// 255-octet wire limit less the root label and the length octet of the first).
const MAX_DNS_NAME: usize = 253;

/// The longest a single DNS label may be (RFC 1035 §2.3.4).
const MAX_DNS_LABEL: usize = 63;

/// Whether a `dns` identifier is a shape this server can act on.
///
/// Two rules, and the second is load-bearing beyond mere tidiness.
///
/// The wildcard rule (§7.1.3): a `*` is legal only as a single leading `*.`.
///
/// The syntax rule: what is left has to actually be a DNS name — bounded
/// length, non-empty labels drawn from letters, digits, `-` and `_`, with no
/// label starting or ending in `-`. Without it an identifier may carry `,`,
/// ` `, `@`, `/`, `#` or a control character, and two subsystems read the
/// resulting string as something other than one opaque name:
///
/// - `filter::custom` joins the identifiers with `,` into
///   `ACME_FILTER_IDENTIFIERS`, so a name *containing* a comma reads to an
///   operator script as two names.
/// - `challenge::http_01` builds `http://{name}/.well-known/…` and hands it to
///   `Url::parse`, which resolves `internal.corp/` to the host `internal.corp`
///   and `a@internal.corp` to userinfo plus that host — neither of which the
///   anchored `deny` regex `internal\.corp` matches. With `challenge.bypass`
///   on, where `[filter]` is the only access control there is, that is a
///   deny-list bypass.
///
/// **This covers the *order*'s identifiers and only those.** It is applied by
/// `OrderService::new_order`, so it reaches everything derived from an order — including
/// the `dns` entries [`csr_identifiers`] projects, which
/// [`check_csr_matches_order`] has already required to equal them. It does *not*
/// reach the `cn` and `other` entries that projection adds, which come from the
/// CSR's subject and are arbitrary text by nature; the delimiter half of this
/// rule is restated for them by `filter::custom::delimiter_free`, at the one
/// sink that cares. The `http_01` half needs no such twin — a challenge is
/// validated against an order identifier, never against a CSR subject.
///
/// `_` is deliberately allowed: this server exists to serve internal networks,
/// where underscore labels are ordinary. The point is to reject delimiters and
/// control characters, not to enforce a public CA's hostname policy.
#[must_use]
pub fn well_formed_name(value: &str) -> bool {
    let name = match value.strip_prefix("*.") {
        Some(rest) => rest,
        None => value,
    };
    // Any remaining `*` is a wildcard somewhere it is not allowed.
    !name.contains('*') && is_dns_name(name)
}

/// Whether `name` is a syntactically valid DNS name in presentation form.
fn is_dns_name(name: &str) -> bool {
    if name.is_empty() || name.len() > MAX_DNS_NAME {
        return false;
    }
    // One trailing dot is the root label and is normalized away before this is
    // ever compared; anything else empty is a malformed name.
    let name = name.strip_suffix('.').unwrap_or(name);
    if name.is_empty() {
        return false;
    }
    name.split('.').all(is_dns_label)
}

/// Whether a `dns` identifier is really an IP address in disguise.
///
/// [`well_formed_name`] accepts `10.0.0.5`: every label is digits, and digits
/// are a legal label. But `challenge::http_01` hands the name to `Url::parse`,
/// whose WHATWG host parser reads `10.0.0.5` — and `2130706433`, `0x7f.1`,
/// `127.1` — as an IPv4 address. A name-shaped `filter.identifiers` regex then
/// judges one string while the validator connects to another address, and the
/// certificate would carry an address in a dNSName SAN. RFC 1123 §2.1 already
/// says a host name's last label is never all-numeric.
///
/// The question is answered by the **same** parser the validator uses, so the
/// two can never disagree about what counts as an address. Kept apart from
/// [`well_formed_name`] on purpose: that function also decides whether a CSR
/// common name is a name being asserted, and `10.0.0.5` must stay one there.
#[must_use]
pub fn names_an_ip_address(value: &str) -> bool {
    let name = value.strip_prefix("*.").unwrap_or(value);
    // A name the parser refuses outright (bad punycode, say) is no address:
    // `Url::parse` refuses it the same way, so the validator never connects.
    matches!(
        url::Host::parse(name),
        Ok(url::Host::Ipv4(_) | url::Host::Ipv6(_))
    )
}

/// Whether one dot-separated component is a valid label.
fn is_dns_label(label: &str) -> bool {
    !label.is_empty()
        && label.len() <= MAX_DNS_LABEL
        && !label.starts_with('-')
        && !label.ends_with('-')
        && label
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}

/// Validates an account's `contact` URLs (RFC 8555 §7.3).
///
/// §7.3: "The server SHOULD validate that the contact URLs in the `contact`
/// field are valid and supported by the server. If the server validates contact
/// URLs, it MUST support the `mailto` scheme." This server supports `mailto:`
/// and nothing else — there is no other scheme it could act on — so anything
/// else is `unsupportedContact`.
///
/// Within `mailto:`, §7.3 names two shapes to reject: "Clients MUST NOT provide
/// a `mailto` URL in the `contact` field that contains `hfields` [RFC6068] or
/// more than one `addr-spec` in the `to` component. If a server encounters a
/// `mailto` contact URL that does not meet these criteria, then it SHOULD
/// reject it as invalid." Both are `invalidContact`; the distinction from
/// `unsupportedContact` is deliberate, since only one of the two tells the
/// client to try a different scheme.
///
/// Deliberately *not* a deliverability check: whether mail reaches the address
/// is not something a syntax check can answer, and refusing a valid-but-unusual
/// local-part would lock an operator out of their own account.
pub(crate) fn validate_contacts(contacts: &[String]) -> Result<(), Problem> {
    match contact_shape_error(contacts) {
        None => Ok(()),
        Some(rejection) if rejection.unsupported => {
            Err(Problem::unsupported_contact(rejection.detail))
        }
        Some(rejection) => Err(Problem::invalid_contact(rejection.detail)),
    }
}

/// A contact RFC 8555 §7.3 refuses, and which of its two refusals applies.
pub struct ContactRejection {
    /// `true` maps to `unsupportedContact`, `false` to `invalidContact`. The
    /// distinction is deliberate: only one of the two tells the client to try
    /// a different scheme.
    pub unsupported: bool,
    pub detail: String,
}

/// The shape check behind [`validate_contacts`], returning the reason rather
/// than a [`Problem`].
///
/// Split out because `Problem`'s fields are private, so the web admin — which
/// answers in its own error shape and not in `application/problem+json` —
/// could not read the detail back out of one. Sharing the check rather than
/// writing a second one is what keeps `PATCH /api/accounts/{id}` from
/// accepting a contact `newAccount` would have refused.
pub fn contact_shape_error(contacts: &[String]) -> Option<ContactRejection> {
    /// Most `contact` entries an account may carry.
    ///
    /// `order.max_identifiers`' reasoning on the account side: the list is
    /// unauthenticated client input bounded only by `server.max_body_bytes`,
    /// it is stored as one JSON column and re-rendered on every account read,
    /// and `notify` walks it per message. Well past any real address book —
    /// the point is that there is a ceiling.
    const MAX_CONTACTS: usize = 32;

    fn unsupported(detail: String) -> Option<ContactRejection> {
        Some(ContactRejection {
            unsupported: true,
            detail,
        })
    }
    fn invalid(detail: String) -> Option<ContactRejection> {
        Some(ContactRejection {
            unsupported: false,
            detail,
        })
    }

    if contacts.len() > MAX_CONTACTS {
        warn!(
            event = "contact_list_too_long",
            outcome = "failure",
            contacts_count = contacts.len()
        );
        return invalid(format!(
            "An account may carry at most {MAX_CONTACTS} contacts; this one carries {}",
            contacts.len()
        ));
    }

    for contact in contacts {
        let Some(rest) = contact.strip_prefix("mailto:") else {
            let scheme = contact.split_once(':').map_or("(none)", |(s, _)| s);
            warn!(event = "contact_scheme_unsupported", outcome = "failure", scheme = %scheme);
            return unsupported(format!(
                "Contact {contact} uses an unsupported scheme; only mailto: is supported"
            ));
        };

        // A control character is never part of an address, and this value does
        // not stay inside a JSON document: it is rendered into the `notify`
        // subsystem's templates, which are `.j2` precisely so auto-escaping is
        // *off*. A `mailto:a@b.test\nBcc: …` would otherwise be accepted,
        // stored, and echoed into a message body verbatim.
        if rest.chars().any(|c| c.is_control()) {
            warn!(
                event = "contact_has_control_characters",
                outcome = "failure"
            );
            return invalid(format!(
                "Contact {contact:?} carries a control character, which is not part of an address"
            ));
        }

        // RFC 6068 §2: `hfields` is everything after a `?`.
        if rest.contains('?') {
            warn!(event = "contact_has_hfields", outcome = "failure");
            return invalid(format!(
                "Contact {contact} carries hfields, which RFC 8555 §7.3 forbids"
            ));
        }

        // RFC 6068 §2: multiple addresses in the `to` component are
        // comma-separated.
        if rest.contains(',') {
            warn!(
                event = "contact_has_multiple_addresses",
                outcome = "failure"
            );
            return invalid(format!(
                "Contact {contact} names more than one address; RFC 8555 §7.3 allows one"
            ));
        }

        // A `mailto:` with nothing to mail, or no domain to mail it to, is not
        // an address anyone could reach.
        let Some((local, domain)) = rest.rsplit_once('@') else {
            warn!(event = "contact_not_an_address", outcome = "failure");
            return invalid(format!("Contact {contact} is not an email address"));
        };
        if local.is_empty() || domain.is_empty() || !domain.contains('.') {
            warn!(event = "contact_address_incomplete", outcome = "failure");
            return invalid(format!("Contact {contact} is not a complete email address"));
        }
    }

    None
}

/// The text of a distinguished-name value, when rcgen exposes it as such.
pub(crate) fn dn_text(value: &DnValue) -> Option<String> {
    match value {
        DnValue::Utf8String(text) => Some(text.clone()),
        DnValue::Ia5String(text) => Some(text.as_str().to_string()),
        DnValue::PrintableString(text) => Some(text.as_str().to_string()),
        DnValue::TeletexString(text) => Some(text.as_str().to_string()),
        _ => None,
    }
}

/// Parses an RFC3339 datetime string into epoch seconds.
pub(crate) fn parse_rfc3339(field: &str, value: &str) -> Result<i64, Problem> {
    OffsetDateTime::parse(value, &Rfc3339)
        .map(time::OffsetDateTime::unix_timestamp)
        .map_err(|_| {
            warn!(event = "order_datetime_invalid", outcome = "failure", field = %field, value = %value);
            Problem::malformed("Invalid notBefore/notAfter datetime")
        })
}

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

    #[test]
    fn wildcard_shapes_are_recognised_and_the_rest_refused() {
        assert!(is_wildcard("*.example.com"));
        assert!(well_formed_name("*.example.com"));

        assert!(!is_wildcard("example.com"));
        assert!(well_formed_name("example.com"));

        for bad in [
            "*example.com",
            "*.*.example.com",
            "a.*.example.com",
            "*",
            "*.",
        ] {
            assert!(!well_formed_name(bad), "{bad} must not be well formed");
        }
        assert!(!is_wildcard("*example.com"));
    }

    /// The rule that keeps a `dns` identifier one opaque name.
    ///
    /// Each rejected value below is not merely untidy: `filter::custom` joins
    /// identifiers with `,` and `challenge::http_01` feeds the name to
    /// `Url::parse`, so a delimiter here means one subsystem reads a different
    /// name than the one being certified.
    #[test]
    fn a_dns_identifier_that_is_not_a_dns_name_is_refused() {
        for good in [
            "example.com",
            "a.example.com",
            "EXAMPLE.com",
            "host-1.example.com",
            // Underscore labels are ordinary on the internal networks this
            // server exists to serve, and are deliberately allowed.
            "_acme.example.com",
            "single-label",
            // Syntactically a name; `names_an_ip_address` is what refuses it.
            "1.2.3.4",
            "*.sub.example.com",
        ] {
            assert!(well_formed_name(good), "{good} must be well formed");
        }

        for bad in [
            // The delimiter cases, each with a subsystem that misreads it.
            "a.example.com,b.example.com",
            "internal.corp/",
            "user@internal.corp",
            "example.com#frag",
            "example.com?q=1",
            "example .com",
            "example.com:8080",
            // Control characters: a log-injection and template vector.
            "example.com\n",
            "example.com\r\nX",
            "example\t.com",
            // Malformed label shapes.
            "",
            ".",
            "..",
            "a..b",
            ".example.com",
            "-example.com",
            "example-.com",
            "a.-b.com",
        ] {
            assert!(!well_formed_name(bad), "{bad:?} must not be well formed");
        }
    }

    /// Every spelling the WHATWG host parser reads as an address, and none it
    /// reads as a name.
    #[test]
    fn an_address_spelled_as_a_dns_name_is_recognised() {
        for address in [
            "10.0.0.5",
            "127.0.0.1",
            "169.254.169.254",
            "2130706433",
            "0x7f.1",
            "127.1",
            "0177.0.0.1",
            "1.2.3.4.",
            "*.10.0.0.5",
        ] {
            assert!(names_an_ip_address(address), "{address} is an address");
        }
        for name in [
            "example.com",
            "1.2.3.4.example.com",
            "10-0-0-5.internal",
            "single-label",
            "_acme.example.com",
            "*.example.com",
            "0x7f.example",
        ] {
            assert!(!names_an_ip_address(name), "{name} is a name");
        }
    }

    #[test]
    fn a_dns_identifier_longer_than_the_protocol_allows_is_refused() {
        let label = "a".repeat(MAX_DNS_LABEL);
        assert!(well_formed_name(&format!("{label}.example.com")));

        let too_long_label = "a".repeat(MAX_DNS_LABEL + 1);
        assert!(!well_formed_name(&format!("{too_long_label}.example.com")));

        // 253 characters exactly, then one more.
        let name = std::iter::repeat_n(label.as_str(), 4)
            .collect::<Vec<_>>()
            .join(".");
        assert_eq!(name.len(), 255);
        assert!(!well_formed_name(&name));

        let fits = format!("{}.com", &name[..MAX_DNS_NAME - 4]);
        assert_eq!(fits.len(), MAX_DNS_NAME);
        assert!(well_formed_name(&fits));
    }

    /// A trailing dot is the root label; `normalize_dns_name` strips it, and
    /// this must not reject a name that arrives before that happens.
    #[test]
    fn a_trailing_root_label_is_accepted_but_a_bare_dot_is_not() {
        assert!(well_formed_name("example.com."));
        assert!(!well_formed_name("example.com.."));
        assert!(!well_formed_name("."));
    }

    /// A control character in a contact reaches the `notify` templates, which
    /// are `.j2` precisely so auto-escaping is off.
    #[test]
    fn a_contact_carrying_a_control_character_is_refused() {
        for bad in [
            "mailto:alice@example.com\nBcc: attacker@evil.test",
            "mailto:alice@example.com\r\n",
            "mailto:al\tice@example.com",
            "mailto:alice@example.com\u{0}",
        ] {
            let rejection = contact_shape_error(&[bad.to_string()])
                .unwrap_or_else(|| panic!("{bad:?} must be refused"));
            // `invalidContact`, not `unsupportedContact`: the scheme is right,
            // the address is not.
            assert!(!rejection.unsupported, "{bad:?}");
        }

        assert!(contact_shape_error(&["mailto:alice@example.com".to_string()]).is_none());
    }

    fn csr_with(sans: Vec<SanType>, common_name: Option<&str>) -> Vec<u8> {
        let key_pair = rcgen::KeyPair::generate().unwrap();
        let mut params = rcgen::CertificateParams::default();
        params.subject_alt_names = sans;
        params.distinguished_name = rcgen::DistinguishedName::new();
        if let Some(name) = common_name {
            params.distinguished_name.push(DnType::CommonName, name);
        }
        params.serialize_request(&key_pair).unwrap().der().to_vec()
    }

    fn find<'a>(identifiers: &'a [Identifier], typ: &str) -> Vec<&'a str> {
        identifiers
            .iter()
            .filter(|id| id.typ == typ)
            .map(|id| id.value.as_str())
            .collect()
    }

    #[test]
    fn csr_identifiers_projects_every_san_type() {
        let der = csr_with(
            vec![
                SanType::DnsName("host.example.com".try_into().unwrap()),
                SanType::IpAddress("10.0.0.1".parse().unwrap()),
                SanType::Rfc822Name("someone@example.com".try_into().unwrap()),
                SanType::URI("https://example.com/x".try_into().unwrap()),
            ],
            None,
        );

        let identifiers = csr_identifiers(&parse_csr(&der).unwrap());
        assert_eq!(find(&identifiers, "dns"), vec!["host.example.com"]);
        assert_eq!(find(&identifiers, "ip"), vec!["10.0.0.1"]);
        assert_eq!(find(&identifiers, "email"), vec!["someone@example.com"]);
        assert_eq!(find(&identifiers, "uri"), vec!["https://example.com/x"]);
    }

    #[test]
    fn csr_identifiers_renders_ipv6_addresses() {
        let der = csr_with(
            vec![SanType::IpAddress("2001:db8::1".parse().unwrap())],
            None,
        );
        assert_eq!(
            find(&csr_identifiers(&parse_csr(&der).unwrap()), "ip"),
            vec!["2001:db8::1"]
        );
    }

    #[test]
    fn csr_identifiers_includes_the_common_name() {
        let der = csr_with(
            vec![SanType::DnsName("ok.example.com".try_into().unwrap())],
            Some("secret.internal.example.com"),
        );

        let identifiers = csr_identifiers(&parse_csr(&der).unwrap());
        assert_eq!(find(&identifiers, "dns"), vec!["ok.example.com"]);
        assert_eq!(
            find(&identifiers, "cn"),
            vec!["secret.internal.example.com"]
        );
    }

    #[test]
    fn csr_identifiers_omits_an_absent_common_name() {
        let der = csr_with(
            vec![SanType::DnsName("ok.example.com".try_into().unwrap())],
            None,
        );
        assert!(find(&csr_identifiers(&parse_csr(&der).unwrap()), "cn").is_empty());
    }

    #[test]
    fn parse_csr_rejects_garbage() {
        assert!(parse_csr(&[0xde, 0xad, 0xbe, 0xef]).is_err());
    }

    use acme_proxy_store::testutil::dns_identifiers as dns;

    #[test]
    fn a_csr_matching_the_order_exactly_is_accepted() {
        let der = csr_with(
            vec![
                SanType::DnsName("a.example.com".try_into().unwrap()),
                SanType::DnsName("b.example.com".try_into().unwrap()),
            ],
            None,
        );
        // The order of SANs must not matter: the comparison is on
        // sets, not on lists.
        let identifiers = dns(&["b.example.com", "a.example.com"]);
        assert!(check_csr_matches_order(&parse_csr(&der).unwrap(), &der, &identifiers).is_ok());
    }

    #[test]
    fn a_csr_naming_another_domain_is_refused() {
        let der = csr_with(
            vec![SanType::DnsName("victim.example".try_into().unwrap())],
            None,
        );
        let value =
            check_csr_matches_order(&parse_csr(&der).unwrap(), &der, &dns(&["a.example.com"]))
                .unwrap_err()
                .to_value();
        assert_eq!(value["type"], "urn:ietf:params:acme:error:badCSR");
        assert_eq!(value["status"], 400);
    }

    #[test]
    fn a_csr_naming_more_than_the_order_is_refused() {
        // RFC 8555 §7.4 asks for "the exact same set": a superset is a
        // refusal, not an acceptable intersection.
        let der = csr_with(
            vec![
                SanType::DnsName("a.example.com".try_into().unwrap()),
                SanType::DnsName("extra.example.com".try_into().unwrap()),
            ],
            None,
        );
        assert!(
            check_csr_matches_order(&parse_csr(&der).unwrap(), &der, &dns(&["a.example.com"]))
                .is_err()
        );
    }

    #[test]
    fn a_csr_naming_less_than_the_order_is_refused() {
        let der = csr_with(
            vec![SanType::DnsName("a.example.com".try_into().unwrap())],
            None,
        );
        assert!(
            check_csr_matches_order(
                &parse_csr(&der).unwrap(),
                &der,
                &dns(&["a.example.com", "b.example.com"]),
            )
            .is_err()
        );
    }

    #[test]
    fn a_csr_smuggling_a_non_dns_san_is_refused() {
        // The DNS name is the one that was ordered; it is the IP address
        // smuggled in beside it that nothing else would ever look at.
        let der = csr_with(
            vec![
                SanType::DnsName("a.example.com".try_into().unwrap()),
                SanType::IpAddress("10.0.0.1".parse().unwrap()),
            ],
            None,
        );
        assert!(
            check_csr_matches_order(&parse_csr(&der).unwrap(), &der, &dns(&["a.example.com"]))
                .is_err()
        );
    }

    #[test]
    fn a_csr_whose_common_name_is_not_an_order_identifier_is_refused() {
        let der = csr_with(
            vec![SanType::DnsName("a.example.com".try_into().unwrap())],
            Some("victim.example"),
        );
        assert!(
            check_csr_matches_order(&parse_csr(&der).unwrap(), &der, &dns(&["a.example.com"]))
                .is_err()
        );
    }

    #[test]
    fn a_csr_whose_common_name_is_an_order_identifier_is_accepted() {
        let der = csr_with(
            vec![SanType::DnsName("a.example.com".try_into().unwrap())],
            Some("a.example.com"),
        );
        assert!(
            check_csr_matches_order(&parse_csr(&der).unwrap(), &der, &dns(&["a.example.com"]))
                .is_ok()
        );
    }

    #[test]
    fn a_common_name_that_is_a_human_label_is_left_alone() {
        // rcgen sets this one by default, and `filter::identifiers` excludes
        // `cn` from its `allow` rules for exactly this reason: it is not a name
        // the certificate covers, it is prose.
        for label in ["rcgen self signed cert", "ACME client", "no-dot-label"] {
            let der = csr_with(
                vec![SanType::DnsName("a.example.com".try_into().unwrap())],
                Some(label),
            );
            assert!(
                check_csr_matches_order(&parse_csr(&der).unwrap(), &der, &dns(&["a.example.com"]))
                    .is_ok(),
                "{label} should not be read as a host name"
            );
        }
    }

    /// A CN rcgen's own distinguished name cannot render as text — and which
    /// `dn_text` therefore skipped — still reaches a `custom` script or an
    /// upstream CA in the DER. Unreadable is refused, not waved through.
    #[test]
    fn a_common_name_in_an_unreadable_encoding_is_refused() {
        let key_pair = rcgen::KeyPair::generate().unwrap();
        let mut params = rcgen::CertificateParams::default();
        params.subject_alt_names = vec![SanType::DnsName("a.example.com".try_into().unwrap())];
        params.distinguished_name = rcgen::DistinguishedName::new();
        params.distinguished_name.push(
            DnType::CommonName,
            DnValue::BmpString("victim.example".try_into().unwrap()),
        );
        let der = params.serialize_request(&key_pair).unwrap().der().to_vec();

        let value =
            check_csr_matches_order(&parse_csr(&der).unwrap(), &der, &dns(&["a.example.com"]))
                .unwrap_err()
                .to_value();
        assert_eq!(value["type"], "urn:ietf:params:acme:error:badCSR");
    }

    /// Two `CommonName` attributes in one subject: rcgen's map keeps the last,
    /// so a check reading `csr.params` would inspect the harmless one and let
    /// the other through. Hand-built, because rcgen cannot emit this shape —
    /// and unsigned, because `subject_common_names` is what is under test.
    #[test]
    fn every_common_name_of_the_subject_is_read() {
        use rcgen::PublicKeyData;

        fn tlv(tag: u8, body: &[u8]) -> Vec<u8> {
            let mut out = vec![tag];
            match body.len() {
                len if len < 0x80 => out.push(len as u8),
                len if len < 0x100 => out.extend([0x81, len as u8]),
                len => out.extend([0x82, (len >> 8) as u8, (len & 0xff) as u8]),
            }
            out.extend(body);
            out
        }
        fn common_name(value: &str) -> Vec<u8> {
            // SET { SEQUENCE { OID 2.5.4.3, UTF8String value } }
            let oid = [0x06, 0x03, 0x55, 0x04, 0x03];
            let mut attribute = oid.to_vec();
            attribute.extend(tlv(0x0c, value.as_bytes()));
            tlv(0x31, &tlv(0x30, &attribute))
        }

        let key_pair = rcgen::KeyPair::generate().unwrap();
        let mut subject = common_name("a.example.com");
        subject.extend(common_name("victim.example"));
        let mut info = tlv(0x02, &[0x00]);
        info.extend(tlv(0x30, &subject));
        info.extend(key_pair.subject_public_key_info());
        info.extend(tlv(0xa0, &[]));
        let mut request = tlv(0x30, &info);
        // ecdsa-with-SHA256, and an empty signature: nothing here verifies one.
        request.extend(tlv(
            0x30,
            &[0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02],
        ));
        request.extend(tlv(0x03, &[0x00]));
        let der = tlv(0x30, &request);

        assert_eq!(
            subject_common_names(&der).unwrap(),
            vec!["a.example.com".to_string(), "victim.example".to_string()]
        );
    }

    /// An order for a single-label name makes a single-label CN a name like
    /// any other — on the networks that shape exists for, `fileserver`
    /// resolves.
    #[test]
    fn a_single_label_common_name_is_checked_against_a_single_label_order() {
        let der = csr_with(
            vec![SanType::DnsName("fileserver".try_into().unwrap())],
            Some("mailserver"),
        );
        assert!(
            check_csr_matches_order(&parse_csr(&der).unwrap(), &der, &dns(&["fileserver"]))
                .is_err()
        );

        let der = csr_with(
            vec![SanType::DnsName("fileserver".try_into().unwrap())],
            Some("fileserver"),
        );
        assert!(
            check_csr_matches_order(&parse_csr(&der).unwrap(), &der, &dns(&["fileserver"])).is_ok()
        );
    }

    #[test]
    fn common_names_are_recognised_as_host_names_or_not() {
        assert!(looks_like_dns_name("a.example.com"));
        assert!(looks_like_dns_name("*.example.com"));

        assert!(!looks_like_dns_name(""));
        assert!(!looks_like_dns_name("localhost"));
        assert!(!looks_like_dns_name("rcgen self signed cert"));
        assert!(!looks_like_dns_name("a.*.example.com"));
    }

    #[test]
    fn a_wildcard_csr_matching_its_order_is_accepted() {
        // `new_order` has already refused the wildcard identifier if
        // `dns-01` is not enabled; here set equality is all that pins the CSR
        // to the order.
        let der = csr_with(
            vec![SanType::DnsName("*.example.com".try_into().unwrap())],
            None,
        );
        assert!(
            check_csr_matches_order(&parse_csr(&der).unwrap(), &der, &dns(&["*.example.com"]))
                .is_ok()
        );
    }

    #[test]
    fn a_csr_differing_only_in_case_is_refused() {
        // A raw comparison: re-normalising here would let a leaf be signed
        // carrying the un-normalised form, which was never the form compared.
        let der = csr_with(
            vec![SanType::DnsName("A.Example.COM".try_into().unwrap())],
            None,
        );
        assert!(
            check_csr_matches_order(&parse_csr(&der).unwrap(), &der, &dns(&["a.example.com"]))
                .is_err()
        );
    }

    #[test]
    fn dn_text_reads_the_string_encodings() {
        assert_eq!(
            dn_text(&DnValue::Utf8String("a.example.com".to_string())).as_deref(),
            Some("a.example.com")
        );
        assert_eq!(
            dn_text(&DnValue::Ia5String("b.example.com".try_into().unwrap())).as_deref(),
            Some("b.example.com")
        );
        assert_eq!(
            dn_text(&DnValue::PrintableString(
                "c.example.com".try_into().unwrap()
            ))
            .as_deref(),
            Some("c.example.com")
        );
        assert_eq!(
            dn_text(&DnValue::TeletexString("d.example.com".try_into().unwrap())).as_deref(),
            Some("d.example.com")
        );
    }

    #[test]
    fn an_unreadable_common_name_becomes_an_other_identifier() {
        let value = DnValue::BmpString("e.example.com".try_into().unwrap());
        assert!(dn_text(&value).is_none());
    }
}