atomic-integration-proxy 0.3.0

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
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
//! `ANY /proxy/{connection_id}/{platform}/{path}`: proxied provider calls
//! (issue #54).
//!
//! Every request is authenticated one of two ways, both ending in a v2
//! request signature (see [`crate::signature`]):
//!
//! - **Signed by an agent with standing** on the connection: its owner; an
//!   app agent holding a delegation for it; or a runtime registered (by the
//!   owner) for such an app. Delegations and runtimes are read on every
//!   request, so revoking one takes effect on the next.
//! - **A frame capability** (`Authorization: Capability …`, see
//!   [`crate::capability`]) signed by the owner for a delegated app, plus a
//!   request signature by the capability's `cnf` key.
//!
//! Nothing rotates: the connection id is not a secret, and a signature is
//! accepted once. The connection id is in the path, so the signature covers
//! it. The owner is then checked against the access policy.
use axum::{
    body::Bytes,
    extract::{OriginalUri, Path, RawQuery, State},
    http::{header, HeaderMap, Method, StatusCode},
    response::{IntoResponse, Response},
};
use serde::{Deserialize, Serialize};
use url::Url;

use crate::{
    agent_id,
    api_error::ApiError,
    capability,
    security::{ConnectionRecord, Security, Standing},
    AppState,
};

/// The provider credential sealed in a connection row, interpreted only here
/// and where it is minted (`oauth.rs`'s callback, `connect.rs`'s apiKey,
/// http and no-credential branches). Its `Debug` output names the kind and
/// platform only, never a secret.
#[derive(Clone, Deserialize, Serialize)]
#[serde(tag = "kind")]
pub(crate) enum StoredCredential {
    #[serde(rename = "oauth")]
    OAuth {
        provider: String,
        access_token: String,
        refresh_token: Option<String>,
        expires_at: Option<u64>,
    },
    /// `scheme` (unreleased; absent in rows written before) names the
    /// `apiKey` security scheme the key was entered for; while it is
    /// present the key is sent only under that scheme.
    #[serde(rename = "api_key")]
    ApiKey {
        provider: String,
        key: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        scheme: Option<String>,
        /// The scheme's `in` and `name` when the key was entered; while
        /// present, the key is sent only to that same place.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        placement: Option<crate::providers::ApiKeyPlacement>,
    },
    /// A token for an `http` `bearer` scheme, sent as
    /// `Authorization: Bearer <token>`. `scheme` binds it as for an API key.
    #[serde(rename = "http_bearer")]
    HttpBearer {
        provider: String,
        token: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        scheme: Option<String>,
    },
    /// The two halves of an `http` `basic` credential, sent as
    /// `Authorization: Basic base64(username:password)`. One half is the
    /// pasted token; the other is fixed by the scheme's
    /// `x-api-key-details.basicCredentials` or, for a username only, typed
    /// by the person. `scheme` and `layout` (the declared layout it was
    /// built from) bind it: while present, it is sent only under that
    /// scheme with that layout.
    #[serde(rename = "http_basic")]
    HttpBasic {
        provider: String,
        username: String,
        password: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        scheme: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        layout: Option<crate::providers::BasicLayout>,
    },
    /// A connection to a platform whose document requires no security
    /// (`SecurityScheme::NoCredential`): only the platform it is for.
    #[serde(rename = "none")]
    NoCredential { provider: String },
}

impl std::fmt::Debug for StoredCredential {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let kind = match self {
            Self::OAuth { .. } => "oauth",
            Self::ApiKey { .. } => "api_key",
            Self::HttpBearer { .. } => "http_bearer",
            Self::HttpBasic { .. } => "http_basic",
            Self::NoCredential { .. } => "none",
        };
        f.debug_struct("StoredCredential")
            .field("kind", &kind)
            .field("provider", &self.provider())
            .finish_non_exhaustive()
    }
}

impl StoredCredential {
    fn provider(&self) -> &str {
        match self {
            Self::OAuth { provider, .. }
            | Self::ApiKey { provider, .. }
            | Self::HttpBearer { provider, .. }
            | Self::HttpBasic { provider, .. }
            | Self::NoCredential { provider } => provider,
        }
    }
}

#[derive(Deserialize)]
struct RefreshToken {
    access_token: String,
    #[serde(default)]
    refresh_token: Option<String>,
    #[serde(default)]
    expires_in: Option<u64>,
}

fn needs_refresh(credential: &StoredCredential) -> bool {
    matches!(
        credential,
        StoredCredential::OAuth { expires_at: Some(expires), .. } if *expires <= crate::now_secs() + 30
    )
}

async fn refresh_token(state: &AppState, credential: &mut StoredCredential) -> Result<(), ()> {
    let StoredCredential::OAuth {
        provider,
        access_token,
        refresh_token,
        expires_at,
    } = credential
    else {
        // A static API key has nothing to refresh.
        return Ok(());
    };
    let refresh_token_value = refresh_token.as_deref().ok_or(())?;
    let configured =
        crate::providers::Provider::configured(&state.catalog, provider).map_err(|_| ())?;
    #[cfg(test)]
    let configured = {
        let mut configured = configured;
        if let Some(upstream) = &state.test_upstream {
            configured.provider.token_url = format!("{}/token", upstream.trim_end_matches('/'));
        }
        configured
    };
    let response = configured
        .token_request(
            &state.http_client,
            &[
                ("grant_type", "refresh_token"),
                ("refresh_token", refresh_token_value),
            ],
        )
        .send()
        .await
        .map_err(|_| ())?
        .error_for_status()
        .map_err(|_| ())?;
    let token = response.json::<RefreshToken>().await.map_err(|_| ())?;
    *access_token = token.access_token;
    if token.refresh_token.is_some() {
        *refresh_token = token.refresh_token;
    }
    *expires_at = token.expires_in.map(|seconds| crate::now_secs() + seconds);
    Ok(())
}

/// Refreshes a connection's OAuth token if it is about to expire, with at
/// most one refresh in flight per connection (see
/// `Security::claim_refresh_lease`). A caller that loses the race waits for
/// the winner's result instead of spending the refresh token again.
async fn refresh_connection(
    state: &AppState,
    security: &Security,
    connection_id: &str,
    credential: &mut StoredCredential,
) -> Result<(), ()> {
    const ATTEMPTS: usize = 50;
    const WAIT: std::time::Duration = std::time::Duration::from_millis(200);
    let reload = |record: Option<ConnectionRecord>| -> Result<StoredCredential, ()> {
        serde_json::from_slice(&record.ok_or(())?.credential).map_err(|_| ())
    };
    for _ in 0..ATTEMPTS {
        if !needs_refresh(credential) {
            return Ok(());
        }
        if security
            .claim_refresh_lease(connection_id)
            .await
            .map_err(|_| ())?
        {
            // Another caller may have finished a refresh between our read
            // and our claim; start from the row as it is now.
            if let Ok(current) =
                reload(security.load_connection(connection_id).await.ok().flatten())
            {
                *credential = current;
            }
            if !needs_refresh(credential) {
                let _ = security.release_refresh_lease(connection_id).await;
                return Ok(());
            }
            if refresh_token(state, credential).await.is_err() {
                let _ = security.release_refresh_lease(connection_id).await;
                return Err(());
            }
            let serialized = serde_json::to_vec(&*credential).map_err(|_| ())?;
            return security
                .store_refreshed_connection(connection_id, &serialized)
                .await
                .map_err(|_| ());
        }
        tokio::time::sleep(WAIT).await;
        *credential = reload(security.load_connection(connection_id).await.ok().flatten())?;
    }
    Err(())
}

/// How a request was allowed to use a connection.
#[derive(Debug, PartialEq, Eq)]
enum Caller {
    Owner,
    Delegate(String),
    Runtime { agent: String, app: String },
    Frame { app: String },
}

/// Authenticates a proxied request against the connection it names. See the
/// module documentation for the two accepted presentations.
#[allow(clippy::too_many_arguments)]
async fn authenticate(
    state: &AppState,
    security: &Security,
    record: &ConnectionRecord,
    platform: &str,
    method: &Method,
    uri: &axum::http::Uri,
    headers: &HeaderMap,
    body: &[u8],
) -> Result<Caller, ApiError> {
    let owner = agent_id::parse(&record.owner).ok_or(ApiError::Internal)?;
    let authorization = headers
        .get(header::AUTHORIZATION)
        .map(|value| {
            value
                .to_str()
                .map_err(|_| ApiError::UnsupportedAuthorization)
        })
        .transpose()?;
    let caller = match authorization {
        Some(value) => {
            let token = value
                .strip_prefix("Capability ")
                .ok_or(ApiError::UnsupportedAuthorization)?;
            let parsed = capability::parse(token)?;
            parsed.verify(&owner, &state.public_origin, crate::now_secs())?;
            if parsed.claims.connection_id != record.connection_id
                || parsed.claims.platform != platform
                || record.platform != platform
            {
                return Err(ApiError::CapabilityScope);
            }
            if !security
                .is_delegated(&record.connection_id, parsed.app.as_str())
                .await
                .map_err(|_| ApiError::Unavailable)?
            {
                return Err(ApiError::NotDelegated);
            }
            let signer =
                crate::signature::authenticate(state, security, method, uri, headers, body).await?;
            if signer != parsed.cnf {
                return Err(ApiError::CapabilityKeyMismatch);
            }
            Caller::Frame {
                app: parsed.app.as_str().to_owned(),
            }
        }
        None => {
            let signer =
                crate::signature::authenticate(state, security, method, uri, headers, body).await?;
            match security
                .standing(&record.connection_id, owner.as_str(), signer.as_str())
                .await
                .map_err(|_| ApiError::Unavailable)?
            {
                Standing::Owner => Caller::Owner,
                Standing::Delegate => Caller::Delegate(signer.as_str().to_owned()),
                Standing::Runtime { app } => Caller::Runtime {
                    agent: signer.as_str().to_owned(),
                    app,
                },
                Standing::None => return Err(ApiError::NotDelegated),
            }
        }
    };
    if record.platform != platform {
        return Err(ApiError::PlatformMismatch);
    }
    crate::check_access(state, &owner).await?;
    Ok(caller)
}

/// How to attach a resolved credential to the outbound upstream request.
/// `None` covers query-located API keys, already appended to the target URL
/// before the request is built.
pub(crate) enum CredentialInjection {
    Bearer(String),
    Basic { username: String, password: String },
    Header { name: String, value: String },
    None,
}

impl CredentialInjection {
    /// Attaches the credential. reqwest marks the `Authorization` value it
    /// builds for `Bearer` and `Basic` as sensitive.
    pub(crate) fn apply(self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
        match self {
            Self::Bearer(token) => request.bearer_auth(token),
            Self::Basic { username, password } => request.basic_auth(username, Some(password)),
            Self::Header { name, value } => request.header(name, value),
            Self::None => request,
        }
    }
}

pub async fn forward(
    Path((connection_id, platform, path)): Path<(String, String, String)>,
    RawQuery(query): RawQuery,
    State(state): State<AppState>,
    method: Method,
    OriginalUri(uri): OriginalUri,
    headers: HeaderMap,
    body: Bytes,
) -> Response {
    match forward_inner(
        &state,
        &connection_id,
        &platform,
        &path,
        query,
        method,
        &uri,
        &headers,
        body,
    )
    .await
    {
        Ok(response) => response,
        Err(error) => error.into_response(),
    }
}

#[allow(clippy::too_many_arguments)]
async fn forward_inner(
    state: &AppState,
    connection_id: &str,
    platform: &str,
    path: &str,
    query: Option<String>,
    method: Method,
    uri: &axum::http::Uri,
    headers: &HeaderMap,
    body: Bytes,
) -> Result<Response, ApiError> {
    let request_path = format!("/{path}");
    if contains_traversal_segment(&request_path) {
        return Err(ApiError::BadRequest(
            "path must not contain traversal segments",
        ));
    }
    if body.len() > 1_048_576 {
        return Ok((StatusCode::PAYLOAD_TOO_LARGE, "request body is too large").into_response());
    }
    let security = state.security.as_ref().ok_or(ApiError::Unavailable)?;
    if connection_id.len() != 43 {
        return Err(ApiError::UnknownConnection);
    }
    let record = security
        .load_connection(connection_id)
        .await
        .map_err(|_| ApiError::Unavailable)?
        .ok_or(ApiError::UnknownConnection)?;
    let caller = authenticate(
        state, security, &record, platform, &method, uri, headers, &body,
    )
    .await?;
    // Only an authenticated use keeps a connection alive.
    let (delegate, runtime) = match &caller {
        Caller::Owner => (None, None),
        Caller::Delegate(agent) => (Some(agent.as_str()), None),
        Caller::Runtime { agent, app } => (
            Some(app.as_str()),
            Some((record.owner.as_str(), agent.as_str())),
        ),
        Caller::Frame { app } => (Some(app.as_str()), None),
    };
    let _ = security.touch(connection_id, delegate, runtime).await;

    let mut credential = serde_json::from_slice::<StoredCredential>(&record.credential)
        .map_err(|_| ApiError::Internal)?;
    if credential.provider() != platform {
        return Err(ApiError::PlatformMismatch);
    }
    if refresh_connection(state, security, connection_id, &mut credential)
        .await
        .is_err()
    {
        return Err(ApiError::CredentialRefreshFailed);
    }
    let not_in_catalog = || {
        (
            StatusCode::NOT_FOUND,
            "method or path is not in the catalog",
        )
            .into_response()
    };
    let Some(required_headers) =
        state
            .catalog
            .required_headers(platform, method.as_str(), &request_path)
    else {
        return Ok(not_in_catalog());
    };
    let Some(mut target) = state
        .catalog
        .allows(platform, method.as_str(), &request_path)
    else {
        return Ok(not_in_catalog());
    };
    if let Err(message) = state.catalog.validate_request(
        platform,
        method.as_str(),
        &request_path,
        query.as_deref(),
        headers
            .get(header::CONTENT_TYPE)
            .and_then(|v| v.to_str().ok()),
        !body.is_empty(),
    ) {
        return Ok((StatusCode::BAD_REQUEST, message).into_response());
    }
    target.set_path(&request_path);
    target.set_query(query.as_deref());
    let injection = match &credential {
        StoredCredential::OAuth { access_token, .. } => {
            // Only while the platform still resolves to OAuth: if its
            // selection has since moved to an apiKey profile, the token must
            // not go to that profile's operations, and the person has to
            // connect again.
            if !matches!(
                state.catalog.security_scheme(platform),
                Ok(crate::providers::SecurityScheme::OAuth(_))
            ) {
                return Err(ApiError::CredentialRefreshFailed);
            }
            CredentialInjection::Bearer(access_token.clone())
        }
        StoredCredential::ApiKey {
            key,
            scheme: bound,
            placement,
            ..
        } => {
            let Ok(crate::providers::SecurityScheme::ApiKey(scheme)) =
                state.catalog.security_scheme(platform)
            else {
                return Err(ApiError::Internal);
            };
            // A key entered for one apiKey scheme is not sent under another,
            // nor to another header or query parameter than it was entered
            // for (rows written before the binding have none, and are sent
            // as before).
            if bound
                .as_ref()
                .is_some_and(|bound| *bound != scheme.scheme_name)
                || placement
                    .as_ref()
                    .is_some_and(|placement| *placement != scheme.placement())
            {
                return Err(ApiError::CredentialRefreshFailed);
            }
            match scheme.location {
                crate::providers::ApiKeyLocation::Header => CredentialInjection::Header {
                    name: scheme.name,
                    value: key.clone(),
                },
                crate::providers::ApiKeyLocation::Query => {
                    target.query_pairs_mut().append_pair(&scheme.name, key);
                    CredentialInjection::None
                }
                crate::providers::ApiKeyLocation::Cookie => {
                    return Ok((
                        StatusCode::NOT_IMPLEMENTED,
                        "cookie-located API keys are not supported",
                    )
                        .into_response());
                }
            }
        }
        StoredCredential::HttpBearer {
            token,
            scheme: bound,
            ..
        } => {
            // Only while the platform still resolves to the bearer scheme
            // the token was entered for: it is not sent under another kind
            // or another scheme.
            match state.catalog.security_scheme(platform) {
                Ok(crate::providers::SecurityScheme::Http(crate::providers::HttpScheme {
                    name,
                    auth: crate::providers::HttpAuth::Bearer,
                    ..
                })) if bound.as_ref().is_none_or(|bound| *bound == name) => {
                    CredentialInjection::Bearer(token.clone())
                }
                _ => return Err(ApiError::CredentialRefreshFailed),
            }
        }
        StoredCredential::HttpBasic {
            username,
            password,
            scheme: bound,
            layout: bound_layout,
            ..
        } => match state.catalog.security_scheme(platform) {
            // The same for Basic, and the declared layout must still be the
            // one the halves were built from.
            Ok(crate::providers::SecurityScheme::Http(crate::providers::HttpScheme {
                name,
                auth: crate::providers::HttpAuth::Basic(layout),
                ..
            })) if bound.as_ref().is_none_or(|bound| *bound == name)
                && bound_layout
                    .as_ref()
                    .is_none_or(|bound| *bound == layout.layout()) =>
            {
                CredentialInjection::Basic {
                    username: username.clone(),
                    password: password.clone(),
                }
            }
            _ => return Err(ApiError::CredentialRefreshFailed),
        },
        StoredCredential::NoCredential { .. } => {
            // Only while the catalog still says the platform needs none: if
            // it has since gained a scheme, this connection holds nothing to
            // send, and the person has to connect again.
            if state.catalog.security_scheme(platform)
                != Ok(crate::providers::SecurityScheme::NoCredential)
            {
                return Err(ApiError::CredentialRefreshFailed);
            }
            CredentialInjection::None
        }
    };
    let upstream = match upstream_request(
        &state.http_client,
        method.clone(),
        target.clone(),
        injection,
        headers,
        &required_headers,
        body,
    )
    .send()
    .await
    {
        Ok(response) => response,
        Err(_) => return Ok((StatusCode::BAD_GATEWAY, "upstream request failed").into_response()),
    };
    let status = upstream.status();
    let forwarded_headers = upstream_response_headers(upstream.headers());
    let bytes = match read_bounded_body(upstream, MAX_RESPONSE_BYTES).await {
        Ok(bytes) => bytes,
        Err(_) => {
            return Ok((
                StatusCode::BAD_GATEWAY,
                "upstream response failed or was too large",
            )
                .into_response())
        }
    };
    let mut response = Response::new(bytes.into());
    *response.status_mut() = status;
    *response.headers_mut() = forwarded_headers;
    Ok(response)
}

// Forward only representation/pagination metadata, never provider cookies or credentials.
fn upstream_response_headers(headers: &HeaderMap) -> HeaderMap {
    let mut result = HeaderMap::new();
    for name in [
        header::CONTENT_TYPE,
        header::LINK,
        header::RETRY_AFTER,
        header::ETAG,
        axum::http::HeaderName::from_static("x-total-count"),
        axum::http::HeaderName::from_static("x-next-page"),
    ] {
        for value in headers.get_all(&name) {
            result.append(name.clone(), value.clone());
        }
    }
    result
}

const MAX_RESPONSE_BYTES: usize = 10_485_760;

/// Reads the upstream body incrementally so an oversized or slow response is
/// rejected as soon as the limit is crossed, instead of after it is fully
/// buffered in memory.
async fn read_bounded_body(mut upstream: reqwest::Response, limit: usize) -> Result<Bytes, ()> {
    if upstream
        .content_length()
        .is_some_and(|len| len > limit as u64)
    {
        return Err(());
    }
    let mut buffer = Vec::new();
    while let Some(chunk) = upstream.chunk().await.map_err(|_| ())? {
        if buffer.len() + chunk.len() > limit {
            return Err(());
        }
        buffer.extend_from_slice(&chunk);
    }
    Ok(Bytes::from(buffer))
}

/// Rejects any `.` or `..` path segment so a client cannot request a path
/// that, once assigned to the upstream URL, normalizes to a different path
/// than the one validated against the catalog allowlist.
fn contains_traversal_segment(path: &str) -> bool {
    path.split('/')
        .any(|segment| segment == "." || segment == "..")
}

fn upstream_request(
    client: &reqwest::Client,
    method: axum::http::Method,
    target: Url,
    injection: CredentialInjection,
    headers: &HeaderMap,
    required_headers: &[(String, String)],
    body: Bytes,
) -> reqwest::RequestBuilder {
    // The caller's own `Authorization` (a frame capability) is consumed by
    // `authenticate` and never copied: only the headers below go upstream.
    let mut request = injection.apply(client.request(method, target));
    if let Some(content_type) = headers.get(header::CONTENT_TYPE) {
        request = request.header(header::CONTENT_TYPE, content_type);
    }
    if let Some(etag) = headers.get(header::IF_MATCH) {
        request = request.header(header::IF_MATCH, etag);
    }
    for (name, value) in required_headers {
        request = request.header(name, value);
    }
    request.body(body)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent_id::test_signer::Agent;
    use crate::capability::{mint, Claims};
    use crate::test_support::{body_json, security, signed_request, state, PUBLIC_ORIGIN};
    use axum::http::{header::AUTHORIZATION, HeaderValue};
    use axum::Json;
    use serde_json::json;
    use tower::ServiceExt;

    fn test_state() -> AppState {
        state(None)
    }

    #[tokio::test]
    async fn forwarded_requests_include_server_owned_user_agent() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let app = axum::Router::new().route(
            "/repos/owner/repo/issues",
            axum::routing::post(|axum::extract::OriginalUri(uri): axum::extract::OriginalUri, headers: HeaderMap, body: Bytes| async move {
                Json(json!({
                    "query": uri.query(),
                    "user_agent": headers.get(header::USER_AGENT).and_then(|v| v.to_str().ok()),
                    "authorization": headers.get(header::AUTHORIZATION).and_then(|v| v.to_str().ok()),
                    "content_type": headers.get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()),
                    "if_match": headers.get(header::IF_MATCH).and_then(|v| v.to_str().ok()),
                    "body": String::from_utf8(body.to_vec()).unwrap(),
                }))
            }),
        );
        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        let client = crate::build_http_client();
        for caller_user_agent in [None, Some("caller-controlled-agent")] {
            let mut headers = HeaderMap::new();
            headers.insert(
                header::CONTENT_TYPE,
                HeaderValue::from_static("application/json"),
            );
            headers.insert(
                header::IF_MATCH,
                HeaderValue::from_static("\"event-version\""),
            );
            if let Some(value) = caller_user_agent {
                headers.insert(header::USER_AGENT, HeaderValue::from_static(value));
            }
            let response = upstream_request(
                &client,
                axum::http::Method::POST,
                Url::parse(&format!("http://{address}/repos/owner/repo/issues?state=all&page=2&per_page=1&labels=a%2Cb")).unwrap(),
                CredentialInjection::Bearer("test-provider-token".to_string()),
                &headers,
                &[],
                Bytes::from_static(b"{}"),
            )
            .send()
            .await
            .unwrap()
            .error_for_status()
            .unwrap()
            .json::<serde_json::Value>()
            .await
            .unwrap();
            assert_eq!(
                response["query"],
                "state=all&page=2&per_page=1&labels=a%2Cb"
            );
            assert_eq!(response["user_agent"], "LocalThought-integration-proxy");
            assert_eq!(response["authorization"], "Bearer test-provider-token");
            assert_eq!(response["content_type"], "application/json");
            assert_eq!(response["body"], "{}");
            assert_eq!(response["if_match"], "\"event-version\"");
        }
        server.abort();
    }

    #[tokio::test]
    async fn api_key_credentials_are_sent_as_the_declared_header_not_bearer() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let app = axum::Router::new().route(
            "/workspaces",
            axum::routing::get(
                |headers: HeaderMap| async move {
                    Json(json!({
                        "authorization": headers.get(header::AUTHORIZATION).and_then(|v| v.to_str().ok()),
                        "x_api_key": headers.get("x-api-key").and_then(|v| v.to_str().ok()),
                    }))
                },
            ),
        );
        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        let client = crate::build_http_client();
        let response = upstream_request(
            &client,
            axum::http::Method::GET,
            Url::parse(&format!("http://{address}/workspaces")).unwrap(),
            CredentialInjection::Header {
                name: "X-Api-Key".to_string(),
                value: "clockify-secret".to_string(),
            },
            &HeaderMap::new(),
            &[],
            Bytes::new(),
        )
        .send()
        .await
        .unwrap()
        .error_for_status()
        .unwrap()
        .json::<serde_json::Value>()
        .await
        .unwrap();
        assert_eq!(response["authorization"], serde_json::Value::Null);
        assert_eq!(response["x_api_key"], "clockify-secret");
        server.abort();
    }

    #[test]
    fn pagination_headers_survive_without_forwarding_provider_credentials() {
        let mut headers = HeaderMap::new();
        headers.insert(
            header::CONTENT_TYPE,
            HeaderValue::from_static("application/json"),
        );
        headers.append(
            header::LINK,
            HeaderValue::from_static(
                "<https://api.github.com/repos/o/r/issues?page=2>; rel=\"next\"",
            ),
        );
        headers.append(
            header::LINK,
            HeaderValue::from_static(
                "<https://api.github.com/repos/o/r/issues?page=3>; rel=\"last\"",
            ),
        );
        headers.insert(
            header::SET_COOKIE,
            HeaderValue::from_static("provider-session=private"),
        );
        headers.insert(
            "x-connection-code",
            HeaderValue::from_static("untrusted-provider-code"),
        );
        headers.insert(header::RETRY_AFTER, HeaderValue::from_static("300"));
        let forwarded = upstream_response_headers(&headers);
        assert_eq!(
            forwarded.get(header::RETRY_AFTER),
            Some(&HeaderValue::from_static("300"))
        );
        assert_eq!(forwarded.get_all(header::LINK).iter().count(), 2);
        assert_eq!(forwarded[header::CONTENT_TYPE], "application/json");
        assert!(!forwarded.contains_key(header::SET_COOKIE));
        assert!(!forwarded.contains_key("x-connection-code"));
    }

    #[test]
    fn traversal_segments_are_rejected_including_encoded_forms() {
        assert!(contains_traversal_segment("/repositories/../issues"));
        assert!(contains_traversal_segment("/repositories/./issues"));
        assert!(contains_traversal_segment("/../etc/passwd"));
        assert!(!contains_traversal_segment("/repositories/123/issues"));
        assert!(!contains_traversal_segment("/repositories/..foo/issues"));
    }

    #[tokio::test]
    async fn forward_rejects_a_path_containing_traversal_segments_before_touching_credentials() {
        let mut state = test_state();
        state.catalog = crate::catalog::Catalog::from_test_document(
            "github-issues",
            json!({
                "servers": [{"url": "https://api.example"}],
                "paths": {"/repositories/{id}/issues": {"get": {}}}
            }),
            json!({}),
        );
        // No Authorization header and no security service configured: if the
        // traversal check did not run first, this would fail with 401/503
        // instead of 400.
        let response = crate::router(state)
            .oneshot(
                axum::http::Request::builder()
                    .uri("/proxy/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/github-issues/repositories/../issues")
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn read_bounded_body_rejects_a_response_over_the_limit() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let app = axum::Router::new().route("/big", axum::routing::get(|| async { vec![0u8; 20] }));
        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        let client = crate::build_http_client();
        let response = client
            .get(format!("http://{address}/big"))
            .send()
            .await
            .unwrap();
        assert!(read_bounded_body(response, 10).await.is_err());

        let response = client
            .get(format!("http://{address}/big"))
            .send()
            .await
            .unwrap();
        assert!(read_bounded_body(response, 20).await.is_ok());
        server.abort();
    }

    /// An upstream that echoes the API key it received, and a catalog for it.
    async fn api_key_upstream() -> (tokio::task::JoinHandle<()>, crate::catalog::Catalog) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let app = axum::Router::new().route(
            "/workspaces",
            axum::routing::any(|headers: HeaderMap| async move {
                axum::Json(json!({
                    "x_api_key": headers.get("x-api-key").and_then(|v| v.to_str().ok()),
                    "signature_forwarded": headers.contains_key("x-atomic-signature"),
                    "authorization": headers.get(AUTHORIZATION).and_then(|v| v.to_str().ok()),
                }))
            }),
        );
        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        let catalog = crate::catalog::Catalog::from_test_document(
            "clockify",
            json!({
                "servers": [{"url": format!("http://{address}")}],
                "components": {"securitySchemes": {"clockifyApiKey": {
                    "type": "apiKey", "in": "header", "name": "X-Api-Key"
                }}},
                "security": [{"clockifyApiKey": []}],
                "paths": {"/workspaces": {"get": {}, "post": {"requestBody": {"content": {"application/json": {}}}}}}
            }),
            json!({}),
        );
        (server, catalog)
    }

    fn basic(username: &str, password: &str) -> String {
        use base64::Engine as _;
        format!(
            "Basic {}",
            base64::engine::general_purpose::STANDARD.encode(format!("{username}:{password}"))
        )
    }

    #[tokio::test]
    async fn http_credentials_are_sent_as_bearer_or_basic_authorization() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let app = axum::Router::new().route(
            "/workspaces",
            axum::routing::get(|headers: HeaderMap| async move {
                Json(json!({
                    "authorization": headers.get_all(AUTHORIZATION).iter()
                        .filter_map(|v| v.to_str().ok()).collect::<Vec<_>>(),
                }))
            }),
        );
        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        let client = crate::build_http_client();
        // A caller's own Authorization in the incoming headers is not copied.
        let mut incoming = HeaderMap::new();
        incoming.insert(AUTHORIZATION, HeaderValue::from_static("Capability x"));
        for (injection, expected) in [
            (
                CredentialInjection::Bearer("pat-secret".into()),
                "Bearer pat-secret".to_owned(),
            ),
            (
                CredentialInjection::Basic {
                    username: "pat-secret".into(),
                    password: "api_token".into(),
                },
                basic("pat-secret", "api_token"),
            ),
            (
                CredentialInjection::Basic {
                    username: "sk_secret".into(),
                    password: String::new(),
                },
                basic("sk_secret", ""),
            ),
        ] {
            let response = upstream_request(
                &client,
                axum::http::Method::GET,
                Url::parse(&format!("http://{address}/workspaces")).unwrap(),
                injection,
                &incoming,
                &[],
                Bytes::new(),
            )
            .send()
            .await
            .unwrap()
            .json::<serde_json::Value>()
            .await
            .unwrap();
            assert_eq!(response["authorization"], json!([expected]));
        }
        server.abort();
    }

    #[test]
    fn a_stored_credential_debugs_without_its_secret() {
        for credential in [
            StoredCredential::HttpBearer {
                scheme: None,
                provider: "service".into(),
                token: "pat-secret".into(),
            },
            StoredCredential::HttpBasic {
                scheme: None,
                layout: None,
                provider: "service".into(),
                username: "user-secret".into(),
                password: "pat-secret".into(),
            },
            StoredCredential::ApiKey {
                placement: None,
                scheme: None,
                provider: "service".into(),
                key: "pat-secret".into(),
            },
            StoredCredential::OAuth {
                provider: "service".into(),
                access_token: "pat-secret".into(),
                refresh_token: Some("user-secret".into()),
                expires_at: None,
            },
        ] {
            let debug = format!("{credential:?}");
            assert!(debug.contains("service"), "{debug}");
            assert!(
                !debug.contains("pat-secret") && !debug.contains("user-secret"),
                "{debug}"
            );
        }
    }

    /// An upstream that echoes the `Authorization` it received, and a
    /// catalog whose one scheme is `scheme` (an `http` scheme, say).
    async fn http_upstream(
        scheme: serde_json::Value,
    ) -> (tokio::task::JoinHandle<()>, crate::catalog::Catalog) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let app = axum::Router::new().route(
            "/workspaces",
            axum::routing::any(|headers: HeaderMap| async move {
                axum::Json(json!({
                    "authorization": headers.get_all(AUTHORIZATION).iter()
                        .filter_map(|v| v.to_str().ok()).collect::<Vec<_>>(),
                    "signature_forwarded": headers.contains_key("x-atomic-signature"),
                }))
            }),
        );
        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        let catalog = crate::catalog::Catalog::from_test_document(
            "clockify",
            json!({
                "servers": [{"url": format!("http://{address}")}],
                "components": {"securitySchemes": {"serviceToken": scheme}},
                "security": [{"serviceToken": []}],
                "paths": {"/workspaces": {"get": {}}}
            }),
            json!({}),
        );
        (server, catalog)
    }

    fn bearer_scheme() -> serde_json::Value {
        json!({"type": "http", "scheme": "bearer"})
    }

    fn basic_scheme() -> serde_json::Value {
        json!({"type": "http", "scheme": "basic", "x-api-key-details": {
            "basicCredentials": {"token": "username", "password": "api_token"}}})
    }

    /// Q-086: a bearer or basic token reaches the provider only as the
    /// `Authorization` the platform's scheme declares; the caller's own
    /// `Authorization` (a frame capability) never does, any other is
    /// refused, and a token connected under one kind is not sent once the
    /// platform resolves to another.
    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
    async fn postgres_http_tokens_reach_the_provider_only_as_declared() {
        let security = security().await;
        let bearer_credential = serde_json::to_vec(&StoredCredential::HttpBearer {
            scheme: None,
            provider: "clockify".into(),
            token: "pat-secret".into(),
        })
        .unwrap();
        let basic_credential = serde_json::to_vec(&StoredCredential::HttpBasic {
            scheme: None,
            layout: None,
            provider: "clockify".into(),
            username: "pat-secret".into(),
            password: "api_token".into(),
        })
        .unwrap();
        let owner = Agent::new(73);
        let fixture = |scheme: serde_json::Value, credential: Vec<u8>| {
            let security = security.clone();
            let owner_id = owner.id();
            async move {
                let (server, catalog) = http_upstream(scheme).await;
                let mut s = state(Some(security.clone()));
                s.catalog = catalog;
                let id = security
                    .create_connection("clockify", &owner_id, &credential)
                    .await
                    .unwrap();
                Fixture {
                    state: s,
                    security,
                    owner: Agent::new(73),
                    id,
                    _server: server,
                }
            }
        };

        // Bearer, signed by the owner.
        let f = fixture(bearer_scheme(), bearer_credential.clone()).await;
        let response = f.get_as(&f.owner).await;
        assert_eq!(response.status(), StatusCode::OK);
        let body = body_json(response).await;
        assert_eq!(body["authorization"], json!(["Bearer pat-secret"]));
        assert_eq!(body["signature_forwarded"], false);
        // Through a frame capability: the capability is consumed here, and
        // only the connection's token goes upstream.
        let app = Agent::new(74);
        let frame = Agent::new(75);
        f.security
            .put_delegation(&f.id, &app.id(), None)
            .await
            .unwrap();
        let token = mint(&f.owner, &f.claims(&app, &frame));
        let response = f.frame_get(&token, &frame).await;
        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            body_json(response).await["authorization"],
            json!(["Bearer pat-secret"])
        );
        // Any other Authorization from the caller is refused, not forwarded.
        for supplied in ["Bearer attacker-token", &basic("attacker", "x")] {
            let mut request = signed_request(&f.state, &f.owner, "GET", &f.path(), vec![]);
            request
                .headers_mut()
                .insert(AUTHORIZATION, HeaderValue::from_str(supplied).unwrap());
            expect_error(
                f.send(request).await,
                StatusCode::UNAUTHORIZED,
                "unsupported_authorization",
            )
            .await;
        }
        // The token is never echoed back to the caller.
        let response = f.get_as(&f.owner).await;
        assert!(!response
            .headers()
            .values()
            .any(|v| v.to_str().is_ok_and(|v| v.contains("pat-secret"))));

        // Basic: the declared layout, base64 of username:password.
        let f = fixture(basic_scheme(), basic_credential.clone()).await;
        let response = f.get_as(&f.owner).await;
        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            body_json(response).await["authorization"],
            json!([basic("pat-secret", "api_token")])
        );

        // A token connected under one kind is not sent under another.
        for (scheme, credential) in [
            (basic_scheme(), bearer_credential.clone()),
            (bearer_scheme(), basic_credential.clone()),
            (
                json!({"type": "apiKey", "in": "header", "name": "X-Api-Key"}),
                bearer_credential,
            ),
            (
                json!({"type": "apiKey", "in": "header", "name": "X-Api-Key"}),
                basic_credential,
            ),
        ] {
            let f = fixture(scheme, credential).await;
            expect_error(
                f.get_as(&f.owner).await,
                StatusCode::UNAUTHORIZED,
                "credential_refresh_failed",
            )
            .await;
        }
    }

    #[test]
    fn credentials_without_a_binding_still_read_and_new_ones_carry_it() {
        // Rows written before the binding have no `scheme` or `layout`.
        for old in [
            json!({"kind": "api_key", "provider": "p", "key": "k"}),
            json!({"kind": "http_bearer", "provider": "p", "token": "t"}),
            json!({"kind": "http_basic", "provider": "p", "username": "u", "password": "w"}),
        ] {
            let credential: StoredCredential = serde_json::from_value(old.clone()).unwrap();
            // ... and are written back without them.
            assert_eq!(serde_json::to_value(&credential).unwrap(), old);
        }
        let new = StoredCredential::HttpBasic {
            provider: "p".into(),
            username: "u".into(),
            password: "w".into(),
            scheme: Some("serviceToken".into()),
            layout: Some(crate::providers::BasicLayout::Username {
                password: "api_token".into(),
            }),
        };
        let value = serde_json::to_value(&new).unwrap();
        assert_eq!(value["scheme"], "serviceToken");
        assert_eq!(
            value["layout"],
            json!({"token": "username", "password": "api_token"})
        );
        assert!(matches!(
            serde_json::from_value::<StoredCredential>(value).unwrap(),
            StoredCredential::HttpBasic {
                scheme: Some(_),
                layout: Some(_),
                ..
            }
        ));
    }

    /// A credential is sent only under the security scheme (and, for Basic,
    /// the declared layout) it was entered for; a credential without a
    /// binding, from before it existed, is sent as before.
    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
    async fn postgres_a_credential_is_sent_only_under_the_scheme_it_was_entered_for() {
        let security = security().await;
        let status = |scheme: serde_json::Value, credential: StoredCredential| {
            let security = security.clone();
            let owner = Agent::new(77);
            async move {
                let (_server, catalog) = http_upstream(scheme).await;
                let mut s = state(Some(security.clone()));
                s.catalog = catalog;
                let id = security
                    .create_connection(
                        "clockify",
                        &owner.id(),
                        &serde_json::to_vec(&credential).unwrap(),
                    )
                    .await
                    .unwrap();
                let request = signed_request(
                    &s,
                    &owner,
                    "GET",
                    &format!("/proxy/{id}/clockify/workspaces"),
                    vec![],
                );
                let response = crate::router(s).oneshot(request).await.unwrap();
                let status = response.status();
                let body = body_json(response).await;
                (status, body)
            }
        };
        let bearer = |scheme: Option<&str>| StoredCredential::HttpBearer {
            provider: "clockify".into(),
            token: "pat-secret".into(),
            scheme: scheme.map(str::to_owned),
        };
        let basic = |scheme: Option<&str>, layout: Option<crate::providers::BasicLayout>| {
            StoredCredential::HttpBasic {
                provider: "clockify".into(),
                username: "pat-secret".into(),
                password: "api_token".into(),
                scheme: scheme.map(str::to_owned),
                layout,
            }
        };
        let declared = || crate::providers::BasicLayout::Username {
            password: "api_token".into(),
        };
        let api_key = |scheme: Option<&str>| StoredCredential::ApiKey {
            placement: None,
            provider: "clockify".into(),
            key: "clockify-secret".into(),
            scheme: scheme.map(str::to_owned),
        };
        // Bound to the right scheme, and to where the key goes.
        let placed = |location: &str, name: &str| StoredCredential::ApiKey {
            placement: Some(crate::providers::ApiKeyPlacement {
                location: location.into(),
                name: name.into(),
            }),
            provider: "clockify".into(),
            key: "clockify-secret".into(),
            scheme: Some("serviceToken".into()),
        };
        let api_key_scheme = || json!({"type": "apiKey", "in": "header", "name": "X-Api-Key"});

        // Bound to the scheme it resolves to, or unbound: sent.
        for (scheme, credential) in [
            (bearer_scheme(), bearer(Some("serviceToken"))),
            (bearer_scheme(), bearer(None)),
            (
                basic_scheme(),
                basic(Some("serviceToken"), Some(declared())),
            ),
            (basic_scheme(), basic(None, None)),
            (api_key_scheme(), api_key(Some("serviceToken"))),
            (api_key_scheme(), api_key(None)),
            // Header names compare case-insensitively.
            (api_key_scheme(), placed("header", "x-api-key")),
        ] {
            let (status, _) = status(scheme.clone(), credential).await;
            assert_eq!(status, StatusCode::OK, "{scheme}");
        }
        // Entered for another scheme, or another Basic layout: not sent.
        let other_layouts = [
            crate::providers::BasicLayout::Username {
                password: String::new(),
            },
            crate::providers::BasicLayout::Password { username: None },
            crate::providers::BasicLayout::Password {
                username: Some("pat-secret".into()),
            },
        ];
        let mut refused = vec![
            (bearer_scheme(), bearer(Some("otherToken"))),
            (basic_scheme(), basic(Some("otherToken"), Some(declared()))),
            (api_key_scheme(), api_key(Some("otherKey"))),
            (api_key_scheme(), placed("query", "X-Api-Key")),
            (api_key_scheme(), placed("header", "x-other-key")),
        ];
        for layout in other_layouts {
            refused.push((basic_scheme(), basic(Some("serviceToken"), Some(layout))));
        }
        for (scheme, credential) in refused {
            let (status, body) = status(scheme.clone(), credential).await;
            assert_eq!(status, StatusCode::UNAUTHORIZED, "{scheme}");
            assert_eq!(body["error"], "credential_refresh_failed");
        }
    }

    /// An `http` bearer scheme as an authentication profile's one scheme:
    /// its token goes only to the operations the profile covers, and a
    /// token connected under it is not sent once the selection names an
    /// OAuth profile.
    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
    async fn postgres_an_http_profile_sends_its_token_only_where_the_profile_allows() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let echo = |headers: HeaderMap| async move {
            Json(json!({
                "authorization": headers.get(AUTHORIZATION).and_then(|v| v.to_str().ok()),
            }))
        };
        let app = axum::Router::new()
            .route("/v1/users/@me", axum::routing::any(echo))
            .route("/v1/users/@me/guilds", axum::routing::any(echo))
            .route("/v1/channels/1/messages", axum::routing::any(echo));
        let _server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        let catalog = |selection| {
            let mut document =
                crate::test_support::mixed_profiles_document(&format!("http://{address}/v1"));
            document["components"]["securitySchemes"]["pat"] = bearer_scheme();
            document["components"]["x-authentication-profiles"]["pat"] =
                json!({"securityScheme": "pat"});
            document["paths"]["/users/@me"]["get"]["security"] =
                json!([{"botToken": []}, {"userOAuth": ["identify"]}, {"pat": []}]);
            crate::catalog::Catalog::from_test_document("mixed", document, selection)
        };
        let security = security().await;
        let mut s = state(Some(security.clone()));
        s.catalog = catalog(json!({"authenticationProfile": "pat"}));
        let owner = Agent::new(76);
        let id = security
            .create_connection(
                "mixed",
                &owner.id(),
                &serde_json::to_vec(&StoredCredential::HttpBearer {
                    scheme: None,
                    provider: "mixed".into(),
                    token: "pat-secret".into(),
                })
                .unwrap(),
            )
            .await
            .unwrap();
        let get = |s: &AppState, path: &str| {
            let request = signed_request(
                s,
                &owner,
                "GET",
                &format!("/proxy/{id}/mixed{path}"),
                vec![],
            );
            let router = crate::router(s.clone());
            async move { router.oneshot(request).await.unwrap() }
        };
        let response = get(&s, "/v1/users/@me").await;
        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            body_json(response).await["authorization"],
            "Bearer pat-secret"
        );
        for path in ["/v1/users/@me/guilds", "/v1/channels/1/messages"] {
            assert_eq!(
                get(&s, path).await.status(),
                StatusCode::NOT_FOUND,
                "{path}"
            );
        }
        // Under the user (OAuth) profile the same connection sends nothing.
        let mut user = s.clone();
        user.catalog = catalog(json!({"authenticationProfile": "user"}));
        expect_error(
            get(&user, "/v1/users/@me").await,
            StatusCode::UNAUTHORIZED,
            "credential_refresh_failed",
        )
        .await;
        // Without a profile the mixed document is refused as before.
        let mut unselected = s.clone();
        unselected.catalog = catalog(json!({"httpSecurityScheme": "pat"}));
        expect_error(
            get(&unselected, "/v1/users/@me").await,
            StatusCode::UNAUTHORIZED,
            "credential_refresh_failed",
        )
        .await;
    }

    fn api_key_credential() -> Vec<u8> {
        serde_json::to_vec(&StoredCredential::ApiKey {
            placement: None,
            scheme: None,
            provider: "clockify".into(),
            key: "clockify-secret".into(),
        })
        .unwrap()
    }

    struct Fixture {
        state: AppState,
        security: Security,
        owner: Agent,
        id: String,
        _server: tokio::task::JoinHandle<()>,
    }

    async fn fixture(owner_seed: u8) -> Fixture {
        let security = security().await;
        let (server, catalog) = api_key_upstream().await;
        let mut s = state(Some(security.clone()));
        s.catalog = catalog;
        let owner = Agent::new(owner_seed);
        let id = security
            .create_connection("clockify", &owner.id(), &api_key_credential())
            .await
            .unwrap();
        Fixture {
            state: s,
            security,
            owner,
            id,
            _server: server,
        }
    }

    impl Fixture {
        fn path(&self) -> String {
            format!("/proxy/{}/clockify/workspaces", self.id)
        }
        async fn send(&self, request: axum::http::Request<axum::body::Body>) -> Response {
            crate::router(self.state.clone())
                .oneshot(request)
                .await
                .unwrap()
        }
        async fn get_as(&self, agent: &Agent) -> Response {
            self.send(signed_request(
                &self.state,
                agent,
                "GET",
                &self.path(),
                vec![],
            ))
            .await
        }
        fn claims(&self, app: &Agent, frame: &Agent) -> Claims {
            Claims {
                v: 2,
                connection_id: self.id.clone(),
                platform: "clockify".into(),
                aud: PUBLIC_ORIGIN.into(),
                app: app.id(),
                cnf: frame.id(),
                exp: crate::now_secs() + 600,
            }
        }
        async fn frame_get(&self, token: &str, signer: &Agent) -> Response {
            let mut request = signed_request(&self.state, signer, "GET", &self.path(), vec![]);
            request.headers_mut().insert(
                AUTHORIZATION,
                HeaderValue::from_str(&format!("Capability {token}")).unwrap(),
            );
            self.send(request).await
        }
    }

    async fn expect_error(response: Response, status: StatusCode, code: &str) {
        assert_eq!(response.status(), status, "expected {code}");
        assert_eq!(body_json(response).await["error"], code);
    }

    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
    async fn postgres_the_owner_signs_requests_that_reach_the_provider_once_each() {
        let f = fixture(31).await;
        let request = signed_request(&f.state, &f.owner, "GET", &f.path(), vec![]);
        let replay = crate::test_support::clone_request(&request);
        let response = f.send(request).await;
        assert_eq!(response.status(), StatusCode::OK);
        assert!(!response.headers().contains_key("x-connection-code"));
        let body = body_json(response).await;
        assert_eq!(body["x_api_key"], "clockify-secret");
        // The caller's own signature headers never reach the provider.
        assert_eq!(body["signature_forwarded"], false);
        // Nothing rotated: a second, freshly signed request works too.
        assert_eq!(f.get_as(&f.owner).await.status(), StatusCode::OK);
        // The exact same signed request is refused.
        expect_error(f.send(replay).await, StatusCode::UNAUTHORIZED, "replayed").await;
        // A signed POST covers its body.
        let post = signed_request(&f.state, &f.owner, "POST", &f.path(), b"{}".to_vec());
        assert_eq!(f.send(post).await.status(), StatusCode::OK);
    }

    /// atomic-plugins#258: on a platform whose document declares a bot token
    /// and OAuth together, the catalog's profile selection decides which
    /// credential a connection holds and which operations it reaches. A
    /// user's OAuth token goes only to operations the user profile covers,
    /// and to none once the selection no longer resolves to OAuth.
    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
    async fn postgres_a_profile_connection_sends_its_credential_only_where_the_profile_allows() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let echo = |headers: HeaderMap| async move {
            Json(json!({
                "authorization": headers.get(AUTHORIZATION).and_then(|v| v.to_str().ok()),
            }))
        };
        let app = axum::Router::new()
            .route("/v1/users/@me", axum::routing::any(echo))
            .route("/v1/users/@me/guilds", axum::routing::any(echo))
            .route("/v1/channels/1/messages", axum::routing::any(echo))
            .route("/v1/public", axum::routing::any(echo));
        let _server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        let catalog = |selection| {
            crate::catalog::Catalog::from_test_document(
                "mixed",
                crate::test_support::mixed_profiles_document(&format!("http://{address}/v1")),
                selection,
            )
        };
        let security = security().await;
        let mut s = state(Some(security.clone()));
        s.catalog = catalog(json!({"authenticationProfile": "user"}));
        let owner = Agent::new(48);
        let connect = |credential: StoredCredential| {
            let security = security.clone();
            let owner = owner.id();
            async move {
                security
                    .create_connection("mixed", &owner, &serde_json::to_vec(&credential).unwrap())
                    .await
                    .unwrap()
            }
        };
        let user = connect(StoredCredential::OAuth {
            provider: "mixed".into(),
            access_token: "user-token".into(),
            refresh_token: None,
            expires_at: None,
        })
        .await;
        let bot = connect(StoredCredential::ApiKey {
            placement: None,
            scheme: None,
            provider: "mixed".into(),
            key: "Bot bot-token".into(),
        })
        .await;
        let get = |s: &AppState, id: &str, path: &str| {
            let request = signed_request(
                s,
                &owner,
                "GET",
                &format!("/proxy/{id}/mixed{path}"),
                vec![],
            );
            let router = crate::router(s.clone());
            async move { router.oneshot(request).await.unwrap() }
        };

        // The user profile: its OAuth token on the two operations it covers.
        for path in ["/v1/users/@me", "/v1/users/@me/guilds"] {
            let response = get(&s, &user, path).await;
            assert_eq!(response.status(), StatusCode::OK, "{path}");
            assert_eq!(
                body_json(response).await["authorization"],
                "Bearer user-token"
            );
        }
        // Bot-only and anonymous-only operations are not in its catalog.
        for path in ["/v1/channels/1/messages", "/v1/public"] {
            assert_eq!(
                get(&s, &user, path).await.status(),
                StatusCode::NOT_FOUND,
                "{path}"
            );
        }

        // The bot profile: the key as declared, never the user's token.
        let mut bot_state = s.clone();
        bot_state.catalog = catalog(json!({"authenticationProfile": "bot"}));
        let response = get(&bot_state, &bot, "/v1/channels/1/messages").await;
        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(body_json(response).await["authorization"], "Bot bot-token");
        assert_eq!(
            get(&bot_state, &bot, "/v1/users/@me/guilds").await.status(),
            StatusCode::NOT_FOUND
        );
        // An OAuth connection made under the user profile sends nothing once
        // the selection is the bot profile, even on an operation both
        // profiles cover.
        expect_error(
            get(&bot_state, &user, "/v1/users/@me").await,
            StatusCode::UNAUTHORIZED,
            "credential_refresh_failed",
        )
        .await;
        // And without a profile selection the mixed document sends nothing.
        let mut unselected = s.clone();
        unselected.catalog = catalog(json!({"oauthSecurityScheme": "userOAuth"}));
        expect_error(
            get(&unselected, &user, "/v1/users/@me").await,
            StatusCode::UNAUTHORIZED,
            "credential_refresh_failed",
        )
        .await;
        expect_error(
            get(&unselected, &bot, "/v1/users/@me").await,
            StatusCode::INTERNAL_SERVER_ERROR,
            "internal",
        )
        .await;
    }

    /// A platform whose document requires no security, served under an API
    /// base path the way a static host serves it.
    fn no_credential_catalog(address: std::net::SocketAddr) -> crate::catalog::Catalog {
        crate::catalog::Catalog::from_test_document(
            "pets",
            json!({
                "servers": [{"url": format!("http://{address}/demo/api")}],
                "security": [],
                "paths": {"/pets": {"get": {}}}
            }),
            json!({}),
        )
    }

    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
    async fn postgres_a_no_credential_connection_forwards_only_catalog_reads_with_no_credential() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let app = axum::Router::new().route(
            "/demo/api/pets",
            axum::routing::any(|headers: HeaderMap| async move {
                (
                    [(header::CONTENT_TYPE, "application/octet-stream")],
                    serde_json::to_string(&json!([{
                        "id": 1,
                        "name": "Rex",
                        "authorization": headers.get(AUTHORIZATION).and_then(|v| v.to_str().ok()),
                        "signature_forwarded": headers.contains_key("x-atomic-signature"),
                    }]))
                    .unwrap(),
                )
            }),
        );
        let _server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        let security = security().await;
        let mut s = state(Some(security.clone()));
        s.catalog = no_credential_catalog(address);
        let owner = Agent::new(37);
        let id = security
            .create_connection(
                "pets",
                &owner.id(),
                &serde_json::to_vec(&StoredCredential::NoCredential {
                    provider: "pets".into(),
                })
                .unwrap(),
            )
            .await
            .unwrap();
        let send =
            |s: AppState, request| async move { crate::router(s).oneshot(request).await.unwrap() };
        let path = format!("/proxy/{id}/pets/demo/api/pets");

        // Signed by the owner: forwarded with nothing attached, and the
        // provider's bytes come back whatever their content type.
        let response = send(s.clone(), signed_request(&s, &owner, "GET", &path, vec![])).await;
        assert_eq!(response.status(), StatusCode::OK);
        let body = body_json(response).await;
        assert_eq!(body[0]["name"], "Rex");
        assert_eq!(body[0]["authorization"], serde_json::Value::Null);
        assert_eq!(body[0]["signature_forwarded"], false);

        // Still not an open relay: unsigned, another method, or another
        // path is refused before anything is sent.
        let unsigned = axum::http::Request::builder()
            .uri(&path)
            .body(axum::body::Body::empty())
            .unwrap();
        expect_error(
            send(s.clone(), unsigned).await,
            StatusCode::UNAUTHORIZED,
            "missing_signature",
        )
        .await;
        let post = signed_request(&s, &owner, "POST", &path, b"{}".to_vec());
        assert_eq!(send(s.clone(), post).await.status(), StatusCode::NOT_FOUND);
        let other = format!("/proxy/{id}/pets/demo/api/owners");
        let other = signed_request(&s, &owner, "GET", &other, vec![]);
        assert_eq!(send(s.clone(), other).await.status(), StatusCode::NOT_FOUND);
        let stranger = signed_request(&s, &Agent::new(38), "GET", &path, vec![]);
        expect_error(
            send(s.clone(), stranger).await,
            StatusCode::FORBIDDEN,
            "not_delegated",
        )
        .await;

        // A catalog that has since given the platform a scheme: this
        // connection holds nothing to send, so connect again.
        let changed = crate::catalog::Catalog::from_test_document(
            "pets",
            json!({
                "servers": [{"url": format!("http://{address}/demo/api")}],
                "components": {"securitySchemes": {"petsKey": {
                    "type": "apiKey", "in": "header", "name": "X-Api-Key"
                }}},
                "security": [{"petsKey": []}],
                "paths": {"/pets": {"get": {}}}
            }),
            json!({}),
        );
        let mut s2 = s.clone();
        s2.catalog = changed;
        expect_error(
            send(
                s2.clone(),
                signed_request(&s2, &owner, "GET", &path, vec![]),
            )
            .await,
            StatusCode::UNAUTHORIZED,
            "credential_refresh_failed",
        )
        .await;
    }

    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
    async fn postgres_each_verification_step_fails_closed() {
        let f = fixture(32).await;
        // No signature at all.
        let unsigned = axum::http::Request::builder()
            .uri(f.path())
            .body(axum::body::Body::empty())
            .unwrap();
        expect_error(
            f.send(unsigned).await,
            StatusCode::UNAUTHORIZED,
            "missing_signature",
        )
        .await;
        // A retired connection code.
        let bearer = axum::http::Request::builder()
            .uri(f.path())
            .header(AUTHORIZATION, "Bearer old-connection-code")
            .body(axum::body::Body::empty())
            .unwrap();
        expect_error(
            f.send(bearer).await,
            StatusCode::UNAUTHORIZED,
            "unsupported_authorization",
        )
        .await;
        // Version 1 header.
        let mut v1 = signed_request(&f.state, &f.owner, "GET", &f.path(), vec![]);
        v1.headers_mut().insert(
            crate::signature::VERSION_HEADER,
            HeaderValue::from_static("1"),
        );
        expect_error(
            f.send(v1).await,
            StatusCode::UNAUTHORIZED,
            "unsupported_signature_version",
        )
        .await;
        // Stale timestamp.
        let stale = crate::test_support::signed_request_at(
            &f.state,
            &f.owner,
            "GET",
            &f.path(),
            vec![],
            crate::now_ms() - crate::signature::MAX_SKEW_MS - 1000,
        );
        expect_error(
            f.send(stale).await,
            StatusCode::UNAUTHORIZED,
            "stale_timestamp",
        )
        .await;
        // Tampered body.
        let mut tampered = signed_request(&f.state, &f.owner, "POST", &f.path(), b"{}".to_vec());
        *tampered.body_mut() = axum::body::Body::from(r#"{"x":1}"#);
        expect_error(
            f.send(tampered).await,
            StatusCode::UNAUTHORIZED,
            "bad_signature",
        )
        .await;
        // A signature over the internal (plain-HTTP) URL instead of BASE_URL.
        let internal = crate::test_support::signed_request_for_url(
            &f.owner,
            "GET",
            &f.path(),
            &format!("http://localhost:8080{}", f.path()),
            vec![],
        );
        expect_error(
            f.send(internal).await,
            StatusCode::UNAUTHORIZED,
            "bad_signature",
        )
        .await;
        // The Host header does not matter: the signed URL is built from BASE_URL.
        let mut spoofed_host = signed_request(&f.state, &f.owner, "GET", &f.path(), vec![]);
        spoofed_host
            .headers_mut()
            .insert(header::HOST, HeaderValue::from_static("evil.example"));
        assert_eq!(f.send(spoofed_host).await.status(), StatusCode::OK);
        // Claiming to be the owner while signing with another key.
        let impostor = Agent::new(33);
        let mut claimed = signed_request(&f.state, &impostor, "GET", &f.path(), vec![]);
        claimed.headers_mut().insert(
            crate::signature::AGENT_HEADER,
            HeaderValue::from_str(&f.owner.id()).unwrap(),
        );
        expect_error(
            f.send(claimed).await,
            StatusCode::UNAUTHORIZED,
            "agent_key_mismatch",
        )
        .await;
        // Someone else's key: no standing on this connection.
        expect_error(
            f.get_as(&impostor).await,
            StatusCode::FORBIDDEN,
            "not_delegated",
        )
        .await;
        // Wrong platform in the path.
        let wrong_platform = signed_request(
            &f.state,
            &f.owner,
            "GET",
            &format!("/proxy/{}/github-issues/workspaces", f.id),
            vec![],
        );
        expect_error(
            f.send(wrong_platform).await,
            StatusCode::FORBIDDEN,
            "platform_mismatch",
        )
        .await;
        // Unknown connection.
        let unknown = signed_request(
            &f.state,
            &f.owner,
            "GET",
            &format!("/proxy/{}/clockify/workspaces", crate::connect::random()),
            vec![],
        );
        expect_error(
            f.send(unknown).await,
            StatusCode::NOT_FOUND,
            "unknown_connection",
        )
        .await;
        // The legacy spelling of the owner's id is the owner.
        let mut legacy = signed_request(&f.state, &f.owner, "GET", &f.path(), vec![]);
        legacy.headers_mut().insert(
            crate::signature::AGENT_HEADER,
            HeaderValue::from_str(&f.owner.legacy_id()).unwrap(),
        );
        assert_eq!(f.send(legacy).await.status(), StatusCode::OK);
    }

    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
    async fn postgres_delegates_and_runtimes_lose_access_the_moment_they_are_revoked() {
        let f = fixture(34).await;
        let app = Agent::new(35);
        let node = Agent::new(36);
        expect_error(f.get_as(&app).await, StatusCode::FORBIDDEN, "not_delegated").await;
        f.security
            .put_delegation(&f.id, &app.id(), Some("Plugin"))
            .await
            .unwrap();
        assert_eq!(f.get_as(&app).await.status(), StatusCode::OK);
        expect_error(
            f.get_as(&node).await,
            StatusCode::FORBIDDEN,
            "not_delegated",
        )
        .await;
        f.security
            .put_runtime(&f.owner.id(), &node.id(), &app.id(), Some("server"))
            .await
            .unwrap();
        assert_eq!(f.get_as(&node).await.status(), StatusCode::OK);
        // Revoke the app's delegation: the app and its runtime stop at once.
        f.security
            .delete_delegation(&f.id, &app.id())
            .await
            .unwrap();
        expect_error(f.get_as(&app).await, StatusCode::FORBIDDEN, "not_delegated").await;
        expect_error(
            f.get_as(&node).await,
            StatusCode::FORBIDDEN,
            "not_delegated",
        )
        .await;
        // Restore, then remove only the runtime.
        f.security
            .put_delegation(&f.id, &app.id(), None)
            .await
            .unwrap();
        f.security
            .delete_runtime(&f.owner.id(), &node.id())
            .await
            .unwrap();
        assert_eq!(f.get_as(&app).await.status(), StatusCode::OK);
        expect_error(
            f.get_as(&node).await,
            StatusCode::FORBIDDEN,
            "not_delegated",
        )
        .await;
        // Deleting the connection ends everyone's access.
        f.security
            .delete_connection(&f.id, &f.owner.id())
            .await
            .unwrap();
        expect_error(
            f.get_as(&f.owner).await,
            StatusCode::NOT_FOUND,
            "unknown_connection",
        )
        .await;
        expect_error(
            f.get_as(&app).await,
            StatusCode::NOT_FOUND,
            "unknown_connection",
        )
        .await;
    }

    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
    async fn postgres_the_access_policy_is_asked_about_the_owner_on_every_request() {
        let mut f = fixture(37).await;
        let app = Agent::new(38);
        f.security
            .put_delegation(&f.id, &app.id(), None)
            .await
            .unwrap();
        assert_eq!(f.get_as(&app).await.status(), StatusCode::OK);
        f.state.access = std::sync::Arc::new(crate::access::EnvAccessPolicy::new(
            None,
            vec![f.owner.id()],
        ));
        expect_error(
            f.get_as(&f.owner).await,
            StatusCode::FORBIDDEN,
            "access_denied",
        )
        .await;
        // A delegate is judged by its owner's standing, not its own.
        expect_error(f.get_as(&app).await, StatusCode::FORBIDDEN, "access_denied").await;
        f.state.access = std::sync::Arc::new(crate::access::EnvAccessPolicy::new(
            Some(vec![f.owner.legacy_id()]),
            vec![],
        ));
        assert_eq!(f.get_as(&app).await.status(), StatusCode::OK);
    }

    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
    async fn postgres_a_frame_capability_works_only_with_the_frame_key_and_a_live_delegation() {
        let f = fixture(39).await;
        let app = Agent::new(40);
        let frame = Agent::new(41);
        let token = mint(&f.owner, &f.claims(&app, &frame));
        // No delegation for the app yet.
        expect_error(
            f.frame_get(&token, &frame).await,
            StatusCode::FORBIDDEN,
            "not_delegated",
        )
        .await;
        f.security
            .put_delegation(&f.id, &app.id(), None)
            .await
            .unwrap();
        assert_eq!(f.frame_get(&token, &frame).await.status(), StatusCode::OK);
        // The capability is reusable within its lifetime, each request freshly signed.
        assert_eq!(f.frame_get(&token, &frame).await.status(), StatusCode::OK);
        // A copied capability used without the frame's key.
        let thief = Agent::new(42);
        expect_error(
            f.frame_get(&token, &thief).await,
            StatusCode::UNAUTHORIZED,
            "capability_key_mismatch",
        )
        .await;
        // ... or with no request signature at all.
        let bare = axum::http::Request::builder()
            .uri(f.path())
            .header(AUTHORIZATION, format!("Capability {token}"))
            .body(axum::body::Body::empty())
            .unwrap();
        expect_error(
            f.send(bare).await,
            StatusCode::UNAUTHORIZED,
            "missing_signature",
        )
        .await;
        // Replaying one of the frame's signed requests.
        let mut request = signed_request(&f.state, &frame, "GET", &f.path(), vec![]);
        request.headers_mut().insert(
            AUTHORIZATION,
            HeaderValue::from_str(&format!("Capability {token}")).unwrap(),
        );
        let replay = crate::test_support::clone_request(&request);
        assert_eq!(f.send(request).await.status(), StatusCode::OK);
        expect_error(f.send(replay).await, StatusCode::UNAUTHORIZED, "replayed").await;
        // The owner key itself cannot stand in for the frame key.
        expect_error(
            f.frame_get(&token, &f.owner).await,
            StatusCode::UNAUTHORIZED,
            "capability_key_mismatch",
        )
        .await;
        // Revoking the delegation stops the capability immediately.
        f.security
            .delete_delegation(&f.id, &app.id())
            .await
            .unwrap();
        expect_error(
            f.frame_get(&token, &frame).await,
            StatusCode::FORBIDDEN,
            "not_delegated",
        )
        .await;
    }

    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
    async fn postgres_capability_misuse_is_refused_with_a_specific_reason() {
        let f = fixture(43).await;
        let app = Agent::new(44);
        let frame = Agent::new(45);
        f.security
            .put_delegation(&f.id, &app.id(), None)
            .await
            .unwrap();
        type Edit = Box<dyn Fn(&mut Claims)>;
        let cases: Vec<(Edit, StatusCode, &str)> = vec![
            (
                Box::new(|c| c.aud = "https://other-proxy.example".into()),
                StatusCode::UNAUTHORIZED,
                "wrong_audience",
            ),
            (
                Box::new(|c| c.exp = crate::now_secs() - 1),
                StatusCode::UNAUTHORIZED,
                "capability_expired",
            ),
            (
                Box::new(|c| c.exp = crate::now_secs() + crate::capability::MAX_LIFETIME_SECS + 60),
                StatusCode::UNAUTHORIZED,
                "capability_too_long",
            ),
            (
                Box::new(|c| c.platform = "github-issues".into()),
                StatusCode::FORBIDDEN,
                "capability_scope",
            ),
            (
                Box::new(|c| c.connection_id = crate::connect::random()),
                StatusCode::FORBIDDEN,
                "capability_scope",
            ),
            (
                Box::new(|c| c.app = Agent::new(46).id()),
                StatusCode::FORBIDDEN,
                "not_delegated",
            ),
        ];
        for (edit, status, code) in cases {
            let mut claims = f.claims(&app, &frame);
            edit(&mut claims);
            let token = mint(&f.owner, &claims);
            expect_error(f.frame_get(&token, &frame).await, status, code).await;
        }
        // Minted by someone other than the connection owner (even by the
        // delegated app itself).
        let token = mint(&app, &f.claims(&app, &frame));
        expect_error(
            f.frame_get(&token, &frame).await,
            StatusCode::UNAUTHORIZED,
            "invalid_capability",
        )
        .await;
        // #72's v1 bearer capability is gone.
        let v1 = format!(
            "{}.sig",
            base64::Engine::encode(
                &base64::engine::general_purpose::URL_SAFE_NO_PAD,
                format!(
                    r#"{{"v":1,"connection_id":"{}","platform":"clockify","exp":1}}"#,
                    f.id
                )
            )
        );
        expect_error(
            f.frame_get(&v1, &frame).await,
            StatusCode::UNAUTHORIZED,
            "invalid_capability",
        )
        .await;
    }

    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL and fixture OAuth credentials; CI runs it"]
    async fn postgres_concurrent_requests_refresh_an_expired_token_once() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        let token_requests = std::sync::Arc::new(AtomicUsize::new(0));
        let token_counter = token_requests.clone();
        let upstream = axum::Router::new()
            .route(
                "/token",
                axum::routing::post(move |body: Bytes| {
                    let token_counter = token_counter.clone();
                    async move {
                        token_counter.fetch_add(1, Ordering::SeqCst);
                        assert!(String::from_utf8(body.to_vec())
                            .unwrap()
                            .contains("grant_type=refresh_token"));
                        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
                        axum::Json(json!({"access_token": "refreshed-token", "expires_in": 3600, "refresh_token": "rotated-refresh"}))
                    }
                }),
            )
            .route(
                "/items",
                axum::routing::get(|headers: HeaderMap| async move {
                    assert_eq!(headers.get(AUTHORIZATION).unwrap(), "Bearer refreshed-token");
                    (
                        [(header::ETAG, "\"v1\""), (header::LINK, "<https://example/items?page=2>; rel=\"next\"")],
                        axum::Json(json!([{"id": 1}])),
                    )
                }),
            );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let upstream_url = format!("http://{}", listener.local_addr().unwrap());
        let server = tokio::spawn(async move { axum::serve(listener, upstream).await.unwrap() });
        let security = security().await;
        let mut s = state(Some(security.clone()));
        s.catalog = crate::catalog::Catalog::from_test_document(
            "github-issues",
            json!({
                "servers": [{"url": upstream_url}],
                "components": {"securitySchemes": {"oauth": {"type": "oauth2", "flows": {
                    "authorizationCode": {
                        "authorizationUrl": "https://auth.example/authorize",
                        "tokenUrl": "https://auth.example/token",
                        "scopes": {"read": "Read items"}
                    }
                }}}},
                "security": [{"oauth": ["read"]}],
                "paths": {"/items": {"get": {}}}
            }),
            json!({}),
        );
        s.test_upstream = Some(upstream_url);
        let owner = Agent::new(47);
        let credential = serde_json::to_vec(&StoredCredential::OAuth {
            provider: "github-issues".into(),
            access_token: "stale-token".into(),
            refresh_token: Some("a-refresh-token".into()),
            expires_at: Some(0),
        })
        .unwrap();
        let id = security
            .create_connection("github-issues", &owner.id(), &credential)
            .await
            .unwrap();
        let path = format!("/proxy/{id}/github-issues/items");
        let (a, b) = tokio::join!(
            crate::router(s.clone()).oneshot(signed_request(&s, &owner, "GET", &path, vec![])),
            crate::router(s.clone()).oneshot(signed_request(&s, &owner, "GET", &path, vec![])),
        );
        let (a, b) = (a.unwrap(), b.unwrap());
        assert_eq!(a.status(), StatusCode::OK);
        assert_eq!(b.status(), StatusCode::OK);
        assert_eq!(a.headers()[header::ETAG], "\"v1\"");
        assert!(a.headers().get(header::LINK).is_some());
        assert_eq!(token_requests.load(Ordering::SeqCst), 1);
        let stored: StoredCredential = serde_json::from_slice(
            &security
                .load_connection(&id)
                .await
                .unwrap()
                .unwrap()
                .credential,
        )
        .unwrap();
        match stored {
            StoredCredential::OAuth {
                access_token,
                refresh_token,
                ..
            } => {
                assert_eq!(access_token, "refreshed-token");
                assert_eq!(refresh_token.as_deref(), Some("rotated-refresh"));
            }
            _ => panic!("expected an OAuth credential"),
        }
        server.abort();
    }
}