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
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
//! Covers the RFC 8555 order → authorization → challenge → finalize → certificate
//! flow end-to-end: newAccount → newOrder (pending) → POST-as-GET authorization →
//! trigger http-01 challenge → POST-as-GET order (ready) → finalize(CSR) →
//! POST-as-GET certificate, plus the account order-list URL. Runs the happy path
//! for both EC and RSA keys, and exercises every rejection branch (wrong url, bad
//! nonce, empty / non-dns identifiers, finalize a non-ready order, bad CSR,
//! POST-as-GET by a different account, a non-empty POST-as-GET payload, unknown
//! order / authorization / challenge).

use std::sync::Arc;

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

mod common;
use base64::prelude::*;
use common::{
    EcSigner, FailingSigner, GarbageChainSigner, PREFIX, RsaSigner, TestSigner, acme, body_json,
    fetch_nonce, make_csr, make_csr_with_sans, p, test_app, test_app_with_signer,
};

const BASE: &str = common::BASE;
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()
}

async fn body_text(response: Response) -> String {
    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    String::from_utf8(bytes.to_vec()).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()
}

/// Registers an account and carries one order as far as `ready` — the state
/// finalize requires — returning `(account_url, order_url)`. Extracted so the
/// finalize-behaviour tests below start where they actually differ, rather
/// than repeating the four steps that get there.
async fn ready_order(app: &Router, signer: &impl TestSigner) -> (String, String) {
    let account_url = register(app, signer).await;

    let nonce = fetch_nonce(app).await;
    let payload = json!({ "identifiers": [{ "type": "dns", "value": "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())
        .expect("newOrder must set a Location header")
        .to_string();
    let authz_url = body_json(res).await["authorizations"][0]
        .as_str()
        .unwrap()
        .to_string();

    // Read the authorization to find its challenge, then trigger it. With the
    // default bypassing registry that is what moves the order to `ready`.
    let nonce = fetch_nonce(app).await;
    let body = signer.sign_kid_empty(&account_url, &authz_url, &nonce);
    let res = post(app, authz_url.strip_prefix(common::HOST).unwrap(), body).await;
    let challenge_url = body_json(res).await["challenges"][0]["url"]
        .as_str()
        .unwrap()
        .to_string();

    // Validation is queued work, so the trigger only starts it; wait for the
    // verdict the way a client polling its `Retry-After` would.
    acme::await_challenge(app, signer, &account_url, &challenge_url).await;

    (account_url, order_url)
}

/// Drives the full lifecycle for a given signer/key type.
async fn full_lifecycle(signer: impl TestSigner) {
    let app = test_app().await;
    let account_url = register(&app, &signer).await;

    // --- newOrder ---
    let nonce = fetch_nonce(&app).await;
    let payload = json!({ "identifiers": [{ "type": "dns", "value": "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())
        .expect("newOrder must set a Location header")
        .to_string();
    let order = body_json(res).await;
    assert_eq!(order["status"], "pending");
    let authz_url = order["authorizations"][0]
        .as_str()
        .expect("order must list an authorization URL")
        .to_string();
    assert_eq!(order["finalize"], format!("{order_url}/finalize"));
    assert_eq!(order["identifiers"][0]["value"], "example.com");

    let order_path = order_url.strip_prefix(common::HOST).unwrap();

    // --- POST-as-GET the authorization ---
    let authz_path = authz_url.strip_prefix(common::HOST).unwrap();
    let nonce = fetch_nonce(&app).await;
    let body = signer.sign_kid_empty(&account_url, &authz_url, &nonce);
    let res = post(&app, authz_path, body).await;
    assert_eq!(res.status(), StatusCode::OK);
    let authz = body_json(res).await;
    assert_eq!(authz["status"], "pending");
    assert_eq!(
        authz["identifier"],
        json!({ "type": "dns", "value": "example.com" })
    );
    let challenge = &authz["challenges"][0];
    assert_eq!(challenge["type"], "http-01");
    assert_eq!(challenge["status"], "pending");
    assert!(challenge["token"].as_str().is_some_and(|t| !t.is_empty()));
    let challenge_url = challenge["url"]
        .as_str()
        .expect("challenge must have a URL")
        .to_string();

    // --- trigger the challenge (stub validation flips it to valid) ---
    let nonce = fetch_nonce(&app).await;
    let body = signer.sign_kid(&account_url, &challenge_url, &nonce, &json!({}));
    let res = post(
        &app,
        challenge_url.strip_prefix(common::HOST).unwrap(),
        body,
    )
    .await;
    assert_eq!(res.status(), StatusCode::OK);
    // The trigger starts the work; §7.1.6's `processing` is what comes back,
    // and the verdict lands in the job runner.
    assert_eq!(body_json(res).await["status"], "processing");
    assert_eq!(
        acme::await_challenge(&app, &signer, &account_url, &challenge_url).await["status"],
        "valid"
    );

    // --- POST-as-GET the order: now ready ---
    let nonce = fetch_nonce(&app).await;
    let body = signer.sign_kid_empty(&account_url, &order_url, &nonce);
    let res = post(&app, order_path, body).await;
    assert_eq!(res.status(), StatusCode::OK);
    assert_eq!(body_json(res).await["status"], "ready");

    // --- finalize ---
    let finalize_url = format!("{order_url}/finalize");
    let finalize_path = finalize_url.strip_prefix(common::HOST).unwrap();
    let nonce = fetch_nonce(&app).await;
    let payload = json!({ "csr": make_csr("example.com") });
    let body = signer.sign_kid(&account_url, &finalize_url, &nonce, &payload);
    let res = post(&app, finalize_path, body).await;
    assert_eq!(res.status(), StatusCode::OK);
    // Issuance is queued work: finalize answers `processing` (RFC 8555 §7.4),
    // and the certificate is there once the worker has signed it.
    assert_eq!(body_json(res).await["status"], "processing");
    let order = await_order_status(&app, &signer, &account_url, &order_url, "valid").await;
    let cert_url = order["certificate"]
        .as_str()
        .expect("certificate URL")
        .to_string();
    assert_eq!(
        cert_url,
        format!(
            "{BASE}/certificate/{}",
            order_path.strip_prefix(&p("/order/")).unwrap()
        )
    );

    // --- POST-as-GET the certificate ---
    let cert_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, cert_path, body).await;
    assert_eq!(res.status(), StatusCode::OK);
    assert_eq!(
        res.headers()
            .get("content-type")
            .and_then(|v| v.to_str().ok()),
        Some("application/pem-certificate-chain"),
    );
    let pem = body_text(res).await;
    assert_eq!(
        pem.matches("-----BEGIN CERTIFICATE-----").count(),
        2,
        "chain should be leaf + CA"
    );

    // --- POST-as-GET the account order list ---
    let orders_url = format!("{account_url}/orders");
    let orders_path = orders_url.strip_prefix(common::HOST).unwrap();
    let nonce = fetch_nonce(&app).await;
    let body = signer.sign_kid_empty(&account_url, &orders_url, &nonce);
    let res = post(&app, orders_path, body).await;
    assert_eq!(res.status(), StatusCode::OK);
    let list = body_json(res).await;
    assert_eq!(list["orders"][0], order_url);
}

#[tokio::test]
async fn full_lifecycle_ec() {
    full_lifecycle(EcSigner::new()).await;
}

#[tokio::test]
async fn full_lifecycle_rsa() {
    full_lifecycle(RsaSigner::new()).await;
}

// --- Rejection paths (EC signer throughout) ---

/// Registers an EC account + creates a fresh (pending) order, returning (app,
/// signer, `account_url`, `order_url`).
async fn setup_order() -> (Router, EcSigner, String, String) {
    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": "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();
    (app, signer, account_url, order_url)
}

/// Reads an order (POST-as-GET) and returns its authorization URLs.
async fn order_authz_urls(
    app: &Router,
    signer: &impl TestSigner,
    account_url: &str,
    order_url: &str,
) -> Vec<String> {
    let order_path = order_url.strip_prefix(common::HOST).unwrap();
    let nonce = fetch_nonce(app).await;
    let body = signer.sign_kid_empty(account_url, order_url, &nonce);
    let res = post(app, order_path, body).await;
    assert_eq!(res.status(), StatusCode::OK);
    body_json(res).await["authorizations"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_str().unwrap().to_string())
        .collect()
}

/// Reads an authorization (POST-as-GET) and returns its first challenge URL.
async fn first_challenge_url(
    app: &Router,
    signer: &impl TestSigner,
    account_url: &str,
    authz_url: &str,
) -> String {
    let authz_path = authz_url.strip_prefix(common::HOST).unwrap();
    let nonce = fetch_nonce(app).await;
    let body = signer.sign_kid_empty(account_url, authz_url, &nonce);
    let res = post(app, authz_path, body).await;
    assert_eq!(res.status(), StatusCode::OK);
    body_json(res).await["challenges"][0]["url"]
        .as_str()
        .unwrap()
        .to_string()
}

/// Triggers a challenge (POSTs `{}`) and returns the response.
async fn trigger_challenge(
    app: &Router,
    signer: &impl TestSigner,
    account_url: &str,
    challenge_url: &str,
) -> Response {
    let challenge_path = challenge_url.strip_prefix(common::HOST).unwrap();
    let nonce = fetch_nonce(app).await;
    let body = signer.sign_kid(account_url, challenge_url, &nonce, &json!({}));
    post(app, challenge_path, body).await
}

/// Polls an order until it reports `status`.
///
/// Promotion to `ready` happens in whichever validation commits last, and that
/// now runs in the job runner rather than in the trigger's own request.
async fn await_order_status(
    app: &Router,
    signer: &impl TestSigner,
    account_url: &str,
    order_url: &str,
    status: &str,
) -> Value {
    for _ in 0..600 {
        let order = post_as_get(app, signer, account_url, order_url).await;
        if order["status"] == status {
            return order;
        }
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
    }
    panic!("`{order_url}` never reached `{status}`");
}

/// Drives every authorization of an order to `valid`, moving the order to
/// `ready` so it can be finalized.
async fn drive_order_to_ready(
    app: &Router,
    signer: &impl TestSigner,
    account_url: &str,
    order_url: &str,
) {
    for authz_url in order_authz_urls(app, signer, account_url, order_url).await {
        let challenge_url = first_challenge_url(app, signer, account_url, &authz_url).await;
        let res = trigger_challenge(app, signer, account_url, &challenge_url).await;
        assert_eq!(res.status(), StatusCode::OK);
        // The trigger queues the check; wait for the verdict before calling the
        // order ready, the way a client polling its `Retry-After` would.
        acme::await_challenge(app, signer, account_url, &challenge_url).await;
    }
}

/// Like [`setup_order`], but drives the order to `ready` (all challenges
/// triggered) so a following finalize reaches the signer.
async fn setup_ready_order() -> (Router, EcSigner, String, String) {
    let (app, signer, account_url, order_url) = setup_order().await;
    drive_order_to_ready(&app, &signer, &account_url, &order_url).await;
    (app, signer, account_url, order_url)
}

/// [`setup_ready_order`] against a caller-supplied signer backend, for the
/// tests that assert on what `finalize` does with an unusual issuance result.
/// Challenge validation never touches the signer, so the drive to `ready` is
/// identical whichever backend is installed.
async fn setup_ready_order_with_signer(
    backend: Arc<dyn acme_proxy_signer::SignerBackend>,
) -> (Router, EcSigner, String, String) {
    let (app, _db) = test_app_with_signer(backend).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": "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();

    drive_order_to_ready(&app, &signer, &account_url, &order_url).await;
    (app, signer, account_url, order_url)
}

async fn assert_problem(res: Response, status: StatusCode, typ: &str) {
    assert_eq!(res.status(), status);
    let problem = body_json(res).await;
    assert_eq!(problem["type"], typ);
}

/// Reads any resource by signed POST-as-GET, asserting a 200.
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
}

/// Finalizes `order_url` with `csr`, returning the response untouched so the
/// caller can assert either success or a problem.
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
}

#[tokio::test]
async fn new_order_rejects_wrong_url() {
    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": "example.com" }] });
    // The JWS `url` disagrees with the routed endpoint.
    let body = signer.sign_kid(&account_url, &format!("{BASE}/wrong"), &nonce, &payload);
    let res = post(&app, &p("/newOrder"), body).await;
    assert_problem(
        res,
        StatusCode::BAD_REQUEST,
        "urn:ietf:params:acme:error:malformed",
    )
    .await;
}

#[tokio::test]
async fn new_order_rejects_bad_nonce() {
    let app = test_app().await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    let payload = json!({ "identifiers": [{ "type": "dns", "value": "example.com" }] });
    let body = signer.sign_kid(&account_url, NEW_ORDER_URL, "not-a-real-nonce", &payload);
    let res = post(&app, &p("/newOrder"), body).await;
    assert_problem(
        res,
        StatusCode::BAD_REQUEST,
        "urn:ietf:params:acme:error:badNonce",
    )
    .await;
}

#[tokio::test]
async fn new_order_rejects_empty_identifiers() {
    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": [] });
    let body = signer.sign_kid(&account_url, NEW_ORDER_URL, &nonce, &payload);
    let res = post(&app, &p("/newOrder"), body).await;
    assert_problem(
        res,
        StatusCode::BAD_REQUEST,
        "urn:ietf:params:acme:error:malformed",
    )
    .await;
}

#[tokio::test]
async fn new_order_rejects_non_dns_identifier() {
    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": "ip", "value": "192.0.2.1" }] });
    let body = signer.sign_kid(&account_url, NEW_ORDER_URL, &nonce, &payload);
    let res = post(&app, &p("/newOrder"), body).await;
    assert_problem(
        res,
        StatusCode::BAD_REQUEST,
        "urn:ietf:params:acme:error:unsupportedIdentifier",
    )
    .await;
}

#[tokio::test]
async fn finalize_rejects_non_ready_order() {
    // A freshly created order is `pending` (its challenges are not yet
    // satisfied), so finalize is rejected until it becomes `ready`.
    let (app, signer, account_url, order_url) = setup_order().await;
    let finalize_url = format!("{order_url}/finalize");
    let finalize_path = finalize_url.strip_prefix(common::HOST).unwrap();

    let nonce = fetch_nonce(&app).await;
    let payload = json!({ "csr": make_csr("example.com") });
    let body = signer.sign_kid(&account_url, &finalize_url, &nonce, &payload);
    let res = post(&app, finalize_path, body).await;
    assert_problem(
        res,
        StatusCode::FORBIDDEN,
        "urn:ietf:params:acme:error:orderNotReady",
    )
    .await;
}

#[tokio::test]
async fn finalize_rejects_ready_order_reused() {
    // Once finalized (→ `valid`), a second finalize is rejected: no longer `ready`.
    let (app, signer, account_url, order_url) = setup_ready_order().await;
    let finalize_url = format!("{order_url}/finalize");
    let finalize_path = finalize_url.strip_prefix(common::HOST).unwrap();

    let nonce = fetch_nonce(&app).await;
    let payload = json!({ "csr": make_csr("example.com") });
    let body = signer.sign_kid(&account_url, &finalize_url, &nonce, &payload);
    assert_eq!(
        post(&app, finalize_path, body).await.status(),
        StatusCode::OK
    );

    let nonce = fetch_nonce(&app).await;
    let payload = json!({ "csr": make_csr("example.com") });
    let body = signer.sign_kid(&account_url, &finalize_url, &nonce, &payload);
    let res = post(&app, finalize_path, body).await;
    assert_problem(
        res,
        StatusCode::FORBIDDEN,
        "urn:ietf:params:acme:error:orderNotReady",
    )
    .await;
}

#[tokio::test]
async fn finalize_rejects_mismatched_csr() {
    let (app, signer, account_url, order_url) = setup_ready_order().await;
    let finalize_url = format!("{order_url}/finalize");
    let finalize_path = finalize_url.strip_prefix(common::HOST).unwrap();

    // The CSR is for a different domain than the order's identifier.
    let nonce = fetch_nonce(&app).await;
    let payload = json!({ "csr": make_csr("attacker.example") });
    let body = signer.sign_kid(&account_url, &finalize_url, &nonce, &payload);
    let res = post(&app, finalize_path, body).await;
    assert_problem(
        res,
        StatusCode::BAD_REQUEST,
        "urn:ietf:params:acme:error:badCSR",
    )
    .await;
}

#[tokio::test]
async fn post_as_get_rejects_different_account() {
    let (app, _owner, _owner_url, order_url) = setup_order().await;
    let order_path = order_url.strip_prefix(common::HOST).unwrap();

    // A second account signs a POST-as-GET for the first account's order.
    let intruder = EcSigner::new();
    let intruder_url = register(&app, &intruder).await;
    let nonce = fetch_nonce(&app).await;
    let body = intruder.sign_kid_empty(&intruder_url, &order_url, &nonce);
    let res = post(&app, order_path, body).await;
    assert_problem(
        res,
        StatusCode::BAD_REQUEST,
        "urn:ietf:params:acme:error:malformed",
    )
    .await;
}

#[tokio::test]
async fn post_as_get_rejects_non_empty_payload() {
    let (app, signer, account_url, order_url) = setup_order().await;
    let order_path = order_url.strip_prefix(common::HOST).unwrap();

    // A POST-as-GET route reached with a non-empty payload is malformed.
    let nonce = fetch_nonce(&app).await;
    let payload = json!({ "not": "empty" });
    let body = signer.sign_kid(&account_url, &order_url, &nonce, &payload);
    let res = post(&app, order_path, body).await;
    assert_problem(
        res,
        StatusCode::BAD_REQUEST,
        "urn:ietf:params:acme:error:malformed",
    )
    .await;
}

#[tokio::test]
async fn finalize_internal_signer_failure_marks_order_invalid() {
    // A signer that always fails internally drives the terminal-failure path.
    let (app, signer, account_url, order_url) =
        setup_ready_order_with_signer(Arc::new(FailingSigner)).await;

    // Finalize with a valid CSR: accepted and queued — the signer is reached by
    // the worker, not by this request.
    let finalize_url = format!("{order_url}/finalize");
    let finalize_path = finalize_url.strip_prefix(common::HOST).unwrap();
    let nonce = fetch_nonce(&app).await;
    let payload = json!({ "csr": make_csr("example.com") });
    let body = signer.sign_kid(&account_url, &finalize_url, &nonce, &payload);
    let res = post(&app, finalize_path, body).await;
    assert_eq!(res.status(), StatusCode::OK);
    assert_eq!(body_json(res).await["status"], "processing");

    // The failure is retried, then recorded on the order once the attempts run
    // out: POST-as-GET shows `invalid` and a `serverInternal` document under
    // `error`.
    let order = await_order_status(&app, &signer, &account_url, &order_url, "invalid").await;
    assert_eq!(
        order["error"]["type"],
        "urn:ietf:params:acme:error:serverInternal"
    );
    assert_eq!(order["error"]["status"], 500);
}

/// Two finalize requests race one `ready` order. Exactly one certificate may
/// come into existence.
///
/// The regression for the double-issuance race: before `Order::claim_for_finalize`
/// both requests passed the `status == "ready"` check, both were signed, and the
/// loser's certificate was a valid CA-signed leaf whose serial reached no row —
/// so `POST /revokeCert` answered "unknown certificate" and the CRL never
/// learned it existed. `calls` is the assertion that matters: a second
/// certificate leaves nothing else behind to look for.
#[tokio::test]
async fn two_concurrent_finalizes_issue_exactly_one_certificate() {
    let backend = Arc::new(common::GatedSigner::new().await);
    let (calls, gate, entered) = backend.handles();
    let (app, signer, account_url, order_url) = setup_ready_order_with_signer(backend).await;

    let finalize_url = format!("{order_url}/finalize");
    let finalize_path = finalize_url.strip_prefix(common::HOST).unwrap().to_string();

    // Both nonces up front, so the race is the one thing under test.
    let nonce_a = fetch_nonce(&app).await;
    let nonce_b = fetch_nonce(&app).await;

    // A goes first: it claims the order and queues its issuance, and the
    // worker then stalls inside `issue` with the order still `processing`.
    let body_a = signer.sign_kid(
        &account_url,
        &finalize_url,
        &nonce_a,
        &json!({ "csr": make_csr("example.com") }),
    );
    let app_a = app.clone();
    let path_a = finalize_path.clone();
    let task_a = tokio::spawn(async move { post(&app_a, &path_a, body_a).await });

    // Wait for A's issuance to be genuinely inside the signing call, not for a
    // duration.
    let _ = entered.acquire().await.unwrap();

    // B arrives with its own CSR — a different key pair, the same identifiers,
    // so it passes `check_csr_matches_order` exactly as A did.
    let body_b = signer.sign_kid(
        &account_url,
        &finalize_url,
        &nonce_b,
        &json!({ "csr": make_csr("example.com") }),
    );
    let res_b = post(&app, &finalize_path, body_b).await;
    assert_problem(
        res_b,
        StatusCode::FORBIDDEN,
        "urn:ietf:params:acme:error:orderNotReady",
    )
    .await;

    // Only now let A's issuance finish, so the refusal above cannot have been
    // a late loser.
    gate.add_permits(1);
    let res_a = task_a.await.unwrap();
    assert_eq!(res_a.status(), StatusCode::OK);

    // The order carries A's certificate, in the terminal state...
    let order = await_order_status(&app, &signer, &account_url, &order_url, "valid").await;
    assert!(order["certificate"].as_str().is_some());

    // ...and, the whole point, B never reached the CA.
    assert_eq!(
        calls.load(std::sync::atomic::Ordering::SeqCst),
        1,
        "a second certificate was signed"
    );
}

#[tokio::test]
async fn post_as_get_unknown_order_is_malformed() {
    let app = test_app().await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    let order_url = format!("{BASE}/order/does-not-exist");
    let nonce = fetch_nonce(&app).await;
    let body = signer.sign_kid_empty(&account_url, &order_url, &nonce);
    let res = post(&app, &p("/order/does-not-exist"), body).await;
    assert_problem(
        res,
        StatusCode::BAD_REQUEST,
        "urn:ietf:params:acme:error:malformed",
    )
    .await;
}

#[tokio::test]
async fn post_as_get_unknown_authz_is_malformed() {
    let app = test_app().await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    let authz_url = format!("{BASE}/authz/does-not-exist");
    let nonce = fetch_nonce(&app).await;
    let body = signer.sign_kid_empty(&account_url, &authz_url, &nonce);
    let res = post(&app, &p("/authz/does-not-exist"), body).await;
    assert_problem(
        res,
        StatusCode::BAD_REQUEST,
        "urn:ietf:params:acme:error:malformed",
    )
    .await;
}

#[tokio::test]
async fn post_as_get_authz_returns_authorization_object() {
    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": "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 = body_json(res).await;
    let authz_url = order["authorizations"][0].as_str().unwrap();
    let path = authz_url.strip_prefix(common::HOST).unwrap();

    let nonce = fetch_nonce(&app).await;
    let body = signer.sign_kid_empty(&account_url, authz_url, &nonce);
    let res = post(&app, path, body).await;

    assert_eq!(res.status(), StatusCode::OK);
    let authz = body_json(res).await;
    assert_eq!(authz["status"], "pending");
    assert_eq!(authz["identifier"]["value"], "example.com");
    assert!(authz["challenges"].is_array());
}

#[tokio::test]
async fn trigger_unknown_challenge_is_malformed() {
    let app = test_app().await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    let challenge_url = format!("{BASE}/chall/does-not-exist");
    let nonce = fetch_nonce(&app).await;
    let body = signer.sign_kid(&account_url, &challenge_url, &nonce, &json!({}));
    let res = post(&app, &p("/chall/does-not-exist"), body).await;
    assert_problem(
        res,
        StatusCode::BAD_REQUEST,
        "urn:ietf:params:acme:error:malformed",
    )
    .await;
}

#[tokio::test]
async fn authz_rejects_different_account() {
    let (app, owner, owner_url, order_url) = setup_order().await;
    let authz_url = order_authz_urls(&app, &owner, &owner_url, &order_url)
        .await
        .remove(0);
    let authz_path = authz_url.strip_prefix(common::HOST).unwrap();

    // A second account POST-as-GETs the first account's authorization.
    let intruder = EcSigner::new();
    let intruder_url = register(&app, &intruder).await;
    let nonce = fetch_nonce(&app).await;
    let body = intruder.sign_kid_empty(&intruder_url, &authz_url, &nonce);
    let res = post(&app, authz_path, body).await;
    assert_problem(
        res,
        StatusCode::BAD_REQUEST,
        "urn:ietf:params:acme:error:malformed",
    )
    .await;
}

#[tokio::test]
async fn challenge_trigger_rejects_different_account() {
    let (app, owner, owner_url, order_url) = setup_order().await;
    let authz_url = order_authz_urls(&app, &owner, &owner_url, &order_url)
        .await
        .remove(0);
    let challenge_url = first_challenge_url(&app, &owner, &owner_url, &authz_url).await;

    // A second account tries to trigger the first account's challenge.
    let intruder = EcSigner::new();
    let intruder_url = register(&app, &intruder).await;
    let res = trigger_challenge(&app, &intruder, &intruder_url, &challenge_url).await;
    assert_problem(
        res,
        StatusCode::BAD_REQUEST,
        "urn:ietf:params:acme:error:malformed",
    )
    .await;
}

#[tokio::test]
async fn multi_identifier_order_becomes_ready_after_all_challenges() {
    let app = test_app().await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    // An order with two identifiers gets two authorizations.
    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_path = order_url.strip_prefix(common::HOST).unwrap();

    let authz_urls = order_authz_urls(&app, &signer, &account_url, &order_url).await;
    assert_eq!(authz_urls.len(), 2, "one authorization per identifier");

    // Prove the first authorization only: the order is not yet ready.
    let challenge_url = first_challenge_url(&app, &signer, &account_url, &authz_urls[0]).await;
    let res = trigger_challenge(&app, &signer, &account_url, &challenge_url).await;
    assert_eq!(res.status(), StatusCode::OK);
    acme::await_challenge(&app, &signer, &account_url, &challenge_url).await;

    let nonce = fetch_nonce(&app).await;
    let body = signer.sign_kid_empty(&account_url, &order_url, &nonce);
    let res = post(&app, order_path, body).await;
    assert_eq!(body_json(res).await["status"], "pending");

    // Prove the second: now every authorization is valid → ready.
    let challenge_url = first_challenge_url(&app, &signer, &account_url, &authz_urls[1]).await;
    let res = trigger_challenge(&app, &signer, &account_url, &challenge_url).await;
    assert_eq!(res.status(), StatusCode::OK);
    acme::await_challenge(&app, &signer, &account_url, &challenge_url).await;

    let nonce = fetch_nonce(&app).await;
    let body = signer.sign_kid_empty(&account_url, &order_url, &nonce);
    let res = post(&app, order_path, body).await;
    assert_eq!(body_json(res).await["status"], "ready");

    // Re-triggering an already-valid challenge is idempotent (still valid).
    let res = trigger_challenge(&app, &signer, &account_url, &challenge_url).await;
    assert_eq!(res.status(), StatusCode::OK);
    assert_eq!(body_json(res).await["status"], "valid");
}

// ---------------------------------------------------------------------------
// Requested validity bounds
// ---------------------------------------------------------------------------

/// `notBefore`/`notAfter` are optional RFC3339 datetimes. They are stored and
/// echoed on the order object — the signer applies its own leaf policy, so they
/// are a record of what the client asked for, not a promise.
#[tokio::test]
async fn new_order_accepts_and_echoes_requested_validity_bounds() {
    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": "example.com" }],
        "notBefore": "2026-01-01T00:00:00Z",
        "notAfter": "2026-04-01T00:00:00Z",
    });
    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 = body_json(res).await;
    assert_eq!(order["notBefore"], "2026-01-01T00:00:00Z");
    assert_eq!(order["notAfter"], "2026-04-01T00:00:00Z");
}

/// A datetime that is not RFC3339 is the client's mistake, not a 500.
#[tokio::test]
async fn new_order_rejects_an_unparsable_datetime() {
    let app = test_app().await;
    let signer = EcSigner::new();
    let account_url = register(&app, &signer).await;

    for field in ["notBefore", "notAfter"] {
        let nonce = fetch_nonce(&app).await;
        let payload = json!({
            "identifiers": [{ "type": "dns", "value": "example.com" }],
            field: "next tuesday",
        });
        let body = signer.sign_kid(&account_url, NEW_ORDER_URL, &nonce, &payload);
        let res = post(&app, &p("/newOrder"), body).await;
        assert_problem(
            res,
            StatusCode::BAD_REQUEST,
            "urn:ietf:params:acme:error:malformed",
        )
        .await;
    }
}

// ---------------------------------------------------------------------------
// Retryability and remaining authorization checks
// ---------------------------------------------------------------------------

/// `post_finalize` documents a `badCSR` as leaving the order `ready` and
/// retryable. Assert the claim rather than trusting the comment: finalize with a
/// mismatched CSR, then again with a correct one.
/// A `csr` that is not even base64url is refused before any signature
/// attempt. The other "bad CSR" tests send a well-formed CSR for the
/// wrong name and land on `SignerError::BadCsr` one step later, so
/// this decoding was not covered by any of them.
#[tokio::test]
async fn finalize_rejects_a_csr_that_is_not_base64url() {
    let (app, signer, account_url, order_url) = setup_ready_order().await;

    let res = finalize(&app, &signer, &account_url, &order_url, "!!!not base64!!!").await;

    assert_problem(
        res,
        StatusCode::BAD_REQUEST,
        "urn:ietf:params:acme:error:badCSR",
    )
    .await;

    // Like any `badCSR`, this leaves the order reusable.
    let order = post_as_get(&app, &signer, &account_url, &order_url).await;
    assert_eq!(order["status"], "ready");
}

/// An unparsable chain returned by the backend is a certificate this server
/// could never revoke, and signing again would only produce another: the
/// issuance fails for good, and the client reads `invalid` with a
/// `serverInternal` document rather than polling for ever.
#[tokio::test]
async fn an_unparsable_issued_chain_invalidates_the_order() {
    let (app, signer, account_url, order_url) =
        setup_ready_order_with_signer(Arc::new(GarbageChainSigner)).await;

    let res = finalize(
        &app,
        &signer,
        &account_url,
        &order_url,
        &make_csr("example.com"),
    )
    .await;

    assert_eq!(res.status(), StatusCode::OK);

    let order = await_order_status(&app, &signer, &account_url, &order_url, "invalid").await;
    assert_eq!(
        order["error"]["type"],
        "urn:ietf:params:acme:error:serverInternal"
    );
    assert!(order.get("certificate").is_none());
}

/// RFC 8555 §7.4: "The CSR MUST indicate the exact same set of requested
/// identifiers as the initial newOrder request."
///
/// Equality, not containment — a superset and a subset are both refused. The
/// order here is for `example.com` alone.
#[tokio::test]
async fn a_csr_must_name_exactly_the_order_s_identifiers() {
    for csr in [
        // A different name entirely.
        make_csr("victim.example"),
        // A superset: the order's name plus one it never authorized.
        make_csr_with_sans(
            "example.com",
            vec![rcgen::SanType::DnsName(
                "extra.example.com".try_into().unwrap(),
            )],
        ),
    ] {
        let (app, signer, account_url, order_url) = setup_ready_order().await;
        let res = finalize(&app, &signer, &account_url, &order_url, &csr).await;
        assert_problem(
            res,
            StatusCode::BAD_REQUEST,
            "urn:ietf:params:acme:error:badCSR",
        )
        .await;
    }
}

/// The point of hoisting the check into `post_finalize`: the refusal must not
/// depend on the backend making it.
///
/// `local_ca` has always checked, so with the real signer a passing test proves
/// nothing about `custom` or `relay` — the two that hand the CSR to an
/// operator script or relay it to an upstream that never saw the local
/// authorizations. `RecordingSigner` accepts everything and records being
/// called, so `was_called() == false` is the assertion that matters.
#[tokio::test]
async fn a_mismatched_csr_never_reaches_the_signer_backend() {
    let backend = Arc::new(common::RecordingSigner::default());
    let (app, signer, account_url, order_url) =
        setup_ready_order_with_signer(backend.clone()).await;

    let res = finalize(
        &app,
        &signer,
        &account_url,
        &order_url,
        &make_csr("victim.example"),
    )
    .await;
    assert_problem(
        res,
        StatusCode::BAD_REQUEST,
        "urn:ietf:params:acme:error:badCSR",
    )
    .await;
    assert!(
        !backend.was_called(),
        "the handler must refuse the CSR before any backend sees it"
    );

    // And the same backend *is* reached once the CSR matches, so the assertion
    // above is about the refusal and not about the backend being unreachable.
    let res = finalize(
        &app,
        &signer,
        &account_url,
        &order_url,
        &make_csr("example.com"),
    )
    .await;
    assert_eq!(res.status(), StatusCode::OK);
    await_order_status(&app, &signer, &account_url, &order_url, "invalid").await;
    assert!(backend.was_called());
}

/// A CSR whose SANs match the order but which smuggles an extra identifier of
/// another kind. An order can only ever carry `dns` identifiers, so this asks
/// for something no order could have authorized.
#[tokio::test]
async fn a_csr_smuggling_a_non_dns_san_is_refused() {
    let backend = Arc::new(common::RecordingSigner::default());
    let (app, signer, account_url, order_url) =
        setup_ready_order_with_signer(backend.clone()).await;

    let csr = make_csr_with_sans(
        "example.com",
        vec![rcgen::SanType::IpAddress("10.0.0.1".parse().unwrap())],
    );
    let res = finalize(&app, &signer, &account_url, &order_url, &csr).await;
    assert_problem(
        res,
        StatusCode::BAD_REQUEST,
        "urn:ietf:params:acme:error:badCSR",
    )
    .await;
    assert!(!backend.was_called());
}

/// A common name naming a domain the order does not cover is refused; the leaf
/// would otherwise assert it, since rcgen copies the CSR's whole subject.
#[tokio::test]
async fn a_csr_whose_common_name_names_another_domain_is_refused() {
    let backend = Arc::new(common::RecordingSigner::default());
    let (app, signer, account_url, order_url) =
        setup_ready_order_with_signer(backend.clone()).await;

    let key_pair = rcgen::KeyPair::generate().unwrap();
    let mut params = rcgen::CertificateParams::new(vec!["example.com".to_string()]).unwrap();
    params
        .distinguished_name
        .push(rcgen::DnType::CommonName, "victim.example");
    let csr = BASE64_URL_SAFE_NO_PAD.encode(params.serialize_request(&key_pair).unwrap().der());

    let res = finalize(&app, &signer, &account_url, &order_url, &csr).await;
    assert_problem(
        res,
        StatusCode::BAD_REQUEST,
        "urn:ietf:params:acme:error:badCSR",
    )
    .await;
    assert!(!backend.was_called());
}

/// The subject the local CA actually signs carries no common name at all.
///
/// rcgen's `CertificateSigningRequestParams::from_der` copies the CSR's whole
/// distinguished name into the params it signs, so without an explicit reset
/// the client picks the subject of a certificate this CA vouches for.
#[tokio::test]
async fn the_issued_leaf_carries_no_common_name_from_the_csr() {
    let (app, signer, account_url, order_url) = setup_ready_order().await;

    // A label rather than a domain, so it passes the order-binding check and
    // the only thing that can remove it is the CA's own subject reset.
    let key_pair = rcgen::KeyPair::generate().unwrap();
    let mut params = rcgen::CertificateParams::new(vec!["example.com".to_string()]).unwrap();
    params
        .distinguished_name
        .push(rcgen::DnType::CommonName, "some client label");
    let csr = BASE64_URL_SAFE_NO_PAD.encode(params.serialize_request(&key_pair).unwrap().der());

    let res = finalize(&app, &signer, &account_url, &order_url, &csr).await;
    assert_eq!(res.status(), StatusCode::OK);

    // Issuance is queued work: read the order once the worker has settled it.
    let order = await_order_status(&app, &signer, &account_url, &order_url, "valid").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 chain = body_text(post(&app, path, body).await).await;

    let leaf = acme_proxy_core::cert::leaf_der_from_chain(&chain).unwrap();
    let (_, parsed) = x509_parser::parse_x509_certificate(&leaf).unwrap();
    assert!(
        parsed.subject().iter_common_name().next().is_none(),
        "the CSR's common name must not survive into the signed leaf: {}",
        parsed.subject()
    );
    // The name the order authorized is still asserted, in the SAN where RFC 5280
    // §4.2.1.6 wants it.
    assert!(chain.contains("BEGIN CERTIFICATE"));
}

#[tokio::test]
async fn a_bad_csr_leaves_the_order_finalizable() {
    let (app, signer, account_url, order_url) = setup_ready_order().await;

    let res = finalize(
        &app,
        &signer,
        &account_url,
        &order_url,
        &make_csr("wrong.example.com"),
    )
    .await;
    assert_problem(
        res,
        StatusCode::BAD_REQUEST,
        "urn:ietf:params:acme:error:badCSR",
    )
    .await;

    // The order is untouched and a corrected CSR still works.
    let order = post_as_get(&app, &signer, &account_url, &order_url).await;
    assert_eq!(order["status"], "ready");

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

/// Fetching the certificate before finalizing: there is nothing to serve.
#[tokio::test]
async fn the_certificate_is_not_available_before_finalize() {
    let (app, signer, account_url, order_url) = setup_ready_order().await;
    let id = order_url.rsplit('/').next().unwrap();
    let cert_url = format!("{BASE}/certificate/{id}");

    let nonce = fetch_nonce(&app).await;
    let body = signer.sign_kid_empty(&account_url, &cert_url, &nonce);
    let res = post(&app, &format!("{PREFIX}/certificate/{id}"), body).await;

    assert_problem(
        res,
        StatusCode::BAD_REQUEST,
        "urn:ietf:params:acme:error:malformed",
    )
    .await;
}

/// The order list is per-account: asking for someone else's is unauthorized.
#[tokio::test]
async fn the_order_list_of_another_account_is_unauthorized() {
    let app = test_app().await;
    let signer_a = EcSigner::new();
    let signer_b = EcSigner::new();
    let url_a = register(&app, &signer_a).await;
    let url_b = register(&app, &signer_b).await;

    // A asks for B's order list, signing correctly as itself.
    let orders_url = format!("{url_b}/orders");
    let path = orders_url.strip_prefix(common::HOST).unwrap();
    let nonce = fetch_nonce(&app).await;
    let body = signer_a.sign_kid_empty(&url_a, &orders_url, &nonce);
    let res = post(&app, path, body).await;

    assert_problem(
        res,
        StatusCode::UNAUTHORIZED,
        "urn:ietf:params:acme:error:unauthorized",
    )
    .await;
}

/// A backend that delegates issuance (the `relay` shape) must leave the
/// order `processing` rather than `valid`, and the response must carry the
/// `Retry-After` RFC 8555 §7.4 asks for so the client knows to poll instead of
/// waiting on the request.
#[tokio::test]
async fn finalize_with_a_delegating_signer_leaves_the_order_processing() {
    let (app, _db) = test_app_with_signer(Arc::new(common::DelegatingSigner)).await;
    let signer = EcSigner::new();
    let (account_url, order_url) = ready_order(&app, &signer).await;
    let order_path = order_url.strip_prefix(common::HOST).unwrap();

    // --- finalize: accepted, but not finished ---
    let finalize_url = format!("{order_url}/finalize");
    let nonce = fetch_nonce(&app).await;
    let payload = json!({ "csr": make_csr("example.com") });
    let body = signer.sign_kid(&account_url, &finalize_url, &nonce, &payload);
    let res = post(&app, finalize_url.strip_prefix(common::HOST).unwrap(), body).await;

    assert_eq!(res.status(), StatusCode::OK);
    assert_eq!(
        res.headers()
            .get(axum::http::header::RETRY_AFTER)
            .and_then(|value| value.to_str().ok()),
        Some("5"),
        "a processing order must pace the client's polling"
    );
    let order = body_json(res).await;
    assert_eq!(order["status"], "processing");
    assert!(
        order.get("certificate").is_none(),
        "no certificate exists yet"
    );

    // --- polling the order keeps reporting processing, with the same hint ---
    let nonce = fetch_nonce(&app).await;
    let body = signer.sign_kid_empty(&account_url, &order_url, &nonce);
    let res = post(&app, order_path, body).await;
    assert_eq!(res.status(), StatusCode::OK);
    assert_eq!(
        res.headers()
            .get(axum::http::header::RETRY_AFTER)
            .and_then(|value| value.to_str().ok()),
        Some("5")
    );
    assert_eq!(body_json(res).await["status"], "processing");
}

/// The counterpart: a local CA answers the same way. Signing needs the key,
/// which only the worker holds, so every backend's finalize is `processing` +
/// `Retry-After` — and the certificate follows once the worker has signed it.
#[tokio::test]
async fn finalize_with_a_local_signer_is_queued_too() {
    let app = test_app().await;
    let signer = EcSigner::new();
    let (account_url, order_url) = ready_order(&app, &signer).await;

    let finalize_url = format!("{order_url}/finalize");
    let nonce = fetch_nonce(&app).await;
    let payload = json!({ "csr": make_csr("example.com") });
    let body = signer.sign_kid(&account_url, &finalize_url, &nonce, &payload);
    let res = post(&app, finalize_url.strip_prefix(common::HOST).unwrap(), body).await;

    assert_eq!(res.status(), StatusCode::OK);
    assert_eq!(
        res.headers()
            .get(axum::http::header::RETRY_AFTER)
            .and_then(|value| value.to_str().ok()),
        Some("5"),
        "a processing order must pace the client's polling"
    );
    let order = body_json(res).await;
    assert_eq!(order["status"], "processing");
    assert!(order.get("certificate").is_none());

    let order = await_order_status(&app, &signer, &account_url, &order_url, "valid").await;
    assert!(order["certificate"].as_str().is_some());
}

/// Two authorizations of one order validated concurrently must both land, and
/// the order must reach `ready`.
///
/// The readiness check used to re-read the authorizations from the pool *after*
/// its own write had committed, so two validations racing could each read before
/// the other's write landed: neither would see a complete set, neither would
/// promote, and the order would sit `pending` with every authorization `valid`
/// and no challenge left to trigger — stuck until it expired. Reading inside the
/// transaction that just wrote is what fixes it.
#[tokio::test]
async fn concurrent_validations_of_one_order_still_promote_it() {
    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": "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 authz_urls = order_authz_urls(&app, &signer, &account_url, &order_url).await;
    assert_eq!(authz_urls.len(), 2);

    // Both triggers are signed up front — each needs its own nonce, and getting
    // one is itself a request — then fired together.
    let mut bodies = Vec::new();
    for authz_url in &authz_urls {
        let challenge_url = first_challenge_url(&app, &signer, &account_url, authz_url).await;
        let path = challenge_url
            .strip_prefix(common::HOST)
            .unwrap()
            .to_string();
        let nonce = fetch_nonce(&app).await;
        let body = signer.sign_kid(&account_url, &challenge_url, &nonce, &json!({}));
        bodies.push((path, body));
    }

    let (first, second) = tokio::join!(
        post(&app, &bodies[0].0, bodies[0].1.clone()),
        post(&app, &bodies[1].0, bodies[1].1.clone()),
    );
    assert_eq!(first.status(), StatusCode::OK);
    assert_eq!(second.status(), StatusCode::OK);

    // Both verdicts land in the job runner, so the promotion — which is what
    // this test is about — happens there rather than in either request.
    let order = await_order_status(&app, &signer, &account_url, &order_url, "ready").await;
    assert_eq!(
        order["status"], "ready",
        "both authorizations are valid, so the order must be ready: {order}"
    );
}

/// A requested `notAfter` reaches the **issued certificate**, not just the
/// order object.
///
/// `new_order_accepts_and_echoes_requested_validity_bounds` above proves the
/// echo, and `LocalCa`'s own tests prove the clamp. Neither covers the wiring
/// between them, and that is precisely where the bug was: `signer/mod.rs`
/// records that these fields "were stored and echoed in the order object while
/// being dropped on the way to the signer". Replacing the handler's
/// `RequestedValidity { .. }` with `::default()` passes every other test in the
/// repository.
#[tokio::test]
async fn a_requested_not_after_reaches_the_issued_certificate() {
    let app = test_app().await;
    let signer = EcSigner::new();
    let account_url = common::acme::register(&app, &signer).await;

    // Seven days out — well inside the CA's 90-day default, so the clamp
    // narrows to this rather than ignoring it.
    let requested_not_after = time::OffsetDateTime::now_utc() + time::Duration::days(7);
    let not_after = requested_not_after
        .format(&time::format_description::well_known::Rfc3339)
        .unwrap();

    let nonce = fetch_nonce(&app).await;
    let payload = json!({
        "identifiers": [{ "type": "dns", "value": "example.com" }],
        "notAfter": not_after,
    });
    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 = body_json(res).await;

    common::acme::drive_to_ready(&app, &signer, &account_url, &order).await;
    let order = common::acme::post_as_get(&app, &signer, &account_url, &order_url).await;

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

    // Issuance is queued work: read the order once the worker has settled it.
    let order = common::acme::await_order(&app, &signer, &account_url, &order_url).await;
    let certificate_url = order["certificate"].as_str().unwrap().to_string();
    let nonce = fetch_nonce(&app).await;
    let body = signer.sign_kid_empty(&account_url, &certificate_url, &nonce);
    let res = post(&app, &common::acme::path_of(&certificate_url), body).await;
    assert_eq!(res.status(), StatusCode::OK);
    let chain = common::acme::body_text(res).await;

    let leaf = acme_proxy_core::cert::leaf_der_from_chain(&chain).unwrap();
    let (_not_before, cert_not_after) = acme_proxy_core::cert::cert_validity(&leaf).unwrap();

    // To the second: the clamp narrows to exactly what was asked for when the
    // request is inside the CA's own window.
    assert_eq!(
        cert_not_after,
        requested_not_after.unix_timestamp(),
        "the certificate's notAfter must be the one the order asked for, \
         not the CA's 90-day default"
    );
}

/// The converse, so the test above cannot pass by the signer simply honouring
/// whatever it is handed: a `notAfter` *beyond* the CA's own window is clamped
/// back to it rather than widening it.
#[tokio::test]
async fn a_not_after_beyond_the_ca_window_is_clamped_rather_than_honoured() {
    let app = test_app().await;
    let signer = EcSigner::new();
    let account_url = common::acme::register(&app, &signer).await;

    let far_future = time::OffsetDateTime::now_utc() + time::Duration::days(3650);
    let nonce = fetch_nonce(&app).await;
    let payload = json!({
        "identifiers": [{ "type": "dns", "value": "example.com" }],
        "notAfter": far_future
            .format(&time::format_description::well_known::Rfc3339)
            .unwrap(),
    });
    let body = signer.sign_kid(&account_url, NEW_ORDER_URL, &nonce, &payload);
    let res = post(&app, &p("/newOrder"), body).await;
    let order_url = res
        .headers()
        .get("location")
        .and_then(|v| v.to_str().ok())
        .unwrap()
        .to_string();
    let order = body_json(res).await;

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

    // Issuance is queued work: read the order once the worker has settled it.
    let order = common::acme::await_order(&app, &signer, &account_url, &order_url).await;
    let certificate_url = order["certificate"].as_str().unwrap().to_string();
    let nonce = fetch_nonce(&app).await;
    let body = signer.sign_kid_empty(&account_url, &certificate_url, &nonce);
    let res = post(&app, &common::acme::path_of(&certificate_url), body).await;
    let chain = common::acme::body_text(res).await;

    let leaf = acme_proxy_core::cert::leaf_der_from_chain(&chain).unwrap();
    let (_not_before, cert_not_after) = acme_proxy_core::cert::cert_validity(&leaf).unwrap();

    assert!(
        cert_not_after < far_future.unix_timestamp(),
        "a request may narrow the CA's window, never widen it"
    );
}

/// A CSR whose own signature does not verify is refused as `badCSR`.
///
/// This is proof of possession (RFC 8555 §11.1), and it is the check standing
/// between "I can prove control of a name" and "I can have a certificate for a
/// key I do not hold". Without it an attacker who completed a challenge —
/// legitimately, for their own domain — could submit a CSR carrying *somebody
/// else's* public key and be handed a certificate for it.
///
/// The eight other `badCSR` cases in this suite and in `tests/filters.rs` cover
/// identifiers, SAN types, `CA:TRUE` and unparsable DER; none of them covers a
/// CSR that parses cleanly and is simply not signed by the key it names. The
/// check is implicit — it lives inside `rcgen`'s
/// `CertificateSigningRequestParams::from_der` — so an upgrade that relaxed it
/// would be invisible here. Hence a test that asserts the behaviour rather than
/// trusting the dependency.
///
/// The last byte of the DER is inside the signature `BIT STRING`, which is what
/// makes flipping it a signature failure and not a structural one.
#[tokio::test]
async fn a_csr_whose_self_signature_does_not_verify_is_bad_csr() {
    let (app, signer, account_url, order_url) = setup_ready_order().await;

    let (csr_b64, _key) = common::make_csr_and_keypair("example.com");
    let mut der = BASE64_URL_SAFE_NO_PAD.decode(&csr_b64).unwrap();
    let last = der.len() - 1;
    der[last] ^= 0xff;
    let tampered = BASE64_URL_SAFE_NO_PAD.encode(&der);

    let res = finalize(&app, &signer, &account_url, &order_url, &tampered).await;
    assert_eq!(res.status(), StatusCode::BAD_REQUEST);
    assert_eq!(
        body_json(res).await["type"],
        "urn:ietf:params:acme:error:badCSR"
    );

    // The order is still finalizable: §7.4 says a rejected CSR leaves it
    // `ready`, and the untampered CSR for the same key goes straight through.
    let res = finalize(&app, &signer, &account_url, &order_url, &csr_b64).await;
    assert_eq!(
        res.status(),
        StatusCode::OK,
        "a refused CSR must not have consumed the order"
    );
}

/// The certificate URL is not readable by another account either.
///
/// `post_as_get_rejects_different_account` covers the *order*, and this suite
/// covers the authorization and the challenge the same way. The one route none
/// of them covers is `/certificate/{id}` — which is the only one that returns
/// the PEM, and therefore the highest-value target of the four.
///
/// The behaviour is almost certainly right by construction (`post_certificate`
/// goes through the shared `load_owned_order`), and the point of the test is
/// exactly that: nothing was asserting it, so a future route that resolved the
/// certificate directly rather than through the order would take the check with
/// it and nothing would fail.
///
/// `malformed` "Unknown order" specifically, not merely "not 200": the same
/// answer an id that never existed gets, so the refusal says nothing about
/// whether the certificate is there (`acme::access`'s module doc).
#[tokio::test]
async fn the_certificate_of_another_account_is_unknown() {
    let (app, owner, owner_url, order_url) = setup_ready_order().await;

    let res = finalize(
        &app,
        &owner,
        &owner_url,
        &order_url,
        &make_csr("example.com"),
    )
    .await;
    assert_eq!(res.status(), StatusCode::OK);
    let certificate_url =
        await_order_status(&app, &owner, &owner_url, &order_url, "valid").await["certificate"]
            .as_str()
            .expect("a finalized order carries its certificate URL")
            .to_string();
    let certificate_path = certificate_url.strip_prefix(common::HOST).unwrap();

    // The owner can read it, so the refusal below is about *who is asking*.
    let nonce = fetch_nonce(&app).await;
    let body = owner.sign_kid_empty(&owner_url, &certificate_url, &nonce);
    assert_eq!(
        post(&app, certificate_path, body).await.status(),
        StatusCode::OK
    );

    let intruder = EcSigner::new();
    let intruder_url = register(&app, &intruder).await;
    let nonce = fetch_nonce(&app).await;
    let body = intruder.sign_kid_empty(&intruder_url, &certificate_url, &nonce);
    assert_problem(
        post(&app, certificate_path, body).await,
        StatusCode::BAD_REQUEST,
        "urn:ietf:params:acme:error:malformed",
    )
    .await;
}