alien-bindings 3.3.69

Alien direct in-process resource bindings
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
//! Kubernetes sandbox provider: a pod under a sandboxed runtime class, reached over the agent
//! protocol.
//!
//! The application never holds a cluster credential. It asks the operator's broker for a
//! sandbox, and gets back a pod address plus a capability scoped to that sandbox. Claiming a pod
//! is a `PATCH` on pods, which does not belong in the binding: `pods/exec`
//! would reach every pod in the namespace.
//!
//! It authenticates to the broker with the ServiceAccount token Kubernetes already mounted in
//! its pod. Nothing of Alien's is created, rotated or torn down for this.

use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};

#[path = "kubernetes_egress.rs"]
mod egress;

use async_trait::async_trait;
use futures::stream::BoxStream;
use serde::{Deserialize, Serialize};

use crate::error::{ErrorData, Result};
use crate::providers::sandbox::agent_protocol::{self, AgentTransport};
use crate::traits::{
    Binding, CommandOutput, CreateSandboxRequest, InteractiveCommand, JobPoll, JobStart,
    PreviewCapability, ResolvedSandbox, RunCommandRequest, Sandbox, SandboxInstance, SandboxState,
};
use alien_core::bindings::KubernetesSandboxBinding;
use alien_core::{Platform, SandboxCapabilities, SandboxCapability};
use alien_error::{AlienError, Context, IntoAlienError};

/// A capability with less than this left is replaced before it is used, so a request built at the
/// end of its life does not reach the agent after it has expired.
const CAPABILITY_REFRESH_MARGIN_SECONDS: i64 = 60;

/// What the broker lists for a sandbox.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SessionList {
    session_ids: Vec<String>,
}

/// What the broker hands back for a claimed sandbox.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ClaimResponse {
    #[serde(default)]
    agent_session_id: Option<String>,
    session_id: String,
    endpoint: String,
    capability: String,
    expires_at: i64,
    /// What the pod records about the session; absent from a broker that predates them.
    #[serde(default = "first_generation")]
    generation: u64,
    /// Whether this request created the session. A broker that predates the field only ever
    /// created.
    #[serde(default = "yes")]
    created: bool,
    /// The tenant key the session was created with.
    #[serde(default)]
    tenant_key: Option<String>,
    /// Unix seconds at which the session ends; absent when it has no lifetime (or the broker
    /// predates the field).
    #[serde(default)]
    deadline: Option<i64>,
    /// Whether the creator is still setting the session up (its egress policy). Absent from a
    /// broker that predates the field, whose sessions are never marked.
    #[serde(default)]
    setup_pending: bool,
}

/// How long the gateway identity of a session without a lifetime is issued for. The issuer caps
/// every identity at this length anyway.
const GATEWAY_IDENTITY_FALLBACK_SECONDS: i64 = 86_400;

fn yes() -> bool {
    true
}

fn first_generation() -> u64 {
    1
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct ClaimRequest<'a> {
    sandbox_id: &'a str,
    session_id: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    tenant_key: Option<&'a str>,
    /// How long the session may live from the claim; the broker refuses more than the sandbox
    /// declares.
    #[serde(skip_serializing_if = "Option::is_none")]
    timeout_ms: Option<u64>,
}

/// What asking the broker about a session id found.
enum Lookup {
    Found(ClaimResponse),
    /// No pod carries the id: a clean not-found.
    NotFound,
    /// The broker has no route for a lookup by id (405, or 404 from one that does not know the
    /// path): an Operator that predates this client.
    Unsupported,
}

/// A broker call that did not get an answer.
///
/// The broker runs inside the Operator pod, so while the Operator restarts (every release) its
/// connections are refused for tens of seconds. Running sandboxes are unaffected; a refused
/// connection means the request never arrived, so repeating the call is safe and the error is
/// retryable. The message names the address, so a wrong broker URL reads differently from a
/// restart.
///
/// Creating a session is the exception once the request may have arrived: a connection that
/// failed after it was sent may already have claimed a pod, and a repeated create makes a second
/// session. That outcome is unknown, and not retried.
fn broker_failure(operation: &str, url: &str, error: reqwest::Error) -> AlienError<ErrorData> {
    let refused = error.is_connect();
    let failed: std::result::Result<(), reqwest::Error> = Err(error);
    if !refused && operation == "sandbox.create" {
        return failed
            .into_alien_error()
            .context(ErrorData::SandboxOutcomeUnknown {
                operation: operation.to_string(),
                reason: format!(
                    "the connection to the sandbox broker at {url} failed after the request was sent"
                ),
            })
            .unwrap_err();
    }
    let details = if refused {
        format!(
            "the sandbox broker at {url} did not accept the connection; if the Operator is \
             restarting, retry in a few seconds, otherwise check the broker address"
        )
    } else {
        format!("the request to the sandbox broker at {url} failed")
    };
    failed
        .into_alien_error()
        .context(ErrorData::RemoteServiceUnavailable {
            operation_context: operation.to_string(),
            details,
        })
        .unwrap_err()
}

/// Asks the broker for a session and a fresh capability.
async fn lookup_claim(client: &reqwest::Client, url: &str, token: &str) -> Result<Lookup> {
    let response = client
        .get(url)
        .bearer_auth(token)
        .send()
        .await
        .map_err(|error| broker_failure("sandbox.get", url, error))?;

    if response.status() == reqwest::StatusCode::NOT_FOUND {
        return Ok(Lookup::NotFound);
    }
    if response.status() == reqwest::StatusCode::METHOD_NOT_ALLOWED {
        return Ok(Lookup::Unsupported);
    }
    if !response.status().is_success() {
        let status = response.status();
        let body = response.text().await.unwrap_or_default();
        return Err(AlienError::new(ErrorData::OperationNotSupported {
            operation: "sandbox.get".to_string(),
            reason: broker_refusal(status, &body),
        }));
    }
    response
        .json()
        .await
        .into_alien_error()
        .context(ErrorData::UnexpectedResponseFormat {
            provider: "kubernetes-sandbox".to_string(),
            binding_name: "sandbox.get".to_string(),
            field: "body".to_string(),
            response_json: "the broker returned a body this provider cannot parse".to_string(),
        })
        .map(Lookup::Found)
}

/// Like [`lookup_claim`], where a broker without the lookup is an error. `None` when no pod
/// carries the id.
async fn fetch_claim(
    client: &reqwest::Client,
    url: &str,
    token: &str,
) -> Result<Option<ClaimResponse>> {
    match lookup_claim(client, url, token).await? {
        Lookup::Found(claim) => Ok(Some(claim)),
        Lookup::NotFound => Ok(None),
        Lookup::Unsupported => Err(AlienError::new(ErrorData::OperationNotSupported {
            operation: "sandbox.get".to_string(),
            reason: "the sandbox broker predates lookups by id; upgrade the Operator".to_string(),
        })),
    }
}

/// How long a caller waits for another caller's setup of a session it found.
const SETUP_WAIT: std::time::Duration = std::time::Duration::from_secs(150);
#[cfg(not(test))]
const SETUP_POLL: std::time::Duration = std::time::Duration::from_millis(500);
#[cfg(test)]
const SETUP_POLL: std::time::Duration = std::time::Duration::from_millis(5);

/// One session's agent for as long as an interactive command runs.
///
/// A command can outlive any capability, and its input is many short requests, so each request
/// checks the capability it holds and asks the broker for a new one before it expires.
#[derive(Debug)]
struct SessionAgent {
    client: reqwest::Client,
    session_url: String,
    token_path: String,
    binding_name: String,
    sandbox_id: String,
    claim: tokio::sync::Mutex<ClaimResponse>,
}

#[async_trait]
impl super::interactive::BoundAgent for SessionAgent {
    async fn request(
        &self,
        method: reqwest::Method,
        path: &str,
    ) -> Result<reqwest::RequestBuilder> {
        let mut claim = self.claim.lock().await;
        if claim.expires_at - chrono::Utc::now().timestamp() <= CAPABILITY_REFRESH_MARGIN_SECONDS {
            let token = read_identity_token(&self.token_path, &self.binding_name).await?;
            *claim = fetch_claim(&self.client, &self.session_url, &token)
                .await?
                .ok_or_else(|| {
                    AlienError::new(ErrorData::OperationNotSupported {
                        operation: "sandbox.agent".to_string(),
                        reason: format!(
                            "sandbox '{}' no longer exists; it ended while a command was running",
                            self.sandbox_id
                        ),
                    })
                })?;
        }
        Ok(self
            .client
            .request(method, format!("{}{path}", claim.endpoint))
            .bearer_auth(&claim.capability))
    }

    fn provider(&self) -> &'static str {
        "kubernetes-sandbox"
    }
}

/// What a broker answer that is not a success means to the caller.
///
/// A 401 is the broker refusing the token itself: neither the token projected for the broker's
/// audience nor the default ServiceAccount token was accepted for this deployment.
fn broker_refusal(status: reqwest::StatusCode, body: &str) -> String {
    if status == reqwest::StatusCode::UNAUTHORIZED {
        return format!(
            "the sandbox broker refused this workload's token ({status}). It accepts the \
             ServiceAccount token projected for the audience `alien-sandbox-broker` (mounted at \
             the sandbox binding's token path in every workload that links the sandbox) and, \
             until the workload is rolled, the default ServiceAccount token of a workload of \
             this deployment"
        );
    }
    format!("the sandbox broker returned {status}: {body}")
}

/// The ServiceAccount token the kubelet mounts in every pod.
const DEFAULT_TOKEN_PATH: &str = "/var/run/secrets/kubernetes.io/serviceaccount/token";

/// Reads the pod's ServiceAccount token. Per call: Kubernetes rotates projected tokens in place.
///
/// A workload started before it was linked to the sandbox, or before an upgrade, has no projected
/// token at `token_path`; it falls back to the default mount, which the broker still accepts, so
/// the workload keeps working until it is rolled.
async fn read_identity_token(token_path: &str, binding_name: &str) -> Result<String> {
    match tokio::fs::read_to_string(token_path).await {
        Ok(token) => Ok(token),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            tokio::fs::read_to_string(DEFAULT_TOKEN_PATH)
                .await
                .into_alien_error()
                .context(ErrorData::BindingConfigInvalid {
                    binding_name: binding_name.to_string(),
                    env_var: alien_core::bindings::binding_env_var_name(binding_name),
                    reason: format!(
                        "could not read the ServiceAccount token at '{token_path}' or at \
                         '{DEFAULT_TOKEN_PATH}'"
                    ),
                })
        }
        Err(error) => Err(error)
            .into_alien_error()
            .context(ErrorData::BindingConfigInvalid {
                binding_name: binding_name.to_string(),
                env_var: alien_core::bindings::binding_env_var_name(binding_name),
                reason: format!("could not read the ServiceAccount token at '{token_path}'"),
            }),
    }
}

/// A Sandbox backed by pods under a sandboxed runtime class.
#[derive(Debug)]
pub struct KubernetesSandbox {
    egress_manager: Option<Arc<crate::sandbox_egress::SandboxEgressManager>>,
    default_policy: Option<alien_core::EgressPolicy>,
    policy_write: tokio::sync::Mutex<()>,
    egress: Option<alien_core::SandboxEgress>,
    resource_id: String,
    broker_url: String,
    token_path: String,
    binding_name: String,
    client: reqwest::Client,
    /// Capabilities this process holds, so most calls need no round trip to the broker.
    ///
    /// Only a cache. The broker reads sessions off the pods themselves, so any process can look
    /// a session up by id, and a capability that is close to expiring is replaced the same way.
    claims: Mutex<BTreeMap<String, ClaimResponse>>,
}

impl KubernetesSandbox {
    /// Builds a provider from its binding.
    pub fn new(
        binding_name: &str,
        binding: &KubernetesSandboxBinding,
        resource_id: &str,
    ) -> Result<Self> {
        Self::new_with_egress_manager(binding_name, binding, resource_id, None)
    }

    pub(crate) fn new_with_egress_manager(
        binding_name: &str,
        binding: &KubernetesSandboxBinding,
        resource_id: &str,
        egress_manager: Option<Arc<crate::sandbox_egress::SandboxEgressManager>>,
    ) -> Result<Self> {
        let gateway = binding.egress.as_ref().and_then(|value| value.gateway());
        if gateway.is_some() != egress_manager.is_some() {
            return Err(super::egress::unsupported("gateway-backed sandbox"));
        }
        let default_policy = binding.default_policy.clone().or_else(|| {
            binding
                .egress
                .as_ref()
                .and_then(|value| value.default_policy().cloned())
        });
        if egress_manager.is_none() {
            super::egress::require_default(
                default_policy.as_ref(),
                binding.egress.as_ref().map(|value| value.declaration()),
            )?;
        }

        let value = |field: &'static str, value: alien_core::bindings::BindingValue<String>| {
            value.into_value(binding_name, field).map_err(|error| {
                AlienError::new(ErrorData::BindingConfigInvalid {
                    binding_name: binding_name.to_string(),
                    env_var: alien_core::bindings::binding_env_var_name(binding_name),
                    reason: error.to_string(),
                })
            })
        };

        Ok(Self {
            egress_manager,
            default_policy,
            policy_write: tokio::sync::Mutex::new(()),
            egress: binding
                .egress
                .as_ref()
                .map(|egress| egress.declaration().clone()),
            resource_id: resource_id.to_string(),
            broker_url: value("brokerUrl", binding.broker_url.clone())?
                .trim_end_matches('/')
                .to_string(),
            token_path: value("tokenPath", binding.token_path.clone())?,
            binding_name: binding_name.to_string(),
            client: reqwest::Client::new(),
            claims: Mutex::new(BTreeMap::new()),
        })
    }

    /// Reads the pod's ServiceAccount token.
    ///
    /// Read per call rather than cached: Kubernetes rotates projected tokens in place, and a
    /// cached copy becomes a token the apiserver refuses at the least convenient moment.
    async fn identity_token(&self) -> Result<String> {
        read_identity_token(&self.token_path, &self.binding_name).await
    }

    fn cached(&self, sandbox_id: &str) -> Option<ClaimResponse> {
        self.claims
            .lock()
            .expect("no panic holds this lock")
            .get(sandbox_id)
            .cloned()
    }

    fn session_url(&self, session_id: &str) -> String {
        format!(
            "{}/v1/sandbox/{}/sessions/{session_id}",
            self.broker_url, self.resource_id
        )
    }

    /// The session with this id, from the cache while its capability has more than a minute left
    /// and the session has not reached its deadline, and from the broker otherwise. `None` when
    /// no pod carries the id, which is a clean not-found rather than an error.
    async fn claimed(&self, sandbox_id: &str) -> Result<Option<ClaimResponse>> {
        if let Some(claim) = self.cached(sandbox_id) {
            let now = chrono::Utc::now().timestamp();
            let capability_current = claim.expires_at - now > CAPABILITY_REFRESH_MARGIN_SECONDS;
            let session_running = claim.deadline.is_none_or(|deadline| deadline > now);
            if capability_current && session_running {
                return Ok(Some(claim));
            }
        }
        self.claimed_by_broker(sandbox_id).await
    }

    /// The session with this id as the broker answers it now, whatever the cache holds.
    async fn claimed_by_broker(&self, sandbox_id: &str) -> Result<Option<ClaimResponse>> {
        let token = self.identity_token().await?;
        match lookup_claim(&self.client, &self.session_url(sandbox_id), &token).await? {
            Lookup::Found(claim) => Ok(Some(self.remember(claim))),
            Lookup::NotFound => {
                self.forget(sandbox_id);
                Ok(None)
            }
            Lookup::Unsupported => Err(AlienError::new(ErrorData::OperationNotSupported {
                operation: "sandbox.get".to_string(),
                reason: "the sandbox broker predates lookups by id; upgrade the Operator"
                    .to_string(),
            })),
        }
    }

    fn remember(&self, claim: ClaimResponse) -> ClaimResponse {
        self.claims
            .lock()
            .expect("no panic holds this lock")
            .insert(claim.session_id.clone(), claim.clone());
        claim
    }

    fn forget(&self, sandbox_id: &str) {
        self.claims
            .lock()
            .expect("no panic holds this lock")
            .remove(sandbox_id);
    }

    /// Waits until the creator of `claim`'s session has finished setting it up. A session the
    /// creator ended because its setup failed is an error here, not a session to use.
    async fn after_setup(&self, mut claim: ClaimResponse) -> Result<ClaimResponse> {
        let started = std::time::Instant::now();
        while claim.setup_pending {
            if started.elapsed() >= SETUP_WAIT {
                return Err(self.failed(
                    "sandbox.getOrCreate",
                    &format!(
                        "sandbox '{}' is still being set up by the process that created it",
                        claim.session_id
                    ),
                ));
            }
            tokio::time::sleep(SETUP_POLL).await;
            claim = self
                .claimed_by_broker(&claim.session_id)
                .await?
                .ok_or_else(|| {
                    self.failed(
                        "sandbox.getOrCreate",
                        &format!(
                            "sandbox '{}' ended while the process that created it was setting it up",
                            claim.session_id
                        ),
                    )
                })?;
        }
        Ok(claim)
    }

    /// Tells the broker this process has finished setting the session up. A broker that predates
    /// the route never marked the session, so there is nothing to clear.
    async fn setup_done(&self, session_id: &str) {
        let outcome = async {
            let response = self
                .client
                .post(format!("{}/ready", self.session_url(session_id)))
                .bearer_auth(self.identity_token().await?)
                .send()
                .await
                .map_err(|error| broker_failure("sandbox.create", &self.broker_url, error))?;
            Ok::<_, AlienError<ErrorData>>(response.status())
        }
        .await;
        match outcome {
            Ok(status)
                if status.is_success()
                    || status == reqwest::StatusCode::NOT_FOUND
                    || status == reqwest::StatusCode::METHOD_NOT_ALLOWED => {}
            // Callers that find the session wait at most the broker's setup window.
            Ok(status) => {
                tracing::warn!(%status, session_id, "the broker did not record the end of setup")
            }
            Err(error) => {
                tracing::warn!(%error, session_id, "the broker did not record the end of setup")
            }
        }
    }

    async fn create_resolved(&self, request: CreateSandboxRequest) -> Result<ResolvedSandbox> {
        self.validate_egress(request.egress.as_ref())?;
        let _policy_write = self.policy_write.lock().await;
        let policy = request
            .egress
            .clone()
            .or_else(|| self.default_policy.clone())
            .unwrap_or(alien_core::EgressPolicy::Internet);
        let sandbox_id = request
            .sandbox_id
            .unwrap_or_else(|| uuid::Uuid::new_v4().simple().to_string());

        // A caller that will set the session up says so, so that others who find it wait. A query
        // parameter: a broker that predates it ignores it.
        let setup = if self.egress_manager.is_some() {
            "?setup=pending"
        } else {
            ""
        };
        let response = self
            .client
            .post(format!("{}/v1/sandbox/sessions{setup}", self.broker_url))
            .bearer_auth(self.identity_token().await?)
            .json(&ClaimRequest {
                sandbox_id: &self.resource_id,
                session_id: &sandbox_id,
                tenant_key: request.tenant_key.as_deref(),
                timeout_ms: request.timeout_ms,
            })
            .send()
            .await
            .map_err(|error| broker_failure("sandbox.create", &self.broker_url, error))?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            // 503 is the pool being empty, which refills on the controller's next health tick.
            // Saying so is the difference between a caller retrying and a caller giving up.
            return Err(self.failed("sandbox.create", &broker_refusal(status, &body)));
        }

        let claim: ClaimResponse = response.json().await.into_alien_error().context(
            ErrorData::UnexpectedResponseFormat {
                provider: "kubernetes-sandbox".to_string(),
                binding_name: "sandbox.create".to_string(),
                field: "body".to_string(),
                response_json: "the broker returned a body this provider cannot parse".to_string(),
            },
        )?;

        let claim = self.remember(claim);

        // Another process created this id between the caller's lookup and this claim; the broker
        // answered with its session, which already carries its own policy.
        if !claim.created {
            let claim = self.after_setup(claim).await?;
            self.require_same_tenant(&claim, request.tenant_key.as_deref())?;
            return Ok(ResolvedSandbox::found(SandboxInstance {
                sandbox_id: claim.session_id,
                state: SandboxState::Running,
                generation: claim.generation,
            }));
        }

        if let Some(manager) = &self.egress_manager {
            let installation = async {
                let identity = Self::egress_identity(&claim)?;
                // The identity token lives as long as the session. `claim.expires_at` is when
                // the agent capability needs renewing (15 minutes), not when the session ends:
                // using it here would cut off the session's internet access after one capability.
                let session_ends_at = match claim.deadline {
                    Some(deadline) => deadline,
                    None => crate::sandbox_egress::now_unix()? + GATEWAY_IDENTITY_FALLBACK_SECONDS,
                };
                let delivery = manager.create(identity, &policy, session_ends_at).await?;
                self.deliver_egress(&claim.session_id, Some(&delivery.token), &delivery.policy)
                    .await
            }
            .await;
            if let Err(error) = installation {
                // Release the claimed pod even if publishing its initial policy failed. When the
                // release fails too, the caller still learns why the policy was not published:
                // that is the error to fix, and the cleanup failure is logged beside it.
                if let Err(cleanup) = self.terminate(&claim.session_id).await {
                    tracing::warn!(
                        sandbox_id = %claim.session_id,
                        error = %cleanup,
                        "the claimed pod could not be released after its initial egress policy failed"
                    );
                }
                return Err(self.explain_denied_signing_key(&claim.session_id, error));
            }
        }

        if self.egress_manager.is_some() {
            self.setup_done(&claim.session_id).await;
        }

        Ok(ResolvedSandbox::created(SandboxInstance {
            sandbox_id: claim.session_id,
            state: SandboxState::Running,
            generation: claim.generation,
        }))
    }

    /// An existing session answers only to the tenant key it was created with. A request with a
    /// different key, or with none for a keyed session (or the reverse), is refused.
    fn require_same_tenant(&self, claim: &ClaimResponse, requested: Option<&str>) -> Result<()> {
        if claim.tenant_key.as_deref() == requested {
            return Ok(());
        }
        Err(self.failed(
            "sandbox.getOrCreate",
            &format!(
                "sandbox '{}' exists with a different tenant key than the request names",
                claim.session_id
            ),
        ))
    }

    /// Creating a session reads the deployment's signing key. A workload whose permission profile
    /// only links the sandbox (execute) cannot read it; say what to grant instead of the bare
    /// access-denied of the secret read.
    fn explain_denied_signing_key(
        &self,
        session_id: &str,
        error: AlienError<ErrorData>,
    ) -> AlienError<ErrorData> {
        fn denied(code: &str, source: Option<&AlienError>) -> bool {
            code == "REMOTE_ACCESS_DENIED"
                || source.is_some_and(|s| denied(&s.code, s.source.as_deref()))
        }
        if denied(&error.code, error.source.as_deref()) {
            return self.failed(
                "sandbox.create",
                &format!(
                    "creating a session for sandbox {session_id} needs sandbox/management in the permission profile of this workload, from the first release: a permission profile cannot be changed by a later release once the stack is deployed. It was denied reading the deployment's signing key ({})",
                    error
                ),
            );
        }
        error
    }

    fn failed(&self, operation: &str, reason: &str) -> AlienError<ErrorData> {
        AlienError::new(ErrorData::OperationNotSupported {
            operation: operation.to_string(),
            reason: reason.to_string(),
        })
    }
}

#[async_trait]
impl AgentTransport for KubernetesSandbox {
    async fn request(
        &self,
        sandbox_id: &str,
        method: reqwest::Method,
        path: &str,
    ) -> Result<reqwest::RequestBuilder> {
        let claim = self.claimed(sandbox_id).await?.ok_or_else(|| {
            self.failed(
                "sandbox.agent",
                &format!("sandbox '{sandbox_id}' does not exist; it may have been terminated"),
            )
        })?;

        Ok(self
            .client
            .request(method, format!("{}{path}", claim.endpoint))
            .bearer_auth(claim.capability))
    }

    fn provider(&self) -> &'static str {
        "kubernetes-sandbox"
    }
}

impl Binding for KubernetesSandbox {}

#[async_trait]
impl Sandbox for KubernetesSandbox {
    fn egress_declaration(&self) -> Option<&alien_core::SandboxEgress> {
        self.egress.as_ref()
    }
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    /// What a Kubernetes sandbox offers: the platform table, unchanged.
    fn capabilities(&self) -> SandboxCapabilities {
        SandboxCapabilities::for_platform(Platform::Kubernetes)
            .expect("Kubernetes has a sandbox backend")
    }

    /// Claims a warm pod through the broker.
    async fn create(&self, request: CreateSandboxRequest) -> Result<SandboxInstance> {
        self.create_resolved(request)
            .await
            .map(|resolved| resolved.sandbox)
    }

    /// Any process of the deployment can look a session up by id: the broker reads it off the pod.
    /// An id no pod carries is `None`. Like `get_or_create`, this asks the broker every time: a
    /// cached capability only says the pod existed when it was minted, and another process may
    /// have ended the session since. It also waits for a creator that is still setting the
    /// session up.
    async fn get(&self, sandbox_id: &str) -> Result<Option<SandboxInstance>> {
        let Some(claim) = self.claimed_by_broker(sandbox_id).await? else {
            return Ok(None);
        };
        let claim = self.after_setup(claim).await?;
        Ok(Some(SandboxInstance {
            sandbox_id: claim.session_id,
            state: SandboxState::Running,
            generation: claim.generation,
        }))
    }

    async fn get_or_create(&self, request: CreateSandboxRequest) -> Result<ResolvedSandbox> {
        self.validate_egress(request.egress.as_ref())?;
        // `timeout_ms` applies when this call creates the session. A session that already exists
        // keeps the deadline it was created with.
        if let Some(id) = request.sandbox_id.as_deref() {
            // The broker decides whether the session exists: a cached capability only says the
            // pod existed when it was minted, and the Operator may have ended it since.
            let token = self.identity_token().await?;
            match lookup_claim(&self.client, &self.session_url(id), &token).await? {
                Lookup::Found(claim) => {
                    let claim = self.remember(claim);
                    // Another process may still be setting its egress up.
                    let claim = self.after_setup(claim).await?;
                    // The id names one session; a caller with a different tenant key does not get
                    // it, and does not get to change its egress policy either.
                    self.require_same_tenant(&claim, request.tenant_key.as_deref())?;
                    if let Some(policy) = request.egress.clone() {
                        self.update_egress(id, policy).await?;
                    }
                    return Ok(ResolvedSandbox::found(SandboxInstance {
                        sandbox_id: claim.session_id,
                        state: SandboxState::Running,
                        generation: claim.generation,
                    }));
                }
                Lookup::NotFound => self.forget(id),
                // An Operator that predates lookups by id: create as it always has. It cannot
                // check a tenant key, so a caller that set one is refused rather than served
                // without the check.
                Lookup::Unsupported => {
                    if request.tenant_key.is_some() {
                        return Err(self.failed(
                            "sandbox.getOrCreate",
                            "the sandbox broker predates lookups by id and cannot honour a tenantKey; upgrade the Operator",
                        ));
                    }
                }
            }
        }

        self.create_resolved(request).await
    }

    async fn update_egress(
        &self,
        sandbox_id: &str,
        policy: alien_core::EgressPolicy,
    ) -> Result<()> {
        self.validate_egress(Some(&policy))?;
        let _policy_write = self.policy_write.lock().await;
        let manager = self
            .egress_manager
            .as_ref()
            .ok_or_else(|| super::egress::unsupported("runtime policy"))?;
        let claim = self
            .claimed(sandbox_id)
            .await?
            .ok_or_else(|| self.failed("sandbox.updateEgress", "the sandbox does not exist"))?;
        let identity = Self::egress_identity(&claim)?;
        manager.update(identity, &policy).await?;
        let record = manager.policy_record(identity).await?;
        self.deliver_egress(sandbox_id, None, &record).await
    }

    async fn list(&self) -> Result<Vec<SandboxInstance>> {
        let response = self
            .client
            .get(format!(
                "{}/v1/sandbox/{}/sessions",
                self.broker_url, self.resource_id
            ))
            .bearer_auth(self.identity_token().await?)
            .send()
            .await
            .map_err(|error| broker_failure("sandbox.list", &self.broker_url, error))?;
        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            return Err(self.failed("sandbox.list", &broker_refusal(status, &body)));
        }
        let list: SessionList = response.json().await.into_alien_error().context(
            ErrorData::UnexpectedResponseFormat {
                provider: "kubernetes-sandbox".to_string(),
                binding_name: "sandbox.list".to_string(),
                field: "body".to_string(),
                response_json: "the broker returned a body this provider cannot parse".to_string(),
            },
        )?;
        Ok(list
            .session_ids
            .into_iter()
            .map(|sandbox_id| SandboxInstance {
                sandbox_id,
                state: SandboxState::Running,
                generation: 1,
            })
            .collect())
    }

    async fn run_command(
        &self,
        sandbox_id: &str,
        request: RunCommandRequest,
    ) -> Result<BoxStream<'static, Result<CommandOutput>>> {
        agent_protocol::run_command(self, sandbox_id, request).await
    }

    async fn run_interactive(
        &self,
        sandbox_id: &str,
        request: RunCommandRequest,
    ) -> Result<InteractiveCommand> {
        let claim = self.claimed(sandbox_id).await?.ok_or_else(|| {
            self.failed(
                "sandbox.agent",
                &format!("sandbox '{sandbox_id}' does not exist; it may have been terminated"),
            )
        })?;
        let agent = Arc::new(SessionAgent {
            client: self.client.clone(),
            session_url: self.session_url(&claim.session_id),
            token_path: self.token_path.clone(),
            binding_name: self.binding_name.clone(),
            sandbox_id: claim.session_id.clone(),
            claim: tokio::sync::Mutex::new(claim),
        });
        super::interactive::run_interactive(agent, request).await
    }

    async fn start_job(&self, sandbox_id: &str, request: RunCommandRequest) -> Result<JobStart> {
        agent_protocol::start_job(self, sandbox_id, request).await
    }

    async fn poll_job(
        &self,
        sandbox_id: &str,
        job_id: &str,
        since_seq: Option<u64>,
    ) -> Result<JobPoll> {
        agent_protocol::poll_job(self, sandbox_id, job_id, since_seq).await
    }

    async fn cancel_job(&self, sandbox_id: &str, job_id: &str) -> Result<()> {
        agent_protocol::cancel_job(self, sandbox_id, job_id).await
    }

    async fn read_file(&self, sandbox_id: &str, path: &str) -> Result<Vec<u8>> {
        agent_protocol::read_file(self, sandbox_id, path).await
    }

    async fn write_files(&self, sandbox_id: &str, files: BTreeMap<String, Vec<u8>>) -> Result<()> {
        agent_protocol::write_files(self, sandbox_id, files).await
    }

    /// Mints a capability for one declared port of the session's own server and returns the
    /// agent's in-cluster URL for it. Only workloads that link the sandbox reach that address.
    async fn preview(&self, sandbox_id: &str, port: u16) -> Result<PreviewCapability> {
        let claim = self.claimed(sandbox_id).await?.ok_or_else(|| {
            self.failed(
                "sandbox.preview",
                &format!("sandbox '{sandbox_id}' does not exist; it may have been terminated"),
            )
        })?;
        let response = self
            .client
            .post(format!("{}/preview", self.session_url(&claim.session_id)))
            .bearer_auth(self.identity_token().await?)
            .json(&serde_json::json!({ "port": port }))
            .send()
            .await
            .map_err(|error| broker_failure("sandbox.preview", &self.broker_url, error))?;
        if !response.status().is_success() {
            let status = response.status();
            let reason = if status == reqwest::StatusCode::FORBIDDEN {
                format!("port {port} is not one of this sandbox's declared preview ports")
            } else {
                broker_refusal(status, "")
            };
            return Err(self.failed("sandbox.preview", &reason));
        }
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Grant {
            endpoint: String,
            capability: String,
            expires_at: i64,
        }
        let grant: Grant =
            response
                .json()
                .await
                .into_alien_error()
                .context(ErrorData::OperationNotSupported {
                    operation: "sandbox.preview".to_string(),
                    reason: "the sandbox broker's answer was unreadable".to_string(),
                })?;
        Ok(PreviewCapability {
            endpoint: grant.endpoint,
            headers: preview_headers(grant.capability, port),
            allowed_ports: vec![port],
            expires_in_seconds: u64::try_from(grant.expires_at - chrono::Utc::now().timestamp())
                .unwrap_or(0),
            caller_authorization_header: "Authorization".to_string(),
            subprotocols: Vec::new(),
        })
    }

    async fn pause(&self, _sandbox_id: &str) -> Result<()> {
        Err(self.failed("pauseResume", "a pod cannot be paused and resumed"))
    }

    /// A pod is never paused, so a sandbox that exists is already running and resuming it is a
    /// no-op. One that does not exist cannot come back.
    async fn resume(&self, sandbox_id: &str) -> Result<()> {
        match self.claimed(sandbox_id).await? {
            Some(_) => Ok(()),
            None => Err(AlienError::new(ErrorData::SandboxCommandFailed {
                failure: "sandboxTerminated".to_string(),
                reason: format!("sandbox.resume: no sandbox '{sandbox_id}' is running"),
            })),
        }
    }

    async fn snapshot(&self, _sandbox_id: &str) -> Result<String> {
        Err(self.failed("snapshot", "a pod has no snapshot primitive"))
    }

    /// Releases the sandbox, which deletes its pod.
    ///
    /// Idempotent: a sandbox this process never claimed is already in the desired end state.
    async fn terminate(&self, sandbox_id: &str) -> Result<()> {
        let Some(claim) = self.claimed(sandbox_id).await? else {
            return Ok(());
        };

        let response = self
            .client
            .delete(self.session_url(&claim.session_id))
            .bearer_auth(self.identity_token().await?)
            .send()
            .await
            .map_err(|error| broker_failure("sandbox.terminate", &self.broker_url, error))?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            return Err(self.failed("sandbox.terminate", &broker_refusal(status, &body)));
        }

        if let Some(manager) = &self.egress_manager {
            if let Some(identity) = claim.agent_session_id.as_deref() {
                manager.delete(identity).await?;
            }
        }
        self.claims
            .lock()
            .expect("no panic holds this lock")
            .remove(sandbox_id);

        Ok(())
    }
}

/// The headers a caller merges into its own request. The capability has its own header, never
/// `Authorization`: the caller's own bearer token belongs to the code inside the sandbox and
/// reaches it untouched. The URL already names the port; the header repeats it so the agent can
/// refuse a mismatch.
fn preview_headers(capability: String, port: u16) -> BTreeMap<String, String> {
    BTreeMap::from([
        (
            alien_core::sandbox_image::PREVIEW_CAPABILITY_HEADER.to_string(),
            capability,
        ),
        (
            alien_core::sandbox_image::PREVIEW_PORT_HEADER.to_string(),
            port.to_string(),
        ),
    ])
}

#[cfg(test)]
mod tests {
    #[test]
    fn preview_headers_never_use_authorization() {
        let headers = super::preview_headers("cap".to_string(), 8081);
        assert!(!headers
            .keys()
            .any(|name| name.eq_ignore_ascii_case("authorization")));
        assert_eq!(headers["x-alien-preview-capability"], "cap");
        assert_eq!(headers["x-alien-preview-port"], "8081");
    }

    /// The broker lives in the Operator pod, so a restart refuses connections for tens of seconds.
    /// That is a wait, not an unsupported operation: the caller must be told it can retry.
    #[tokio::test]
    async fn an_unreachable_broker_is_a_retryable_error_that_says_the_operator_is_restarting() {
        let port = {
            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
            listener.local_addr().unwrap().port()
        };
        let error = lookup_claim(
            &reqwest::Client::new(),
            &format!("http://127.0.0.1:{port}/sessions/s1"),
            "token",
        )
        .await
        .err()
        .expect("nothing listens on that port");

        assert!(error.retryable, "an unreachable broker must be retryable");
        assert!(
            error.message.contains("Operator is restarting"),
            "the message says why and what to do: {}",
            error.message
        );
    }

    /// A sandbox over a broker at `broker_url`, with a token file in place.
    fn sandbox_at(broker_url: String) -> KubernetesSandbox {
        let token_path = std::env::temp_dir().join("kube-sandbox-test-token");
        std::fs::write(&token_path, "token").unwrap();
        KubernetesSandbox {
            egress_manager: None,
            default_policy: None,
            policy_write: tokio::sync::Mutex::new(()),
            egress: None,
            resource_id: "sbx".to_string(),
            broker_url,
            token_path: token_path.to_string_lossy().into_owned(),
            binding_name: "sandbox".to_string(),
            client: reqwest::Client::new(),
            claims: Mutex::new(BTreeMap::new()),
        }
    }

    /// A refused connection never reached the broker, so creating again cannot make a second
    /// session: the caller may retry, and the message names the broker address.
    #[tokio::test]
    async fn create_is_retryable_when_the_connection_is_refused() {
        let port = {
            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
            listener.local_addr().unwrap().port()
        };
        let url = format!("http://127.0.0.1:{port}");
        let error = sandbox_at(url.clone())
            .create(CreateSandboxRequest::default())
            .await
            .expect_err("nothing listens on that port");
        assert!(error.retryable, "a refused connection is retryable");
        assert!(error.message.contains(&url), "{}", error.message);
        assert!(
            error.source.is_some(),
            "the connect error stays in the chain: {error:?}"
        );
    }

    /// A connection that dies after the request was sent may already have claimed a pod. Creating
    /// again would make a second session and orphan the first, so the outcome is unknown and the
    /// error is not retryable.
    #[tokio::test]
    async fn create_outcome_is_unknown_when_the_connection_drops_after_the_request() {
        use tokio::io::AsyncReadExt;
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap());
        tokio::spawn(async move {
            let (mut socket, _) = listener.accept().await.unwrap();
            let mut buffer = [0u8; 1024];
            let _ = socket.read(&mut buffer).await;
            drop(socket);
        });
        let error = sandbox_at(url)
            .create(CreateSandboxRequest::default())
            .await
            .expect_err("the broker hung up");
        assert!(!error.retryable, "a possible claim must not be repeated");
        assert!(
            matches!(error.error, Some(ErrorData::SandboxOutcomeUnknown { .. })),
            "{error:?}"
        );
        assert!(
            error.source.is_some(),
            "the cause stays in the chain: {error:?}"
        );
    }

    /// An Operator that predates `tenantKey` and `timeoutMs` rejects unknown fields, so a caller
    /// that sets neither must send neither: the body is what an old Operator accepts.
    #[test]
    fn a_claim_omits_the_fields_the_caller_did_not_set() {
        let body = serde_json::to_value(ClaimRequest {
            sandbox_id: "sbx",
            session_id: "s1",
            tenant_key: None,
            timeout_ms: None,
        })
        .unwrap();
        assert_eq!(
            body,
            serde_json::json!({"sandboxId": "sbx", "sessionId": "s1"})
        );
        let body = serde_json::to_value(ClaimRequest {
            sandbox_id: "sbx",
            session_id: "s1",
            tenant_key: Some("t"),
            timeout_ms: Some(5),
        })
        .unwrap();
        assert_eq!(
            body["tenantKey"], "t",
            "a tenant the caller set is never dropped"
        );
        assert_eq!(body["timeoutMs"], 5);
    }

    #[tokio::test]
    async fn the_token_falls_back_to_the_default_mount_when_the_projected_file_is_missing() {
        let error = read_identity_token("/nonexistent/alien/token", "sbx")
            .await
            .expect_err("neither file exists in the test environment");
        let message = format!("{error:?}");
        assert!(message.contains(DEFAULT_TOKEN_PATH), "{message}");
    }

    use super::*;

    #[test]
    fn a_refused_token_names_the_audience_and_the_accepted_tokens() {
        let message = broker_refusal(reqwest::StatusCode::UNAUTHORIZED, "");
        assert!(message.contains("alien-sandbox-broker"), "{message}");
        assert!(
            message.contains("default ServiceAccount token"),
            "{message}"
        );
        assert_eq!(
            broker_refusal(reqwest::StatusCode::NOT_FOUND, "no such pod"),
            "the sandbox broker returned 404 Not Found: no such pod"
        );
    }
    use alien_core::bindings::BindingValue;
    use axum::extract::{Path, Request};
    use axum::http::StatusCode;
    use axum::routing::{delete, post};
    use axum::{Json, Router};
    use std::net::SocketAddr;
    use std::sync::Arc;

    /// Copied verbatim from `broker_router` in `alien-infra`'s `sandbox::kubernetes_route`, so a
    /// client path the broker does not route falls through to the fallback below.
    const BROKER_RELEASE_ROUTE: &str = "/v1/sandbox/{sandbox}/sessions/{session}";

    async fn serve(router: Router) -> String {
        let listener = tokio::net::TcpListener::bind::<SocketAddr>("127.0.0.1:0".parse().unwrap())
            .await
            .expect("bind");
        let address = listener.local_addr().expect("address");
        tokio::spawn(async move {
            axum::serve(listener, router).await.expect("serve");
        });
        format!("http://{address}")
    }

    fn sandbox_over(broker: String, token: &tempfile::NamedTempFile) -> KubernetesSandbox {
        std::fs::write(token.path(), "service-account-token").expect("the token is written");
        KubernetesSandbox::new(
            "sbx",
            &KubernetesSandboxBinding {
                default_policy: None,
                egress: None,
                namespace: BindingValue::Value("alien".to_string()),
                runtime_class: BindingValue::Value("gvisor".to_string()),
                selector: BindingValue::Value("alien/sandbox=sbx-pool".to_string()),
                broker_url: BindingValue::Value(broker),
                key_name: BindingValue::Value("sandbox-key".to_string()),
                token_path: BindingValue::Value(token.path().display().to_string()),
            },
            "sbx-pool",
        )
        .expect("the binding is complete")
    }

    /// A vault whose signing-key read is denied, as a workload that only links the sandbox sees.
    #[derive(Debug)]
    struct DeniedVault;
    impl crate::traits::Binding for DeniedVault {}
    #[async_trait]
    impl crate::traits::Vault for DeniedVault {
        async fn get_secret(&self, _name: &str) -> Result<String> {
            use alien_error::ContextError;
            Err(
                AlienError::new(alien_client_core::ErrorData::RemoteAccessDenied {
                    resource_type: "Secret".to_string(),
                    resource_name: "signing-key".to_string(),
                })
                .context(ErrorData::CloudPlatformError {
                    message: "Failed to get secret 'signing-key'".to_string(),
                    resource_id: None,
                }),
            )
        }
        async fn secret_presence(&self, _: &str) -> Result<crate::traits::SecretPresence> {
            unimplemented!()
        }
        async fn set_secret(&self, _: &str, _: &str) -> Result<()> {
            unimplemented!()
        }
        async fn delete_secret(&self, _: &str) -> Result<()> {
            unimplemented!()
        }
        async fn list_secrets(&self) -> Result<Vec<String>> {
            unimplemented!()
        }
    }

    /// Creating a session reads the signing key. When that is denied, and releasing the claimed
    /// pod fails too, the caller learns which permission is missing, not the release failure and
    /// not a bare access-denied.
    #[tokio::test]
    async fn a_denied_signing_key_read_names_the_missing_permission() {
        let released = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let expires = chrono::Utc::now().timestamp() + 900;
        let broker = serve(
            Router::new()
                .route(
                    BROKER_RELEASE_ROUTE,
                    delete({
                        let released = released.clone();
                        move || async move {
                            released.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                            StatusCode::INTERNAL_SERVER_ERROR
                        }
                    }),
                )
                .route(
                    "/v1/sandbox/sessions",
                    post(move |Json(body): Json<serde_json::Value>| async move {
                        Json(serde_json::json!({
                            "agentSessionId": "uid-2", "sessionId": body["sessionId"],
                            "endpoint": "http://10.0.0.2:8080", "capability": "c",
                            "expiresAt": expires, "generation": 1, "created": true,
                        }))
                    }),
                ),
        )
        .await;
        let token = tempfile::NamedTempFile::new().expect("a token file");
        std::fs::write(token.path(), "service-account-token").unwrap();
        let gateway = alien_core::SandboxEgressGateway {
            container: "gateway".to_string(),
            audience: "prefix/sbx".to_string(),
            signing_key: alien_core::bindings::SandboxEgressSigningKey {
                vault: "secrets".to_string(),
                key: "signing-key".to_string(),
            },
            kid: "key-1".to_string(),
            admin_ca_pem: None,
            replicas: None,
        };
        let manager = crate::sandbox_egress::SandboxEgressManager::new(
            gateway.clone(),
            Arc::new(DeniedVault),
            "http://127.0.0.1:3128",
            "http://127.0.0.1:3129",
        )
        .expect("a manager");
        let sandbox = KubernetesSandbox::new_with_egress_manager(
            "sbx",
            &KubernetesSandboxBinding {
                default_policy: None,
                egress: Some(alien_core::bindings::SandboxEgressBinding::Gateway(gateway)),
                namespace: BindingValue::Value("alien".to_string()),
                runtime_class: BindingValue::Value("gvisor".to_string()),
                selector: BindingValue::Value("alien/sandbox=sbx-pool".to_string()),
                broker_url: BindingValue::Value(broker),
                key_name: BindingValue::Value("sandbox-key".to_string()),
                token_path: BindingValue::Value(token.path().display().to_string()),
            },
            "sbx-pool",
            Some(Arc::new(manager)),
        )
        .expect("the binding is complete");

        let error = sandbox
            .get_or_create(CreateSandboxRequest {
                sandbox_id: Some("s1".to_string()),
                ..Default::default()
            })
            .await
            .expect_err("the signing key cannot be read");
        let message = format!("{error}");
        assert!(
            message.contains("creating a session for sandbox s1 needs sandbox/management in the permission profile"),
            "{message}"
        );
        assert!(
            message.contains("from the first release")
                && message.contains("cannot be changed by a later release"),
            "the message says the permission must be there from the first release: {message}"
        );
        assert_eq!(
            released.load(std::sync::atomic::Ordering::SeqCst),
            1,
            "the claimed pod's release route is called once, and its failure does not hide the denial"
        );
    }

    /// A pod is never paused, so resuming a running sandbox succeeds without changing anything
    /// and resuming one the broker does not know is refused.
    #[tokio::test]
    async fn resume_is_a_no_op_for_a_running_sandbox_and_refused_for_an_unknown_one() {
        let broker = serve(Router::new().route(
            BROKER_RELEASE_ROUTE,
            axum::routing::get(|Path((_, session)): Path<(String, String)>| async move {
                if session == "running" {
                    Ok(Json(serde_json::json!({
                        "sessionId": "running",
                        "endpoint": "http://10.0.0.1:8080",
                        "capability": "cap",
                        "expiresAt": chrono::Utc::now().timestamp() + 300,
                    })))
                } else {
                    Err(StatusCode::NOT_FOUND)
                }
            }),
        ))
        .await;
        let token = tempfile::NamedTempFile::new().expect("a token file");
        let sandbox = sandbox_over(broker, &token);

        sandbox.resume("running").await.expect("a no-op");
        let error = sandbox.resume("gone").await.expect_err("nothing to resume");
        assert_eq!(error.code, "SANDBOX_COMMAND_FAILED", "{error}");
    }

    /// Terminate releases the claim at the route the broker serves, with the resource and the
    /// session in the order it serves them.
    ///
    /// The broker is the only thing that can delete the pod, so a DELETE to a path it does not
    /// route leaves the sandbox running and the claim held while the caller is told it is gone.
    /// Mutation check: change the path in `terminate` and the fallback records the request.
    #[tokio::test]
    async fn terminate_releases_at_the_route_the_broker_serves() {
        let released = Arc::new(Mutex::new(Vec::new()));
        let unrouted = Arc::new(Mutex::new(Vec::new()));
        let released_seen = Arc::clone(&released);
        let unrouted_seen = Arc::clone(&unrouted);

        let broker = serve(
            Router::new()
                .route(
                    "/v1/sandbox/sessions",
                    post(|| async {
                        Json(serde_json::json!({
                            "sessionId": "s1",
                            "endpoint": "http://10.0.0.1:8080",
                            "capability": "cap",
                            "expiresAt": chrono::Utc::now().timestamp() + 300,
                        }))
                    }),
                )
                .route(
                    BROKER_RELEASE_ROUTE,
                    // Once released, the broker finds no pod carrying the session.
                    axum::routing::get(|| async { StatusCode::NOT_FOUND }).delete(
                        move |Path(addressed): Path<(String, String)>| {
                            let released = Arc::clone(&released);
                            async move {
                                released
                                    .lock()
                                    .expect("no panic holds this lock")
                                    .push(addressed);
                                StatusCode::NO_CONTENT
                            }
                        },
                    ),
                )
                .fallback(move |request: Request| {
                    let unrouted = Arc::clone(&unrouted);
                    async move {
                        unrouted
                            .lock()
                            .expect("no panic holds this lock")
                            .push(format!("{} {}", request.method(), request.uri().path()));
                        StatusCode::NOT_FOUND
                    }
                }),
        )
        .await;

        let token = tempfile::NamedTempFile::new().expect("a token file");
        let sandbox = sandbox_over(broker, &token);

        let claimed = sandbox
            .create(CreateSandboxRequest {
                sandbox_id: Some("s1".to_string()),
                tenant_key: None,
                env: BTreeMap::new(),
                ..Default::default()
            })
            .await
            .expect("the broker claims a pod");

        let released_claim = sandbox.terminate(&claimed.sandbox_id).await;

        assert!(
            unrouted_seen
                .lock()
                .expect("no panic holds this lock")
                .is_empty(),
            "terminate reached a path the broker does not route: {:?}",
            unrouted_seen.lock().expect("no panic holds this lock")
        );
        released_claim.expect("the broker releases the claim");
        assert_eq!(
            *released_seen.lock().expect("no panic holds this lock"),
            vec![("sbx-pool".to_string(), "s1".to_string())],
            "the release names the resource and then the session"
        );
        assert!(
            sandbox
                .get(&claimed.sandbox_id)
                .await
                .expect("a released sandbox reads back")
                .is_none(),
            "a released sandbox is no longer claimed"
        );
    }

    /// A second process has no claim of its own and still reaches the session by id, because the
    /// broker reads it off the pod. An id no pod carries is a clean not-found, and a capability
    /// near its end is replaced before a request is built with it.
    #[tokio::test]
    async fn another_process_reattaches_by_id_and_capabilities_are_refreshed() {
        use axum::routing::get;
        let lookups = Arc::new(Mutex::new(0_u32));
        let counted = Arc::clone(&lookups);
        let broker = serve(Router::new().route(
            BROKER_RELEASE_ROUTE,
            get(move |Path((_, session)): Path<(String, String)>| {
                let counted = Arc::clone(&counted);
                async move {
                    *counted.lock().expect("no panic holds this lock") += 1;
                    if session == "known" {
                        Ok(Json(serde_json::json!({
                            "agentSessionId": "uid-1",
                            "sessionId": "known",
                            "endpoint": "http://10.0.0.1:8080",
                            "capability": "fresh",
                            "expiresAt": chrono::Utc::now().timestamp() + 900,
                        })))
                    } else {
                        Err(StatusCode::NOT_FOUND)
                    }
                }
            }),
        ))
        .await;
        let token = tempfile::NamedTempFile::new().expect("a token file");
        let sandbox = sandbox_over(broker, &token);

        let found = sandbox
            .get("known")
            .await
            .expect("lookup works")
            .expect("a process that never claimed it still finds it");
        assert_eq!(found.sandbox_id, "known");
        assert!(sandbox
            .get("probe-id")
            .await
            .expect("an unknown id is not an error")
            .is_none());

        // Every `get` asks the broker; the capability it returns is remembered for later calls.
        sandbox.get("known").await.unwrap().unwrap();
        assert_eq!(*lookups.lock().unwrap(), 3, "one lookup per call");
    }

    /// Agent requests reuse the capability this process holds, and replace it before it ends.
    #[tokio::test]
    async fn an_agent_request_refreshes_a_capability_near_its_expiry() {
        use axum::routing::get;
        let lookups = Arc::new(Mutex::new(0_u32));
        let counted = Arc::clone(&lookups);
        let broker = serve(Router::new().route(
            BROKER_RELEASE_ROUTE,
            get(move |Path((_, session)): Path<(String, String)>| {
                let counted = Arc::clone(&counted);
                async move {
                    *counted.lock().expect("no panic holds this lock") += 1;
                    Json(session_body(&session, false, None))
                }
            }),
        ))
        .await;
        let token = tempfile::NamedTempFile::new().expect("a token file");
        let sandbox = sandbox_over(broker, &token);
        sandbox.remember(serde_json::from_value(session_body("s1", false, None)).unwrap());

        // A capability with time left is reused without asking the broker.
        let _ = sandbox
            .request("s1", reqwest::Method::GET, "/v1/health")
            .await
            .expect("a request is built");
        assert_eq!(
            *lookups.lock().unwrap(),
            0,
            "served from the held capability"
        );

        // Close to expiry, building the next request asks the broker again.
        sandbox
            .claims
            .lock()
            .unwrap()
            .get_mut("s1")
            .unwrap()
            .expires_at = chrono::Utc::now().timestamp() + 10;
        let _ = sandbox
            .request("s1", reqwest::Method::GET, "/v1/health")
            .await
            .expect("a request is built");
        assert_eq!(*lookups.lock().unwrap(), 1, "refreshed before it expired");
    }

    fn session_body(session: &str, pending: bool, deadline: Option<i64>) -> serde_json::Value {
        let mut body = serde_json::json!({
            "agentSessionId": "uid-1", "sessionId": session,
            "endpoint": "http://10.0.0.1:8080", "capability": "c",
            "expiresAt": chrono::Utc::now().timestamp() + 900, "created": false,
        });
        if pending {
            body["setupPending"] = true.into();
        }
        if let Some(deadline) = deadline {
            body["deadline"] = deadline.into();
        }
        body
    }

    /// A session another process is still setting up is not handed out until that process says
    /// it is done; if the creator ends the session because its setup failed, the caller gets an
    /// error and not a session without its egress.
    #[tokio::test]
    async fn a_session_still_being_set_up_by_its_creator_is_waited_for() {
        use axum::routing::get;
        let lookups = Arc::new(Mutex::new(0));
        let seen = Arc::clone(&lookups);
        let broker = serve(Router::new().route(
            BROKER_RELEASE_ROUTE,
            get(move |Path((_, session)): Path<(String, String)>| {
                let seen = Arc::clone(&seen);
                async move {
                    let mut lookups = seen.lock().unwrap();
                    *lookups += 1;
                    match (session.as_str(), *lookups) {
                        // Pending for the first two lookups, then the creator reports.
                        ("ready-later", 1 | 2) => Ok(Json(session_body(&session, true, None))),
                        ("ready-later", _) => Ok(Json(session_body(&session, false, None))),
                        // The creator's setup failed and it ended the session.
                        (_, 1) => Ok(Json(session_body(&session, true, None))),
                        _ => Err(StatusCode::NOT_FOUND),
                    }
                }
            }),
        ))
        .await;
        let token = tempfile::NamedTempFile::new().unwrap();
        let sandbox = sandbox_over(broker, &token);

        let found = sandbox
            .get_or_create(CreateSandboxRequest {
                sandbox_id: Some("ready-later".to_string()),
                ..Default::default()
            })
            .await
            .expect("found once the creator reports");
        assert!(!found.created);
        assert_eq!(
            *lookups.lock().unwrap(),
            3,
            "it waited for two pending answers"
        );

        *lookups.lock().unwrap() = 0;
        let error = sandbox
            .get_or_create(CreateSandboxRequest {
                sandbox_id: Some("failed".to_string()),
                ..Default::default()
            })
            .await
            .expect_err("the creator's setup failed");
        assert!(error.to_string().contains("ended while"), "{error}");
    }

    /// The broker, not the cache, says whether a session still exists: the Operator may have
    /// ended it at its deadline while the capability this process holds is still unexpired.
    #[tokio::test]
    async fn get_or_create_asks_the_broker_even_when_the_cached_capability_is_unexpired() {
        use axum::routing::get;
        let gone = Arc::new(Mutex::new(false));
        let flag = Arc::clone(&gone);
        let broker = serve(
            Router::new()
                .route(
                    BROKER_RELEASE_ROUTE,
                    get(move |Path((_, session)): Path<(String, String)>| {
                        let flag = Arc::clone(&flag);
                        async move {
                            if *flag.lock().unwrap() {
                                Err(StatusCode::NOT_FOUND)
                            } else {
                                Ok(Json(session_body(&session, false, None)))
                            }
                        }
                    }),
                )
                .route(
                    "/v1/sandbox/sessions",
                    axum::routing::post(|| async {
                        let mut body = session_body("s1", false, None);
                        body["created"] = true.into();
                        Json(body)
                    }),
                ),
        )
        .await;
        let token = tempfile::NamedTempFile::new().unwrap();
        let sandbox = sandbox_over(broker, &token);
        let request = || CreateSandboxRequest {
            sandbox_id: Some("s1".to_string()),
            ..Default::default()
        };

        assert!(!sandbox.get_or_create(request()).await.unwrap().created);
        *gone.lock().unwrap() = true;
        assert!(
            sandbox.get_or_create(request()).await.unwrap().created,
            "the session ended; a replacement is created"
        );

        // `get` does not trust a cached session either: it was terminated by another process.
        sandbox.remember(serde_json::from_value(session_body("s1", false, None)).unwrap());
        assert!(sandbox.get("s1").await.unwrap().is_none());
    }

    /// `get` waits for a creator that is still setting the session up, as `get_or_create` does.
    #[tokio::test]
    async fn get_waits_for_a_session_that_is_still_being_set_up() {
        use axum::routing::get;
        let lookups = Arc::new(Mutex::new(0));
        let seen = Arc::clone(&lookups);
        let broker = serve(Router::new().route(
            BROKER_RELEASE_ROUTE,
            get(move |Path((_, session)): Path<(String, String)>| {
                let seen = Arc::clone(&seen);
                async move {
                    let mut lookups = seen.lock().unwrap();
                    *lookups += 1;
                    Json(session_body(&session, *lookups <= 2, None))
                }
            }),
        ))
        .await;
        let token = tempfile::NamedTempFile::new().unwrap();
        let sandbox = sandbox_over(broker, &token);
        sandbox.get("s1").await.unwrap().expect("found after setup");
        assert_eq!(*lookups.lock().unwrap(), 3);
    }

    /// A new SDK with an Operator that predates lookups by id: the lookup answers 405, and the
    /// create goes on as it always did. A caller that set a tenant key is refused, because that
    /// Operator cannot check it.
    #[tokio::test]
    async fn get_or_create_falls_back_to_create_on_an_operator_without_lookups() {
        use axum::routing::post;
        let posts = Arc::new(Mutex::new(Vec::new()));
        let seen = Arc::clone(&posts);
        let broker = serve(
            Router::new()
                .route(
                    BROKER_RELEASE_ROUTE,
                    // The only method an old Operator routes here.
                    axum::routing::delete(|| async { StatusCode::NO_CONTENT }),
                )
                .route(
                    "/v1/sandbox/sessions",
                    post(move |Json(body): Json<serde_json::Value>| {
                        let seen = Arc::clone(&seen);
                        async move {
                            seen.lock().unwrap().push(body.clone());
                            let mut reply =
                                session_body(body["sessionId"].as_str().unwrap(), false, None);
                            reply["created"] = true.into();
                            Json(reply)
                        }
                    }),
                ),
        )
        .await;
        let token = tempfile::NamedTempFile::new().unwrap();
        let sandbox = sandbox_over(broker, &token);

        let created = sandbox
            .get_or_create(CreateSandboxRequest {
                sandbox_id: Some("s1".to_string()),
                ..Default::default()
            })
            .await
            .expect("falls back to the old create");
        assert!(created.created);
        assert_eq!(posts.lock().unwrap().len(), 1);

        let refused = sandbox
            .get_or_create(CreateSandboxRequest {
                sandbox_id: Some("s2".to_string()),
                tenant_key: Some("tenant".to_string()),
                ..Default::default()
            })
            .await
            .expect_err("a tenant key cannot be honoured");
        assert!(refused.to_string().contains("tenantKey"), "{refused}");
        assert_eq!(posts.lock().unwrap().len(), 1, "nothing was created for it");
    }

    /// `get_or_create` from a new process per command: the known id is found (`created` false,
    /// generation from the pod), a new id is created, and a create that lost a race to another
    /// process is reported as found.
    #[tokio::test]
    async fn get_or_create_reports_whether_this_call_created_the_session() {
        use axum::routing::{get, post};
        let expires = chrono::Utc::now().timestamp() + 900;
        let broker = serve(
            Router::new()
                .route(
                    BROKER_RELEASE_ROUTE,
                    get(
                        move |Path((_, session)): Path<(String, String)>| async move {
                            if session == "known" {
                                Ok(Json(serde_json::json!({
                                    "agentSessionId": "uid-1", "sessionId": "known",
                                    "endpoint": "http://10.0.0.1:8080", "capability": "c",
                                    "expiresAt": expires, "generation": 3, "created": false,
                                })))
                            } else {
                                Err(StatusCode::NOT_FOUND)
                            }
                        },
                    ),
                )
                .route(
                    "/v1/sandbox/sessions",
                    post(move |Json(body): Json<serde_json::Value>| async move {
                        let id = body["sessionId"].as_str().unwrap().to_string();
                        // "raced" was created by another process while this one was looking.
                        let created = id != "raced";
                        Json(serde_json::json!({
                            "agentSessionId": "uid-2", "sessionId": id,
                            "endpoint": "http://10.0.0.2:8080", "capability": "c",
                            "expiresAt": expires, "generation": 1, "created": created,
                        }))
                    }),
                ),
        )
        .await;
        let token = tempfile::NamedTempFile::new().expect("a token file");
        std::fs::write(token.path(), "service-account-token").unwrap();
        let sandbox = sandbox_over(broker, &token);
        let request = |id: &str| CreateSandboxRequest {
            sandbox_id: Some(id.to_string()),
            ..Default::default()
        };

        let known = sandbox
            .get_or_create(request("known"))
            .await
            .expect("found");
        assert!(!known.created);
        assert_eq!(
            known.sandbox.generation, 3,
            "the pod's generation, not a constant"
        );

        let fresh = sandbox
            .get_or_create(request("fresh"))
            .await
            .expect("created");
        assert!(fresh.created);

        let raced = sandbox
            .get_or_create(request("raced"))
            .await
            .expect("found");
        assert!(!raced.created, "losing the create race is a find");
    }

    /// An id names one session. A request carrying another tenant key (or none for a keyed
    /// session, or one for an unkeyed session) is refused on every path that returns an existing
    /// session: the lookup, and the answer to a create that lost a race.
    #[tokio::test]
    async fn get_or_create_refuses_an_existing_session_with_another_tenant_key() {
        use axum::routing::{get, post};
        let expires = chrono::Utc::now().timestamp() + 900;
        let session = move |id: &str, key: Option<&str>, created: bool| {
            let mut body = serde_json::json!({
                "agentSessionId": "uid-1", "sessionId": id,
                "endpoint": "http://10.0.0.1:8080", "capability": "c",
                "expiresAt": expires, "generation": 1, "created": created,
            });
            if let Some(key) = key {
                body["tenantKey"] = serde_json::json!(key);
            }
            body
        };
        let broker = serve(
            Router::new()
                .route(
                    BROKER_RELEASE_ROUTE,
                    get(move |Path((_, id)): Path<(String, String)>| async move {
                        match id.as_str() {
                            "keyed" => Ok(Json(session("keyed", Some("a"), false))),
                            "open" => Ok(Json(session("open", None, false))),
                            _ => Err(StatusCode::NOT_FOUND),
                        }
                    }),
                )
                .route(
                    "/v1/sandbox/sessions",
                    // "raced" was created for tenant "a" by another process during this call.
                    post(move |Json(body): Json<serde_json::Value>| async move {
                        let id = body["sessionId"].as_str().unwrap().to_string();
                        Json(session(&id, Some("a"), false))
                    }),
                ),
        )
        .await;
        let token = tempfile::NamedTempFile::new().expect("a token file");
        std::fs::write(token.path(), "service-account-token").unwrap();
        let sandbox = sandbox_over(broker, &token);
        let request = |id: &str, tenant: Option<&str>| CreateSandboxRequest {
            sandbox_id: Some(id.to_string()),
            tenant_key: tenant.map(str::to_string),
            ..Default::default()
        };

        for (id, tenant) in [
            ("keyed", Some("b")),
            ("keyed", None),
            ("open", Some("b")),
            ("raced", Some("b")),
            ("raced", None),
        ] {
            let error = sandbox
                .get_or_create(request(id, tenant))
                .await
                .expect_err(&format!("{id} with {tenant:?} must be refused"));
            assert!(
                error.to_string().contains("different tenant key"),
                "{error}"
            );
        }
        assert!(sandbox
            .get_or_create(request("keyed", Some("a")))
            .await
            .is_ok());
        assert!(sandbox.get_or_create(request("open", None)).await.is_ok());
        assert!(sandbox
            .get_or_create(request("raced", Some("a")))
            .await
            .is_ok());
    }

    /// A command's input is many short requests over hours, so the agent handle replaces its
    /// capability before it expires instead of letting a request reach the pod with a dead one.
    #[tokio::test]
    async fn an_interactive_command_refreshes_its_capability_before_it_expires() {
        use super::super::interactive::BoundAgent;
        let broker = serve(Router::new().route(
            BROKER_RELEASE_ROUTE,
            axum::routing::get(|| async {
                Json(serde_json::json!({
                    "agentSessionId": "uid-1",
                    "sessionId": "s1",
                    "endpoint": "http://10.0.0.9:8080",
                    "capability": "second",
                    "expiresAt": chrono::Utc::now().timestamp() + 900,
                }))
            }),
        ))
        .await;
        let token = tempfile::NamedTempFile::new().expect("a token file");
        std::fs::write(token.path(), "service-account-token").unwrap();
        let first = ClaimResponse {
            agent_session_id: None,
            session_id: "s1".to_string(),
            endpoint: "http://10.0.0.1:8080".to_string(),
            capability: "first".to_string(),
            expires_at: chrono::Utc::now().timestamp() + 20,
            generation: 1,
            created: false,
            tenant_key: None,
            deadline: None,
            setup_pending: false,
        };
        let agent = SessionAgent {
            client: reqwest::Client::new(),
            session_url: format!("{broker}/v1/sandbox/sbx-pool/sessions/s1"),
            token_path: token.path().display().to_string(),
            binding_name: "sbx".to_string(),
            sandbox_id: "s1".to_string(),
            claim: tokio::sync::Mutex::new(first),
        };

        let request = agent
            .request(reqwest::Method::POST, "/v1/interactive/input")
            .await
            .expect("a request is built")
            .build()
            .unwrap();
        assert_eq!(
            request.url().as_str(),
            "http://10.0.0.9:8080/v1/interactive/input"
        );
        assert_eq!(
            request.headers()["authorization"].to_str().unwrap(),
            "Bearer second"
        );
    }
}