atomic-integration-proxy 0.4.3

OAuth/catalog integration proxy (pinned OpenAPI catalog, connections owned by Atomic agents, Atomic v2 request signatures, delegations and frame capabilities) used by Atomic Server and LocalThought
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
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
//! The webhook routes end to end: signed consumer requests and signed
//! provider deliveries through the real router, against PostgreSQL and a
//! stand-in provider. Ignored without `TEST_DATABASE_URL`.

use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use axum::{
    body::Body,
    extract::{Path, State as AxumState},
    http::{HeaderMap, Request, StatusCode},
    response::IntoResponse,
    Json,
};
use base64::{engine::general_purpose::STANDARD, Engine as _};
use hmac::{Hmac, Mac};
use serde_json::{json, Value};
use tower::ServiceExt;

use super::{Policy, Store, Webhooks};
use crate::agent_id::test_signer::Agent;
use crate::security::tests::{admin, test_database_url, TEST_KEY};
use crate::security::Security;
use crate::test_support::{body_json, signed_request};
use crate::AppState;

// Invented for these tests; never configured anywhere.
const TRACKER_SECRET: &[u8] = b"fixture-only-tracker-app-secret-not-real-000";
const GITHUB_FIXTURE_SECRET: &[u8] = b"fixture-only-github-app-secret-not-real-0000";

/// What the stand-in provider lets each API key read: key -> source ids.
type Grants = Arc<Mutex<HashMap<String, HashSet<String>>>>;

/// Hook deletions the stand-in provider received: `project/hook`.
static DELETED_HOOKS: Mutex<Vec<String>> = Mutex::new(Vec::new());

fn examples() -> std::path::PathBuf {
    std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../openapi-extensions/spec/webhook-deliveries/examples")
}

/// A spec example as a catalog document, served by `address` and needing
/// an API key: generic additions only, the declaration is the example's.
fn document(name: &str, address: std::net::SocketAddr) -> Value {
    let mut document: Value =
        serde_yaml::from_str(&std::fs::read_to_string(examples().join(name)).unwrap()).unwrap();
    document["servers"] = json!([{"url": format!("http://{address}")}]);
    document["components"]["securitySchemes"] =
        json!({"key": {"type": "apiKey", "in": "header", "name": "X-Api-Key"}});
    document["security"] = json!([{"key": []}]);
    document
}

async fn provider(grants: Grants) -> std::net::SocketAddr {
    async fn read(
        AxumState(grants): AxumState<Grants>,
        headers: HeaderMap,
        id: String,
        numeric: Option<u64>,
    ) -> axum::response::Response {
        let key = headers
            .get("x-api-key")
            .and_then(|v| v.to_str().ok())
            .unwrap_or_default()
            .to_owned();
        let allowed = grants
            .lock()
            .unwrap()
            .get(&key)
            .is_some_and(|ids| ids.contains(&id));
        if !allowed {
            return StatusCode::NOT_FOUND.into_response();
        }
        match numeric {
            Some(n) => Json(json!({"id": n})).into_response(),
            None => Json(json!({"id": id})).into_response(),
        }
    }
    let app = axum::Router::new()
        .route(
            "/projects/:id",
            axum::routing::get(
                |state: AxumState<Grants>, headers: HeaderMap, Path(id): Path<String>| async move {
                    read(state, headers, id, None).await
                },
            ),
        )
        .route(
            "/projects/:id/webhooks",
            axum::routing::get(|| async {
                // Another receiver's hook, and the one created for ours.
                Json(json!([
                    {"id": "wh-other", "target": "https://elsewhere.example/hook"},
                    {"id": "wh-found", "target": "https://proxy.example/webhooks/fixture-endpoint"}
                ]))
            }),
        )
        .route(
            "/projects/:id/webhooks/:hook",
            axum::routing::delete(|Path((id, hook)): Path<(String, String)>| async move {
                DELETED_HOOKS.lock().unwrap().push(format!("{id}/{hook}"));
                StatusCode::NO_CONTENT
            }),
        )
        .route(
            "/repos/:owner/:repo",
            axum::routing::get(
                |state: AxumState<Grants>,
                 headers: HeaderMap,
                 Path((owner, repo)): Path<(String, String)>| async move {
                    // The synthetic fixture's repository has id 2000002.
                    let id = format!("{owner}/{repo}");
                    read(state, headers, id, Some(2_000_002)).await
                },
            ),
        )
        .with_state(grants);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = listener.local_addr().unwrap();
    tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
    address
}

fn small() -> Policy {
    let mut policy = Policy::pilot(1 << 20);
    policy.subscription_max_pending_events = 10;
    policy.subscription_max_pending_bytes = 4096;
    policy.owner_max_pending_bytes = 8192;
    policy.owner_max_pending_references = 15;
    policy.owner_max_live_subscriptions = 3;
    policy.max_verified_bytes = 4096;
    policy.max_body_bytes = 1024;
    policy
}

struct Env {
    state: AppState,
    security: Security,
    store: Arc<Store>,
    grants: Grants,
    schema: String,
    tag: String,
}

async fn env_for(platform: &str, example: &str, secret: &[u8], policy: Policy) -> Env {
    let schema = format!("webhook_routes_{:016x}", rand::random::<u64>());
    admin()
        .await
        .batch_execute(&format!("CREATE SCHEMA \"{schema}\""))
        .await
        .unwrap();
    let tag = format!("routes_{:016x}", rand::random::<u64>());
    let mut url = url::Url::parse(&test_database_url()).unwrap();
    url.query_pairs_mut()
        .append_pair("options", &format!("-csearch_path={schema}"))
        .append_pair("application_name", &tag);
    let security = Security::connect(url.as_str(), TEST_KEY).await.unwrap();
    let store = Arc::new(
        Store::connect(url.as_str(), &security, policy)
            .await
            .unwrap(),
    );
    let grants: Grants = Arc::default();
    let address = provider(grants.clone()).await;
    let mut state = crate::test_support::state(Some(security.clone()));
    state.catalog = crate::catalog::Catalog::from_test_document(
        platform,
        document(example, address),
        json!({}),
    );
    state.webhooks = Some(Arc::new(Webhooks::new(
        store.clone(),
        BTreeMap::from([(platform.to_owned(), secret.to_vec())]),
    )));
    Env {
        state,
        security,
        store,
        grants,
        schema,
        tag,
    }
}

async fn env(policy: Policy) -> Env {
    env_for("tracker", "tracker.yaml", TRACKER_SECRET, policy).await
}

impl Env {
    async fn send(&self, request: Request<Body>) -> axum::response::Response {
        crate::router(self.state.clone())
            .oneshot(request)
            .await
            .unwrap()
    }

    /// A connection for `agent` holding API key `key`, which may read `ids`.
    async fn connection(&self, platform: &str, agent: &Agent, key: &str, ids: &[&str]) -> String {
        self.grants.lock().unwrap().insert(
            key.to_owned(),
            ids.iter().map(|id| (*id).to_owned()).collect(),
        );
        let credential = json!({"kind": "api_key", "provider": platform, "key": key});
        self.security
            .create_connection(
                platform,
                &agent.id(),
                &serde_json::to_vec(&credential).unwrap(),
            )
            .await
            .unwrap()
    }

    async fn subscribe(
        &self,
        agent: &Agent,
        connection: &str,
        source: &str,
        parameters: Value,
        events: Value,
    ) -> axum::response::Response {
        let body = json!({"source": source, "parameters": parameters, "events": events});
        self.send(signed_request(
            &self.state,
            agent,
            "POST",
            &format!("/connections/{connection}/subscriptions"),
            serde_json::to_vec(&body).unwrap(),
        ))
        .await
    }

    async fn subscribe_project(&self, agent: &Agent, connection: &str, project: &str) -> Value {
        let response = self
            .subscribe(
                agent,
                connection,
                "project",
                json!({"projectId": project}),
                json!(["task"]),
            )
            .await;
        assert_eq!(response.status(), StatusCode::CREATED);
        body_json(response).await
    }

    async fn endpoint(&self, platform: &str) -> String {
        self.store
            .ensure_shared_hook(platform, super::store::now())
            .await
            .unwrap()
            .endpoint_id
    }

    fn signed_delivery(&self, endpoint: &str, id: &str, body: &[u8]) -> Request<Body> {
        let mut mac = <Hmac<sha2::Sha256> as Mac>::new_from_slice(TRACKER_SECRET).unwrap();
        mac.update(body);
        let signature: String = mac
            .finalize()
            .into_bytes()
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect();
        Request::post(format!("/webhooks/{endpoint}"))
            .header("Tracker-Delivery", id)
            .header("Tracker-Signature", format!("v1={signature}"))
            .header("Content-Type", "application/json")
            .body(Body::from(body.to_vec()))
            .unwrap()
    }

    async fn deliver(&self, endpoint: &str, id: &str, project: &str) -> StatusCode {
        let body = task(project, "t/1");
        self.send(self.signed_delivery(endpoint, id, &body))
            .await
            .status()
    }

    async fn get(&self, agent: &Agent, path: &str) -> axum::response::Response {
        self.send(signed_request(&self.state, agent, "GET", path, vec![]))
            .await
    }

    async fn post(&self, agent: &Agent, path: &str, body: Value) -> axum::response::Response {
        self.send(signed_request(
            &self.state,
            agent,
            "POST",
            path,
            serde_json::to_vec(&body).unwrap(),
        ))
        .await
    }

    async fn count(&self, query: &str) -> i64 {
        let mut url = url::Url::parse(&test_database_url()).unwrap();
        url.query_pairs_mut()
            .append_pair("options", &format!("-csearch_path={}", self.schema));
        let (client, connection) = tokio_postgres::connect(url.as_str(), tokio_postgres::NoTls)
            .await
            .unwrap();
        tokio::spawn(connection);
        client.query_one(query, &[]).await.unwrap().get(0)
    }

    async fn drop_schema(self) {
        drop(self.state);
        let _ = admin()
            .await
            .batch_execute(&format!("DROP SCHEMA \"{}\" CASCADE", self.schema))
            .await;
    }
}

fn task(project: &str, task_id: &str) -> Vec<u8> {
    serde_json::to_vec(&json!({
        "kind": "task", "change": "updated",
        "project": {"id": project, "workspace": "w-1"},
        "task": {"id": task_id, "title": "Fixture task"}
    }))
    .unwrap()
}

fn id(subscription: &Value) -> String {
    subscription["id"].as_str().unwrap().to_owned()
}

// --- the whole flow --------------------------------------------------------------------

#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn subscribe_receive_fetch_acknowledge_reconcile() {
    let env = env(small()).await;
    let alice = Agent::new(81);
    let connection = env.connection("tracker", &alice, "key-a", &["p-100"]).await;
    let subscription = env.subscribe_project(&alice, &connection, "p-100").await;
    assert_eq!(subscription["state"], "needs-reconciliation");
    assert_eq!(
        subscription["source"],
        json!({"kind": "project", "key": "p-100"})
    );
    let sub = id(&subscription);

    let endpoint = env.endpoint("tracker").await;
    let body = task("p-100", "t/7");
    let response = env.send(env.signed_delivery(&endpoint, "d-1", &body)).await;
    assert_eq!(response.status(), StatusCode::NO_CONTENT);

    let page = body_json(
        env.get(&alice, &format!("/subscriptions/{sub}/events"))
            .await,
    )
    .await;
    let event = &page["events"][0];
    assert_eq!(event["deliveryId"], "d-1");
    assert_eq!(event["eventType"], "task");
    assert_eq!(event["action"], "updated");
    assert_eq!(
        STANDARD
            .decode(event["payload"]["body"].as_str().unwrap())
            .unwrap(),
        body
    );
    assert!(
        event.get("headers").is_none(),
        "no provider header is passed on"
    );

    let acknowledged = env
        .post(
            &alice,
            &format!("/subscriptions/{sub}/ack"),
            json!({"generation": page["generation"], "cursor": event["cursor"]}),
        )
        .await;
    assert_eq!(acknowledged.status(), StatusCode::OK);
    let reconciliation = &subscription["reconciliationRequired"];
    let done = env
        .post(
            &alice,
            &format!("/subscriptions/{sub}/reconciled"),
            json!({"generation": reconciliation["generation"], "barrier": reconciliation["barrier"]}),
        )
        .await;
    assert_eq!(done.status(), StatusCode::OK);
    assert_eq!(body_json(done).await["state"], "active");
    let renewed = env
        .post(&alice, &format!("/subscriptions/{sub}/renew"), json!({}))
        .await;
    assert_eq!(renewed.status(), StatusCode::OK);
    let deleted = env
        .send(signed_request(
            &env.state,
            &alice,
            "DELETE",
            &format!("/subscriptions/{sub}"),
            vec![],
        ))
        .await;
    assert_eq!(body_json(deleted).await["state"], "closed");
    let gone = env.get(&alice, &format!("/subscriptions/{sub}")).await;
    assert_eq!(gone.status(), StatusCode::GONE);
    assert_eq!(body_json(gone).await["action"], "resubscribe");
    env.drop_schema().await;
}

/// The synthetic GitHub fixtures, replayed through the same generic code:
/// the document is the spec's fixture, the deliveries are its signed files.
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn the_synthetic_github_fixtures_pass_through_the_generic_path() {
    let env = env_for(
        "github-fixture",
        "github-fixture.yaml",
        GITHUB_FIXTURE_SECRET,
        Policy::pilot(1 << 30),
    )
    .await;
    let alice = Agent::new(82);
    let connection = env
        .connection(
            "github-fixture",
            &alice,
            "key-g",
            &["fixture-owner/fixture-repo"],
        )
        .await;
    let response = env
        .subscribe(
            &alice,
            &connection,
            "repository",
            json!({"owner": "fixture-owner", "repo": "fixture-repo"}),
            json!(["issues"]),
        )
        .await;
    assert_eq!(response.status(), StatusCode::CREATED);
    let subscription = body_json(response).await;
    assert_eq!(
        subscription["source"]["key"], "2000002",
        "the key comes from the provider's answer"
    );
    let endpoint = env.endpoint("github-fixture").await;
    let replay = |name: &str| {
        let data: Value =
            serde_json::from_str(&std::fs::read_to_string(examples().join(name)).unwrap()).unwrap();
        let mut request = Request::post(format!("/webhooks/{endpoint}"));
        for pair in data["headers"].as_array().unwrap() {
            request = request.header(pair[0].as_str().unwrap(), pair[1].as_str().unwrap());
        }
        request
            .body(Body::from(data["body"].as_str().unwrap().to_owned()))
            .unwrap()
    };
    let response = env
        .send(replay("github-deliveries/issues-edited.json"))
        .await;
    assert_eq!(response.status(), StatusCode::NO_CONTENT);
    let sub = id(&subscription);
    let page = body_json(
        env.get(&alice, &format!("/subscriptions/{sub}/events"))
            .await,
    )
    .await;
    assert_eq!(
        page["events"][0]["deliveryId"],
        "00000000-0000-4000-8000-000000000001"
    );
    assert_eq!(page["events"][0]["action"], "edited");
    // The repository's removal from the installation suspends the binding.
    let response = env
        .send(replay(
            "github-deliveries/installation-repositories-removed.json",
        ))
        .await;
    assert_eq!(response.status(), StatusCode::NO_CONTENT);
    assert_eq!(
        env.count("SELECT count(*) FROM webhook_subscriptions WHERE suspended")
            .await,
        1
    );
    env.drop_schema().await;
}

// --- isolation and access ----------------------------------------------------------------

#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn deliveries_reach_only_subscriptions_with_access_to_their_source() {
    let env = env(small()).await;
    let alice = Agent::new(83);
    let bob = Agent::new(84);
    let ac = env.connection("tracker", &alice, "key-a", &["p-100"]).await;
    let bc = env.connection("tracker", &bob, "key-b", &["p-200"]).await;
    let a = id(&env.subscribe_project(&alice, &ac, "p-100").await);
    let b = id(&env.subscribe_project(&bob, &bc, "p-200").await);

    // Bob's key cannot read p-100, so he cannot subscribe to it, and the
    // shared hook does not make him see it.
    let refused = env
        .subscribe(
            &bob,
            &bc,
            "project",
            json!({"projectId": "p-100"}),
            json!(["task"]),
        )
        .await;
    assert_eq!(refused.status(), StatusCode::FORBIDDEN);
    let endpoint = env.endpoint("tracker").await;
    assert_eq!(
        env.deliver(&endpoint, "d-1", "p-100").await,
        StatusCode::NO_CONTENT
    );
    let alice_page = body_json(env.get(&alice, &format!("/subscriptions/{a}/events")).await).await;
    let bob_page = body_json(env.get(&bob, &format!("/subscriptions/{b}/events")).await).await;
    assert_eq!(alice_page["events"].as_array().unwrap().len(), 1);
    assert_eq!(bob_page["events"].as_array().unwrap().len(), 0);
    // Bob cannot read Alice's subscription, nor use his own connection's
    // id to subscribe as Alice.
    assert_eq!(
        env.get(&bob, &format!("/subscriptions/{a}/events"))
            .await
            .status(),
        StatusCode::NOT_FOUND
    );
    assert_eq!(
        env.subscribe(
            &bob,
            &ac,
            "project",
            json!({"projectId": "p-100"}),
            json!(["task"])
        )
        .await
        .status(),
        StatusCode::FORBIDDEN
    );
    // Access parameters are one path segment each: `../p-100` is sent
    // encoded, as one segment the provider does not know; `..` and a
    // missing parameter are refused before any call.
    let encoded = env
        .subscribe(
            &alice,
            &ac,
            "project",
            json!({"projectId": "../p-100"}),
            json!(["task"]),
        )
        .await;
    assert_eq!(encoded.status(), StatusCode::FORBIDDEN);
    for parameters in [
        json!({"projectId": ".."}),
        json!({"projectId": "."}),
        json!({}),
    ] {
        let response = env
            .subscribe(&alice, &ac, "project", parameters, json!(["task"]))
            .await;
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }
    // Only declared events of the source kind.
    let response = env
        .subscribe(
            &alice,
            &ac,
            "project",
            json!({"projectId": "p-100"}),
            json!(["unknown"]),
        )
        .await;
    assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    env.drop_schema().await;
}

/// A revocation suspends the binding; deliveries meanwhile are not routed;
/// the next fetch re-runs the access check: a failure closes, a pass
/// resumes with an `access-suspended` gap.
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn a_revocation_suspends_until_the_access_check_decides() {
    let env = env(small()).await;
    let alice = Agent::new(85);
    let bob = Agent::new(86);
    let ac = env.connection("tracker", &alice, "key-a", &["p-100"]).await;
    let bc = env.connection("tracker", &bob, "key-b", &["p-100"]).await;
    let a = id(&env.subscribe_project(&alice, &ac, "p-100").await);
    let b = id(&env.subscribe_project(&bob, &bc, "p-100").await);
    let endpoint = env.endpoint("tracker").await;
    let revocation = serde_json::to_vec(&json!({
        "kind": "access", "change": "revoked", "projects": [{"id": "p-100"}]
    }))
    .unwrap();
    assert_eq!(
        env.send(env.signed_delivery(&endpoint, "r-1", &revocation))
            .await
            .status(),
        StatusCode::NO_CONTENT
    );
    assert_eq!(
        env.deliver(&endpoint, "d-1", "p-100").await,
        StatusCode::NO_CONTENT
    );
    assert_eq!(
        env.count("SELECT count(*) FROM webhook_event_refs").await,
        0,
        "nobody suspended gets it"
    );

    // Alice really lost access; Bob did not.
    env.grants
        .lock()
        .unwrap()
        .insert("key-a".into(), HashSet::new());
    let closed = env.get(&alice, &format!("/subscriptions/{a}/events")).await;
    assert_eq!(closed.status(), StatusCode::GONE);
    assert_eq!(body_json(closed).await["gap"]["reason"], "access-denied");
    let resumed = env.get(&bob, &format!("/subscriptions/{b}/events")).await;
    assert_eq!(resumed.status(), StatusCode::OK);
    assert_eq!(
        body_json(resumed).await["reconciliationRequired"]["gap"]["reason"],
        "access-suspended"
    );
    env.drop_schema().await;
}

/// Removing a delegation stops a delegate's reads at once; deleting the
/// connection ends its subscriptions in the same transaction.
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn standing_and_connection_deletion_end_subscriptions() {
    let env = env(small()).await;
    let owner = Agent::new(87);
    let app = Agent::new(88);
    let connection = env
        .connection("tracker", &owner, "key-o", &["p-100", "p-200"])
        .await;
    env.security
        .put_delegation(&connection, &owner.id(), &app.id(), None)
        .await
        .unwrap();
    let delegated = id(&env.subscribe_project(&app, &connection, "p-100").await);
    let own = id(&env.subscribe_project(&owner, &connection, "p-200").await);
    assert!(env
        .security
        .delete_delegation(&connection, &owner.id(), &app.id())
        .await
        .unwrap());
    let refused = env
        .get(&app, &format!("/subscriptions/{delegated}/events"))
        .await;
    assert_eq!(refused.status(), StatusCode::FORBIDDEN);
    assert_eq!(
        env.count(
            "SELECT count(*) FROM webhook_subscriptions WHERE closed_reason = 'standing-lost'"
        )
        .await,
        1
    );
    let deleted = env
        .send(signed_request(
            &env.state,
            &owner,
            "DELETE",
            &format!("/connections/{connection}"),
            vec![],
        ))
        .await;
    assert_eq!(deleted.status(), StatusCode::NO_CONTENT);
    assert_eq!(
        env.count(
            "SELECT count(*) FROM webhook_subscriptions WHERE closed_reason = 'connection-deleted'"
        )
        .await,
        1,
        "ended in the deleting transaction, no sweep needed"
    );
    let _ = own;
    env.drop_schema().await;
}

// --- the receiver's refusals -------------------------------------------------------------

#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn tampered_reserialized_or_ambiguous_deliveries_are_refused() {
    let env = env(small()).await;
    let alice = Agent::new(89);
    let connection = env.connection("tracker", &alice, "key-a", &["p-100"]).await;
    env.subscribe_project(&alice, &connection, "p-100").await;
    let endpoint = env.endpoint("tracker").await;
    let body = task("p-100", "t/1");

    let mut tampered = env.signed_delivery(&endpoint, "d-1", &body);
    *tampered.body_mut() = Body::from(task("p-100", "t/2"));
    assert_eq!(env.send(tampered).await.status(), StatusCode::UNAUTHORIZED);

    let pretty =
        serde_json::to_vec_pretty(&serde_json::from_slice::<Value>(&body).unwrap()).unwrap();
    let mut reserialized = env.signed_delivery(&endpoint, "d-1", &body);
    *reserialized.body_mut() = Body::from(pretty);
    assert_eq!(
        env.send(reserialized).await.status(),
        StatusCode::UNAUTHORIZED
    );

    let mut repeated = env.signed_delivery(&endpoint, "d-1", &body);
    let signature = repeated.headers()["tracker-signature"].clone();
    repeated
        .headers_mut()
        .append("tracker-signature", signature);
    assert_eq!(env.send(repeated).await.status(), StatusCode::UNAUTHORIZED);

    let mut two_ids = env.signed_delivery(&endpoint, "d-1", &body);
    two_ids
        .headers_mut()
        .append("tracker-delivery", "d-2".parse().unwrap());
    assert_eq!(env.send(two_ids).await.status(), StatusCode::BAD_REQUEST);

    let unknown = env.signed_delivery(&"x".repeat(43), "d-1", &body);
    assert_eq!(env.send(unknown).await.status(), StatusCode::NOT_FOUND);
    assert_eq!(
        env.count("SELECT count(*) FROM webhook_receipts").await,
        0,
        "a refusal writes nothing"
    );
    assert_eq!(env.count("SELECT count(*) FROM webhook_payloads").await, 0);

    // A platform without a configured secret refuses every delivery.
    let mut unconfigured = env.state.clone();
    unconfigured.webhooks = Some(Arc::new(Webhooks::new(env.store.clone(), BTreeMap::new())));
    let response = crate::router(unconfigured)
        .oneshot(env.signed_delivery(&endpoint, "d-1", &body))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    env.drop_schema().await;
}

/// Over the verification cap: refused unread. Between the retention and
/// the verification cap: routed, recorded as an `oversized-delivery` gap.
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn oversized_deliveries() {
    let env = env(small()).await;
    let alice = Agent::new(90);
    let connection = env.connection("tracker", &alice, "key-a", &["p-100"]).await;
    let sub = id(&env.subscribe_project(&alice, &connection, "p-100").await);
    let endpoint = env.endpoint("tracker").await;
    let padded = |size: usize| {
        let mut value: Value = serde_json::from_slice(&task("p-100", "t/1")).unwrap();
        value["pad"] = json!("x".repeat(size));
        serde_json::to_vec(&value).unwrap()
    };
    let huge = padded(5000);
    assert_eq!(
        env.send(env.signed_delivery(&endpoint, "big", &huge))
            .await
            .status(),
        StatusCode::PAYLOAD_TOO_LARGE
    );
    assert_eq!(env.count("SELECT count(*) FROM webhook_receipts").await, 0);
    let large = padded(2000);
    assert_eq!(
        env.send(env.signed_delivery(&endpoint, "large", &large))
            .await
            .status(),
        StatusCode::NO_CONTENT
    );
    let page = body_json(
        env.get(&alice, &format!("/subscriptions/{sub}/events"))
            .await,
    )
    .await;
    assert_eq!(page["events"].as_array().unwrap().len(), 0);
    assert_eq!(
        page["reconciliationRequired"]["gap"]["reason"],
        "oversized-delivery"
    );
    env.drop_schema().await;
}

/// The database fails before the delivery commits: no 2xx, nothing kept,
/// and the provider's retry is accepted as new.
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn a_database_failure_before_commit_is_never_acknowledged() {
    let env = env(small()).await;
    env.store.check_payload_mode(true).await.unwrap();
    assert!(env.store.check_payload_mode(false).await.is_err());
    let alice = Agent::new(91);
    let connection = env.connection("tracker", &alice, "key-a", &["p-100"]).await;
    env.subscribe_project(&alice, &connection, "p-100").await;
    let endpoint = env.endpoint("tracker").await;
    env.store
        .fail_before_commit
        .store(true, std::sync::atomic::Ordering::SeqCst);
    assert_eq!(
        env.deliver(&endpoint, "d-1", "p-100").await,
        StatusCode::SERVICE_UNAVAILABLE
    );
    env.store
        .fail_before_commit
        .store(false, std::sync::atomic::Ordering::SeqCst);
    assert_eq!(env.count("SELECT count(*) FROM webhook_receipts").await, 0);
    assert_eq!(
        env.deliver(&endpoint, "d-1", "p-100").await,
        StatusCode::NO_CONTENT
    );
    assert_eq!(
        env.count("SELECT count(*) FROM webhook_event_refs").await,
        1
    );
    // The connection is killed while the delivery waits for a lock.
    let admin = admin().await;
    let mut url = url::Url::parse(&test_database_url()).unwrap();
    url.query_pairs_mut()
        .append_pair("options", &format!("-csearch_path={}", env.schema));
    let (mut blocker, driver) = tokio_postgres::connect(url.as_str(), tokio_postgres::NoTls)
        .await
        .unwrap();
    tokio::spawn(driver);
    let lock = blocker.transaction().await.unwrap();
    lock.batch_execute("LOCK TABLE webhook_deployment_usage IN ACCESS EXCLUSIVE MODE")
        .await
        .unwrap();
    let state = env.state.clone();
    let request = env.signed_delivery(&endpoint, "d-2", &task("p-100", "t/2"));
    let pending = tokio::spawn(async move { crate::router(state).oneshot(request).await.unwrap() });
    let mut terminated = 0;
    for _ in 0..100 {
        terminated = admin
            .execute(
                "SELECT pg_terminate_backend(pid) FROM pg_stat_activity
                 WHERE application_name = $1 AND wait_event_type = 'Lock'",
                &[&env.tag],
            )
            .await
            .unwrap();
        if terminated > 0 {
            break;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
    assert!(terminated > 0);
    assert_eq!(
        pending.await.unwrap().status(),
        StatusCode::SERVICE_UNAVAILABLE
    );
    lock.rollback().await.unwrap();
    assert_eq!(
        env.count("SELECT count(*) FROM webhook_event_refs").await,
        1
    );
    assert_eq!(
        env.deliver(&endpoint, "d-2", "p-100").await,
        StatusCode::NO_CONTENT
    );
    env.drop_schema().await;
}

// --- consumption -------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn a_long_poll_wakes_when_a_delivery_is_stored() {
    let env = env(small()).await;
    let alice = Agent::new(92);
    let connection = env.connection("tracker", &alice, "key-a", &["p-100"]).await;
    let subscription = env.subscribe_project(&alice, &connection, "p-100").await;
    let sub = id(&subscription);
    let reconciliation = &subscription["reconciliationRequired"];
    env.post(
        &alice,
        &format!("/subscriptions/{sub}/reconciled"),
        json!({"generation": reconciliation["generation"], "barrier": reconciliation["barrier"]}),
    )
    .await;
    let endpoint = env.endpoint("tracker").await;
    let request = signed_request(
        &env.state,
        &alice,
        "GET",
        &format!("/subscriptions/{sub}/events?wait=20"),
        vec![],
    );
    let state = env.state.clone();
    let started = std::time::Instant::now();
    let poll = tokio::spawn(async move { crate::router(state).oneshot(request).await.unwrap() });
    tokio::time::sleep(Duration::from_millis(500)).await;
    assert!(!poll.is_finished(), "it waits while there is nothing");
    assert_eq!(
        env.deliver(&endpoint, "d-1", "p-100").await,
        StatusCode::NO_CONTENT
    );
    let page = body_json(poll.await.unwrap()).await;
    assert_eq!(page["events"].as_array().unwrap().len(), 1);
    assert!(
        started.elapsed() < Duration::from_secs(10),
        "woken, not timed out"
    );
    env.drop_schema().await;
}

/// `maxBytes` on the route (Webhook Subscriptions 0.2.0-draft §7): an event
/// over it alone comes back alone, marked `omitted` and without `body`; a
/// value below 1, or not an integer, is refused with `400`.
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn events_take_max_bytes() {
    let env = env(small()).await;
    let alice = Agent::new(94);
    let connection = env.connection("tracker", &alice, "key-a", &["p-100"]).await;
    let sub = id(&env.subscribe_project(&alice, &connection, "p-100").await);
    let endpoint = env.endpoint("tracker").await;
    for n in 0..2 {
        env.deliver(&endpoint, &format!("d-{n}"), "p-100").await;
    }
    for bad in ["0", "-1", "lots"] {
        assert_eq!(
            env.get(
                &alice,
                &format!("/subscriptions/{sub}/events?maxBytes={bad}")
            )
            .await
            .status(),
            StatusCode::BAD_REQUEST,
            "maxBytes={bad}"
        );
    }
    let page = body_json(
        env.get(&alice, &format!("/subscriptions/{sub}/events?maxBytes=1"))
            .await,
    )
    .await;
    let events = page["events"].as_array().unwrap();
    assert_eq!(events.len(), 1);
    assert_eq!(events[0]["payload"]["omitted"], true);
    assert!(events[0]["payload"].get("body").is_none());
    assert!(events[0]["payload"]["sha256"].is_string());
    assert_eq!(page["more"], true);
    let page = body_json(
        env.get(
            &alice,
            &format!("/subscriptions/{sub}/events?maxBytes=1000000"),
        )
        .await,
    )
    .await;
    let events = page["events"].as_array().unwrap();
    assert_eq!(events.len(), 2);
    assert!(events
        .iter()
        .all(|e| e["payload"]["body"].is_string() && e["payload"].get("omitted").is_none()));
    env.drop_schema().await;
}

#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn forged_future_and_obsolete_cursors_are_refused_on_the_routes() {
    let env = env(small()).await;
    let alice = Agent::new(93);
    let connection = env.connection("tracker", &alice, "key-a", &["p-100"]).await;
    let sub = id(&env.subscribe_project(&alice, &connection, "p-100").await);
    let endpoint = env.endpoint("tracker").await;
    for n in 0..3 {
        env.deliver(&endpoint, &format!("d-{n}"), "p-100").await;
    }
    let page = body_json(
        env.get(&alice, &format!("/subscriptions/{sub}/events?limit=1"))
            .await,
    )
    .await;
    let cursor = page["events"][0]["cursor"].as_str().unwrap().to_owned();
    let key =
        super::cursor::CursorKey::new(env.security.derive_subkey(super::cursor::SUBKEY_LABEL));
    let cases = [
        (
            json!({"generation": "g1", "cursor": super::cursor::CursorKey::new([3; 32]).encode(&sub, 1, 1)}),
            "cursor-not-issued",
        ),
        (
            json!({"generation": "g1", "cursor": key.encode(&sub, 1, 3)}),
            "cursor-ahead",
        ),
        (
            json!({"generation": "g1", "cursor": key.encode(&sub, 9, 1)}),
            "obsolete-generation",
        ),
        (
            json!({"generation": "g2", "cursor": cursor}),
            "obsolete-generation",
        ),
    ];
    for (body, code) in cases {
        let response = env
            .post(&alice, &format!("/subscriptions/{sub}/ack"), body)
            .await;
        assert_eq!(response.status(), StatusCode::CONFLICT, "{code}");
        assert_eq!(body_json(response).await["code"], code);
    }
    let response = env
        .get(
            &alice,
            &format!(
                "/subscriptions/{sub}/events?after={}",
                key.encode(&sub, 1, 3)
            ),
        )
        .await;
    assert_eq!(response.status(), StatusCode::CONFLICT);
    env.drop_schema().await;
}

/// Concurrent signed subscriptions stop exactly at the owner's quota.
#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn concurrent_subscriptions_through_the_routes_stop_at_the_quota() {
    let env = env(small()).await;
    let alice = Agent::new(94);
    let projects: Vec<String> = (0..10).map(|n| format!("p-{n}")).collect();
    let ids: Vec<&str> = projects.iter().map(String::as_str).collect();
    let connection = env.connection("tracker", &alice, "key-a", &ids).await;
    let mut tasks = tokio::task::JoinSet::new();
    for project in &projects {
        let body =
            json!({"source": "project", "parameters": {"projectId": project}, "events": ["task"]});
        let request = signed_request(
            &env.state,
            &alice,
            "POST",
            &format!("/connections/{connection}/subscriptions"),
            serde_json::to_vec(&body).unwrap(),
        );
        let state = env.state.clone();
        tasks.spawn(async move {
            crate::router(state)
                .oneshot(request)
                .await
                .unwrap()
                .status()
        });
    }
    let mut created = 0;
    while let Some(status) = tasks.join_next().await {
        match status.unwrap() {
            StatusCode::CREATED => created += 1,
            StatusCode::TOO_MANY_REQUESTS => {}
            other => panic!("{other}"),
        }
    }
    assert_eq!(created, 3);
    env.drop_schema().await;
}

/// With the inbox off, none of the routes exists.
#[tokio::test]
async fn no_webhook_route_exists_when_disabled() {
    let router = crate::test_support::router_without_database();
    for (method, path) in [
        (
            "POST",
            "/webhooks/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
        ),
        ("GET", "/subscriptions/x"),
        ("POST", "/subscriptions/x/ack"),
        ("POST", "/connections/x/subscriptions"),
    ] {
        let response = router
            .clone()
            .oneshot(
                Request::builder()
                    .method(method)
                    .uri(path)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert!(
            matches!(
                response.status(),
                StatusCode::NOT_FOUND | StatusCode::METHOD_NOT_ALLOWED
            ),
            "{method} {path}: {}",
            response.status()
        );
    }
}

/// A dedicated hook's cleanup re-runs the managing connection's access
/// check with the hook's recorded parameters, requires the bound key, and
/// only then sends the allowlisted delete.
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn hook_cleanup_rechecks_access_before_deleting() {
    use super::cleanup::HookDeleter as _;
    use super::provider::ProviderHookDeleter;
    let env = env(small()).await;
    let alice = Agent::new(95);
    let connection = env
        .connection("tracker", &alice, "key-del", &["p-del", "p-moved"])
        .await;
    let deleter = ProviderHookDeleter {
        state: env.state.clone(),
    };
    let hook = |key: &str, provider: &str| super::store::HookToDelete {
        hook_id: "fixture-hook".into(),
        endpoint_id: "fixture-endpoint".into(),
        platform: "tracker".into(),
        source_kind: "project".into(),
        source_key: key.into(),
        access_parameters: serde_json::to_string(&json!({"projectId": key})).unwrap(),
        provider_hook_id: Some(provider.into()),
        management_connection_id: Some(connection.clone()),
    };
    deleter.delete(&hook("p-del", "wh-1")).await.unwrap();
    assert!(DELETED_HOOKS
        .lock()
        .unwrap()
        .contains(&"p-del/wh-1".to_owned()));

    // Provisioning ended before the provider's answer: the hook is found by
    // its endpoint URL in the declared list, and only that one is deleted.
    let mut unanswered = hook("p-del", "unused");
    unanswered.provider_hook_id = None;
    deleter.delete(&unanswered).await.unwrap();
    let deleted = DELETED_HOOKS.lock().unwrap().clone();
    assert!(deleted.contains(&"p-del/wh-found".to_owned()));
    assert!(!deleted.iter().any(|d| d.ends_with("wh-other")));
    // Not listed: nothing was created, nothing to delete.
    let mut never = hook("p-del", "unused");
    never.provider_hook_id = None;
    never.endpoint_id = "never-created".into();
    deleter.delete(&never).await.unwrap();

    // The source answers with another key now (renamed, name reused): no
    // delete is sent.
    let mut moved = hook("p-moved", "wh-2");
    moved.source_key = "p-other".into();
    assert_eq!(
        deleter.delete(&moved).await,
        Err(super::cleanup::CleanupError::Permanent(
            "access-check-failed"
        ))
    );
    // Access lost: no delete either.
    env.grants
        .lock()
        .unwrap()
        .insert("key-del".into(), HashSet::new());
    assert_eq!(
        deleter.delete(&hook("p-del", "wh-3")).await,
        Err(super::cleanup::CleanupError::Permanent(
            "access-check-failed"
        ))
    );
    let mut orphan = hook("p-del", "wh-4");
    orphan.management_connection_id = None;
    assert_eq!(
        deleter.delete(&orphan).await,
        Err(super::cleanup::CleanupError::Permanent(
            "no-managing-connection"
        ))
    );
    let deleted = DELETED_HOOKS.lock().unwrap().clone();
    assert!(!deleted
        .iter()
        .any(|d| d.ends_with("wh-2") || d.ends_with("wh-3") || d.ends_with("wh-4")));
    env.drop_schema().await;
}

// --- review of #394 --------------------------------------------------------------------

/// A request body that never arrives.
fn never_ending() -> Body {
    Body::from_stream(futures_util::stream::pending::<
        Result<axum::body::Bytes, std::io::Error>,
    >())
}

/// The webhooks state with another ingress gate.
fn with_gate(env: &Env, change: impl FnOnce(&mut super::IngressGate)) -> AppState {
    let mut webhooks = Webhooks::new(
        env.store.clone(),
        BTreeMap::from([("tracker".to_owned(), TRACKER_SECRET.to_vec())]),
    );
    change(&mut webhooks.gate);
    let mut state = env.state.clone();
    state.webhooks = Some(Arc::new(webhooks));
    state
}

/// B1: nothing is read before the endpoint is known and the declared
/// length fits; a body is read only within a timeout and by a bounded
/// number of requests at once.
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn ingress_reads_no_body_before_its_checks_and_bounds_what_it_reads() {
    let env = env(small()).await;
    let alice = Agent::new(99);
    let connection = env.connection("tracker", &alice, "key-a", &["p-100"]).await;
    env.subscribe_project(&alice, &connection, "p-100").await;
    let endpoint = env.endpoint("tracker").await;
    let quick = Duration::from_secs(2);

    // Unknown or malformed endpoints answer without reading the body.
    for path in [
        format!("/webhooks/{}", "A".repeat(43)),
        "/webhooks/short".into(),
        format!("/webhooks/{}", "!".repeat(43)),
    ] {
        let request = Request::post(path).body(never_ending()).unwrap();
        let response = tokio::time::timeout(quick, env.send(request))
            .await
            .expect("answered without reading");
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }
    // A declared length over the cap: 413 at once.
    let request = Request::post(format!("/webhooks/{endpoint}"))
        .header("content-length", "30000000")
        .body(never_ending())
        .unwrap();
    let response = tokio::time::timeout(quick, env.send(request))
        .await
        .expect("answered at once");
    assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE);
    // An undeclared length over the cap: refused once the cap is passed.
    let chunks = futures_util::stream::iter(
        (0..10).map(|_| Ok::<_, std::io::Error>(axum::body::Bytes::from(vec![b'x'; 1000]))),
    );
    let request = Request::post(format!("/webhooks/{endpoint}"))
        .body(Body::from_stream(chunks))
        .unwrap();
    assert_eq!(
        env.send(request).await.status(),
        StatusCode::PAYLOAD_TOO_LARGE
    );

    // A slow upload is cut off by the read timeout.
    let state = with_gate(&env, |gate| gate.read_timeout = Duration::from_millis(300));
    let request = Request::post(format!("/webhooks/{endpoint}"))
        .body(never_ending())
        .unwrap();
    let response = tokio::time::timeout(quick, crate::router(state).oneshot(request))
        .await
        .expect("timed out by the gate")
        .unwrap();
    assert_eq!(response.status(), StatusCode::REQUEST_TIMEOUT);

    // With every read slot taken by slow uploads, the next one is refused
    // after a short wait instead of being buffered.
    let state = with_gate(&env, |gate| {
        gate.reads = tokio::sync::Semaphore::new(1);
        gate.wait = Duration::from_millis(200);
    });
    let slow = {
        let state = state.clone();
        let request = Request::post(format!("/webhooks/{endpoint}"))
            .body(never_ending())
            .unwrap();
        tokio::spawn(async move { crate::router(state).oneshot(request).await })
    };
    tokio::time::sleep(Duration::from_millis(200)).await;
    let request = env.signed_delivery(&endpoint, "d-1", &task("p-100", "t/1"));
    let response = crate::router(state).oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
    slow.abort();
    assert_eq!(env.count("SELECT count(*) FROM webhook_receipts").await, 0);
    env.drop_schema().await;
}

/// B1: with every inbox connection busy, requests fail after a bounded
/// wait instead of queueing without end.
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn a_busy_inbox_pool_answers_503_after_a_bounded_wait() {
    let env = env(small()).await;
    let alice = Agent::new(100);
    let connection = env.connection("tracker", &alice, "key-a", &["p-100"]).await;
    let sub = id(&env.subscribe_project(&alice, &connection, "p-100").await);
    let endpoint = env.endpoint("tracker").await;
    let held = [
        env.store.hold_connection().await,
        env.store.hold_connection().await,
        env.store.hold_connection().await,
        env.store.hold_connection().await,
    ];
    let started = std::time::Instant::now();
    let response = env.get(&alice, &format!("/subscriptions/{sub}")).await;
    assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
    let response = env
        .send(env.signed_delivery(&endpoint, "d-1", &task("p-100", "t/1")))
        .await;
    assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
    assert!(started.elapsed() < Duration::from_secs(15));
    drop(held);
    assert_eq!(
        env.deliver(&endpoint, "d-1", "p-100").await,
        StatusCode::NO_CONTENT
    );
    env.drop_schema().await;
}

/// N1: a long poll is woken by its own subscription's deliveries only, and
/// waiting polls are capped per consumer.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn long_polls_wake_per_subscription_and_are_capped() {
    let env = env(small()).await;
    let alice = Agent::new(101);
    let connection = env
        .connection("tracker", &alice, "key-a", &["p-1", "p-2"])
        .await;
    let mut ids = Vec::new();
    for project in ["p-1", "p-2"] {
        let subscription = env.subscribe_project(&alice, &connection, project).await;
        let reconciliation = &subscription["reconciliationRequired"];
        let sub = id(&subscription);
        env.post(
            &alice,
            &format!("/subscriptions/{sub}/reconciled"),
            json!({"generation": reconciliation["generation"], "barrier": reconciliation["barrier"]}),
        )
        .await;
        ids.push(sub);
    }
    let endpoint = env.endpoint("tracker").await;
    let poll = |sub: &str| {
        let request = signed_request(
            &env.state,
            &alice,
            "GET",
            &format!("/subscriptions/{sub}/events?wait=20"),
            vec![],
        );
        let state = env.state.clone();
        tokio::spawn(async move { crate::router(state).oneshot(request).await.unwrap() })
    };
    let first = poll(&ids[0]);
    tokio::time::sleep(Duration::from_millis(300)).await;
    // A delivery to the other subscription does not wake it.
    assert_eq!(
        env.deliver(&endpoint, "d-2", "p-2").await,
        StatusCode::NO_CONTENT
    );
    tokio::time::sleep(Duration::from_millis(300)).await;
    assert!(!first.is_finished());
    assert_eq!(
        env.deliver(&endpoint, "d-1", "p-1").await,
        StatusCode::NO_CONTENT
    );
    let page = body_json(
        tokio::time::timeout(Duration::from_secs(5), first)
            .await
            .unwrap()
            .unwrap(),
    )
    .await;
    assert_eq!(page["events"][0]["deliveryId"], "d-1");
    // Acknowledged, so the next polls have nothing and wait.
    let acknowledged = env
        .post(
            &alice,
            &format!("/subscriptions/{}/ack", ids[0]),
            json!({"generation": page["generation"], "cursor": page["events"][0]["cursor"]}),
        )
        .await;
    assert_eq!(acknowledged.status(), StatusCode::OK);

    // Four waiting polls of one consumer; a fifth is told to retry.
    let waiting: Vec<_> = (0..4).map(|_| poll(&ids[0])).collect();
    let waiters =
        |webhooks: &Webhooks| -> usize { webhooks.waiting.lock().unwrap().values().sum() };
    let webhooks = env.state.webhooks.clone().unwrap();
    eventually("four polls waiting", || waiters(&webhooks) == 4).await;
    let started = std::time::Instant::now();
    let extra = poll(&ids[0]).await.unwrap();
    assert_eq!(extra.status(), StatusCode::TOO_MANY_REQUESTS);
    assert!(extra.headers().contains_key("retry-after"));
    assert!(started.elapsed() < Duration::from_secs(5), "not waiting");
    // Cancelled polls (clients gone) leave no wakeup behind.
    assert_eq!(env.store.waiter_count(), 1);
    for task in waiting {
        task.abort();
    }
    eventually("no wakeup left", || env.store.waiter_count() == 0).await;
    assert_eq!(waiters(&webhooks), 0);
    env.drop_schema().await;
}

/// N3: a subscription created while its connection is being deleted never
/// outlives the deletion.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn a_subscription_racing_its_connections_deletion_does_not_outlive_it() {
    let env = env(Policy::pilot(1 << 30)).await;
    for round in 0..10u8 {
        let owner = Agent::new(110 + round);
        let connection = env
            .connection("tracker", &owner, &format!("key-{round}"), &["p-1"])
            .await;
        let body =
            json!({"source": "project", "parameters": {"projectId": "p-1"}, "events": ["task"]});
        let subscribe = signed_request(
            &env.state,
            &owner,
            "POST",
            &format!("/connections/{connection}/subscriptions"),
            serde_json::to_vec(&body).unwrap(),
        );
        let delete = signed_request(
            &env.state,
            &owner,
            "DELETE",
            &format!("/connections/{connection}"),
            vec![],
        );
        let (a, b) = (env.state.clone(), env.state.clone());
        let (_created, deleted) = tokio::join!(
            async move { crate::router(a).oneshot(subscribe).await.unwrap() },
            async move { crate::router(b).oneshot(delete).await.unwrap() },
        );
        assert_eq!(deleted.status(), StatusCode::NO_CONTENT);
        let live = env
            .count(&format!(
                "SELECT count(*) FROM webhook_subscriptions WHERE connection_id = '{connection}'
                 AND state IN ('provisioning', 'needs-reconciliation', 'active')"
            ))
            .await;
        assert_eq!(live, 0, "round {round}");
    }
    env.drop_schema().await;
}

/// A former consumer reads nothing once it lost standing, not even the
/// closed subscription.
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn a_former_consumer_cannot_read_a_closed_subscription() {
    let env = env(small()).await;
    let owner = Agent::new(102);
    let app = Agent::new(103);
    let connection = env.connection("tracker", &owner, "key-o", &["p-1"]).await;
    env.security
        .put_delegation(&connection, &owner.id(), &app.id(), None)
        .await
        .unwrap();
    let sub = id(&env.subscribe_project(&app, &connection, "p-1").await);
    let deleted = env
        .send(signed_request(
            &env.state,
            &app,
            "DELETE",
            &format!("/subscriptions/{sub}"),
            vec![],
        ))
        .await;
    assert_eq!(deleted.status(), StatusCode::OK);
    assert!(env
        .security
        .delete_delegation(&connection, &owner.id(), &app.id())
        .await
        .unwrap());
    let response = env.get(&app, &format!("/subscriptions/{sub}")).await;
    assert_eq!(response.status(), StatusCode::FORBIDDEN);
    env.drop_schema().await;
}

/// A broken upload is a 400, not a 413; one endpoint cannot hold every read
/// slot.
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn broken_uploads_and_the_per_endpoint_read_cap() {
    let env = env(small()).await;
    let alice = Agent::new(104);
    let connection = env.connection("tracker", &alice, "key-a", &["p-100"]).await;
    env.subscribe_project(&alice, &connection, "p-100").await;
    let endpoint = env.endpoint("tracker").await;
    let broken = futures_util::stream::iter([
        Ok(axum::body::Bytes::from_static(b"{\"kind\"")),
        Err(std::io::Error::other("connection reset")),
    ]);
    let request = Request::post(format!("/webhooks/{endpoint}"))
        .body(Body::from_stream(broken))
        .unwrap();
    assert_eq!(env.send(request).await.status(), StatusCode::BAD_REQUEST);

    let state = with_gate(&env, |gate| {
        gate.reads_per_endpoint = 1;
        gate.wait = Duration::from_millis(200);
    });
    let slow = {
        let state = state.clone();
        let request = Request::post(format!("/webhooks/{endpoint}"))
            .body(never_ending())
            .unwrap();
        tokio::spawn(async move { crate::router(state).oneshot(request).await })
    };
    tokio::time::sleep(Duration::from_millis(200)).await;
    let request = env.signed_delivery(&endpoint, "d-1", &task("p-100", "t/1"));
    let response = crate::router(state.clone()).oneshot(request).await.unwrap();
    assert_eq!(
        response.status(),
        StatusCode::SERVICE_UNAVAILABLE,
        "the endpoint's one read slot is taken"
    );
    slow.abort();
    tokio::time::sleep(Duration::from_millis(100)).await;
    let request = env.signed_delivery(&endpoint, "d-1", &task("p-100", "t/1"));
    assert_eq!(
        crate::router(state)
            .oneshot(request)
            .await
            .unwrap()
            .status(),
        StatusCode::NO_CONTENT,
        "released when the slow upload went away"
    );
    env.drop_schema().await;
}

fn with_limits(env: &Env, endpoint: u32, network: u32, owner: u32) -> AppState {
    let config = crate::config::WebhookConfig {
        ingress_per_endpoint_per_minute: endpoint,
        ingress_per_network_per_minute: network,
        subscribe_per_owner_per_hour: owner,
        ..Default::default()
    };
    let mut state = env.state.clone();
    state.webhooks = Some(Arc::new(Webhooks::with_limits(
        env.store.clone(),
        BTreeMap::from([("tracker".to_owned(), TRACKER_SECRET.to_vec())]),
        super::limits::Limits::from_config(&config),
    )));
    state
}

/// Ingress limits (reviews of the rate-limits PR): they count refusals only.
/// Blocker A: a third party that points a provider's hooks at junk URLs, or
/// signs junk for a real endpoint, makes the provider's own address collect
/// refusals; its real deliveries must still be accepted (here with the
/// lookup slot free; `a_blocked_network_queues_for_the_lookup_slot_only_a_little`
/// covers a busy slot). Only ids that name no endpoint are refused for a
/// network's refusals, and an endpoint's window counts only its failed
/// verifications.
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn ingress_limits_never_refuse_a_delivery_that_verifies() {
    let mut env = env(small()).await;
    let alice = Agent::new(96);
    let connection = env.connection("tracker", &alice, "key-a", &["p-100"]).await;
    env.subscribe_project(&alice, &connection, "p-100").await;
    let endpoint = env.endpoint("tracker").await;
    env.state.trust_forwarded_for = crate::config::TrustForwardedFor::RightMost;
    let state = with_limits(&env, 2, 2, 20);
    let from = |network: &str, request: Request<Body>| {
        let mut request = request;
        request
            .headers_mut()
            .insert("x-forwarded-for", network.parse().unwrap());
        request
    };
    let delivery = |id: &str| env.signed_delivery(&endpoint, id, &task("p-100", id));
    let send = |request: Request<Body>| {
        let state = state.clone();
        async move { crate::router(state).oneshot(request).await.unwrap() }
    };
    let junk_id = |n: u32| {
        Request::post(format!("/webhooks/{:0>43}", n))
            .body(Body::from("{}"))
            .unwrap()
    };
    let bad_signature = |id: &str| {
        let mut request = delivery(id);
        request
            .headers_mut()
            .insert("tracker-signature", "v1=00".parse().unwrap());
        request
    };
    let provider = "192.0.2.1";
    // Junk arrives from the provider's own address: unknown ids, then bad
    // signatures for the real endpoint, over both limits (2).
    for n in 0..2 {
        assert_eq!(
            send(from(provider, junk_id(n))).await.status(),
            StatusCode::NOT_FOUND
        );
    }
    assert_eq!(
        send(from(provider, junk_id(9))).await.status(),
        StatusCode::TOO_MANY_REQUESTS,
        "unknown ids from a network over its limit are refused"
    );
    assert_eq!(
        send(from(provider, bad_signature("j1"))).await.status(),
        StatusCode::UNAUTHORIZED
    );
    assert_eq!(
        send(from(provider, bad_signature("j2"))).await.status(),
        StatusCode::UNAUTHORIZED
    );
    let limited = send(from(provider, bad_signature("j3"))).await;
    assert_eq!(limited.status(), StatusCode::TOO_MANY_REQUESTS);
    assert!(limited.headers().contains_key("retry-after"));
    // The provider's real deliveries still go through, more of them than
    // either limit.
    for id in ["a1", "a2", "a3", "a4"] {
        assert_eq!(
            send(from(provider, delivery(id))).await.status(),
            StatusCode::NO_CONTENT,
            "{id}"
        );
    }
    // Random endpoint ids, from many networks, never take a key of the
    // endpoint limiter.
    for n in 0..50 {
        assert_eq!(
            send(from(&format!("203.0.113.{n}"), junk_id(100 + n)))
                .await
                .status(),
            StatusCode::NOT_FOUND
        );
    }
    let webhooks = state.webhooks.clone().unwrap();
    assert_eq!(webhooks.limits.ingress_per_endpoint.tracked(), 1);
    assert_eq!(
        env.count("SELECT count(*) FROM webhook_event_refs").await,
        4
    );
    env.drop_schema().await;
}

/// Re-reviews of the rate-limits PR: a blocked network may queue for the
/// one lookup slot, but only `INGRESS_BLOCKED_WAITERS` of its requests at a
/// time; the rest get `429` at once. So a real delivery from a blocked
/// network that shares its addresses with junk (a provider's) still gets
/// through while the slot is busy, and a flood from blocked networks cannot
/// hold up deliveries from other networks.
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn a_blocked_network_queues_for_the_lookup_slot_only_a_little() {
    // Room for every real delivery below (12), so each one is stored rather
    // than recorded as a gap, and the test can count them.
    let mut policy = small();
    policy.subscription_max_pending_events = 32;
    policy.subscription_max_pending_bytes = 1 << 16;
    policy.owner_max_pending_bytes = 1 << 17;
    policy.owner_max_pending_references = 64;
    let mut env = env(policy).await;
    let alice = Agent::new(99);
    let connection = env.connection("tracker", &alice, "key-a", &["p-100"]).await;
    env.subscribe_project(&alice, &connection, "p-100").await;
    let endpoint = env.endpoint("tracker").await;
    env.state.trust_forwarded_for = crate::config::TrustForwardedFor::RightMost;
    let state = with_limits(&env, 600, 2, 20);
    let from = |network: &str, request: Request<Body>| {
        let mut request = request;
        request
            .headers_mut()
            .insert("x-forwarded-for", network.parse().unwrap());
        request
    };
    let junk = |n: usize| {
        Request::post(format!("/webhooks/{:0>43}", n))
            .body(Body::from("{}"))
            .unwrap()
    };
    let send = |request: Request<Body>| {
        let state = state.clone();
        async move { crate::router(state).oneshot(request).await.unwrap() }
    };
    let delivery = |id: &str| env.signed_delivery(&endpoint, id, &task("p-100", id));
    // The provider's address, pushed over its limit by junk sent to it.
    let provider = "192.0.2.1";
    let other = "203.0.113.9";
    for n in 0..3 {
        send(from(provider, junk(n))).await;
    }
    assert_eq!(
        send(from(provider, junk(9))).await.status(),
        StatusCode::TOO_MANY_REQUESTS,
        "the provider's network is blocked"
    );

    // The lookup slot is busy. A real delivery from the blocked network
    // queues; so does one junk request; the queue is then full, and further
    // requests from blocked networks get 429 at once.
    let webhooks = state.webhooks.clone().unwrap();
    let held = webhooks.gate.lookups.acquire().await.unwrap();
    let real = tokio::spawn(send(from(provider, delivery("real-blocked"))));
    tokio::time::sleep(Duration::from_millis(50)).await;
    let queued_junk = tokio::spawn(send(from(provider, junk(50))));
    tokio::time::sleep(Duration::from_millis(50)).await;
    let elsewhere = tokio::spawn(send(from(other, delivery("real-other"))));
    let started = std::time::Instant::now();
    for n in 0..20 {
        assert_eq!(
            send(from(provider, junk(100 + n))).await.status(),
            StatusCode::TOO_MANY_REQUESTS
        );
    }
    assert!(
        started.elapsed() < Duration::from_secs(1),
        "over the queue cap nothing waits"
    );
    tokio::time::sleep(Duration::from_millis(200)).await;
    drop(held);
    assert_eq!(
        real.await.unwrap().status(),
        StatusCode::NO_CONTENT,
        "a real delivery from a blocked network that queued gets through"
    );
    assert_eq!(elsewhere.await.unwrap().status(), StatusCode::NO_CONTENT);
    assert_eq!(
        queued_junk.await.unwrap().status(),
        StatusCode::TOO_MANY_REQUESTS
    );

    // A flood from the blocked network, with real deliveries from another
    // network interleaved: every real one is stored, no flood request
    // anything but refused.
    let mut flood = Vec::new();
    let mut real = Vec::new();
    for n in 0..200 {
        flood.push(tokio::spawn(send(from(provider, junk(1000 + n)))));
        if n % 20 == 0 {
            let id = format!("interleaved-{n}");
            real.push(tokio::spawn(send(from(other, delivery(&id)))));
        }
    }
    for (n, request) in real.into_iter().enumerate() {
        assert_eq!(
            request.await.unwrap().status(),
            StatusCode::NO_CONTENT,
            "interleaved delivery {n}"
        );
    }
    for request in flood {
        let status = request.await.unwrap().status();
        assert!(matches!(status, StatusCode::TOO_MANY_REQUESTS), "{status}");
    }
    // Every real delivery above was stored: the two queued while the slot
    // was busy and the ten interleaved with the flood. No flood request
    // stored anything.
    assert_eq!(
        env.count("SELECT count(*) FROM webhook_event_refs").await,
        12
    );
    env.drop_schema().await;
}

/// Subscription requests are limited per owner before the access check
/// reaches the provider.
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn subscribing_is_rate_limited_per_owner() {
    let env = env(small()).await;
    let alice = Agent::new(97);
    let bob = Agent::new(98);
    let ac = env
        .connection("tracker", &alice, "key-a", &["p-1", "p-2", "p-3"])
        .await;
    let bc = env.connection("tracker", &bob, "key-b", &["p-9"]).await;
    let state = with_limits(&env, 600, 120, 2);
    let subscribe = |agent: &Agent, connection: &str, project: &str| {
        let body =
            json!({"source": "project", "parameters": {"projectId": project}, "events": ["task"]});
        signed_request(
            &state,
            agent,
            "POST",
            &format!("/connections/{connection}/subscriptions"),
            serde_json::to_vec(&body).unwrap(),
        )
    };
    let send = |request: Request<Body>| {
        let state = state.clone();
        async move { crate::router(state).oneshot(request).await.unwrap() }
    };
    assert_eq!(
        send(subscribe(&alice, &ac, "p-1")).await.status(),
        StatusCode::CREATED
    );
    // A refused access check counts as well: it reached the provider.
    assert_eq!(
        send(subscribe(&alice, &ac, "p-404")).await.status(),
        StatusCode::FORBIDDEN
    );
    let limited = send(subscribe(&alice, &ac, "p-3")).await;
    assert_eq!(limited.status(), StatusCode::TOO_MANY_REQUESTS);
    assert!(limited.headers().contains_key("retry-after"));
    assert_eq!(
        send(subscribe(&bob, &bc, "p-9")).await.status(),
        StatusCode::CREATED
    );
    env.drop_schema().await;
}

/// Waits up to ten seconds for `condition`, checking every 20 ms.
async fn eventually(what: &str, condition: impl Fn() -> bool) {
    let deadline = std::time::Instant::now() + Duration::from_secs(10);
    while !condition() {
        assert!(
            std::time::Instant::now() < deadline,
            "timed out waiting for: {what}"
        );
        tokio::time::sleep(Duration::from_millis(20)).await;
    }
}

#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL"]
async fn notification_only_receiver_discards_provider_body_before_persistence() {
    let mut env = env(small()).await;
    Arc::get_mut(env.state.webhooks.as_mut().unwrap())
        .unwrap()
        .notifications_only = true;
    env.store.check_payload_mode(true).await.unwrap();
    assert!(env.store.check_payload_mode(false).await.is_err());
    let alice = Agent::new(91);
    let connection = env
        .connection("tracker", &alice, "key-notice", &["p-notice"])
        .await;
    let _subscription = env.subscribe_project(&alice, &connection, "p-notice").await;
    let endpoint = env.endpoint("tracker").await;
    let body = task("p-notice", "private-provider-record");
    assert_eq!(
        env.send(env.signed_delivery(&endpoint, "notice-1", &body))
            .await
            .status(),
        StatusCode::NO_CONTENT
    );
    let row = env
        .security
        .client()
        .await
        .query_one(
            "SELECT body FROM webhook_payloads WHERE delivery_id='notice-1'",
            &[],
        )
        .await
        .unwrap();
    assert_eq!(row.get::<_, Vec<u8>>(0), br#"{"notification":true}"#);
    env.drop_schema().await;
}

#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL"]
async fn device_notifications_require_selected_connection_and_notification_only_storage() {
    let mut env = env(small()).await;
    assert_eq!(
        env.send(
            Request::builder()
                .uri("/manage")
                .body(Body::empty())
                .unwrap()
        )
        .await
        .status(),
        StatusCode::OK
    );
    env.state
        .device
        .clients
        .insert("notification-client".into(), "Notification client".into());
    env.state.device.approval_url = Some("http://localhost/approve".into());
    let alice = Agent::new(92);
    let connection = env
        .connection("tracker", &alice, "key-device-notice", &["p-one", "p-two"])
        .await;
    let subscription = env.subscribe_project(&alice, &connection, "p-one").await;
    let other_connection = env
        .connection("tracker", &alice, "key-device-other", &["p-two"])
        .await;
    let other = env
        .subscribe_project(&alice, &other_connection, "p-two")
        .await;
    let (device, code) = crate::device::store::create(
        &env.security,
        "notification-client",
        &env.state.base_url,
        "notifications:consume",
    )
    .await
    .unwrap();
    let challenge = crate::device::store::challenge(
        &env.security,
        &code.replace('-', ""),
        &alice.id(),
        &env.state.base_url,
    )
    .await
    .unwrap();
    crate::device::store::approve(
        &env.security,
        challenge["challenge"].as_str().unwrap(),
        &alice.id(),
        &env.state.base_url,
        &[connection],
        true,
    )
    .await
    .unwrap();
    env.security
        .client()
        .await
        .execute(
            "UPDATE device_grants SET next_poll=NOW()-INTERVAL '1 second'",
            &[],
        )
        .await
        .unwrap();
    let grant = crate::device::store::poll(
        &env.security,
        &device,
        "notification-client",
        &env.state.base_url,
    )
    .await
    .unwrap();
    let get = |sub: &Value| {
        Request::builder()
            .uri(format!("/subscriptions/{}", id(sub)))
            .header(
                "authorization",
                format!("Bearer {}", grant["access_token"].as_str().unwrap()),
            )
            .body(Body::empty())
            .unwrap()
    };
    // A notification grant cannot expose a raw-payload inbox, even with standing.
    assert_eq!(
        env.send(get(&subscription)).await.status(),
        StatusCode::FORBIDDEN
    );
    Arc::get_mut(env.state.webhooks.as_mut().unwrap())
        .unwrap()
        .notifications_only = true;
    assert_eq!(env.send(get(&subscription)).await.status(), StatusCode::OK);
    assert_eq!(env.send(get(&other)).await.status(), StatusCode::FORBIDDEN);
    env.drop_schema().await;
}