acme-proxy 0.6.0

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

use std::sync::Arc;
use std::sync::atomic::Ordering;

use axum::Router;
use axum::body::Body;
use axum::http::{Request, StatusCode};
use axum::response::Response;
use serde_json::{Value, json};
use tower::ServiceExt;

mod common;
use common::{
    BlockingValidator, EcSigner, RecordingValidator, StubValidator, TestSigner, body_json,
    bypassing_challenges, challenges_with, fetch_nonce, make_csr, p, test_app,
    test_app_with_challenges,
};

use acme_proxy_core::config::Config;
use acme_proxy_core::jws::signature::jwk_thumbprint;

const NEW_ACCOUNT_URL: &str = "http://localhost:3000/profile/default/newAccount";
const NEW_ORDER_URL: &str = "http://localhost:3000/profile/default/newOrder";

async fn post(app: &Router, path: &str, body: String) -> Response {
    app.clone()
        .oneshot(
            Request::post(path)
                .header("content-type", "application/jose+json")
                .body(Body::from(body))
                .unwrap(),
        )
        .await
        .unwrap()
}

/// Registers an account and returns its account URL (used as `kid`).
async fn register(app: &Router, signer: &impl TestSigner) -> String {
    let nonce = fetch_nonce(app).await;
    let res = post(
        app,
        &p("/newAccount"),
        signer.sign(
            NEW_ACCOUNT_URL,
            &nonce,
            &json!({ "termsOfServiceAgreed": true }),
        ),
    )
    .await;
    assert_eq!(res.status(), StatusCode::CREATED);
    res.headers()
        .get("location")
        .and_then(|v| v.to_str().ok())
        .expect("newAccount must set a Location header")
        .to_string()
}

/// Creates an order for `names`, returning the response as-is so rejection
/// tests can inspect it.
async fn new_order(
    app: &Router,
    signer: &impl TestSigner,
    account_url: &str,
    names: &[&str],
) -> Response {
    let identifiers: Vec<Value> = names
        .iter()
        .map(|name| json!({ "type": "dns", "value": name }))
        .collect();
    let nonce = fetch_nonce(app).await;
    post(
        app,
        &p("/newOrder"),
        signer.sign_kid(
            account_url,
            NEW_ORDER_URL,
            &nonce,
            &json!({ "identifiers": identifiers }),
        ),
    )
    .await
}

/// Signed POST-as-GET of any resource, returning its JSON.
async fn read(app: &Router, signer: &impl TestSigner, account_url: &str, url: &str) -> Value {
    let nonce = fetch_nonce(app).await;
    let path = url
        .strip_prefix(common::HOST)
        .expect("URL must be under the base");
    let res = post(app, path, signer.sign_kid_empty(account_url, url, &nonce)).await;
    assert_eq!(res.status(), StatusCode::OK, "POST-as-GET of {url}");
    body_json(res).await
}

/// Triggers a challenge, returning the raw response so a test can read the
/// `Link` header as well as the body.
async fn trigger(app: &Router, signer: &impl TestSigner, account_url: &str, url: &str) -> Response {
    let nonce = fetch_nonce(app).await;
    let path = url.strip_prefix(common::HOST).unwrap();
    post(
        app,
        path,
        signer.sign_kid(account_url, url, &nonce, &json!({})),
    )
    .await
}

/// Triggers a challenge and waits for the server to decide it, returning the
/// challenge object.
///
/// Validation is queued work: the trigger claims the challenge and answers it
/// `processing` (§7.1.6), and the job runner reaches the verdict moments later.
/// A real client polls exactly this way, against the `Retry-After` the trigger
/// carries (§8.2). Bounded, so a challenge that never settles fails the test
/// with a diagnosis instead of hanging it.
async fn settle(app: &Router, signer: &impl TestSigner, account_url: &str, url: &str) -> Value {
    let res = trigger(app, signer, account_url, url).await;
    assert_eq!(res.status(), StatusCode::OK, "trigger of {url}");
    await_decided(app, signer, account_url, url).await
}

/// Polls a challenge until it is no longer `processing`.
///
/// By re-POSTing `{}`, not POST-as-GET: §7.5.1 defines the challenge resource's
/// POST body as the trigger and this server accepts no empty payload there, and
/// the same section makes a retry explicitly *not* a state change — the claim
/// simply fails and the object comes back as it stands. That is what a client
/// polling a `processing` challenge against its `Retry-After` actually sends.
async fn await_decided(
    app: &Router,
    signer: &impl TestSigner,
    account_url: &str,
    url: &str,
) -> Value {
    for _ in 0..600 {
        let challenge = body_json(trigger(app, signer, account_url, url).await).await;
        if challenge["status"] != "processing" {
            return challenge;
        }
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
    }
    panic!("`{url}` never left `processing`");
}

/// The challenge of a given type on an authorization, by URL.
fn challenge_url_of_type(authz: &Value, typ: &str) -> String {
    authz["challenges"]
        .as_array()
        .expect("challenges must be an array")
        .iter()
        .find(|challenge| challenge["type"] == typ)
        .unwrap_or_else(|| panic!("no {typ} challenge in {authz}"))["url"]
        .as_str()
        .expect("a challenge must have a URL")
        .to_string()
}

// ---------------------------------------------------------------------------
// What an authorization offers
// ---------------------------------------------------------------------------

/// The default configuration must still produce exactly what it did before the
/// subsystem existed: one `http-01` challenge, accepted without a network check.
#[tokio::test]
async fn the_default_configuration_offers_one_bypassing_http_01_challenge() {
    let app = test_app().await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    let order = body_json(new_order(&app, &signer, &account_url, &["example.com"]).await).await;
    let authz = read(
        &app,
        &signer,
        &account_url,
        order["authorizations"][0].as_str().unwrap(),
    )
    .await;

    assert_eq!(authz["challenges"].as_array().unwrap().len(), 1);
    assert_eq!(authz["challenges"][0]["type"], "http-01");
    assert!(authz.get("wildcard").is_none());

    let challenge_url = challenge_url_of_type(&authz, "http-01");
    let challenge = settle(&app, &signer, &account_url, &challenge_url).await;
    assert_eq!(challenge["status"], "valid");
}

/// Every enabled type is offered, each with its own token — a key authorization
/// is derived per challenge, so sharing one would be wrong.
#[tokio::test]
async fn every_enabled_type_is_offered_with_its_own_token() {
    let (app, _db) = test_app_with_challenges(
        Config::default(),
        bypassing_challenges(&["http-01", "dns-01", "tls-alpn-01"]),
    )
    .await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    let order = body_json(new_order(&app, &signer, &account_url, &["example.com"]).await).await;
    let authz = read(
        &app,
        &signer,
        &account_url,
        order["authorizations"][0].as_str().unwrap(),
    )
    .await;

    let challenges = authz["challenges"].as_array().unwrap();
    assert_eq!(challenges.len(), 3);

    let types: Vec<_> = challenges
        .iter()
        .map(|c| c["type"].as_str().unwrap())
        .collect();
    assert_eq!(types, ["http-01", "dns-01", "tls-alpn-01"]);

    let tokens: std::collections::BTreeSet<_> = challenges
        .iter()
        .map(|c| c["token"].as_str().unwrap())
        .collect();
    assert_eq!(tokens.len(), 3, "each challenge needs its own token");
    let urls: std::collections::BTreeSet<_> = challenges
        .iter()
        .map(|c| c["url"].as_str().unwrap())
        .collect();
    assert_eq!(urls.len(), 3);
}

// ---------------------------------------------------------------------------
// Validation, success and failure
// ---------------------------------------------------------------------------

/// The whole flow with a validator that passes: challenge → authorization →
/// order `ready` → a certificate.
#[tokio::test]
async fn a_passing_validator_carries_the_order_through_to_a_certificate() {
    let validator = StubValidator::passing("http-01");
    let calls = validator.counter();
    let (app, _db) = test_app_with_challenges(
        Config::default(),
        challenges_with(&["http-01"], vec![Arc::new(validator)]),
    )
    .await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    let res = new_order(&app, &signer, &account_url, &["example.com"]).await;
    let order_url = res
        .headers()
        .get("location")
        .and_then(|v| v.to_str().ok())
        .unwrap()
        .to_string();
    let order = body_json(res).await;
    let authz_url = order["authorizations"][0].as_str().unwrap().to_string();

    let authz = read(&app, &signer, &account_url, &authz_url).await;
    let challenge_url = challenge_url_of_type(&authz, "http-01");

    let challenge = settle(&app, &signer, &account_url, &challenge_url).await;
    assert_eq!(challenge["status"], "valid");
    assert_eq!(calls.load(Ordering::SeqCst), 1);

    assert_eq!(
        read(&app, &signer, &account_url, &authz_url).await["status"],
        "valid"
    );
    assert_eq!(
        read(&app, &signer, &account_url, &order_url).await["status"],
        "ready"
    );

    // And it finalizes.
    let finalize_url = format!("{order_url}/finalize");
    let nonce = fetch_nonce(&app).await;
    let res = post(
        &app,
        finalize_url.strip_prefix(common::HOST).unwrap(),
        signer.sign_kid(
            &account_url,
            &finalize_url,
            &nonce,
            &json!({ "csr": make_csr("example.com") }),
        ),
    )
    .await;
    assert_eq!(res.status(), StatusCode::OK);
    assert_eq!(body_json(res).await["status"], "processing");
    assert_eq!(
        common::acme::await_order(&app, &signer, &account_url, &order_url).await["status"],
        "valid"
    );
}

/// RFC 8555 §7.5.1: "The server SHOULD provide information about its retry
/// state to the client via the `Retry-After` HTTP header field" — the same
/// pacing courtesy `order_response` extends to a `processing` order.
///
/// Only while `pending`: any other status is decided, and telling a client to
/// come back for an answer it already has would be noise.
#[tokio::test]
async fn a_pending_authorization_and_challenge_carry_a_retry_after() {
    let app = test_app().await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    let res = new_order(&app, &signer, &account_url, &["example.com"]).await;
    let order = body_json(res).await;
    let authz_url = order["authorizations"][0].as_str().unwrap().to_string();

    // The authorization, while pending.
    let nonce = fetch_nonce(&app).await;
    let path = authz_url.strip_prefix(common::HOST).unwrap();
    let res = post(
        &app,
        path,
        signer.sign_kid_empty(&account_url, &authz_url, &nonce),
    )
    .await;
    assert_eq!(res.status(), StatusCode::OK);
    assert_eq!(
        res.headers()
            .get("retry-after")
            .and_then(|v| v.to_str().ok()),
        Some("5"),
        "a pending authorization should pace the client"
    );

    let authz = body_json(res).await;
    assert_eq!(authz["status"], "pending");
    let challenge_url = challenge_url_of_type(&authz, "http-01");

    // Triggering it starts the work rather than doing it, so the answer that
    // comes back is `processing` — and §8.2 makes the `Retry-After` beside it a
    // MUST, since the client now has something to come back for.
    let res = trigger(&app, &signer, &account_url, &challenge_url).await;
    assert_eq!(res.status(), StatusCode::OK);
    assert_eq!(
        res.headers()
            .get("retry-after")
            .and_then(|v| v.to_str().ok()),
        Some("5"),
        "a processing challenge must pace the client (RFC 8555 §8.2)"
    );
    assert_eq!(body_json(res).await["status"], "processing");

    // Once the runner has decided it, there is nothing left to wait for.
    assert_eq!(
        await_decided(&app, &signer, &account_url, &challenge_url).await["status"],
        "valid"
    );

    let nonce = fetch_nonce(&app).await;
    let res = post(
        &app,
        path,
        signer.sign_kid_empty(&account_url, &authz_url, &nonce),
    )
    .await;
    assert!(
        res.headers().get("retry-after").is_none(),
        "a decided authorization has nothing to come back for"
    );
    assert_eq!(body_json(res).await["status"], "valid");
}

/// A failure is reported **in the challenge object**, not as an HTTP error:
/// RFC 8555 §7.5.1 makes the object the response, and certbot's `acme` library
/// reads `error` from it. A 4xx would look like a transport failure instead.
#[tokio::test]
async fn a_failing_validator_reports_the_reason_in_the_challenge_object() {
    let validator = StubValidator::failing("http-01", "served the wrong body");
    let (app, _db) = test_app_with_challenges(
        Config::default(),
        challenges_with(&["http-01"], vec![Arc::new(validator)]),
    )
    .await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    let res = new_order(&app, &signer, &account_url, &["example.com"]).await;
    let order_url = res
        .headers()
        .get("location")
        .and_then(|v| v.to_str().ok())
        .unwrap()
        .to_string();
    let order = body_json(res).await;
    let authz_url = order["authorizations"][0].as_str().unwrap().to_string();

    let authz = read(&app, &signer, &account_url, &authz_url).await;
    let challenge_url = challenge_url_of_type(&authz, "http-01");

    let res = trigger(&app, &signer, &account_url, &challenge_url).await;
    assert_eq!(
        res.status(),
        StatusCode::OK,
        "a failed challenge is still a 200"
    );
    // The `up` link must survive the failure path too, or the client cannot
    // find the authorization to poll — and it must survive *alongside* the
    // `index` link RFC 8555 §7.1 puts on every resource, which is why that
    // middleware appends rather than sets. Reading only the first `Link` header
    // would not catch an overwrite, so collect them all.
    let links: Vec<&str> = res
        .headers()
        .get_all("link")
        .iter()
        .filter_map(|v| v.to_str().ok())
        .collect();
    assert!(
        links.iter().any(|link| link.contains("rel=\"up\"")),
        "the up link must survive: {links:?}"
    );
    assert!(
        links.iter().any(|link| link.contains("rel=\"index\"")),
        "the index link must be present too: {links:?}"
    );

    // The trigger only starts the work; the refusal lands once the runner has
    // performed the check. It is still reported *in the challenge object* —
    // never as an HTTP error — which is what this test is really about.
    let challenge = await_decided(&app, &signer, &account_url, &challenge_url).await;
    assert_eq!(challenge["status"], "invalid");
    assert_eq!(
        challenge["error"]["type"],
        "urn:ietf:params:acme:error:incorrectResponse"
    );
    assert_eq!(challenge["error"]["detail"], "served the wrong body");
    assert!(challenge.get("validated").is_none());

    // The failure propagates: authorization and order are both terminal.
    assert_eq!(
        read(&app, &signer, &account_url, &authz_url).await["status"],
        "invalid"
    );
    let order = read(&app, &signer, &account_url, &order_url).await;
    assert_eq!(order["status"], "invalid");
    assert_eq!(order["error"], challenge["error"]);

    // And an invalid order cannot be finalized.
    let finalize_url = format!("{order_url}/finalize");
    let nonce = fetch_nonce(&app).await;
    let res = post(
        &app,
        finalize_url.strip_prefix(common::HOST).unwrap(),
        signer.sign_kid(
            &account_url,
            &finalize_url,
            &nonce,
            &json!({ "csr": make_csr("example.com") }),
        ),
    )
    .await;
    assert_eq!(res.status(), StatusCode::FORBIDDEN);
    assert_eq!(
        body_json(res).await["type"],
        "urn:ietf:params:acme:error:orderNotReady"
    );
}

/// `invalid` is terminal (RFC 8555 §7.1.6): re-triggering returns the stored
/// object rather than trying again.
#[tokio::test]
async fn re_triggering_a_failed_challenge_does_not_revalidate() {
    let validator = StubValidator::failing("http-01", "still wrong");
    let calls = validator.counter();
    let (app, _db) = test_app_with_challenges(
        Config::default(),
        challenges_with(&["http-01"], vec![Arc::new(validator)]),
    )
    .await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    let order = body_json(new_order(&app, &signer, &account_url, &["example.com"]).await).await;
    let authz = read(
        &app,
        &signer,
        &account_url,
        order["authorizations"][0].as_str().unwrap(),
    )
    .await;
    let challenge_url = challenge_url_of_type(&authz, "http-01");

    // Settled first: what this test is about is a challenge that is *decided*,
    // and the trigger only starts the work. Re-triggering before the verdict
    // lands exercises the claim instead, and which of the two a bare pair of
    // triggers reaches is a matter of how loaded the machine is.
    let response = trigger(&app, &signer, &account_url, &challenge_url).await;
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(body_json(response).await["status"], "processing");

    let settled = await_decided(&app, &signer, &account_url, &challenge_url).await;
    assert_eq!(settled["status"], "invalid");

    let again = body_json(trigger(&app, &signer, &account_url, &challenge_url).await).await;
    assert_eq!(again, settled, "the stored object, unchanged");
    assert_eq!(
        calls.load(Ordering::SeqCst),
        1,
        "a decided challenge is not re-run"
    );
}

/// A client that triggers a second challenge type after the first succeeded must
/// not be able to knock the authorization back to `invalid`.
#[tokio::test]
async fn a_sibling_challenge_is_not_run_once_the_authorization_is_valid() {
    let passing = StubValidator::passing("http-01");
    let failing = StubValidator::failing("dns-01", "no TXT record");
    let dns_calls = failing.counter();

    let (app, _db) = test_app_with_challenges(
        Config::default(),
        challenges_with(
            &["http-01", "dns-01"],
            vec![Arc::new(passing), Arc::new(failing)],
        ),
    )
    .await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    let order = body_json(new_order(&app, &signer, &account_url, &["example.com"]).await).await;
    let authz_url = order["authorizations"][0].as_str().unwrap().to_string();
    let authz = read(&app, &signer, &account_url, &authz_url).await;

    // Satisfy http-01 first.
    let http_url = challenge_url_of_type(&authz, "http-01");
    assert_eq!(
        settle(&app, &signer, &account_url, &http_url).await["status"],
        "valid"
    );

    // Then trigger the dns-01 sibling, whose validator would fail.
    let dns_url = challenge_url_of_type(&authz, "dns-01");
    let challenge = body_json(trigger(&app, &signer, &account_url, &dns_url).await).await;
    assert_eq!(challenge["status"], "pending", "the sibling is left alone");
    assert_eq!(dns_calls.load(Ordering::SeqCst), 0);

    // The authorization is still proved.
    assert_eq!(
        read(&app, &signer, &account_url, &authz_url).await["status"],
        "valid"
    );
}

/// Every authorization must be satisfied before the order is `ready` — one
/// challenge per authorization, not one per order.
#[tokio::test]
async fn an_order_is_ready_only_once_every_authorization_is_valid() {
    let (app, _db) =
        test_app_with_challenges(Config::default(), bypassing_challenges(&["http-01"])).await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    let res = new_order(
        &app,
        &signer,
        &account_url,
        &["a.example.com", "b.example.com"],
    )
    .await;
    let order_url = res
        .headers()
        .get("location")
        .and_then(|v| v.to_str().ok())
        .unwrap()
        .to_string();
    let order = body_json(res).await;
    let authz_urls: Vec<String> = order["authorizations"]
        .as_array()
        .unwrap()
        .iter()
        .map(|u| u.as_str().unwrap().to_string())
        .collect();
    assert_eq!(authz_urls.len(), 2);

    let first = read(&app, &signer, &account_url, &authz_urls[0]).await;
    settle(
        &app,
        &signer,
        &account_url,
        &challenge_url_of_type(&first, "http-01"),
    )
    .await;
    assert_eq!(
        read(&app, &signer, &account_url, &order_url).await["status"],
        "pending",
        "one authorization out of two is not enough"
    );

    let second = read(&app, &signer, &account_url, &authz_urls[1]).await;
    settle(
        &app,
        &signer,
        &account_url,
        &challenge_url_of_type(&second, "http-01"),
    )
    .await;
    assert_eq!(
        read(&app, &signer, &account_url, &order_url).await["status"],
        "ready"
    );
}

// ---------------------------------------------------------------------------
// The key authorization
// ---------------------------------------------------------------------------

/// The server must derive the key authorization the way a client does, from the
/// account's own JWK. This computes it independently from the signer's JWK and
/// compares — the in-CI stand-in for running a real ACME client.
#[tokio::test]
async fn the_key_authorization_matches_what_a_client_would_compute() {
    let validator = RecordingValidator::new("http-01");
    let seen = validator.seen();
    let (app, db) = test_app_with_challenges(
        Config::default(),
        challenges_with(&["http-01"], vec![Arc::new(validator)]),
    )
    .await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    let order = body_json(new_order(&app, &signer, &account_url, &["example.com"]).await).await;
    let authz = read(
        &app,
        &signer,
        &account_url,
        order["authorizations"][0].as_str().unwrap(),
    )
    .await;
    let token = authz["challenges"][0]["token"]
        .as_str()
        .unwrap()
        .to_string();

    settle(
        &app,
        &signer,
        &account_url,
        &challenge_url_of_type(&authz, "http-01"),
    )
    .await;

    // The thumbprint of the key that registered the account.
    let account_id = account_url.rsplit('/').next().unwrap();
    let account = acme_proxy_store::account::Account::find_by_id(common::PROFILE, account_id, &db)
        .await
        .unwrap()
        .expect("the account must exist");
    let expected = format!("{token}.{}", jwk_thumbprint(&account.pubkey).unwrap());

    let recorded = seen.lock().unwrap();
    assert_eq!(recorded.len(), 1);
    let parts: Vec<&str> = recorded[0].split('|').collect();
    assert_eq!(parts[0], "example.com");
    assert_eq!(parts[1], "false");
    assert_eq!(parts[2], token);
    assert_eq!(parts[3], expected);
}

// ---------------------------------------------------------------------------
// Wildcards
// ---------------------------------------------------------------------------

/// A wildcard order becomes a `dns-01`-only authorization on the **base** name,
/// flagged with `wildcard` (RFC 8555 §7.1.4).
#[tokio::test]
async fn a_wildcard_order_offers_dns_01_on_the_base_name() {
    let validator = RecordingValidator::new("dns-01");
    let seen = validator.seen();
    let (app, _db) = test_app_with_challenges(
        Config::default(),
        challenges_with(&["http-01", "dns-01"], vec![Arc::new(validator)]),
    )
    .await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    let res = new_order(&app, &signer, &account_url, &["*.example.com"]).await;
    assert_eq!(res.status(), StatusCode::CREATED);
    let order_url = res
        .headers()
        .get("location")
        .and_then(|v| v.to_str().ok())
        .unwrap()
        .to_string();
    let order = body_json(res).await;
    // The order keeps the wildcard form: it is what the certificate is for.
    assert_eq!(order["identifiers"][0]["value"], "*.example.com");

    let authz_url = order["authorizations"][0].as_str().unwrap().to_string();
    let authz = read(&app, &signer, &account_url, &authz_url).await;

    // ...while the authorization shows the base name plus the flag.
    assert_eq!(
        authz["identifier"],
        json!({ "type": "dns", "value": "example.com" })
    );
    assert_eq!(authz["wildcard"], true);
    // http-01 is enabled but cannot prove a wildcard, so it is not offered.
    let challenges = authz["challenges"].as_array().unwrap();
    assert_eq!(challenges.len(), 1);
    assert_eq!(challenges[0]["type"], "dns-01");

    settle(
        &app,
        &signer,
        &account_url,
        &challenge_url_of_type(&authz, "dns-01"),
    )
    .await;
    assert_eq!(
        read(&app, &signer, &account_url, &order_url).await["status"],
        "ready"
    );

    // The validator was asked about the base name, with the wildcard flag set.
    let recorded = seen.lock().unwrap();
    let parts: Vec<&str> = recorded[0].split('|').collect();
    assert_eq!(parts[0], "example.com");
    assert_eq!(parts[1], "true");
}

/// The canonical wildcard order: the bare name and the wildcard together. Two
/// authorizations, which must not collide on `UNIQUE(order_id, identifier)`.
#[tokio::test]
async fn a_name_and_its_wildcard_get_separate_authorizations() {
    let (app, _db) = test_app_with_challenges(
        Config::default(),
        bypassing_challenges(&["http-01", "dns-01"]),
    )
    .await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    let res = new_order(
        &app,
        &signer,
        &account_url,
        &["example.com", "*.example.com"],
    )
    .await;
    assert_eq!(
        res.status(),
        StatusCode::CREATED,
        "the two must not collide"
    );
    let order_url = res
        .headers()
        .get("location")
        .and_then(|v| v.to_str().ok())
        .unwrap()
        .to_string();
    let order = body_json(res).await;

    let authz_urls: Vec<String> = order["authorizations"]
        .as_array()
        .unwrap()
        .iter()
        .map(|u| u.as_str().unwrap().to_string())
        .collect();
    assert_eq!(authz_urls.len(), 2);

    let plain = read(&app, &signer, &account_url, &authz_urls[0]).await;
    let wildcard = read(&app, &signer, &account_url, &authz_urls[1]).await;

    // Both name `example.com`; only one is flagged, and only one offers http-01.
    assert_eq!(plain["identifier"]["value"], "example.com");
    assert!(plain.get("wildcard").is_none());
    assert_eq!(plain["challenges"].as_array().unwrap().len(), 2);

    assert_eq!(wildcard["identifier"]["value"], "example.com");
    assert_eq!(wildcard["wildcard"], true);
    assert_eq!(wildcard["challenges"].as_array().unwrap().len(), 1);

    // Both must be satisfied before the order is ready.
    settle(
        &app,
        &signer,
        &account_url,
        &challenge_url_of_type(&plain, "http-01"),
    )
    .await;
    assert_eq!(
        read(&app, &signer, &account_url, &order_url).await["status"],
        "pending"
    );
    settle(
        &app,
        &signer,
        &account_url,
        &challenge_url_of_type(&wildcard, "dns-01"),
    )
    .await;
    assert_eq!(
        read(&app, &signer, &account_url, &order_url).await["status"],
        "ready"
    );
}

/// And the certificate really carries the wildcard SAN.
#[tokio::test]
async fn a_wildcard_order_issues_a_wildcard_certificate() {
    let (app, _db) =
        test_app_with_challenges(Config::default(), bypassing_challenges(&["dns-01"])).await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    let res = new_order(&app, &signer, &account_url, &["*.example.com"]).await;
    let order_url = res
        .headers()
        .get("location")
        .and_then(|v| v.to_str().ok())
        .unwrap()
        .to_string();
    let order = body_json(res).await;
    let authz = read(
        &app,
        &signer,
        &account_url,
        order["authorizations"][0].as_str().unwrap(),
    )
    .await;
    settle(
        &app,
        &signer,
        &account_url,
        &challenge_url_of_type(&authz, "dns-01"),
    )
    .await;

    let finalize_url = format!("{order_url}/finalize");
    let nonce = fetch_nonce(&app).await;
    let res = post(
        &app,
        finalize_url.strip_prefix(common::HOST).unwrap(),
        signer.sign_kid(
            &account_url,
            &finalize_url,
            &nonce,
            &json!({ "csr": make_csr("*.example.com") }),
        ),
    )
    .await;
    assert_eq!(res.status(), StatusCode::OK);
    let cert_url =
        common::acme::await_order(&app, &signer, &account_url, &order_url).await["certificate"]
            .as_str()
            .expect("an issued order has a certificate URL")
            .to_string();

    let nonce = fetch_nonce(&app).await;
    let res = post(
        &app,
        cert_url.strip_prefix(common::HOST).unwrap(),
        signer.sign_kid_empty(&account_url, &cert_url, &nonce),
    )
    .await;
    assert_eq!(res.status(), StatusCode::OK);

    let pem = String::from_utf8(
        http_body_util::BodyExt::collect(res.into_body())
            .await
            .unwrap()
            .to_bytes()
            .to_vec(),
    )
    .unwrap();
    let leaf = pem
        .split("-----END CERTIFICATE-----")
        .next()
        .and_then(|block| block.split("-----BEGIN CERTIFICATE-----").nth(1))
        .map(|body| {
            use base64::prelude::*;
            BASE64_STANDARD
                .decode(body.replace(['\n', '\r'], ""))
                .unwrap()
        })
        .expect("a leaf certificate");

    let (_, parsed) = x509_parser::parse_x509_certificate(&leaf).unwrap();
    let sans = &parsed
        .subject_alternative_name()
        .unwrap()
        .unwrap()
        .value
        .general_names;
    assert!(
        matches!(&sans[0], x509_parser::extensions::GeneralName::DNSName(name)
            if *name == "*.example.com"),
        "{sans:?}"
    );
}

/// With `dns-01` off there is no challenge that could prove a wildcard, so the
/// order is refused rather than made unsatisfiable.
#[tokio::test]
async fn a_wildcard_is_refused_when_dns_01_is_not_enabled() {
    let (app, _db) = test_app_with_challenges(
        Config::default(),
        bypassing_challenges(&["http-01", "tls-alpn-01"]),
    )
    .await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    let res = new_order(&app, &signer, &account_url, &["*.example.com"]).await;
    assert_eq!(res.status(), StatusCode::FORBIDDEN);
    let problem = body_json(res).await;
    assert_eq!(
        problem["type"],
        "urn:ietf:params:acme:error:rejectedIdentifier"
    );
    assert!(problem["detail"].as_str().unwrap().contains("dns-01"));
}

/// A `*` that is not the leading `*.` is malformed, not refused by policy.
#[tokio::test]
async fn a_malformed_wildcard_is_a_400_even_with_dns_01_enabled() {
    let (app, _db) =
        test_app_with_challenges(Config::default(), bypassing_challenges(&["dns-01"])).await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    for value in ["*example.com", "*.*.example.com", "a.*.example.com", "*"] {
        let res = new_order(&app, &signer, &account_url, &[value]).await;
        assert_eq!(res.status(), StatusCode::BAD_REQUEST, "{value}");
        assert_eq!(
            body_json(res).await["type"],
            "urn:ietf:params:acme:error:malformed",
            "{value}"
        );
    }
}

/// Two triggers for one `pending` challenge, overlapping. Validation runs once.
///
/// `re_triggering_a_failed_challenge_does_not_revalidate` covers the sequential
/// case, where the second request sees a challenge that is already `valid` or
/// `invalid` and does nothing. This is the window that check cannot close: both
/// requests read the same `pending` row before either has written a result, so
/// both conclude there is work to do.
///
/// What that costs is not just a duplicated notification. The validator reaches
/// out to an address **the client chose**, so N simultaneous triggers are N
/// probes to that host from this server — a reflector bounded only by
/// `server.max_concurrent_requests`, with no filter configured by default. The
/// fix is the same compare-and-swap `Order::claim_for_finalize` uses: the
/// `pending → processing` transition is the claim, and only the winner probes.
#[tokio::test]
async fn two_overlapping_triggers_validate_once() {
    let validator = BlockingValidator::gating_the_first("http-01");
    let (calls, gate, entered) = validator.handles();
    let (app, _db) = test_app_with_challenges(
        Config::default(),
        challenges_with(&["http-01"], vec![Arc::new(validator)]),
    )
    .await;

    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;
    let order = body_json(new_order(&app, &signer, &account_url, &["example.com"]).await).await;
    let authz = read(
        &app,
        &signer,
        &account_url,
        order["authorizations"][0].as_str().unwrap(),
    )
    .await;
    let challenge_url = challenge_url_of_type(&authz, "http-01");

    // Both bodies up front: `EcSigner` is not `Clone`, and signing needs a
    // nonce, which needs a request of its own.
    let path = challenge_url
        .strip_prefix(common::HOST)
        .unwrap()
        .to_string();
    let nonce_a = fetch_nonce(&app).await;
    let body_a = signer.sign_kid(&account_url, &challenge_url, &nonce_a, &json!({}));
    let nonce_b = fetch_nonce(&app).await;
    let body_b = signer.sign_kid(&account_url, &challenge_url, &nonce_b, &json!({}));

    let first = tokio::spawn({
        let (app, path) = (app.clone(), path.clone());
        async move { post(&app, &path, body_a).await }
    });
    // Wait for the first to be genuinely inside the validator — the claim is
    // taken and the row is `processing` — rather than for a duration.
    let _ = entered.acquire().await.unwrap();

    // The second arrives squarely inside that window. It must be answered from
    // the row rather than starting a probe of its own.
    let second = post(&app, &path, body_b).await;
    assert_eq!(second.status(), StatusCode::OK);

    gate.add_permits(1);
    assert_eq!(first.await.unwrap().status(), StatusCode::OK);

    assert_eq!(
        calls.load(Ordering::SeqCst),
        1,
        "an overlapping trigger must not start a second validation"
    );
}

/// `challenge.max_in_flight_per_account` is what keeps one account from
/// filling the runner with probes of addresses it named while signings and
/// revocations wait behind them. Over the cap the trigger is `429 rateLimited`
/// with a `Retry-After`, and the challenge is left `pending`, so the client
/// asks again rather than losing the order.
#[tokio::test]
async fn a_trigger_over_the_accounts_validation_cap_is_rate_limited() {
    let validator = BlockingValidator::gating_the_first("http-01");
    let (_calls, gate, entered) = validator.handles();
    let (app, _db) = test_app_with_challenges(
        Config::default(),
        Arc::new(
            Arc::try_unwrap(challenges_with(&["http-01"], vec![Arc::new(validator)]))
                .expect("the registry is not shared yet")
                .with_max_in_flight_per_account(1),
        ),
    )
    .await;

    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;
    let mut challenge_paths = Vec::new();
    for name in ["a.example.com", "b.example.com"] {
        let order = body_json(new_order(&app, &signer, &account_url, &[name]).await).await;
        let authz = read(
            &app,
            &signer,
            &account_url,
            order["authorizations"][0].as_str().unwrap(),
        )
        .await;
        challenge_paths.push(challenge_url_of_type(&authz, "http-01"));
    }

    let first_url = challenge_paths[0].clone();
    let second_url = challenge_paths[1].clone();
    let nonce = fetch_nonce(&app).await;
    let body = signer.sign_kid(&account_url, &first_url, &nonce, &json!({}));
    let first = tokio::spawn({
        let (app, path) = (
            app.clone(),
            first_url.strip_prefix(common::HOST).unwrap().to_string(),
        );
        async move { post(&app, &path, body).await }
    });
    // The first validation is genuinely in flight — claimed, `processing`.
    let _ = entered.acquire().await.unwrap();

    let nonce = fetch_nonce(&app).await;
    let body = signer.sign_kid(&account_url, &second_url, &nonce, &json!({}));
    let res = post(&app, second_url.strip_prefix(common::HOST).unwrap(), body).await;
    assert_eq!(res.status(), StatusCode::TOO_MANY_REQUESTS);
    assert!(res.headers().contains_key("retry-after"));
    assert_eq!(
        body_json(res).await["type"],
        "urn:ietf:params:acme:error:rateLimited"
    );

    gate.add_permits(1);
    assert_eq!(first.await.unwrap().status(), StatusCode::OK);

    // Once the first has settled, the second is accepted.
    let decided = await_decided(&app, &signer, &account_url, &first_url).await;
    assert_eq!(decided["status"], "valid");
    let nonce = fetch_nonce(&app).await;
    let body = signer.sign_kid(&account_url, &second_url, &nonce, &json!({}));
    let res = post(&app, second_url.strip_prefix(common::HOST).unwrap(), body).await;
    assert_eq!(res.status(), StatusCode::OK);
}