postrust-proxy 2.0.0

Reverse proxy for Postrust with load balancing and automatic TLS certificates
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
//! The SaaS control plane, driven through `saas_router` against PostgreSQL.
//!
//! Each test here is one of the ways a tenant could reach past its own
//! credential, its own names or the network it was meant to stay out of, and
//! checks it is refused through the router a deployment actually mounts --
//! not through the function underneath, which can be right while the handler
//! forgets to call it.
//!
//! These need a live PostgreSQL, so they are `#[ignore]`d:
//!
//!     DATABASE_URL=postgres://postgres:postgres@localhost:5432/postrust_test \
//!         cargo test -p postrust-proxy --test control_plane -- --ignored
//!
//! Every test applies the migrations itself (see `tests/config_persistence.rs`
//! for why under a lock), creates its own tenants, and names its domains with
//! a fresh UUID, so the file runs in parallel with itself and against a
//! database other runs have used.

use axum::body::Body;
use axum::http::{Request, StatusCode};
use http_body_util::BodyExt;
use postrust_proxy::saas::api_keys::hash_api_key;
use postrust_proxy::saas::handlers::{saas_router, SaasState};
use postrust_proxy::saas::{ReservedDomains, SaasOptions, UploadTrust};
use serde_json::{json, Value};
use sqlx::{AssertSqlSafe, Executor, PgPool};
use std::sync::Arc;
use tower::ServiceExt;
use uuid::Uuid;

const MIGRATIONS: [&str; 4] = [
    include_str!("../migrations/20240115000001_saas_domains.sql"),
    include_str!("../migrations/20260901000001_proxy_config.sql"),
    include_str!("../migrations/20260901000002_proxy_acme.sql"),
    include_str!("../migrations/20261030000001_proxy_control_plane.sql"),
];

/// See `tests/config_persistence.rs` for why the migration is locked.
const MIGRATION_LOCK: i64 = 0x706f7374_72757374;

const JWT_SECRET: &str = "control-plane-test-secret";

/// Connect, with the schema in place.
///
/// The migrations are applied once per process, not once per test. They
/// re-run cleanly, but re-running takes table locks -- `DROP TRIGGER` in the
/// first migration is ACCESS EXCLUSIVE -- that deadlock with the transactions
/// of the tests already running alongside.
async fn migrated_pool() -> PgPool {
    static MIGRATED: tokio::sync::OnceCell<()> = tokio::sync::OnceCell::const_new();

    let url = std::env::var("DATABASE_URL")
        .expect("DATABASE_URL must be set for the database-backed tests");
    let pool = PgPool::connect(&url)
        .await
        .expect("could not connect to DATABASE_URL");

    MIGRATED
        .get_or_init(|| async {
            let mut tx = pool.begin().await.expect("begin");
            sqlx::query("SELECT pg_advisory_xact_lock($1)")
                .bind(MIGRATION_LOCK)
                .execute(&mut *tx)
                .await
                .expect("migration lock");
            for migration in MIGRATIONS {
                (&mut *tx)
                    .execute(migration)
                    .await
                    .expect("could not apply a migration");
            }
            tx.commit().await.expect("commit");
        })
        .await;
    pool
}

/// The router, its pool, and where its certificate store keeps files.
struct Harness {
    app: axum::Router,
    pool: PgPool,
    cert_dir: std::path::PathBuf,
}

impl Harness {
    async fn new() -> Self {
        Self::with(|_| {}).await
    }

    async fn with(configure: impl FnOnce(&mut SaasOptions)) -> Self {
        let pool = migrated_pool().await;
        let mut options = SaasOptions::default();
        options.jwt_secret = Some(JWT_SECRET.to_string());
        configure(&mut options);
        Self::on(pool, options).await
    }

    async fn on(pool: PgPool, options: SaasOptions) -> Self {
        let cert_dir = std::env::temp_dir().join(format!("postrust-cp-{}", Uuid::new_v4()));
        let state = SaasState::with_options(pool.clone(), options, &cert_dir)
            .await
            .expect("saas state");
        Self {
            app: saas_router(state),
            pool,
            cert_dir,
        }
    }

    /// A fresh active tenant.
    async fn tenant(&self) -> Uuid {
        sqlx::query_scalar(
            "INSERT INTO proxy_tenants (name, slug, email) VALUES ('cp', $1, 'cp@postrust.invalid') \
             RETURNING id",
        )
        .bind(format!("cp-{}", Uuid::new_v4()))
        .fetch_one(&self.pool)
        .await
        .expect("insert tenant")
    }

    /// An API key for `tenant` with exactly these scopes, written directly so
    /// the test does not depend on the endpoint it may be testing.
    async fn key(&self, tenant: Uuid, scopes: &[&str]) -> String {
        let raw = format!("pr_test_{}", Uuid::new_v4().simple());
        let scopes: Vec<String> = scopes.iter().map(|s| s.to_string()).collect();
        sqlx::query(
            "INSERT INTO proxy_api_keys (tenant_id, name, key_hash, key_prefix, scopes) \
             VALUES ($1, 'test', $2, $3, $4)",
        )
        .bind(tenant)
        .bind(hash_api_key(&raw))
        .bind(&raw[..8])
        .bind(&scopes)
        .execute(&self.pool)
        .await
        .expect("insert key");
        format!("ApiKey {raw}")
    }

    async fn call(
        &self,
        method: &str,
        path: &str,
        auth: &str,
        body: Option<Value>,
    ) -> (StatusCode, Value) {
        self.request(method, path, &[("authorization", auth)], body)
            .await
    }

    async fn request(
        &self,
        method: &str,
        path: &str,
        headers: &[(&str, &str)],
        body: Option<Value>,
    ) -> (StatusCode, Value) {
        let mut builder = Request::builder().method(method).uri(path);
        for (name, value) in headers {
            builder = builder.header(*name, *value);
        }
        let request = match body {
            Some(body) => builder
                .header("content-type", "application/json")
                .body(Body::from(body.to_string())),
            None => builder.body(Body::empty()),
        }
        .unwrap();

        let response = self.app.clone().oneshot(request).await.unwrap();
        let status = response.status();
        let bytes = response.into_body().collect().await.unwrap().to_bytes();
        let value = serde_json::from_slice(&bytes)
            .unwrap_or_else(|_| Value::String(String::from_utf8_lossy(&bytes).into_owned()));
        (status, value)
    }

    /// Register a domain through the API and return its id and token.
    async fn domain(&self, key: &str, name: &str) -> (Uuid, String) {
        let (status, body) = self
            .call(
                "POST",
                "/api/v1/domains",
                key,
                Some(json!({ "domain": name })),
            )
            .await;
        assert_eq!(status, StatusCode::CREATED, "{body}");
        (
            body["data"]["id"].as_str().unwrap().parse().unwrap(),
            body["data"]["verification_token"]
                .as_str()
                .unwrap()
                .to_string(),
        )
    }

    /// Mark a domain verified, as a successful check would.
    async fn verify(&self, id: Uuid) {
        sqlx::query(
            "UPDATE proxy_domains SET verification_status = 'verified', verified_at = NOW() \
             WHERE id = $1",
        )
        .bind(id)
        .execute(&self.pool)
        .await
        .unwrap();
    }

    async fn upstream(&self, key: &str) -> Uuid {
        let (status, body) = self
            .call(
                "POST",
                "/api/v1/upstreams",
                key,
                Some(json!({ "name": unique("up") })),
            )
            .await;
        assert_eq!(status, StatusCode::CREATED, "{body}");
        body["data"]["id"].as_str().unwrap().parse().unwrap()
    }
}

fn unique(prefix: &str) -> String {
    format!("{prefix}-{}", Uuid::new_v4().simple())
}

fn name() -> String {
    format!("{}.test", unique("d"))
}

const ALL: &[&str] = &["*"];

// ---------------------------------------------------------------------------
// 1. API-key endpoints are scoped, and a key cannot mint more than it holds.
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn api_key_endpoints_need_api_key_scopes() {
    let h = Harness::new().await;
    let t = h.tenant().await;
    let other = h.key(t, ALL).await;
    let other_id: Uuid = sqlx::query_scalar(
        "SELECT id FROM proxy_api_keys WHERE tenant_id = $1 ORDER BY created_at LIMIT 1",
    )
    .bind(t)
    .fetch_one(&h.pool)
    .await
    .unwrap();

    for scopes in [
        &["domains:read"][..],
        &[],
        &["domains:write", "upstreams:write"],
    ] {
        let key = h.key(t, scopes).await;
        let (status, body) = h
            .call(
                "POST",
                "/api/v1/auth/api-keys",
                &key,
                Some(json!({ "name": "x", "scopes": ["*"] })),
            )
            .await;
        assert_eq!(
            status,
            StatusCode::FORBIDDEN,
            "{scopes:?} created a key: {body}"
        );
        assert_eq!(body["code"], "insufficient_scope");

        let (status, _) = h.call("GET", "/api/v1/auth/api-keys", &key, None).await;
        assert_eq!(status, StatusCode::FORBIDDEN, "{scopes:?} listed keys");

        let (status, _) = h
            .call(
                "DELETE",
                &format!("/api/v1/auth/api-keys/{other_id}"),
                &key,
                None,
            )
            .await;
        assert_eq!(status, StatusCode::FORBIDDEN, "{scopes:?} revoked a key");
    }

    // The `*` key is still there and still works.
    let (status, _) = h.call("GET", "/api/v1/auth/api-keys", &other, None).await;
    assert_eq!(status, StatusCode::OK);
}

#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn a_key_cannot_grant_more_than_it_holds() {
    let h = Harness::new().await;
    let t = h.tenant().await;
    let narrow = h.key(t, &["api_keys:write", "domains:read"]).await;

    for scopes in [
        json!(["*"]),
        json!(["domains:write"]),
        json!(["routes:read"]),
    ] {
        let (status, body) = h
            .call(
                "POST",
                "/api/v1/auth/api-keys",
                &narrow,
                Some(json!({ "name": "escalate", "scopes": scopes })),
            )
            .await;
        assert_eq!(
            status,
            StatusCode::FORBIDDEN,
            "{scopes} was granted: {body}"
        );
    }

    // The default scopes include domains:write, which this key lacks.
    let (status, _) = h
        .call(
            "POST",
            "/api/v1/auth/api-keys",
            &narrow,
            Some(json!({ "name": "default" })),
        )
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);

    // A subset is fine, and the new key has exactly what was asked for.
    let (status, body) = h
        .call(
            "POST",
            "/api/v1/auth/api-keys",
            &narrow,
            Some(json!({ "name": "subset", "scopes": ["domains:read"] })),
        )
        .await;
    assert_eq!(status, StatusCode::CREATED, "{body}");
    assert_eq!(body["data"]["scopes"], json!(["domains:read"]));
    let minted = format!("ApiKey {}", body["data"]["key"].as_str().unwrap());
    let (status, _) = h.call("GET", "/api/v1/domains", &minted, None).await;
    assert_eq!(status, StatusCode::OK);
    let (status, _) = h.call("GET", "/api/v1/upstreams", &minted, None).await;
    assert_eq!(status, StatusCode::FORBIDDEN);

    // Unknown scopes are refused as invalid, for every caller.
    let star = h.key(t, ALL).await;
    for key in [&narrow, &star] {
        let (status, body) = h
            .call(
                "POST",
                "/api/v1/auth/api-keys",
                key,
                Some(json!({ "name": "typo", "scopes": ["domain:read"] })),
            )
            .await;
        assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
        assert_eq!(body["code"], "validation_failed");
    }

    // Only `*` mints `*`.
    let (status, _) = h
        .call(
            "POST",
            "/api/v1/auth/api-keys",
            &star,
            Some(json!({ "name": "star", "scopes": ["*"] })),
        )
        .await;
    assert_eq!(status, StatusCode::CREATED);
}

#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn a_narrow_key_cannot_revoke_a_broader_one() {
    let h = Harness::new().await;
    let t = h.tenant().await;
    let star = h.key(t, ALL).await;
    let narrow = h.key(t, &["api_keys:write"]).await;

    let (_, body) = h.call("GET", "/api/v1/auth/api-keys", &star, None).await;
    let keys = body["data"].as_array().unwrap();
    let id_of = |scope: &str| {
        keys.iter().find(|k| k["scopes"] == json!([scope])).unwrap()["id"]
            .as_str()
            .unwrap()
            .to_string()
    };
    let (star_id, narrow_id) = (id_of("*"), id_of("api_keys:write"));

    let (status, _) = h
        .call(
            "DELETE",
            &format!("/api/v1/auth/api-keys/{star_id}"),
            &narrow,
            None,
        )
        .await;
    assert_eq!(
        status,
        StatusCode::FORBIDDEN,
        "a narrow key revoked the * key"
    );

    let (status, _) = h
        .call(
            "DELETE",
            &format!("/api/v1/auth/api-keys/{narrow_id}"),
            &star,
            None,
        )
        .await;
    assert_eq!(status, StatusCode::OK);
}

// ---------------------------------------------------------------------------
// 2. Every read checks its scope.
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn every_read_needs_its_scope() {
    let h = Harness::new().await;
    let t = h.tenant().await;
    let star = h.key(t, ALL).await;
    let (domain, _) = h.domain(&star, &name()).await;
    let upstream = h.upstream(&star).await;
    let anything = Uuid::new_v4();

    let reads = [
        ("/api/v1/domains".to_string(), "domains:read"),
        (format!("/api/v1/domains/{domain}"), "domains:read"),
        (format!("/api/v1/domains/{domain}/routes"), "routes:read"),
        (
            format!("/api/v1/domains/{domain}/routes/{anything}"),
            "routes:read",
        ),
        ("/api/v1/upstreams".to_string(), "upstreams:read"),
        (format!("/api/v1/upstreams/{upstream}"), "upstreams:read"),
        ("/api/v1/tenant/me".to_string(), "tenant:read"),
        ("/api/v1/tenant/usage".to_string(), "tenant:read"),
        ("/api/v1/auth/api-keys".to_string(), "api_keys:read"),
    ];

    let none = h.key(t, &[]).await;
    for (path, scope) in &reads {
        let (status, body) = h.call("GET", path, &none, None).await;
        assert_eq!(
            status,
            StatusCode::FORBIDDEN,
            "GET {path} with no scopes: {body}"
        );
        assert!(
            body.get("data").is_none(),
            "GET {path} returned data with no scopes"
        );

        // The scope it needs is enough, or the 404 a missing row gets.
        let key = h.key(t, &[scope]).await;
        let (status, _) = h.call("GET", path, &key, None).await;
        assert!(
            status == StatusCode::OK || status == StatusCode::NOT_FOUND,
            "GET {path} with {scope}: {status}"
        );
    }

    // Reading one resource does not read the others.
    let domains_only = h.key(t, &["domains:read"]).await;
    for path in ["/api/v1/upstreams", "/api/v1/tenant/usage"] {
        let (status, _) = h.call("GET", path, &domains_only, None).await;
        assert_eq!(status, StatusCode::FORBIDDEN, "{path}");
    }
    let (status, _) = h
        .call(
            "GET",
            &format!("/api/v1/domains/{domain}/routes"),
            &domains_only,
            None,
        )
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

// ---------------------------------------------------------------------------
// 3. A domain is one name, whatever its case.
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn a_case_variant_of_an_owned_domain_is_refused() {
    let h = Harness::new().await;
    let owner = h.key(h.tenant().await, ALL).await;
    let squatter = h.key(h.tenant().await, ALL).await;

    let victim = name();
    let (status, body) = h
        .call(
            "POST",
            "/api/v1/domains",
            &owner,
            Some(json!({ "domain": victim, "verification_method": "http" })),
        )
        .await;
    assert_eq!(status, StatusCode::CREATED, "{body}");
    let owner_token = body["data"]["verification_token"]
        .as_str()
        .unwrap()
        .to_string();

    for variant in [
        victim.to_uppercase(),
        format!("{victim}."),
        format!("{}.", victim.to_uppercase()),
    ] {
        let (status, body) = h
            .call(
                "POST",
                "/api/v1/domains",
                &squatter,
                Some(json!({ "domain": variant })),
            )
            .await;
        assert_eq!(
            status,
            StatusCode::CONFLICT,
            "{variant} was registered: {body}"
        );
        assert_eq!(body["code"], "conflict");
    }

    // The only challenge answerable on the victim's host is the owner's.
    let (status, body) = h
        .request(
            "GET",
            &format!("/.well-known/postrust-verification/{owner_token}"),
            &[("host", &victim.to_uppercase())],
            None,
        )
        .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(
        body,
        Value::String(format!("postrust-verify={owner_token}"))
    );
}

#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn domains_are_stored_normalised() {
    let h = Harness::new().await;
    let key = h.key(h.tenant().await, ALL).await;
    let base = name();

    let (status, body) = h
        .call(
            "POST",
            "/api/v1/domains",
            &key,
            Some(json!({ "domain": format!("{}.", base.to_uppercase()) })),
        )
        .await;
    assert_eq!(status, StatusCode::CREATED, "{body}");
    assert_eq!(body["data"]["domain"], base);
}

#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn names_that_are_not_public_domains_are_refused() {
    let h = Harness::new().await;
    let key = h.key(h.tenant().await, ALL).await;

    for (domain, hint) in [
        ("bücher.test", "punycode"),
        ("127.0.0.1", "IP"),
        ("[::1]", "IP"),
        ("::1", "IP"),
        ("intranet", "two labels"),
        ("a_b.test", "letters"),
        ("127.1", "numeric"),
        ("api.localhost", "reserved"),
        ("metadata.google.internal", "reserved"),
    ] {
        let (status, body) = h
            .call(
                "POST",
                "/api/v1/domains",
                &key,
                Some(json!({ "domain": domain })),
            )
            .await;
        assert_eq!(
            status,
            StatusCode::BAD_REQUEST,
            "{domain} was accepted: {body}"
        );
        let error = body["error"].as_str().unwrap();
        assert!(error.contains(hint), "{domain}: {error}");
    }
}

#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn the_database_refuses_a_case_duplicate_written_directly() {
    let h = Harness::new().await;
    let t = h.tenant().await;
    let base = name();
    for domain in [base.clone(), base.to_uppercase()] {
        let inserted = sqlx::query(
            "INSERT INTO proxy_domains (tenant_id, domain, verification_token) VALUES ($1, $2, 't')",
        )
        .bind(t)
        .bind(&domain)
        .execute(&h.pool)
        .await;
        if domain == base {
            inserted.expect("the first insert");
        } else {
            let error = inserted.expect_err("a case duplicate was inserted");
            let db = error.as_database_error().expect("a database error");
            assert_eq!(db.kind(), sqlx::error::ErrorKind::UniqueViolation);
        }
    }
}

/// The migration's handling of rows that already collide, run in a schema of
/// its own so the index on the shared tables is not disturbed.
#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn the_migration_keeps_the_verified_row_of_a_case_collision() {
    use sqlx::Connection;
    let url = std::env::var("DATABASE_URL").unwrap();
    let mut conn = sqlx::PgConnection::connect(&url).await.unwrap();
    let schema = format!("cp_{}", Uuid::new_v4().simple());

    conn.execute(AssertSqlSafe(format!(
        "CREATE SCHEMA {schema}; SET search_path TO {schema}"
    )))
    .await
    .unwrap();
    // The first migration alters proxy_certificates if a table of that name
    // exists anywhere; give it one here, shaped as a pre-ACME install had it.
    conn.execute(
        "CREATE TABLE proxy_certificates (domain VARCHAR(253) PRIMARY KEY, cert_pem BYTEA NOT NULL, \
         key_pem BYTEA NOT NULL, expires_at TIMESTAMPTZ, \
         created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW())",
    )
    .await
    .unwrap();
    for migration in &MIGRATIONS[..3] {
        conn.execute(*migration).await.unwrap();
    }

    let tenant: Uuid = sqlx::query_scalar(
        "INSERT INTO proxy_tenants (name, slug, email) VALUES ('m', 'm', 'm@x') RETURNING id",
    )
    .fetch_one(&mut conn)
    .await
    .unwrap();
    let insert = |domain: &'static str, status: &'static str, age: i32| {
        sqlx::query_scalar::<_, Uuid>(
            "INSERT INTO proxy_domains (tenant_id, domain, verification_token, verification_status, \
             verified_at, created_at) \
             VALUES ($1, $2, 't', $3, CASE WHEN $3 = 'verified' THEN NOW() END, \
                     NOW() - make_interval(days => $4)) RETURNING id",
        )
        .bind(tenant)
        .bind(domain)
        .bind(status)
        .bind(age)
    };
    // Registered first, never verified.
    let first = insert("dup.test", "pending", 3)
        .fetch_one(&mut conn)
        .await
        .unwrap();
    // Registered later by someone else, but verified: this one proved control.
    let verified = insert("Dup.test", "verified", 2)
        .fetch_one(&mut conn)
        .await
        .unwrap();
    let third = insert("DUP.TEST", "pending", 1)
        .fetch_one(&mut conn)
        .await
        .unwrap();
    let unrelated = insert("other.test", "pending", 1)
        .fetch_one(&mut conn)
        .await
        .unwrap();

    conn.execute(MIGRATIONS[3]).await.unwrap();
    // And again: it has to be safe to re-run.
    conn.execute(MIGRATIONS[3]).await.unwrap();

    let left: Vec<Uuid> = sqlx::query_scalar("SELECT id FROM proxy_domains ORDER BY domain")
        .fetch_all(&mut conn)
        .await
        .unwrap();
    assert_eq!(left, vec![verified, unrelated]);

    let removed: Vec<(Uuid, Uuid)> = sqlx::query_as(
        "SELECT removed_domain_id, kept_domain_id FROM proxy_domain_case_conflicts \
         ORDER BY removed_domain_id",
    )
    .fetch_all(&mut conn)
    .await
    .unwrap();
    let mut expected = vec![(first, verified), (third, verified)];
    expected.sort();
    assert_eq!(removed, expected);

    let duplicate = insert("dUP.test", "pending", 0).fetch_one(&mut conn).await;
    assert!(
        duplicate.is_err(),
        "the index does not refuse a case duplicate"
    );

    conn.execute(AssertSqlSafe(format!("DROP SCHEMA {schema} CASCADE")))
        .await
        .unwrap();
}

// ---------------------------------------------------------------------------
// 4. Certificates need a verified, unreserved domain and a trusted chain;
//    a pending registration does not hold a name for ever.
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn reserved_names_cannot_be_registered() {
    let platform = format!("{}.example", unique("platform"));
    let api = format!("api.{}.example", unique("other"));
    let (p, a) = (platform.clone(), api.clone());
    let h = Harness::with(move |o| {
        o.domains.reserved = ReservedDomains::default().with_suffix(&p).with_exact(&a);
    })
    .await;
    let key = h.key(h.tenant().await, ALL).await;

    for domain in [
        platform.clone(),
        format!("app.{platform}"),
        platform.to_uppercase(),
        api.clone(),
    ] {
        let (status, body) = h
            .call(
                "POST",
                "/api/v1/domains",
                &key,
                Some(json!({ "domain": domain })),
            )
            .await;
        assert_eq!(status, StatusCode::BAD_REQUEST, "{domain}: {body}");
        assert!(body["error"].as_str().unwrap().contains("reserved"));
    }

    // An exact reservation does not cover its subdomains.
    let (status, _) = h
        .call(
            "POST",
            "/api/v1/domains",
            &key,
            Some(json!({ "domain": format!("x.{api}") })),
        )
        .await;
    assert_eq!(status, StatusCode::CREATED);
}

const LEAF: &str = include_str!("testdata/leaf.pem");
const LEAF_KEY: &str = include_str!("testdata/leaf.key.pem");
const CA: &str = include_str!("testdata/ca.pem");
const SELF_SIGNED: &str = include_str!("testdata/selfsigned.pem");
const SELF_SIGNED_KEY: &str = include_str!("testdata/selfsigned.key.pem");
/// The name the fixtures cover. Shared, so exactly one test uses it.
const UPLOAD_DOMAIN: &str = "upload-chain.test";

fn private_roots() -> Arc<rustls::RootCertStore> {
    let mut roots = rustls::RootCertStore::empty();
    for cert in rustls_pemfile::certs(&mut CA.as_bytes()) {
        roots.add(cert.unwrap()).unwrap();
    }
    Arc::new(roots)
}

#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn certificate_upload_needs_a_verified_domain_and_a_trusted_chain() {
    let h = Harness::with(|o| o.domains.upload_trust = UploadTrust::Roots(private_roots())).await;
    sqlx::query("DELETE FROM proxy_domains WHERE lower(domain) = $1")
        .bind(UPLOAD_DOMAIN)
        .execute(&h.pool)
        .await
        .unwrap();
    sqlx::query("DELETE FROM proxy_certificates WHERE domain = $1")
        .bind(UPLOAD_DOMAIN)
        .execute(&h.pool)
        .await
        .unwrap();

    let t = h.tenant().await;
    let key = h.key(t, ALL).await;
    let (id, _) = h.domain(&key, UPLOAD_DOMAIN).await;
    let upload = |cert: &str, key_pem: &str| json!({ "cert_pem": cert, "key_pem": key_pem });
    let path = format!("/api/v1/domains/{id}/ssl/upload");
    let chain = format!("{LEAF}{CA}");

    // Unverified: refused, however good the certificate.
    let (status, body) = h
        .call("POST", &path, &key, Some(upload(&chain, LEAF_KEY)))
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
    assert!(body["error"].as_str().unwrap().contains("verified"));
    let stored: i64 =
        sqlx::query_scalar("SELECT COUNT(*) FROM proxy_certificates WHERE domain = $1")
            .bind(UPLOAD_DOMAIN)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(
        stored, 0,
        "an unverified domain's certificate reached the store"
    );

    // Nor may it carry routes.
    let upstream = h.upstream(&key).await;
    let (status, _) = h
        .call(
            "POST",
            &format!("/api/v1/domains/{id}/routes"),
            &key,
            Some(json!({ "name": "r", "upstream_id": upstream })),
        )
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);

    h.verify(id).await;

    // Verified, but self-signed: trusted by nobody.
    let (status, body) = h
        .call(
            "POST",
            &path,
            &key,
            Some(upload(SELF_SIGNED, SELF_SIGNED_KEY)),
        )
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
    assert!(body["error"].as_str().unwrap().contains("not trusted"));

    // Under the public roots, the private CA's leaf is refused too.
    let public = Harness::on(h.pool.clone(), SaasOptions::default()).await;
    let (status, _) = public
        .call("POST", &path, &key, Some(upload(&chain, LEAF_KEY)))
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);

    // With the private root trusted, the chain is accepted, stored, and
    // linked to its domain.
    let (status, body) = h
        .call("POST", &path, &key, Some(upload(&chain, LEAF_KEY)))
        .await;
    assert_eq!(status, StatusCode::OK, "{body}");
    let linked: Option<Uuid> =
        sqlx::query_scalar("SELECT domain_id FROM proxy_certificates WHERE domain = $1")
            .bind(UPLOAD_DOMAIN)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(linked, Some(id));
    let key_file = h.cert_dir.join(format!("{UPLOAD_DOMAIN}.key"));
    assert!(key_file.exists(), "the store did not cache the key");

    // Deleting the domain takes the certificate and its cached key with it.
    let (status, _) = h
        .call("DELETE", &format!("/api/v1/domains/{id}"), &key, None)
        .await;
    assert_eq!(status, StatusCode::OK);
    let stored: i64 =
        sqlx::query_scalar("SELECT COUNT(*) FROM proxy_certificates WHERE domain = $1")
            .bind(UPLOAD_DOMAIN)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(stored, 0, "the certificate outlived its domain");
    assert!(
        !key_file.exists(),
        "the private key outlived its domain on disk"
    );
}

#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn a_stale_pending_registration_stops_holding_its_name() {
    let h = Harness::new().await;
    let squatter = h.key(h.tenant().await, ALL).await;
    let owner = h.key(h.tenant().await, ALL).await;
    let contested = name();

    let (squat, _) = h.domain(&squatter, &contested).await;

    // While it is fresh, the name is taken.
    let (status, _) = h
        .call(
            "POST",
            "/api/v1/domains",
            &owner,
            Some(json!({ "domain": contested })),
        )
        .await;
    assert_eq!(status, StatusCode::CONFLICT);

    // Eight days on, unverified, it no longer is.
    sqlx::query("UPDATE proxy_domains SET created_at = NOW() - INTERVAL '8 days' WHERE id = $1")
        .bind(squat)
        .execute(&h.pool)
        .await
        .unwrap();
    let (claimed, _) = h.domain(&owner, &contested).await;
    assert_ne!(claimed, squat);

    let gone: bool =
        sqlx::query_scalar("SELECT NOT EXISTS(SELECT 1 FROM proxy_domains WHERE id = $1)")
            .bind(squat)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert!(gone, "the stale registration was left in place");
}

#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn a_verified_registration_does_not_go_stale() {
    let h = Harness::new().await;
    let owner = h.key(h.tenant().await, ALL).await;
    let other = h.key(h.tenant().await, ALL).await;
    let held = name();
    let (id, _) = h.domain(&owner, &held).await;
    h.verify(id).await;
    sqlx::query("UPDATE proxy_domains SET created_at = NOW() - INTERVAL '90 days' WHERE id = $1")
        .bind(id)
        .execute(&h.pool)
        .await
        .unwrap();

    let (status, _) = h
        .call(
            "POST",
            "/api/v1/domains",
            &other,
            Some(json!({ "domain": held })),
        )
        .await;
    assert_eq!(status, StatusCode::CONFLICT);
}

// ---------------------------------------------------------------------------
// 5. Verification is throttled and honours expiry. (The SSRF defences of the
//    HTTP check itself are unit-tested in saas::verification.)
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn verification_is_throttled_and_expires() {
    let h = Harness::new().await;
    let key = h.key(h.tenant().await, ALL).await;
    let (id, _) = h.domain(&key, &name()).await;
    let verify = format!("/api/v1/domains/{id}/verify");
    let set = |sql: &'static str| {
        let pool = h.pool.clone();
        async move {
            sqlx::query(sql).bind(id).execute(&pool).await.unwrap();
        }
    };

    // Just attempted: too soon. No lookup is made, so no network is needed.
    set("UPDATE proxy_domains SET last_verification_attempt = NOW() WHERE id = $1").await;
    let (status, body) = h.call("POST", &verify, &key, None).await;
    assert_eq!(status, StatusCode::TOO_MANY_REQUESTS, "{body}");
    assert_eq!(body["code"], "rate_limited");

    // Out of attempts.
    set(
        "UPDATE proxy_domains SET last_verification_attempt = NOW() - INTERVAL '1 hour', \
         verification_attempts = 50 WHERE id = $1",
    )
    .await;
    let (status, body) = h.call("POST", &verify, &key, None).await;
    assert_eq!(status, StatusCode::OK);
    assert!(
        body["data"]["failed"]["reason"]
            .as_str()
            .unwrap()
            .contains("all its verification attempts"),
        "{body}"
    );

    // The challenge has expired: refused, and the domain marked so.
    set("UPDATE proxy_domains SET verification_attempts = 0 WHERE id = $1").await;
    set("UPDATE proxy_verification_challenges SET expires_at = NOW() - INTERVAL '1 second' WHERE domain_id = $1")
        .await;
    let (status, body) = h.call("POST", &verify, &key, None).await;
    assert_eq!(status, StatusCode::OK);
    assert!(
        body["data"]["failed"]["reason"]
            .as_str()
            .unwrap()
            .contains("expired"),
        "{body}"
    );
    let status: String =
        sqlx::query_scalar("SELECT verification_status FROM proxy_domains WHERE id = $1")
            .bind(id)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(status, "expired");

    // An expired challenge is no longer served either.
    let token: String =
        sqlx::query_scalar("SELECT verification_token FROM proxy_domains WHERE id = $1")
            .bind(id)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    let host: String = sqlx::query_scalar("SELECT domain FROM proxy_domains WHERE id = $1")
        .bind(id)
        .fetch_one(&h.pool)
        .await
        .unwrap();
    let (status, _) = h
        .request(
            "GET",
            &format!("/.well-known/postrust-verification/{token}"),
            &[("host", &host)],
            None,
        )
        .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn a_verified_domain_is_not_checked_again() {
    let h = Harness::new().await;
    let key = h.key(h.tenant().await, ALL).await;
    let (id, _) = h.domain(&key, &name()).await;
    h.verify(id).await;
    let before: i32 =
        sqlx::query_scalar("SELECT verification_attempts FROM proxy_domains WHERE id = $1")
            .bind(id)
            .fetch_one(&h.pool)
            .await
            .unwrap();

    let (status, body) = h
        .call("POST", &format!("/api/v1/domains/{id}/verify"), &key, None)
        .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["data"], "verified");

    let after: i32 =
        sqlx::query_scalar("SELECT verification_attempts FROM proxy_domains WHERE id = $1")
            .bind(id)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(before, after, "a verified domain made an outbound check");
}

// ---------------------------------------------------------------------------
// 6. Database errors are not returned to tenants.
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn constraint_violations_are_answered_without_the_database_text() {
    let h = Harness::new().await;
    let key = h.key(h.tenant().await, ALL).await;
    let upstream = unique("dup");
    let create = json!({ "name": upstream });

    let (status, _) = h
        .call("POST", "/api/v1/upstreams", &key, Some(create.clone()))
        .await;
    assert_eq!(status, StatusCode::CREATED);
    let (status, body) = h
        .call("POST", "/api/v1/upstreams", &key, Some(create))
        .await;
    assert_eq!(status, StatusCode::CONFLICT, "{body}");
    assert_eq!(body["code"], "conflict");
    let text = body.to_string();
    for leak in [
        "duplicate key",
        "proxy_domain_upstreams",
        "constraint",
        &upstream,
    ] {
        assert!(!text.contains(leak), "the response leaked {leak:?}: {text}");
    }
}

// ---------------------------------------------------------------------------
// 7. Upstreams with backends: the trigger works, and creation is atomic.
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn an_upstream_with_backends_is_created_whole() {
    let h = Harness::new().await;
    let t = h.tenant().await;
    let key = h.key(t, ALL).await;

    let (status, body) = h
        .call(
            "POST",
            "/api/v1/upstreams",
            &key,
            Some(json!({
                "name": unique("up"),
                "backends": [
                    { "address": "api.example.com:443", "scheme": "https" },
                    { "address": "8.8.8.8:80" },
                ],
            })),
        )
        .await;
    assert_eq!(status, StatusCode::CREATED, "{body}");
    assert_eq!(body["data"]["backends"].as_array().unwrap().len(), 2);

    // Adding and removing one fires the same trigger.
    let id = body["data"]["id"].as_str().unwrap();
    let (status, added) = h
        .call(
            "POST",
            &format!("/api/v1/upstreams/{id}/backends"),
            &key,
            Some(json!({ "address": "backend.example.com:8080" })),
        )
        .await;
    assert_eq!(status, StatusCode::CREATED, "{added}");
    let backend = added["data"]["id"].as_str().unwrap();
    let (status, _) = h
        .call(
            "DELETE",
            &format!("/api/v1/upstreams/{id}/backends/{backend}"),
            &key,
            None,
        )
        .await;
    assert_eq!(status, StatusCode::OK);

    // One bad backend refuses the lot: no upstream is left behind.
    let name = unique("half");
    let (status, _) = h
        .call(
            "POST",
            "/api/v1/upstreams",
            &key,
            Some(json!({
                "name": name,
                "backends": [
                    { "address": "api.example.com:443" },
                    { "address": "api.example.com:443", "scheme": "gopher" },
                ],
            })),
        )
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    let left: i64 = sqlx::query_scalar(
        "SELECT COUNT(*) FROM proxy_domain_upstreams WHERE tenant_id = $1 AND name = $2",
    )
    .bind(t)
    .bind(&name)
    .fetch_one(&h.pool)
    .await
    .unwrap();
    assert_eq!(left, 0, "a refused upstream was half-created");
}

// ---------------------------------------------------------------------------
// 8. Tenant backends, headers and paths are validated.
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn backends_cannot_point_inside_the_network() {
    let h = Harness::new().await;
    let key = h.key(h.tenant().await, ALL).await;
    let upstream = h.upstream(&key).await;

    for address in [
        "169.254.169.254:80",
        "10.0.0.5:5432",
        "127.0.0.1:8080",
        "[::1]:80",
        "[::ffff:169.254.169.254]:80",
        "localhost:6379",
        "redis.internal:6379",
        "backend:80",
    ] {
        let (status, body) = h
            .call(
                "POST",
                &format!("/api/v1/upstreams/{upstream}/backends"),
                &key,
                Some(json!({ "address": address })),
            )
            .await;
        assert_eq!(
            status,
            StatusCode::BAD_REQUEST,
            "{address} was accepted: {body}"
        );
    }

    let (status, body) = h
        .call(
            "POST",
            &format!("/api/v1/upstreams/{upstream}/backends"),
            &key,
            Some(json!({ "address": "Origin.Example.com:443", "scheme": "ftp" })),
        )
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
    assert!(body["error"].as_str().unwrap().contains("scheme"));

    let (status, body) = h
        .call(
            "POST",
            &format!("/api/v1/upstreams/{upstream}/backends"),
            &key,
            Some(json!({ "address": "Origin.Example.com:443", "scheme": "https" })),
        )
        .await;
    assert_eq!(status, StatusCode::CREATED, "{body}");
    assert_eq!(body["data"]["address"], "origin.example.com:443");
}

#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn headers_and_paths_are_validated() {
    let h = Harness::new().await;
    let key = h.key(h.tenant().await, ALL).await;

    for health_check_path in ["health", "/a b", "/a\r\nHost: evil"] {
        let (status, body) = h
            .call(
                "POST",
                "/api/v1/upstreams",
                &key,
                Some(json!({ "name": unique("hc"), "health_check_path": health_check_path })),
            )
            .await;
        assert_eq!(
            status,
            StatusCode::BAD_REQUEST,
            "{health_check_path:?}: {body}"
        );
    }

    let upstream = h.upstream(&key).await;
    let (status, body) = h
        .call(
            "PUT",
            &format!("/api/v1/upstreams/{upstream}"),
            &key,
            Some(json!({ "health_check_path": "/ok\nX: y" })),
        )
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");

    let (domain, _) = h.domain(&key, &name()).await;
    h.verify(domain).await;
    let routes = format!("/api/v1/domains/{domain}/routes");
    for bad in [
        json!({ "add_headers": { "X-Ok": "a\r\nInjected: 1" } }),
        json!({ "add_headers": { "Bad Name": "v" } }),
        json!({ "add_headers": { "Host": "other.example" } }),
        json!({ "remove_headers": ["x\r\ny"] }),
        json!({ "path_pattern": "no-slash" }),
        json!({ "path_pattern": "(", "path_type": "regex" }),
    ] {
        let mut request = json!({ "name": unique("r"), "upstream_id": upstream });
        request
            .as_object_mut()
            .unwrap()
            .extend(bad.as_object().unwrap().clone());
        let (status, body) = h.call("POST", &routes, &key, Some(request)).await;
        assert_eq!(status, StatusCode::BAD_REQUEST, "{bad}: {body}");
    }

    let (status, body) = h
        .call(
            "POST",
            &routes,
            &key,
            Some(json!({
                "name": unique("r"),
                "upstream_id": upstream,
                "add_headers": { "X-Tenant": "acme" },
                "remove_headers": ["x-powered-by"],
            })),
        )
        .await;
    assert_eq!(status, StatusCode::CREATED, "{body}");
}

// ---------------------------------------------------------------------------
// 9. Proxy JWTs need exp and the proxy's audience; no scopes means none.
// ---------------------------------------------------------------------------

fn jwt(tenant: Uuid, extra: Value) -> String {
    let mut claims = json!({
        "sub": "user",
        "tenant_id": tenant,
        "exp": chrono::Utc::now().timestamp() + 600,
        "aud": "postrust-proxy",
    });
    for (k, v) in extra.as_object().unwrap() {
        if v.is_null() {
            claims.as_object_mut().unwrap().remove(k);
        } else {
            claims[k] = v.clone();
        }
    }
    let token = jsonwebtoken::encode(
        &jsonwebtoken::Header::default(),
        &claims,
        &jsonwebtoken::EncodingKey::from_secret(JWT_SECRET.as_bytes()),
    )
    .unwrap();
    format!("Bearer {token}")
}

#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn jwts_are_held_to_exp_audience_and_their_scopes() {
    let h = Harness::new().await;
    let t = h.tenant().await;

    let (status, body) = h
        .call(
            "GET",
            "/api/v1/domains",
            &jwt(t, json!({ "exp": null, "scopes": ["*"] })),
            None,
        )
        .await;
    assert_eq!(status, StatusCode::UNAUTHORIZED, "no exp: {body}");

    for aud in [Value::Null, json!("postrust"), json!("authenticated")] {
        let (status, _) = h
            .call(
                "GET",
                "/api/v1/domains",
                &jwt(t, json!({ "aud": aud, "scopes": ["*"] })),
                None,
            )
            .await;
        assert_eq!(status, StatusCode::UNAUTHORIZED, "aud {aud}");
    }

    let (status, _) = h
        .call("GET", "/api/v1/domains", &jwt(t, json!({})), None)
        .await;
    assert_eq!(
        status,
        StatusCode::FORBIDDEN,
        "a token without scopes could read"
    );

    let (status, _) = h
        .call(
            "GET",
            "/api/v1/domains",
            &jwt(t, json!({ "scopes": ["domains:read"] })),
            None,
        )
        .await;
    assert_eq!(status, StatusCode::OK);

    // A configured audience replaces the default.
    let custom = Harness::with(|o| o.jwt_audience = "tenant-api".into()).await;
    let (status, _) = custom
        .call(
            "GET",
            "/api/v1/domains",
            &jwt(t, json!({ "scopes": ["*"] })),
            None,
        )
        .await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
    let (status, _) = custom
        .call(
            "GET",
            "/api/v1/domains",
            &jwt(t, json!({ "scopes": ["*"], "aud": "tenant-api" })),
            None,
        )
        .await;
    assert_eq!(status, StatusCode::OK);
}

// ---------------------------------------------------------------------------
// 10. Quotas.
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn quotas_are_enforced() {
    let h = Harness::new().await;
    let t = h.tenant().await;
    let key = h.key(t, ALL).await;
    sqlx::query(
        "UPDATE proxy_tenants SET max_routes_per_domain = 1, max_upstreams = 2, \
         max_backends_per_upstream = 1, max_api_keys = 1 WHERE id = $1",
    )
    .bind(t)
    .execute(&h.pool)
    .await
    .unwrap();

    let upstream = h.upstream(&key).await;
    let (domain, _) = h.domain(&key, &name()).await;
    h.verify(domain).await;
    let routes = format!("/api/v1/domains/{domain}/routes");
    let route =
        |path: &str| json!({ "name": unique("r"), "upstream_id": upstream, "path_pattern": path });

    let (status, body) = h.call("POST", &routes, &key, Some(route("/a"))).await;
    assert_eq!(status, StatusCode::CREATED, "{body}");
    let (status, body) = h.call("POST", &routes, &key, Some(route("/b"))).await;
    assert_eq!(status, StatusCode::PAYMENT_REQUIRED, "{body}");
    assert_eq!(body["code"], "quota_exceeded");

    // Two backends inline against a limit of one.
    let (status, _) = h
        .call(
            "POST",
            "/api/v1/upstreams",
            &key,
            Some(json!({
                "name": unique("up"),
                "backends": [{ "address": "a.example.com:80" }, { "address": "b.example.com:80" }],
            })),
        )
        .await;
    assert_eq!(status, StatusCode::PAYMENT_REQUIRED);

    // One backend, then a second added.
    let backends = format!("/api/v1/upstreams/{upstream}/backends");
    let (status, _) = h
        .call(
            "POST",
            &backends,
            &key,
            Some(json!({ "address": "a.example.com:80" })),
        )
        .await;
    assert_eq!(status, StatusCode::CREATED);
    let (status, _) = h
        .call(
            "POST",
            &backends,
            &key,
            Some(json!({ "address": "b.example.com:80" })),
        )
        .await;
    assert_eq!(status, StatusCode::PAYMENT_REQUIRED);

    // The second upstream fits, the third does not.
    h.upstream(&key).await;
    let (status, _) = h
        .call(
            "POST",
            "/api/v1/upstreams",
            &key,
            Some(json!({ "name": unique("up") })),
        )
        .await;
    assert_eq!(status, StatusCode::PAYMENT_REQUIRED);

    // The key in use already fills the key quota.
    let (status, _) = h
        .call(
            "POST",
            "/api/v1/auth/api-keys",
            &key,
            Some(json!({ "name": "more", "scopes": ["domains:read"] })),
        )
        .await;
    assert_eq!(status, StatusCode::PAYMENT_REQUIRED);

    let (status, usage) = h.call("GET", "/api/v1/tenant/usage", &key, None).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(usage["data"]["upstreams_limit"], 2);
    assert_eq!(usage["data"]["api_keys_limit"], 1);
}

#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn another_tenants_domain_cannot_be_enabled_or_disabled() {
    let h = Harness::new().await;
    let owner = h.key(h.tenant().await, ALL).await;
    let stranger = h.key(h.tenant().await, ALL).await;
    let (id, _) = h.domain(&owner, &name()).await;
    h.verify(id).await;

    for action in ["enable", "disable"] {
        let (status, _) = h
            .call(
                "POST",
                &format!("/api/v1/domains/{id}/{action}"),
                &stranger,
                None,
            )
            .await;
        assert_eq!(status, StatusCode::NOT_FOUND, "{action}");
    }
    let (status, _) = h
        .call(
            "POST",
            &format!("/api/v1/domains/{id}/enable"),
            &owner,
            None,
        )
        .await;
    assert_eq!(status, StatusCode::OK);
}