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
//! Regression tests for the security defects fixed in this pass.
//!
//! Each test names the thing that used to be possible. They run through the real
//! router so they cover the handler wiring as well as the model logic, and they
//! are grouped here rather than scattered so the set is easy to re-read as a
//! whole: this is the list of ways a client could once get more than it proved.

use std::sync::Arc;

use acme_proxy_store::db::Database;
use axum::Router;
use axum::body::Body;
use axum::http::{Request, StatusCode};
use axum::response::Response;
use base64::prelude::*;
use serde_json::{Value, json};
use tower::ServiceExt;

mod common;
use common::{
    EcSigner, TestSigner, body_json, fetch_nonce, first_certificate, make_csr, make_csr_for, p,
    test_app, test_app_with_db,
};

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 payload = json!({ "termsOfServiceAgreed": true });
    let res = post(
        app,
        &p("/newAccount"),
        signer.sign(NEW_ACCOUNT_URL, &nonce, &payload),
    )
    .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()
}

async fn new_order(
    app: &Router,
    signer: &impl TestSigner,
    account_url: &str,
    dns: &str,
) -> Response {
    let nonce = fetch_nonce(app).await;
    let payload = json!({ "identifiers": [{ "type": "dns", "value": dns }] });
    let body = signer.sign_kid(account_url, NEW_ORDER_URL, &nonce, &payload);
    post(app, &p("/newOrder"), body).await
}

async fn post_as_get(
    app: &Router,
    signer: &impl TestSigner,
    account_url: &str,
    url: &str,
) -> Value {
    let path = url.strip_prefix(common::HOST).unwrap();
    let nonce = fetch_nonce(app).await;
    let body = signer.sign_kid_empty(account_url, url, &nonce);
    let res = post(app, path, body).await;
    assert_eq!(res.status(), StatusCode::OK);
    body_json(res).await
}

/// Creates an order for `dns` and drives every challenge so it becomes `ready`.
/// Returns the order URL.
async fn ready_order(
    app: &Router,
    signer: &impl TestSigner,
    account_url: &str,
    dns: &str,
) -> String {
    let res = new_order(app, signer, account_url, dns).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 = post_as_get(app, signer, account_url, &order_url).await;
    for authz_url in order["authorizations"].as_array().unwrap() {
        let authz_url = authz_url.as_str().unwrap();
        let authz = post_as_get(app, signer, account_url, authz_url).await;
        for challenge in authz["challenges"].as_array().unwrap() {
            let chall_url = challenge["url"].as_str().unwrap();
            // Validation is queued work, so the trigger only starts it. Poll
            // with the repeat `{}` POST §7.5.1 makes explicitly not a state
            // change.
            let path = chall_url.strip_prefix(common::HOST).unwrap();
            for _ in 0..600 {
                let nonce = fetch_nonce(app).await;
                let body = signer.sign_kid(account_url, chall_url, &nonce, &json!({}));
                let res = post(app, path, body).await;
                assert_eq!(res.status(), StatusCode::OK);
                if body_json(res).await["status"] != "processing" {
                    break;
                }
                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            }
        }
    }
    order_url
}

async fn finalize(
    app: &Router,
    signer: &impl TestSigner,
    account_url: &str,
    order_url: &str,
    csr: &str,
) -> Response {
    let url = format!("{order_url}/finalize");
    let path = url.strip_prefix(common::HOST).unwrap();
    let nonce = fetch_nonce(app).await;
    let body = signer.sign_kid(account_url, &url, &nonce, &json!({ "csr": csr }));
    post(app, path, body).await
}

// ---------------------------------------------------------------------------
// Deactivated accounts (RFC 8555 §7.3.6)
// ---------------------------------------------------------------------------

/// Deactivating an account used to block only further *account updates*.
/// `signer_account` never looked at `status`, so the key kept full issuance
/// rights: a client could deactivate and then keep ordering certificates.
#[tokio::test]
async fn a_deactivated_account_cannot_create_an_order() {
    let app = test_app().await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;
    let path = account_url.strip_prefix(common::HOST).unwrap();

    let nonce = fetch_nonce(&app).await;
    let body = signer.sign_kid(
        &account_url,
        &account_url,
        &nonce,
        &json!({ "status": "deactivated" }),
    );
    assert_eq!(post(&app, path, body).await.status(), StatusCode::OK);

    let res = new_order(&app, &signer, &account_url, "example.com").await;
    assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
    let problem = body_json(res).await;
    assert_eq!(problem["type"], "urn:ietf:params:acme:error:unauthorized");
}

/// Deactivation must also stop an order that was already `ready` — otherwise a
/// client could stage its orders first and cash them in afterwards.
#[tokio::test]
async fn a_deactivated_account_cannot_finalize_a_ready_order() {
    let app = test_app().await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;
    let order_url = ready_order(&app, &signer, &account_url, "example.com").await;

    let path = account_url.strip_prefix(common::HOST).unwrap();
    let nonce = fetch_nonce(&app).await;
    let body = signer.sign_kid(
        &account_url,
        &account_url,
        &nonce,
        &json!({ "status": "deactivated" }),
    );
    assert_eq!(post(&app, path, body).await.status(), StatusCode::OK);

    let res = finalize(
        &app,
        &signer,
        &account_url,
        &order_url,
        &make_csr("example.com"),
    )
    .await;
    assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
    assert_eq!(
        body_json(res).await["type"],
        "urn:ietf:params:acme:error:unauthorized"
    );
}

/// `newAccount` must refuse a deactivated key too — on **both** its branches.
///
/// RFC 8555 §7.3.6 makes this a MUST, and every other path already kept it
/// (`signer_account` for the order side and `keyChange`, `post_account`
/// directly). `newAccount` did not: a deactivated key got `200` + `Location` +
/// its own `contact` array back, either by asking `onlyReturnExisting` or by
/// simply re-registering. Read-only and limited to the key's own holder, but a
/// hole in a boundary that is otherwise uniform — and it let a key whose account
/// had been shut down confirm the account still existed.
#[tokio::test]
async fn a_deactivated_key_is_refused_by_new_account() {
    for only_return_existing in [true, false] {
        let app = test_app().await;
        let signer = EcSigner::new();
        let account_url = register(&app, &signer).await;
        let path = account_url.strip_prefix(common::HOST).unwrap();

        let nonce = fetch_nonce(&app).await;
        let body = signer.sign_kid(
            &account_url,
            &account_url,
            &nonce,
            &json!({ "status": "deactivated" }),
        );
        assert_eq!(post(&app, path, body).await.status(), StatusCode::OK);

        // Signed with `jwk`, not `kid`: `newAccount` is how a key introduces
        // itself, so there is no account named in the header to reject on.
        let nonce = fetch_nonce(&app).await;
        let payload = if only_return_existing {
            json!({ "onlyReturnExisting": true })
        } else {
            json!({ "termsOfServiceAgreed": true })
        };
        let res = post(
            &app,
            &p("/newAccount"),
            signer.sign(NEW_ACCOUNT_URL, &nonce, &payload),
        )
        .await;

        assert_eq!(
            res.status(),
            StatusCode::UNAUTHORIZED,
            "onlyReturnExisting={only_return_existing}"
        );
        let problem = body_json(res).await;
        assert_eq!(problem["type"], "urn:ietf:params:acme:error:unauthorized");
        // And specifically not the account object it used to hand back.
        assert!(problem.get("contact").is_none());
    }
}

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

/// A wildcard needs `dns-01` proof over the whole zone (RFC 8555 §7.1.3), so
/// with the default configuration — which offers `http-01` alone — there is no
/// challenge that could ever satisfy it. Refused up front rather than turned
/// into an authorization nobody can complete.
#[tokio::test]
async fn a_wildcard_identifier_is_rejected_when_dns_01_is_disabled() {
    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;
    assert_eq!(res.status(), StatusCode::FORBIDDEN);
    let problem = body_json(res).await;
    assert_eq!(
        problem["type"],
        "urn:ietf:params:acme:error:rejectedIdentifier"
    );
    // The detail names the challenge the operator would have to enable.
    assert!(
        problem["detail"].as_str().unwrap().contains("dns-01"),
        "{problem}"
    );
}

/// RFC 8555 §6.7.1: when several identifiers are rejected, the problem document
/// "MAY contain the `subproblems` field […] each of which MAY contain an
/// `identifier` field", so the client can resubmit without the bad names
/// instead of discovering them one round trip at a time.
///
/// Also pins two constraints the same section imposes: subproblems "need not
/// all have the same type", and `identifier` "MUST NOT be present at the top
/// level in ACME problem documents".
#[tokio::test]
async fn several_bad_identifiers_are_reported_together_as_subproblems() {
    let app = test_app().await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    let nonce = fetch_nonce(&app).await;
    let payload = json!({
        "identifiers": [
            { "type": "dns", "value": "fine.example.com" },
            { "type": "dns", "value": "*.*.example.com" },   // malformed
            { "type": "dns", "value": "*.example.com" },     // needs dns-01
        ]
    });
    let res = post(
        &app,
        &p("/newOrder"),
        signer.sign_kid(&account_url, NEW_ORDER_URL, &nonce, &payload),
    )
    .await;

    // The most severe part decides the status: a policy refusal (403) must not
    // be downgraded to 400 by a malformed name sitting next to it.
    assert_eq!(res.status(), StatusCode::FORBIDDEN);
    let problem = body_json(res).await;
    assert_eq!(problem["type"], "urn:ietf:params:acme:error:compound");
    assert!(
        problem.get("identifier").is_none(),
        "§6.7.1 forbids `identifier` at the top level: {problem}"
    );

    let subproblems = problem["subproblems"].as_array().expect("subproblems");
    assert_eq!(subproblems.len(), 2, "only the bad names: {problem}");

    let by_value: Vec<(&str, &str)> = subproblems
        .iter()
        .map(|sub| {
            (
                sub["identifier"]["value"].as_str().unwrap(),
                sub["type"].as_str().unwrap(),
            )
        })
        .collect();
    assert!(by_value.contains(&("*.*.example.com", "urn:ietf:params:acme:error:malformed")));
    assert!(by_value.contains(&(
        "*.example.com",
        "urn:ietf:params:acme:error:rejectedIdentifier"
    )));

    // The good name is not mentioned — that is what makes the list actionable.
    assert!(
        !by_value
            .iter()
            .any(|(value, _)| *value == "fine.example.com")
    );
}

/// A lone rejection stays itself. Wrapping one problem in a `compound` would
/// bury the type a client actually switches on, for no gain — which is why the
/// two wildcard tests above still assert their specific types.
#[tokio::test]
async fn a_single_bad_identifier_is_not_wrapped_in_a_compound() {
    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 problem = body_json(res).await;
    assert_eq!(
        problem["type"],
        "urn:ietf:params:acme:error:rejectedIdentifier"
    );
    assert!(problem.get("subproblems").is_none(), "{problem}");
}

/// A `*` anywhere but as the single leading `*.` is not a wildcard anyone could
/// prove — it is a malformed identifier, and gets a 400 rather than a policy
/// refusal (RFC 8555 §6.7 draws that line).
#[tokio::test]
async fn a_malformed_wildcard_identifier_is_rejected_as_malformed() {
    let app = test_app().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}");
        let problem = body_json(res).await;
        assert_eq!(
            problem["type"], "urn:ietf:params:acme:error:malformed",
            "{value}"
        );
    }
}

/// An address spelled as a `dns` identifier used to pass: every label is
/// digits, and digits are a legal label. `http-01` then handed it to the WHATWG
/// URL parser, which reads `2130706433` as `127.0.0.1` — so a name-shaped
/// `filter.identifiers` pattern judged one string while the validator connected
/// to another address, and the certificate would have carried an address in a
/// dNSName SAN.
#[tokio::test]
async fn an_ip_address_is_not_a_dns_identifier() {
    let app = test_app().await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    for value in [
        "10.0.0.5",
        "169.254.169.254",
        "2130706433",
        "0x7f.1",
        "*.10.0.0.5",
    ] {
        let res = new_order(&app, &signer, &account_url, value).await;
        assert_eq!(res.status(), StatusCode::FORBIDDEN, "{value}");
        let problem = body_json(res).await;
        assert_eq!(
            problem["type"], "urn:ietf:params:acme:error:rejectedIdentifier",
            "{value}"
        );
        assert!(
            problem["detail"].as_str().unwrap().contains("IP address"),
            "{problem}"
        );
    }

    // A name that merely starts with digits is still a name.
    let res = new_order(&app, &signer, &account_url, "10.0.0.5.example.com").await;
    assert_eq!(res.status(), StatusCode::CREATED);
}

// ---------------------------------------------------------------------------
// Identifier normalization
// ---------------------------------------------------------------------------

/// A fully-qualified name (trailing dot) and a shouted one name the same host.
/// Storing them verbatim meant a filter's anchored pattern only matched the one
/// spelling the operator happened to write; the order now records one canonical
/// form, which is also what the CSR is compared against at finalize.
#[tokio::test]
async fn identifiers_are_normalized_before_they_are_stored() {
    let app = test_app().await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    for spelling in ["EXAMPLE.com.", "Example.COM", "example.com."] {
        let res = new_order(&app, &signer, &account_url, spelling).await;
        assert_eq!(res.status(), StatusCode::CREATED);
        let order = body_json(res).await;
        assert_eq!(
            order["identifiers"][0]["value"], "example.com",
            "{spelling} should normalize to example.com"
        );
    }
}

/// The normalized name is what the signer compares the CSR against, so an order
/// placed in one spelling finalizes with a CSR in the canonical one.
#[tokio::test]
async fn an_order_placed_with_a_trailing_dot_finalizes_normally() {
    let app = test_app().await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;
    let order_url = ready_order(&app, &signer, &account_url, "EXAMPLE.com.").await;

    let res = finalize(
        &app,
        &signer,
        &account_url,
        &order_url,
        &make_csr("example.com"),
    )
    .await;
    assert_eq!(res.status(), StatusCode::OK);
}

// ---------------------------------------------------------------------------
// Expiry (RFC 8555 §7.1.3)
// ---------------------------------------------------------------------------

/// `expires` was written and echoed but never compared against the clock, so an
/// order stayed finalizable indefinitely.
#[tokio::test]
async fn an_expired_order_cannot_be_finalized() {
    let (app, db) = test_app_with_db().await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;
    let order_url = ready_order(&app, &signer, &account_url, "example.com").await;

    expire_orders(&db).await;

    let res = finalize(
        &app,
        &signer,
        &account_url,
        &order_url,
        &make_csr("example.com"),
    )
    .await;
    assert_eq!(res.status(), StatusCode::BAD_REQUEST);
    let problem = body_json(res).await;
    assert_eq!(problem["type"], "urn:ietf:params:acme:error:malformed");
    assert!(
        problem["detail"]
            .as_str()
            .unwrap()
            .to_lowercase()
            .contains("expired"),
        "the problem should say the order expired, got {problem}"
    );
}

/// An expired authorization proves nothing, so triggering its challenge must not
/// carry the order to `ready`.
#[tokio::test]
async fn an_expired_authorization_cannot_be_validated() {
    let (app, db) = test_app_with_db().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 = post_as_get(&app, &signer, &account_url, &order_url).await;
    let authz_url = order["authorizations"][0].as_str().unwrap().to_string();
    let authz = post_as_get(&app, &signer, &account_url, &authz_url).await;
    let chall_url = authz["challenges"][0]["url"].as_str().unwrap().to_string();

    // Expire the authorization (and its order) behind the client's back.
    sqlx::query("UPDATE authorizations SET expires = 1;")
        .execute(db.raw_pool())
        .await
        .unwrap();

    let path = chall_url.strip_prefix(common::HOST).unwrap();
    let nonce = fetch_nonce(&app).await;
    let body = signer.sign_kid(&account_url, &chall_url, &nonce, &json!({}));
    let res = post(&app, path, body).await;

    assert_eq!(res.status(), StatusCode::BAD_REQUEST);
    let problem = body_json(res).await;
    assert_eq!(problem["type"], "urn:ietf:params:acme:error:malformed");
}

/// An order that already produced a certificate stays readable after it expires
/// — the client still has to fetch the chain it paid for.
#[tokio::test]
async fn an_issued_order_is_still_readable_after_it_expires() {
    let (app, db) = test_app_with_db().await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;
    let order_url = ready_order(&app, &signer, &account_url, "example.com").await;

    let res = finalize(
        &app,
        &signer,
        &account_url,
        &order_url,
        &make_csr("example.com"),
    )
    .await;
    assert_eq!(res.status(), StatusCode::OK);
    let order = common::acme::await_order(&app, &signer, &account_url, &order_url).await;
    let cert_url = order["certificate"].as_str().unwrap().to_string();

    expire_orders(&db).await;

    // Both the order and its certificate remain retrievable.
    let order = post_as_get(&app, &signer, &account_url, &order_url).await;
    assert_eq!(order["status"], "valid");

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

async fn expire_orders(db: &Arc<Database>) {
    sqlx::query("UPDATE orders SET expires = 1;")
        .execute(db.raw_pool())
        .await
        .unwrap();
}

// ---------------------------------------------------------------------------
// Order integrity
// ---------------------------------------------------------------------------

/// The readiness check used to be "every authorization row is valid", which is
/// only equivalent to "every identifier was authorized" while the rows and the
/// identifiers stay in step. Deleting one authorization simulates the partial
/// write a non-transactional `newOrder` could leave behind: the surviving
/// challenge must not be enough to make a two-name order `ready`.
#[tokio::test]
async fn an_order_missing_an_authorization_never_becomes_ready() {
    let (app, db) = test_app_with_db().await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    let nonce = fetch_nonce(&app).await;
    let payload = json!({ "identifiers": [
        { "type": "dns", "value": "a.example.com" },
        { "type": "dns", "value": "b.example.com" },
    ]});
    let body = signer.sign_kid(&account_url, NEW_ORDER_URL, &nonce, &payload);
    let res = post(&app, &p("/newOrder"), body).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 = post_as_get(&app, &signer, &account_url, &order_url).await;
    let authz_urls: Vec<String> = order["authorizations"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_str().unwrap().to_string())
        .collect();
    assert_eq!(authz_urls.len(), 2);

    // Drop the second authorization and its challenge, leaving the order row
    // still claiming two identifiers.
    // Parsed, not bound as the string the URL carries: an id column holds the
    // 16 bytes, and SQLite never compares text equal to a blob -- so a `!=`
    // over an unparsed id is true of *every* row, and these two statements
    // would empty both tables instead of leaving one authorization behind.
    let surviving: uuid::Uuid = authz_urls[0].rsplit('/').next().unwrap().parse().unwrap();
    sqlx::query("DELETE FROM challenges WHERE authz_id != ?;")
        .bind(surviving)
        .execute(db.raw_pool())
        .await
        .unwrap();
    sqlx::query("DELETE FROM authorizations WHERE id != ?;")
        .bind(surviving)
        .execute(db.raw_pool())
        .await
        .unwrap();

    // Validate the one remaining challenge.
    let authz = post_as_get(&app, &signer, &account_url, &authz_urls[0]).await;
    let chall_url = authz["challenges"][0]["url"].as_str().unwrap().to_string();
    let path = chall_url.strip_prefix(common::HOST).unwrap();
    let nonce = fetch_nonce(&app).await;
    let body = signer.sign_kid(&account_url, &chall_url, &nonce, &json!({}));
    assert_eq!(post(&app, path, body).await.status(), StatusCode::OK);

    // The order must stay `pending`: one authorization cannot speak for two
    // identifiers.
    let order = post_as_get(&app, &signer, &account_url, &order_url).await;
    assert_eq!(
        order["status"], "pending",
        "an order with fewer authorizations than identifiers must not be ready"
    );

    // And so it cannot be finalized.
    let csr = make_csr_for(&["a.example.com", "b.example.com"]);
    let res = finalize(&app, &signer, &account_url, &order_url, &csr).await;
    assert_eq!(res.status(), StatusCode::FORBIDDEN);
    let problem = body_json(res).await;
    assert_eq!(problem["type"], "urn:ietf:params:acme:error:orderNotReady");
}

// ---------------------------------------------------------------------------
// CA escalation, end to end
// ---------------------------------------------------------------------------

/// The whole flow with a CSR that asks to be a CA. It is signed — the name
/// matches the order — but the leaf that comes back must not carry the powers
/// the CSR requested. `crates/signer/src/local_ca.rs` tests the same thing at the unit
/// level; this one proves the wiring in between does not reintroduce it.
#[tokio::test]
async fn a_csr_requesting_ca_powers_yields_a_leaf_without_them() {
    let app = test_app().await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;
    let order_url = ready_order(&app, &signer, &account_url, "example.com").await;

    let key_pair = rcgen::KeyPair::generate().unwrap();
    let mut params = rcgen::CertificateParams::new(vec!["example.com".to_string()]).unwrap();
    params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
    params.key_usages = vec![
        rcgen::KeyUsagePurpose::KeyCertSign,
        rcgen::KeyUsagePurpose::CrlSign,
    ];
    let csr = params.serialize_request(&key_pair).unwrap();
    let csr_b64 = BASE64_URL_SAFE_NO_PAD.encode(csr.der());

    let res = finalize(&app, &signer, &account_url, &order_url, &csr_b64).await;
    assert_eq!(res.status(), StatusCode::OK);
    let order = common::acme::await_order(&app, &signer, &account_url, &order_url).await;
    let cert_url = order["certificate"].as_str().unwrap().to_string();

    let path = cert_url.strip_prefix(common::HOST).unwrap();
    let nonce = fetch_nonce(&app).await;
    let body = signer.sign_kid_empty(&account_url, &cert_url, &nonce);
    let res = post(&app, path, body).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_der = first_certificate(&pem);
    let (_, parsed) = x509_parser::parse_x509_certificate(&leaf_der).unwrap();
    // Either no `basicConstraints` at all, or one saying `cA: FALSE`. Both refuse
    // CA status per RFC 5280 §6.1.4(k); the signer omits the extension.
    assert!(
        parsed
            .basic_constraints()
            .unwrap()
            .is_none_or(|bc| !bc.value.ca),
        "the issued leaf must not be a CA"
    );
    assert!(
        !parsed.key_usage().unwrap().unwrap().value.key_cert_sign(),
        "the issued leaf must not be able to sign certificates"
    );
}

/// One `newOrder` may not name an unbounded number of identifiers.
///
/// Before `order.max_identifiers` the only bound was `server.max_body_bytes`
/// (128 KiB), which at roughly thirty bytes an identifier admits some four
/// thousand names in one request. Each becomes an authorization plus a
/// challenge per offered type, inserted in a **single** transaction — and
/// SQLite has one writer, so that transaction stalls every other write in the
/// process while it runs. The refusal is `malformed` rather than `rateLimited`:
/// the order is malformed for this server whenever it is sent, so telling the
/// client to come back later would be a lie.
#[tokio::test]
async fn an_order_naming_more_identifiers_than_the_limit_is_refused() {
    async fn order_naming(
        app: &Router,
        signer: &impl TestSigner,
        account_url: &str,
        names: &[String],
    ) -> Response {
        let identifiers: Vec<Value> = names
            .iter()
            .map(|name| json!({ "type": "dns", "value": name }))
            .collect();
        let nonce = fetch_nonce(app).await;
        let payload = json!({ "identifiers": identifiers });
        let body = signer.sign_kid(account_url, NEW_ORDER_URL, &nonce, &payload);
        post(app, &p("/newOrder"), body).await
    }

    let app = test_app().await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    let limit = acme_proxy_core::config::Config::default()
        .order
        .max_identifiers;
    let names: Vec<String> = (0..=limit).map(|n| format!("h{n}.example.com")).collect();

    let res = order_naming(&app, &signer, &account_url, &names).await;
    assert_eq!(res.status(), StatusCode::BAD_REQUEST);
    let problem = body_json(res).await;
    assert_eq!(problem["type"], "urn:ietf:params:acme:error:malformed");
    assert!(
        problem["detail"]
            .as_str()
            .unwrap_or_default()
            .contains(&limit.to_string()),
        "the refusal must say what the limit is: {problem}"
    );

    // The boundary itself is accepted, so the ceiling is a ceiling and not an
    // off-by-one that costs a legitimate client its largest order.
    let res = order_naming(&app, &signer, &account_url, &names[..limit]).await;
    assert_eq!(res.status(), StatusCode::CREATED);
}

/// A panic in a handler used to abort the connection with no response at all —
/// the client got a transport error where every other refusal is a document.
/// `CatchPanicLayer` on each listener now turns it into that listener's own
/// error shape (ASVS V16.5.4). The layers are exercised here over a route that
/// panics on purpose, since the real app has none.
#[tokio::test]
async fn a_panicking_acme_handler_answers_a_problem_document() {
    use axum::routing::get;

    async fn boom() -> &'static str {
        panic!("boom")
    }

    let app = Router::new()
        .route("/boom", get(boom))
        .layer(acme_proxy_protocol::router::catch_panic_acme());

    let res = app
        .oneshot(Request::get("/boom").body(Body::empty()).unwrap())
        .await
        .unwrap();

    assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
    assert_eq!(
        res.headers()
            .get("content-type")
            .and_then(|v| v.to_str().ok()),
        Some("application/problem+json"),
    );
    let problem = body_json(res).await;
    assert_eq!(problem["type"], "urn:ietf:params:acme:error:serverInternal");
}

/// The admin listener splits by surface: a `/api` panic stays JSON for a
/// script, a page panic is HTML for a browser — the same reason `AdminError`
/// and `PageError` are separate types.
#[tokio::test]
async fn a_panicking_admin_handler_answers_in_the_right_shape_per_surface() {
    use axum::body::to_bytes;
    use axum::routing::get;

    async fn boom() -> &'static str {
        panic!("boom")
    }

    let api = Router::new()
        .route("/boom", get(boom))
        .layer(acme_proxy_admin::webadmin::catch_panic_admin_api());
    let res = api
        .oneshot(Request::get("/boom").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
    assert_eq!(
        res.headers()
            .get("content-type")
            .and_then(|v| v.to_str().ok()),
        Some("application/json"),
    );
    let body = body_json(res).await;
    assert_eq!(body["error"], "internal");

    let pages = Router::new()
        .route("/boom", get(boom))
        .layer(acme_proxy_admin::webadmin::catch_panic_admin_pages());
    let res = pages
        .oneshot(Request::get("/boom").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
    let bytes = to_bytes(res.into_body(), 64 * 1024).await.unwrap();
    assert!(
        String::from_utf8(bytes.to_vec())
            .unwrap()
            .starts_with("<!doctype html>"),
    );
}