devsandbox 0.9.0

Manage devcontainer-style sandboxes on docker, podman, or Apple container — many throwaway instances per repo from one TOML config.
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
//! The trust table (docs/architecture/daemon/fleet.md, *The trust table*):
//! what a remote caller (a [`Peer`]: the other end of a peer link, over its
//! streams this daemon answers in-process or the connections its
//! `link.attach` turned) may do on this member.
//! Each such connection is served with a [`Peer`] (the daemon's
//! `Table::Peer`); every request on it goes through
//! [`admit`] first and its answer through [`filter_answer`], every
//! `instances.snapshot` pushed to it through [`filter_snapshot`], each
//! against the [`Reach`] read from this host's files for that request
//! ([`Reach::load`]: `member.toml`'s `trust` and `roots`, `state.toml`).
//!
//! Under `trust = "worker"` (the default) a peer reaches this member's own
//! roots ([`own_roots`] plus `member.toml`'s `roots`: each exactly, not
//! what's nested in one) and its fleet root (all under it):
//!
//! - [`decide`] (pure, over the method and params): hello, `subscribe` /
//!   `unsubscribe` to `instances` only, `instances.watch` / `unwatch`, the
//!   quick calls (`machines::forward::QUICK`), `capacity.get`, `code.haves`, `roots.list`
//!   and the verbs but `gc` (host maintenance); never a `machine` param or a federated (`machines:
//!   true`) request but `instances.watch` (a member watching its hub);
//!   everything else (`machines.*`,
//!   `shutdown`, `helper.call`, `forwards.*`, the
//!   Inbox, …) is `denied`.
//! - [`admit`] then confines the params: every `root` / `dir` canonicalized
//!   and admitted by the [`Reach`] (rewritten to its canonical form), every
//!   instance or container named one whose `config_dir` the reach admits (a
//!   service container: one of those roots'), a verb's `all` only while
//!   every instance in `state.toml` is reached, `config.migrate` /
//!   `config.ack` (edits of a config) only under the fleet root, and a
//!   verb's `env` replaced by the peer's when it has one.
//!
//! Under `trust = "full"` none of that: the peer has the API a local client
//! has, except `member.*`, `membership.*`, `graph.*`, `link.*` and `links.*` (this member's own
//! settings, membership log and link graph, and its links), refused under both; a verb's `env` is still the peer's when it
//! has one.
//!
//! `fleet.*` (a removal from the fleet, `machines::leave`; a membership
//! change proposed to the authority or pushed from it, `machines::changes`;
//! a member's run placed by the hub, `fleet.place`; link reports,
//! `fleet.report` / `fleet.graph`) goes by who the peer proved it is
//! (its key, [`Peer::key`], against this host's membership log), not by
//! trust: [`admit_fleet`], before any of the above.

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Component, Path, PathBuf};

use serde_json::Value;

use crate::serve::api::ApiError;
use crate::serve::fleet::identity::PublicKey;
use crate::serve::fleet::member::{self, Member};
use crate::serve::fleet::membership::Stored;
use crate::serve::machines::forward as fwd;
use crate::serve::verbs;
use crate::state::State;
use crate::worker_policy::Trust;

/// A remote caller of this member: one per machine link stream this
/// daemon answers in-process, one per attached connection
/// (`link.attach {channel}`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Peer {
    /// Who it is (a link peer's machine name), for the log.
    pub name: String,
    /// This member's fleet root for it, canonical ([`peer_fleet_root`]).
    /// `None` only in tests.
    pub fleet_root: Option<PathBuf>,
    /// `Some`: the env its verbs run with, whatever it sent (a link peer's:
    /// this host's own, the daemon's). `None`: a verb's env as sent.
    pub env: Option<BTreeMap<String, String>>,
    /// The linking host's agent relayed here (a peer link's
    /// `agent-link-<peer>.sock`, `endpoint::link_agent_socket`): with `env`,
    /// a verb's `SSH_AUTH_SOCK` while it answers, so host git there (a
    /// worktree's clone) uses the agent the linking host serves. `None`:
    /// `env` as it is.
    pub agent: Option<PathBuf>,
    /// The member key the link proved for it (`fleet::proof`); `None` only
    /// in tests: [`admit_fleet`] admits nothing from a peer without one.
    pub key: Option<PublicKey>,
    /// Who introduced it, while this host's log doesn't list it (capped,
    /// fleet plan decisions 46 and 51).
    pub introduced_by: Option<String>,
}

/// The longest `link.attach` `peer` taken: a hostname fits well within it.
pub const PEER_NAME_MAX: usize = 255;

/// `link.attach`'s `peer` (pure): a non-empty string of at most
/// [`PEER_NAME_MAX`] bytes without control characters ([`attach_params`]
/// then holds it to `machines::check_name`).
pub fn attach_peer(params: &Value) -> Result<String, ApiError> {
    let Some(name) = params.get("peer").and_then(Value::as_str) else {
        return Err(ApiError::invalid("`link.attach` needs `peer`, the link peer's machine name"));
    };
    if name.is_empty() || name.len() > PEER_NAME_MAX || name.chars().any(char::is_control) {
        return Err(ApiError::invalid(format!(
            "`peer` must be 1 to {PEER_NAME_MAX} bytes without control characters"
        )));
    }
    Ok(name.to_string())
}

/// What a `link.attach {channel}` stream carries: one link channel's
/// streams handed to the daemon (docs/reference/api.md, `link.attach`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Channel {
    /// API requests, served with the trust table.
    Api,
    /// A session attach or an exec (`fleet::pty::serve`).
    Pty,
    /// A forward's bridge (`fleet::tunnel::serve`).
    Tunnel,
    /// One bulk transfer into the peer's fleet root (`fleet::code::receivers`).
    Transfer,
    /// This host's ssh agent, while its `member.toml` grants it to the
    /// peer's proven key (`daemon::agent_for`).
    Agent,
    /// A routed stream to relay or answer (`fleet::route`).
    Route,
}

impl Channel {
    pub fn parse(s: &str) -> Option<Channel> {
        Some(match s {
            "api" => Channel::Api,
            "pty" => Channel::Pty,
            "tunnel" => Channel::Tunnel,
            "transfer" => Channel::Transfer,
            "agent" => Channel::Agent,
            "route" => Channel::Route,
            _ => return None,
        })
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Channel::Api => "api",
            Channel::Pty => "pty",
            Channel::Tunnel => "tunnel",
            Channel::Transfer => "transfer",
            Channel::Agent => "agent",
            Channel::Route => "route",
        }
    }
}

/// `link.attach`'s params, parsed ([`attach_params`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Attach {
    pub name: String,
    pub channel: Channel,
    /// The key the link proved for the peer.
    pub key: PublicKey,
    /// Its introducer, when it's held as an introduction.
    pub introduced_by: Option<String>,
}

/// `link.attach`'s params (pure): [`attach_peer`]'s `peer`, the required
/// `channel` and `key` (the peer's proven member key: no link stream
/// without one), and `introduced_by` (none, or a name). The peer's name
/// also names its fleet root ([`peer_fleet_root`]): it must pass
/// `machines::check_name`.
pub fn attach_params(params: &Value) -> Result<Attach, ApiError> {
    let name = attach_peer(params)?;
    let channel = match params.get("channel") {
        None | Some(Value::Null) => return Err(ApiError::invalid("`link.attach` needs `channel`")),
        Some(Value::String(s)) => Channel::parse(s)
            .ok_or_else(|| ApiError::invalid(format!("no channel `{s}` (api, pty, tunnel, transfer, agent or route)")))?,
        Some(_) => return Err(ApiError::invalid("`channel` must be a string")),
    };
    crate::serve::machines::check_name(&name).map_err(|e| ApiError::invalid(format!("`peer`: {e:#}")))?;
    let key = match params.get("key") {
        None | Some(Value::Null) => {
            return Err(ApiError::invalid("`link.attach` needs `key`, the member key the link proved for the peer"));
        }
        Some(Value::String(s)) => s.parse::<PublicKey>().map_err(|e| ApiError::invalid(format!("`key`: {e:#}")))?,
        Some(_) => return Err(ApiError::invalid("`key` must be a string")),
    };
    let introduced_by = match params.get("introduced_by") {
        None | Some(Value::Null) => None,
        Some(Value::String(s)) => {
            member::check_member_name(s).map_err(|e| ApiError::invalid(format!("`introduced_by`: {e:#}")))?;
            Some(s.clone())
        }
        Some(_) => return Err(ApiError::invalid("`introduced_by` must be a string")),
    };
    Ok(Attach { name, channel, key, introduced_by })
}

/// A fleet member `peer`'s fleet root under data dir `data`:
/// `<data>/fleet/<peer>/` (decision 24 of the fleet plan), created,
/// canonical. `peer` must be a machine name (one plain path component).
pub fn peer_fleet_root(data: &Path, peer: &str) -> anyhow::Result<PathBuf> {
    use anyhow::Context;
    crate::serve::machines::check_name(peer)?;
    let root = data.join("fleet").join(peer);
    std::fs::create_dir_all(&root).with_context(|| format!("cannot create {}", root.display()))?;
    std::fs::canonicalize(&root).with_context(|| format!("cannot resolve {}", root.display()))
}

/// Where a [`Reach`] is read from: this host's files.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Files {
    pub state: PathBuf,
    /// `member.toml`; `None` without a data dir (then: `worker`, no picked
    /// roots).
    pub member: Option<PathBuf>,
    /// The home `~/.devsandboxes` is found in ([`own_roots`]).
    pub home: Option<PathBuf>,
}

/// What a [`Peer`] reaches here, for one request (see the module doc).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Reach {
    pub trust: Trust,
    /// Canonical; everything under it is reached.
    pub fleet_root: Option<PathBuf>,
    /// This member's own roots (canonical where they exist): each is
    /// reached exactly, not what's nested in it.
    pub own: BTreeSet<PathBuf>,
}

/// This host's own config roots: every distinct `config_dir` in `state`,
/// plus `~/.devsandboxes` when `home` has one, canonicalized (a root that's
/// gone stays as recorded). What `roots.list` answers, and the base of a
/// [`Reach`]'s `own`.
pub fn own_roots(state: &State, home: Option<&Path>) -> BTreeSet<PathBuf> {
    let recorded = state.instances.values().filter_map(|i| i.config_dir.clone());
    let home = home.map(|h| h.join(".devsandboxes")).filter(|d| d.is_dir());
    recorded.chain(home).map(|r| std::fs::canonicalize(&r).unwrap_or(r)).collect()
}

impl Reach {
    /// Over what's read (pure but for canonicalizing): `member`'s `trust`
    /// (none: `worker`), [`own_roots`] of `state` plus `member`'s `roots`.
    pub fn of(member: Option<&Member>, state: &State, home: Option<&Path>, fleet_root: Option<&Path>) -> Reach {
        let mut own = own_roots(state, home);
        if let Some(m) = member {
            own.extend(m.roots.iter().map(|r| std::fs::canonicalize(r).unwrap_or_else(|_| r.clone())));
        }
        let trust = member.map(|m| m.trust).unwrap_or_default();
        Reach { trust, fleet_root: fleet_root.map(Path::to_path_buf), own }
    }

    /// [`Reach::of`] this host's `files`. Fails closed: a `member.toml` that
    /// doesn't load is `worker` with no picked roots, a `state.toml` that
    /// doesn't load is no instances' roots; either comes back as the error
    /// to log.
    pub fn load(files: &Files, fleet_root: Option<&Path>) -> (Reach, Option<String>) {
        let mut warning = None;
        let member = match files.member.as_deref().map(member::load) {
            None | Some(Ok(None)) => None,
            Some(Ok(Some(m))) => Some(m),
            Some(Err(e)) => {
                warning = Some(format!("{e:#}; taken as `trust = \"worker\"`, no `roots`"));
                None
            }
        };
        let state = State::load_at(&files.state).unwrap_or_else(|e| {
            warning = Some(format!("{e:#}; taken as no instances"));
            State::default()
        });
        (Reach::of(member.as_ref(), &state, files.home.as_deref(), fleet_root), warning)
    }

    /// Whether the peer reaches canonical path `real`: anything under
    /// `full`; else under the fleet root, or exactly an own root.
    pub fn admits(&self, real: &Path) -> bool {
        self.trust == Trust::Full || self.in_fleet_root(real) || self.own.contains(real)
    }

    /// Whether canonical path `real` is under the fleet root.
    pub fn in_fleet_root(&self, real: &Path) -> bool {
        self.fleet_root.as_deref().is_some_and(|r| real.starts_with(r))
    }

    /// Whether recorded config root `dir` is admitted: canonicalized when it
    /// still exists, else as recorded; never with a `..`.
    pub fn admits_recorded(&self, dir: &Path) -> bool {
        if dir.components().any(|c| c == Component::ParentDir) {
            return false;
        }
        self.admits(&std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf()))
    }
}

/// What kind of request [`decide`] let through.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Gate {
    Hello,
    Subscribe,
    Watch,
    Unwatch,
    Quick,
    /// `capacity.get`: this host's report, for the hub's placement.
    Capacity,
    /// `code.haves`: what the caller's own fleet root here has (the daemon
    /// answers it about that root only).
    Code,
    /// `instances.fetch`: an instance under the caller's fleet root (never
    /// one of this member's own roots), bundled for it (fetch-back).
    Fetch,
    /// `roots.list`, with or without `paths`: read-only (`machines.add`
    /// checks typed roots through it).
    Roots,
    Verb,
}

/// Whether a `worker` member's peer may send `method` with `params` at all
/// (pure).
pub fn decide(method: &str, params: &Value) -> Result<Gate, ApiError> {
    if fwd::machine_of(params)?.is_some() {
        return Err(ApiError::denied("a remote caller can't reach past this member (`machine`)"));
    }
    // But a federated watch: a member watching its hub, which only a hub
    // serves (the daemon's `watch_root`).
    if fwd::federated(params) && method != "instances.watch" {
        return Err(ApiError::denied("a remote caller can't reach past this member (`machines`)"));
    }
    let gate = match method {
        "hello" => Gate::Hello,
        "subscribe" | "unsubscribe" => {
            let topics = params.get("topics").and_then(Value::as_array);
            if topics.is_some_and(|t| t.iter().any(|t| t.as_str() != Some("instances"))) {
                return Err(ApiError::denied("a remote caller subscribes to `instances` only"));
            }
            Gate::Subscribe
        }
        "instances.watch" => Gate::Watch,
        "instances.unwatch" => Gate::Unwatch,
        m if fwd::is_quick(m) => Gate::Quick,
        "capacity.get" => Gate::Capacity,
        "code.haves" => Gate::Code,
        "instances.fetch" => Gate::Fetch,
        "roots.list" => Gate::Roots,
        "gc" => return Err(ApiError::denied(format!(
            "`gc` is host maintenance: not open to remote callers under this member's `worker` trust ({FULL_HINT})"
        ))),
        m if verbs::is_verb(m) => Gate::Verb,
        m => return Err(ApiError::denied(format!("`{m}` isn't open to remote callers under this member's `worker` trust ({FULL_HINT})"))),
    };
    Ok(gate)
}

/// How a `worker` refusal says what opens it.
const FULL_HINT: &str = "`devsandbox machine trust full` there opens it";

/// The params naming an instance (an exact name or id, as the quick calls
/// take it), per method.
fn instance_keys(method: &str) -> &'static [&'static str] {
    match method {
        "instances.cancel" | "instances.signal" | "instances.rename" | "instances.done" | "instances.buildLog"
        | "sessions.list" | "sessions.rm" => &["instance"],
        "rebuild" | "start" | "stop" | "rm" => &["instance"],
        _ => &[],
    }
}

/// The verbs that act on an existing instance, which a hub must name.
fn needs_instance(method: &str) -> bool {
    matches!(method, "rebuild" | "start" | "stop" | "rm")
}

/// `path` checked against `reach`: absolute, no `..`, and canonicalized
/// (symlinks resolved) to one the reach admits ([`Reach::admits`]). A path
/// that doesn't exist is `not-found`, unless `!exists` (an unwatch of a
/// removed root), where it is checked as written.
pub fn confine_path(reach: &Reach, path: &Path, exists: bool) -> Result<PathBuf, ApiError> {
    if !path.is_absolute() {
        return Err(ApiError::invalid(format!("`{}` must be absolute", path.display())));
    }
    if path.components().any(|c| c == Component::ParentDir) {
        return Err(ApiError::denied(format!("`{}` has a `..`", path.display())));
    }
    let real = match std::fs::canonicalize(path) {
        Ok(real) => real,
        Err(_) if !exists => path.to_path_buf(),
        Err(_) => return Err(ApiError::not_found(format!("no directory {}", path.display()))),
    };
    if !reach.admits(&real) {
        return Err(ApiError::denied(format!(
            "`{}` isn't one of this member's roots (`devsandbox machine roots add <path>` there adds one)",
            path.display()
        )));
    }
    Ok(real)
}

/// Whether recorded config root `dir` is under `root`: canonicalized when it
/// still exists, else as recorded; never with a `..`.
pub(crate) fn root_under(dir: &Path, root: &Path) -> bool {
    if dir.components().any(|c| c == Component::ParentDir) {
        return false;
    }
    std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf()).starts_with(root)
}

/// The instances of `state` the peer may name: names and ids of those whose
/// `config_dir` `reach` admits ([`Reach::admits_recorded`]).
pub fn lent_instances(state: &State, reach: &Reach) -> Lent {
    let mut lent = Lent::default();
    for (name, i) in &state.instances {
        if i.config_dir.as_deref().is_some_and(|d| reach.admits_recorded(d)) {
            lent.names.insert(name.clone());
            lent.ids.insert(i.instance_id.clone());
            lent.containers.insert(i.container.clone());
            if let Some(dir) = &i.config_dir {
                lent.roots.insert(dir.clone());
            }
        }
    }
    lent
}

/// [`lent_instances`]' answer.
#[derive(Debug, Default)]
pub struct Lent {
    pub names: BTreeSet<String>,
    pub ids: BTreeSet<String>,
    pub containers: BTreeSet<String>,
    /// Their config roots, as recorded.
    pub roots: BTreeSet<PathBuf>,
}

impl Lent {
    /// The `project_id`s of [`Lent::roots`] (`commands::services`): what
    /// their service containers are labelled and named by. A root that no
    /// longer resolves has none.
    fn projects(&self) -> BTreeSet<String> {
        self.roots.iter().filter_map(|d| crate::commands::services::project_id(d).ok()).collect()
    }
}

/// This host's membership, as [`admit_fleet`] reads it: its stored log and
/// held introductions, its own member name and its own key (`None`: no
/// `member.key` yet).
#[derive(Debug, Clone, Copy)]
pub struct Log<'a> {
    pub stored: &'a Stored,
    pub own: &'a str,
    pub key: Option<PublicKey>,
}

/// The `fleet.*` methods [`admit_fleet`] knows.
pub const FLEET_METHODS: &[&str] =
    &["fleet.leave", "fleet.forget", "fleet.rm", "fleet.place", "fleet.propose", "fleet.sync", "fleet.report", "fleet.graph"];

/// Whether `fleet.*` `method` with `params` is admitted (pure), under either
/// trust, by the key `from` proved (`None`: a local client, which uses
/// `machines.*`) against `log` (`None`: this host is in no fleet's log).
/// Fleet plan decisions 31, 32 and 49, step 10a.6:
///
/// - `fleet.leave` / `fleet.forget` come only from the log's hub (its name
///   and its key in the log, never the name alone), and follow a revoke:
///   `leave` only once the log revokes this host's own key, `forget
///   {name}` only once it revokes `name`.
/// - `fleet.rm` and `fleet.place` run only on the hub (the log's hub is this
///   host): `fleet.rm {name}` from a member of the log (name and key), of
///   itself (leaving) or of a member the log has revoked; `fleet.place` from
///   a member or a held introduction's (a capped member runs work as the
///   others do, but changes no one's membership, decision 51).
/// - `fleet.propose` runs only on the authority (this host's key is the
///   log's authority's), from a member of the log; never from a capped one.
/// - `fleet.sync` and `fleet.graph` from a member of the log or an
///   introduced (capped) one: what they carry verifies itself.
/// - `fleet.report` runs only on the hub, from a member of the log or a
///   held introduction's (name and key): a capped member's links route too.
pub fn admit_fleet(method: &str, params: &Value, from: Option<&Peer>, log: Option<Log>) -> Result<(), ApiError> {
    let Some(peer) = from else {
        return Err(ApiError::denied(format!(
            "`{method}` comes over a fleet link: here `devsandbox machine rm|unlink|approve` (`machines.*`, `membership.*`)"
        )));
    };
    if !FLEET_METHODS.contains(&method) {
        return Err(ApiError::unknown_method(method));
    }
    let from = peer.name.as_str();
    let Some(key) = peer.key else {
        return Err(ApiError::denied(format!("`{method}` from `{from}`, which proved no member key")));
    };
    let Some((log, m)) = log.and_then(|l| Some((l, l.stored.log.membership()?))) else {
        return Err(ApiError::denied(format!("`{method}`: this host is in no fleet's membership log")));
    };
    let member = m.key_of(from) == Some(key);
    let introduced = peer.introduced_by.is_some() || log.stored.introductions.iter().any(|i| i.name == from && i.key == key);
    let name = || -> Result<&str, ApiError> {
        params.get("name").and_then(Value::as_str).ok_or_else(|| ApiError::invalid(format!("`{method}` needs `name`")))
    };
    match method {
        "fleet.leave" | "fleet.forget" => {
            if m.hub != from || m.hub_key() != Some(key) {
                return Err(ApiError::denied(format!(
                    "`{method}` is taken from this host's hub only (by its key in the log), and `{from}` isn't it"
                )));
            }
            if method == "fleet.leave" {
                if !log.key.is_some_and(|k| m.revoked.contains(&k)) {
                    return Err(ApiError::denied(format!(
                        "`fleet.leave` follows a revoke of this host's key, and this host's membership log has none \
                         (the authority `{}` signs it)",
                        m.authority.0
                    )));
                }
            } else {
                let name = name()?;
                if !log.stored.log.revoked_name(name) {
                    return Err(ApiError::denied(format!(
                        "`fleet.forget` of `{name}` follows a revoke of its key, and this host's membership log has none \
                         (the authority `{}` signs it)",
                        m.authority.0
                    )));
                }
            }
            Ok(())
        }
        "fleet.propose" => {
            if m.authority.0 != log.own || log.key != Some(m.authority.1) {
                return Err(ApiError::denied(format!(
                    "`fleet.propose` goes to the fleet's authority `{}`, and this host isn't it",
                    m.authority.0
                )));
            }
            if member {
                Ok(())
            } else if introduced {
                Err(ApiError::denied(format!("`fleet.propose` from `{from}`: an introduced member (capped) proposes no membership change")))
            } else {
                Err(ApiError::denied(format!("`fleet.propose` is taken from the fleet's members (by their keys in the log), and `{from}` isn't one")))
            }
        }
        "fleet.sync" | "fleet.graph" if member || introduced => Ok(()),
        "fleet.sync" | "fleet.graph" => {
            Err(ApiError::denied(format!("`{method}` from `{from}`, which is neither a member nor introduced")))
        }
        _ if m.hub != log.own => Err(ApiError::denied(format!("`{method}` runs on the hub, and this host isn't it"))),
        "fleet.rm" if member => {
            let name = name()?;
            if name == from || log.stored.log.revoked_name(name) {
                Ok(())
            } else {
                Err(ApiError::denied(format!(
                    "`fleet.rm` of `{name}`: its key isn't revoked in the hub's membership log \
                     (the authority `{}` signs that: `devsandbox machine rm {name}` there)",
                    m.authority.0
                )))
            }
        }
        "fleet.place" | "fleet.report" if member => Ok(()),
        "fleet.place" | "fleet.report" if log.stored.introductions.iter().any(|i| i.name == from && i.key == key) => Ok(()),
        "fleet.rm" if introduced || log.stored.introductions.iter().any(|i| i.name == from) => Err(ApiError::denied(format!(
            "`{method}` from `{from}`: an introduced member (capped) changes no one's membership"
        ))),
        _ => Err(ApiError::denied(format!("`{method}` is taken from the fleet's members (by their keys in the log), and `{from}` isn't one"))),
    }
}

/// Gate, then confine, a peer's request (see the module doc): the params
/// to run it with. `state` is this host's `state.toml`, read only when the
/// request names an instance or a container under `worker`.
pub fn admit(method: &str, mut params: Value, peer: &Peer, reach: &Reach, state: &Path) -> Result<Value, ApiError> {
    if ["member.", "membership.", "graph.", "link.", "links.", "placements."].iter().any(|p| method.starts_with(p)) {
        return Err(ApiError::denied(format!("`{method}` is this member's own: local clients only")));
    }
    // [`admit_fleet`]'s, which knows this host's hub: never through here.
    if method.starts_with("fleet.") {
        return Err(ApiError::denied(format!("`{method}` goes by this host's hub, not its trust table")));
    }
    if reach.trust == Trust::Full {
        if verbs::is_verb(method)
            && let Some(obj) = params.as_object_mut()
        {
            peer_env(obj, peer)?;
        }
        return Ok(params);
    }
    let gate = decide(method, &params)?;
    let Some(obj) = params.as_object_mut() else {
        return Ok(params);
    };
    for key in ["root", "dir"] {
        let Some(v) = obj.get(key) else { continue };
        let Some(path) = v.as_str() else {
            return Err(ApiError::invalid(format!("`{key}` must be a path")));
        };
        let real = confine_path(reach, Path::new(path), gate != Gate::Unwatch)?;
        if matches!(method, "config.migrate" | "config.ack") && !reach.in_fleet_root(&real) {
            return Err(ApiError::denied(format!(
                "`{method}` edits this member's own config at {}: that needs `devsandbox machine trust full` on it",
                real.display()
            )));
        }
        obj.insert(key.into(), Value::String(real.to_string_lossy().into_owned()));
    }
    // The methods whose path is how they find what they act on: without
    // one they'd fall back to something outside the scope, or fail anyway.
    let path_key = match gate {
        Gate::Watch | Gate::Unwatch => Some("dir"),
        Gate::Verb => Some("root"),
        Gate::Quick if method == "instances.list" => Some("dir"),
        Gate::Quick
            if method.starts_with("sandboxes.")
                || method.starts_with("config.")
                || method.starts_with("sessions.")
                || method == "services.get" =>
        {
            Some("root")
        }
        _ => None,
    };
    if let Some(key) = path_key
        && !obj.contains_key(key)
    {
        return Err(ApiError::invalid(format!("`{method}` needs `{key}`")));
    }

    if gate == Gate::Fetch {
        fetch_in_fleet_root(obj, reach, state)?;
    }
    let keys = instance_keys(method);
    let named_container = matches!(method, "containers.logs" | "containers.inspect");
    // `--all` is every instance in `state.toml`, not the root's.
    let all = gate == Gate::Verb && obj.get("all").and_then(Value::as_bool) == Some(true);
    if !keys.is_empty() || method == "instances.procs" || named_container || all {
        let state = State::load_at(state).map_err(ApiError::internal)?;
        let lent = lent_instances(&state, reach);
        let unknown = |what: &str| ApiError::not_found(format!("no instance `{what}`"));
        for key in keys {
            let Some(name) = obj.get(*key).and_then(Value::as_str) else {
                if needs_instance(method) && !all {
                    return Err(ApiError::invalid(format!("`{method}` from a remote caller needs `{key}`")));
                }
                // Not a string: the method's own parse refuses it.
                continue;
            };
            if gate == Gate::Verb {
                // Resolved as the CLI resolves it (`commands::resolve_instance`):
                // every candidate must be lent.
                let matches = crate::commands::instance_matches(&state, name);
                if matches.iter().any(|m| !lent.names.contains(m)) {
                    return Err(unknown(name));
                }
            } else if !lent.names.contains(name) && !lent.ids.contains(name) {
                return Err(unknown(name));
            }
        }
        if method == "instances.procs"
            && let Some(names) = obj.get("instances").and_then(Value::as_array)
            && let Some(bad) = names.iter().filter_map(Value::as_str).find(|n| !lent.names.contains(*n))
        {
            return Err(unknown(bad));
        }
        if named_container
            && let Some(c) = obj.get("container").and_then(Value::as_str)
            && !lent.containers.contains(c)
            && !lent.projects().iter().any(|p| c.starts_with(&crate::commands::services::service_container(p, "")))
        {
            return Err(ApiError::not_found(format!("no container `{c}` in this member's reach")));
        }
        if all && state.instances.len() != lent.names.len() {
            return Err(ApiError::denied(format!(
                "`{method}` with `all` reaches instances outside this member's roots ({FULL_HINT})"
            )));
        }
    }
    if gate == Gate::Verb {
        peer_env(obj, peer)?;
    }
    Ok(params)
}

/// `instances.fetch`'s `instance` under `worker`: an instance in `state`
/// whose config root and `folder` are both under the caller's fleet root
/// (fleet plan decision 76: an own root's code never moves off this member
/// for another machine); else `not-found`, as a quick call's unlent one.
fn fetch_in_fleet_root(obj: &serde_json::Map<String, Value>, reach: &Reach, state: &Path) -> Result<(), ApiError> {
    let Some(name) = obj.get("instance").and_then(Value::as_str) else {
        return Err(ApiError::invalid("`instances.fetch` needs `instance`"));
    };
    let state = State::load_at(state).map_err(ApiError::internal)?;
    let under = |p: &Path| !p.components().any(|c| c == Component::ParentDir) && reach.in_fleet_root(&std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()));
    match crate::serve::fleet::code::fetch::find_instance(&state, name) {
        Some((_, i)) if i.config_dir.as_deref().is_some_and(under) && under(&i.folder) => Ok(()),
        _ => Err(ApiError::not_found(format!("no instance `{name}` under this member's fleet root for the caller"))),
    }
}

/// A verb's `env` replaced by the peer's, when it has one, its
/// `SSH_AUTH_SOCK` the peer's relayed agent while that answers
/// ([`Peer::agent`]).
fn peer_env(obj: &mut serde_json::Map<String, Value>, peer: &Peer) -> Result<(), ApiError> {
    if let Some(env) = &peer.env {
        let mut env = env.clone();
        if let Some(agent) = peer.agent.as_deref().filter(|a| std::os::unix::net::UnixStream::connect(a).is_ok()) {
            env.insert("SSH_AUTH_SOCK".into(), agent.to_string_lossy().into_owned());
        }
        obj.insert("env".into(), serde_json::to_value(env).map_err(|e| ApiError::internal(e.into()))?);
    }
    Ok(())
}

/// A local answer to a peer's request, cut to `reach` (nothing cut under
/// `full`): an `instances.list` like a snapshot ([`filter_snapshot`]); an
/// `instances.resolve`'s matches to lent instances (none left is
/// `not-found`); `containers.list` / `containers.stats` rows to the lent
/// instances' containers and their config roots' services
/// ([`cut_containers`]; `state` is this host's `state.toml`, read for
/// those two only). Others pass as they are: their params were confined.
pub fn filter_answer(method: &str, mut answer: Value, reach: &Reach, state: &Path) -> Result<Value, ApiError> {
    if reach.trust == Trust::Full {
        return Ok(answer);
    }
    match method {
        "instances.list" => filter_snapshot(&mut answer, reach),
        "containers.list" | "containers.stats" => {
            let state = State::load_at(state).map_err(ApiError::internal)?;
            let lent = lent_instances(&state, reach);
            cut_containers(method, &mut answer, &lent.containers, &lent.projects());
        }
        "instances.resolve" => {
            let found: Vec<Value> = answer
                .get("found")
                .and_then(Value::as_array)
                .map(|f| f.iter().filter(|f| row_lent(f, reach)).cloned().collect())
                .unwrap_or_default();
            if found.is_empty() {
                return Err(ApiError::not_found("no instance matches"));
            }
            let names: Vec<Value> = found.iter().filter_map(|f| f.get("name").cloned()).collect();
            answer["found"] = Value::Array(found);
            answer["matches"] = Value::Array(names);
        }
        _ => {}
    }
    Ok(answer)
}

/// A `roots.list` answer (the listing, not a `paths` check) to a peer with
/// a fleet root, that root added last unless listed already (as
/// `{root, sandboxes: [], error: null, fleet: true}`: the placed configs
/// are under it), flagged `fleet` either way: what the peer reaches here
/// besides this member's own roots, so a peer link's other end lists it
/// among this member's roots (an inbound machine's roots) and knows where
/// its placement moves code to (`fleet::placed::fleet_root`).
pub fn with_fleet_root(mut answer: Value, reach: &Reach) -> Value {
    let (Some(root), Some(rows)) = (&reach.fleet_root, answer.as_array_mut()) else { return answer };
    match rows.iter_mut().find(|r| r.get("root").and_then(Value::as_str) == root.to_str()) {
        Some(row) => {
            if let Some(row) = row.as_object_mut() {
                row.insert("fleet".into(), Value::Bool(true));
            }
        }
        None => rows.push(serde_json::json!({ "root": root, "sandboxes": [], "error": null, "fleet": true })),
    }
    answer
}

/// A `containers.list` / `containers.stats` answer's `rows` cut, in place,
/// to `containers` (the lent instances') and the service containers of
/// `projects` (the lent instances' config roots' `project_id`s): a
/// listing row by its `devsandbox.project` label (none: dropped), a stats
/// row, which has no labels, by its name (`services::service_container`'s
/// `devsandbox-svc-<project>-` prefix, isolated ones' too).
pub fn cut_containers(method: &str, answer: &mut Value, containers: &BTreeSet<String>, projects: &BTreeSet<String>) {
    let Some(rows) = answer.get_mut("rows").and_then(Value::as_array_mut) else { return };
    let prefixes: Vec<String> = projects.iter().map(|p| crate::commands::services::service_container(p, "")).collect();
    rows.retain(|r| {
        let Some(name) = r.get("name").and_then(Value::as_str) else { return false };
        if containers.contains(name) {
            return true;
        }
        if method == "containers.stats" {
            return prefixes.iter().any(|p| name.starts_with(p.as_str()));
        }
        let project = r.get("labels").and_then(|l| l.get("devsandbox.project")).and_then(Value::as_str);
        project.is_some_and(|p| projects.contains(p))
    });
}

/// Whether a row (`InstanceRow`, a resolve's `found`) has a `root` `reach`
/// admits; a row without one isn't lent.
fn row_lent(row: &Value, reach: &Reach) -> bool {
    row.get("root").and_then(Value::as_str).is_some_and(|r| reach.admits_recorded(Path::new(r)))
}

/// An `instances.list` answer / `instances.snapshot` params cut to the
/// instances `reach` admits (by their rows' `root`), in place: other rows
/// gone, and their names from services' `used_by` and from
/// `thread_children`. The snapshot lists every instance in `state.toml`,
/// whatever `dir`, so this is what keeps what isn't reached out. Rows
/// tagged `machine` (a hub's federated push: other machines' rows, their
/// `root` a path there) aren't this host's and stay. Nothing is cut under
/// `full`.
pub fn filter_snapshot(snapshot: &mut Value, reach: &Reach) {
    if reach.trust == Trust::Full {
        return;
    }
    let remote = |r: &Value| r.get("machine").is_some_and(|m| !m.is_null());
    let mut kept = BTreeSet::new();
    let mut ids = BTreeSet::new();
    if let Some(rows) = snapshot.get_mut("instances").and_then(Value::as_array_mut) {
        rows.retain(|r| remote(r) || row_lent(r, reach));
        let own = rows.iter().filter(|r| !remote(r));
        for r in own {
            kept.extend(r.get("name").and_then(Value::as_str).map(String::from));
            ids.extend(r.get("instance_id").and_then(Value::as_str).map(String::from));
        }
    }
    let keep = |v: &Value| v.as_str().is_some_and(|n| kept.contains(n));
    // An isolated service's container is per instance
    // (`services::isolated_service_container`: `…svc-<project>-<instance id>-<name>`),
    // so another root's instance of a same-named sandbox would show by name.
    let lent_container = |c: &Value| {
        let name = c.get(0).and_then(Value::as_str).unwrap_or_default();
        ids.iter().any(|id| name.contains(&format!("-{id}-")))
    };
    if let Some(services) = snapshot.get_mut("services").and_then(Value::as_array_mut) {
        for s in services.iter_mut().filter(|s| !remote(s)) {
            if let Some(used) = s.get_mut("used_by").and_then(Value::as_array_mut) {
                used.retain(keep);
            }
            if s.get("scope").and_then(Value::as_str) == Some("isolated")
                && let Some(containers) = s.get_mut("containers").and_then(Value::as_array_mut)
            {
                containers.retain(lent_container);
            }
        }
    }
    if let Some(owners) = snapshot.get_mut("thread_children").and_then(Value::as_object_mut) {
        for children in owners.values_mut() {
            if let Some(c) = children.as_object_mut() {
                c.retain(|_, child| keep(child));
            }
        }
        owners.retain(|_, c| c.as_object().is_some_and(|c| !c.is_empty()));
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    fn scratch(tag: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("dsv-lent-{tag}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::canonicalize(&dir).unwrap()
    }

    /// A `worker` reach of fleet root `root` and own roots `own`.
    fn worker(root: &Path, own: &[&Path]) -> Reach {
        Reach { trust: Trust::Worker, fleet_root: Some(root.to_path_buf()), own: own.iter().map(|p| p.to_path_buf()).collect() }
    }

    /// The fleet root only.
    fn fleet(root: &Path) -> Reach {
        worker(root, &[])
    }

    #[test]
    fn the_allow_list() {
        use Gate::*;
        let p = json!({});
        let cases: &[(&str, Value, Result<Gate, &str>)] = &[
            ("hello", p.clone(), Ok(Hello)),
            ("subscribe", json!({"topics": ["instances"]}), Ok(Subscribe)),
            ("unsubscribe", json!({"topics": ["instances"]}), Ok(Subscribe)),
            ("subscribe", json!({"topics": ["instances", "inbox"]}), Err("denied")),
            ("subscribe", json!({"topics": ["forwards"]}), Err("denied")),
            ("instances.watch", json!({"dir": "/x"}), Ok(Watch)),
            // A member watching its hub: the daemon serves it on a hub only.
            ("instances.watch", json!({"dir": "/x", "machines": true}), Ok(Watch)),
            ("instances.unwatch", json!({"dir": "/x"}), Ok(Unwatch)),
            ("instances.list", json!({"dir": "/x"}), Ok(Quick)),
            ("instances.resolve", json!({"name": "a"}), Ok(Quick)),
            ("instances.resolve", json!({"name": "a", "machines": true}), Err("denied")),
            ("containers.logs", json!({"container": "c"}), Ok(Quick)),
            ("containers.list", json!({"all": true}), Ok(Quick)),
            ("containers.stats", p.clone(), Ok(Quick)),
            ("containers.list", json!({"machine": "m"}), Err("denied")),
            ("sandboxes.list", json!({"root": "/x"}), Ok(Quick)),
            ("config.migrate", json!({"root": "/x"}), Ok(Quick)),
            ("capacity.get", p.clone(), Ok(Capacity)),
            ("capacity.get", json!({"machine": "m"}), Err("denied")),
            ("code.haves", json!({"repos": []}), Ok(Code)),
            ("code.haves", json!({"repos": [], "machine": "m"}), Err("denied")),
            ("instances.fetch", json!({"instance": "web-2"}), Ok(Fetch)),
            ("instances.fetch", json!({"instance": "web-2", "machine": "m"}), Err("denied")),
            ("placements.fetch", json!({"instance": "web-2"}), Err("denied")),
            ("run", json!({"root": "/x"}), Ok(Verb)),
            ("rm", json!({"root": "/x"}), Ok(Verb)),
            ("services.rebuild", json!({"root": "/x"}), Ok(Verb)),
            ("gc", json!({"root": "/x"}), Err("denied")),
            ("gc", json!({"root": "/x", "force": true}), Err("denied")),
            ("stop", json!({"root": "/x", "all": true}), Ok(Verb)),
            ("stop", json!({"root": "/x", "machine": "m"}), Err("denied")),
            ("instances.list", json!({"dir": "/x", "machine": "m"}), Err("denied")),
            ("instances.list", json!({"machine": 3}), Err("invalid")),
            ("machines.list", p.clone(), Err("denied")),
            ("machines.get", json!({"name": "m"}), Err("denied")),
            ("member.get", p.clone(), Err("denied")),
            ("member.set", json!({"trust": "full"}), Err("denied")),
            ("membership.get", p.clone(), Err("denied")),
            ("shutdown", p.clone(), Err("denied")),
            ("helper.call", p.clone(), Err("denied")),
            ("forwards.add", p.clone(), Err("denied")),
            ("forwards.list", p.clone(), Err("denied")),
            ("roots.list", p.clone(), Ok(Roots)),
            ("roots.list", json!({"paths": ["~/x"]}), Ok(Roots)),
            ("roots.list", json!({"machine": "m"}), Err("denied")),
            ("bridges.ensure", p.clone(), Err("denied")),
            ("inbox.threads.list", p.clone(), Err("denied")),
            ("nope", p.clone(), Err("denied")),
        ];
        for (method, params, want) in cases {
            let got = decide(method, params).map_err(|e| e.code);
            assert_eq!(got, *want, "{method} {params}");
        }
        // A refusal says what opens it.
        let e = decide("machines.list", &p).unwrap_err();
        assert_eq!(
            e.message,
            "`machines.list` isn't open to remote callers under this member's `worker` trust (`devsandbox machine trust full` there opens it)"
        );
        let e = decide("gc", &json!({"root": "/x"})).unwrap_err();
        assert_eq!(
            e.message,
            "`gc` is host maintenance: not open to remote callers under this member's `worker` trust (`devsandbox machine trust full` there opens it)"
        );
        // Every quick call and verb but `gc` is lent (with confined params).
        for m in fwd::QUICK {
            assert_eq!(decide(m, &p).unwrap(), Quick, "{m}");
        }
        for m in ["run", "rebuild", "start", "stop", "rm", "services.rebuild"] {
            assert!(verbs::is_verb(m));
            assert_eq!(decide(m, &p).unwrap(), Verb, "{m}");
        }
    }

    #[test]
    fn an_attach_names_its_peer() {
        assert_eq!(attach_peer(&json!({"peer": "lap.local"})).unwrap(), "lap.local");
        let long = "x".repeat(PEER_NAME_MAX + 1);
        for bad in [json!({}), json!({"peer": 3}), json!({"peer": ""}), json!({"peer": "a\nb"}), json!({"peer": long})] {
            assert_eq!(attach_peer(&bad).unwrap_err().code, "invalid", "{bad}");
        }
    }

    #[test]
    fn an_attach_names_a_channel_a_machine_name_and_its_key() {
        let key = pk(1);
        for c in ["api", "pty", "tunnel", "transfer", "agent", "route"] {
            let a = attach_params(&json!({"peer": "lap.local", "channel": c, "key": key.to_string()})).unwrap();
            assert_eq!(a, Attach { name: "lap.local".into(), channel: Channel::parse(c).unwrap(), key, introduced_by: None });
        }
        let a = attach_params(&json!({"peer": "pi", "channel": "api", "key": key.to_string(), "introduced_by": "lap"})).unwrap();
        assert_eq!(a.introduced_by.as_deref(), Some("lap"));
        let k = key.to_string();
        for bad in [
            json!({"peer": "lap", "key": k}),
            json!({"peer": "lap", "channel": null, "key": k}),
            json!({"peer": "lap", "channel": "rpc", "key": k}),
            json!({"peer": "lap", "channel": 1, "key": k}),
            // The name names a directory: one plain component.
            json!({"peer": "lap/../x", "channel": "api", "key": k}),
            json!({"peer": "..", "channel": "pty", "key": k}),
            json!({"peer": "a b", "channel": "transfer", "key": k}),
            json!({"channel": "api", "key": k}),
            // No proven key: no link stream.
            json!({"peer": "lap", "channel": "api"}),
            json!({"peer": "lap", "channel": "api", "key": null}),
            json!({"peer": "lap", "channel": "api", "key": "ed25519:00"}),
            json!({"peer": "lap", "channel": "api", "key": 1}),
            json!({"peer": "lap", "channel": "api", "key": k, "introduced_by": 1}),
            json!({"peer": "lap", "channel": "api", "key": k, "introduced_by": "a/b"}),
        ] {
            assert_eq!(attach_params(&bad).unwrap_err().code, "invalid", "{bad}");
        }
    }

    #[test]
    fn a_peers_fleet_root_is_created_under_fleet() {
        let data = scratch("peer-root");
        let root = peer_fleet_root(&data, "lap").unwrap();
        assert_eq!(root, std::fs::canonicalize(data.join("fleet/lap")).unwrap());
        assert!(root.is_dir());
        assert_eq!(peer_fleet_root(&data, "lap").unwrap(), root, "again: the same");
        assert!(peer_fleet_root(&data, "..").is_err());
        assert!(peer_fleet_root(&data, "a/b").is_err());
        let _ = std::fs::remove_dir_all(&data);
    }

    #[test]
    fn paths_are_confined_to_the_fleet_root() {
        let base = scratch("paths");
        let root = base.join("fleet/hub");
        std::fs::create_dir_all(root.join("cfg/sub")).unwrap();
        std::fs::create_dir_all(base.join("mine")).unwrap();
        std::os::unix::fs::symlink(base.join("mine"), root.join("escape")).unwrap();
        std::os::unix::fs::symlink(root.join("cfg"), base.join("into")).unwrap();

        let reach = fleet(&root);
        assert_eq!(confine_path(&reach, &root.join("cfg"), true).unwrap(), root.join("cfg"));
        assert_eq!(confine_path(&reach, &root, true).unwrap(), root, "the root itself");
        // A symlink from outside into the root resolves inside: fine.
        assert_eq!(confine_path(&reach, &base.join("into/sub"), true).unwrap(), root.join("cfg/sub"));
        let code = |p: &Path, exists| confine_path(&reach, p, exists).unwrap_err().code;
        assert_eq!(code(&base.join("mine"), true), "denied", "outside");
        assert_eq!(code(&root.join("escape"), true), "denied", "a symlink out");
        assert_eq!(code(&root.join("cfg/../../../mine"), true), "denied", "`..`");
        assert_eq!(code(&root.join("cfg/.."), true), "denied", "`..` even when it stays inside");
        assert_eq!(code(Path::new("rel"), true), "invalid");
        assert_eq!(code(&root.join("gone"), true), "not-found");
        assert_eq!(confine_path(&reach, &root.join("gone"), false).unwrap(), root.join("gone"), "an unwatch");
        assert_eq!(code(&base.join("gone"), false), "denied");
        // A sibling whose name extends the root's isn't under it.
        std::fs::create_dir_all(base.join("fleet/hub2")).unwrap();
        assert_eq!(code(&base.join("fleet/hub2"), true), "denied");
        let _ = std::fs::remove_dir_all(&base);
    }

    /// `state.toml` with `in` under the fleet root and `own` outside.
    fn state_with(base: &Path, root: &Path) -> PathBuf {
        let state = base.join("state.toml");
        let inst = |name: &str, dir: &Path| {
            format!(
                "[instance.{name}]\ninstance_id = \"id-{name}\"\nsandbox = \"web\"\ncontainer = \"devsandbox-{name}\"\n\
                 folder = \"/w\"\nworkspace = \"/w\"\ncreated_unix = 1\nconfig_dir = {:?}\n",
                dir.to_str().unwrap()
            )
        };
        std::fs::write(&state, inst("in", &root.join("cfg")) + &inst("own", &base.join("mine"))).unwrap();
        state
    }

    /// A link peer: this host's env.
    fn peer(root: &Path) -> Peer {
        Peer {
            name: "me@hub".into(),
            fleet_root: Some(root.to_path_buf()),
            env: Some(BTreeMap::from([("PATH".into(), "/worker/bin".into())])),
            agent: None,
            key: None,
            introduced_by: None,
        }
    }

    #[test]
    fn admit_confines_paths_instances_and_containers() {
        let base = scratch("admit");
        let root = base.join("fleet/hub");
        std::fs::create_dir_all(root.join("cfg")).unwrap();
        std::fs::create_dir_all(base.join("mine")).unwrap();
        let state = state_with(&base, &root);
        let (s, r) = (peer(&root), fleet(&root));
        let ok = |m: &str, p: Value| admit(m, p, &s, &r, &state).unwrap();
        let code = |m: &str, p: Value| admit(m, p, &s, &r, &state).unwrap_err().code;
        let admit = |m: &str, p: Value, s: &Peer, state: &Path| admit(m, p, s, &r, state);

        let cfg = root.join("cfg");
        assert_eq!(ok("instances.list", json!({"dir": cfg})), json!({"dir": cfg}));
        assert_eq!(code("instances.list", json!({"dir": base.join("mine")})), "denied");
        assert_eq!(code("instances.list", json!({})), "invalid", "a path is needed");
        assert_eq!(code("sandboxes.list", json!({"root": 3})), "invalid");
        assert_eq!(code("config.findings", json!({"root": base.join("mine")})), "denied");

        assert!(admit("instances.done", json!({"instance": "in", "done": true}), &s, &state).is_ok());
        assert!(admit("instances.buildLog", json!({"instance": "id-in"}), &s, &state).is_ok(), "by id");
        assert_eq!(code("instances.done", json!({"instance": "own", "done": true})), "not-found");
        assert_eq!(code("instances.buildLog", json!({"instance": "id-own"})), "not-found");
        assert_eq!(code("instances.signal", json!({"instance": "own", "pid": "1", "signal": "TERM"})), "not-found");
        assert!(admit("instances.procs", json!({"instances": ["in"]}), &s, &state).is_ok());
        assert_eq!(code("instances.procs", json!({"instances": ["in", "own"]})), "not-found");
        assert!(admit("containers.logs", json!({"container": "devsandbox-in"}), &s, &state).is_ok());
        assert_eq!(code("containers.inspect", json!({"container": "devsandbox-own"})), "not-found");
        // A reached root's service containers, global or isolated; not another root's.
        let svc = |dir: &Path, rest: &str| {
            crate::commands::services::service_container(&crate::commands::services::project_id(dir).unwrap(), rest)
        };
        assert!(admit("containers.logs", json!({"container": svc(&cfg, "db")}), &s, &state).is_ok());
        assert!(admit("containers.inspect", json!({"container": svc(&cfg, "id-in-db")}), &s, &state).is_ok());
        assert_eq!(code("containers.logs", json!({"container": svc(&base.join("mine"), "db")})), "not-found");

        // `all`: only while every instance in `state.toml` is reached.
        let e = admit("stop", json!({"root": cfg, "all": true}), &s, &state).unwrap_err();
        assert_eq!(e.code, "denied");
        assert!(e.message.contains("machine trust full"), "{}", e.message);

        // Sessions: the root confined and needed, the instance lent.
        assert_eq!(ok("sessions.list", json!({"root": cfg, "instance": "id-in"})), json!({"root": cfg, "instance": "id-in"}));
        assert!(admit("sessions.rm", json!({"root": cfg, "instance": "in", "id": "1700000000-ab12"}), &s, &state).is_ok());
        assert_eq!(code("sessions.list", json!({"root": cfg, "instance": "own"})), "not-found");
        assert_eq!(code("sessions.rm", json!({"root": base.join("mine"), "instance": "own", "id": "x"})), "denied");
        assert_eq!(code("sessions.list", json!({"instance": "in"})), "invalid", "a root is needed");

        // Verbs: the root confined, the instance resolved (a sandbox name
        // matching both is refused), and named.
        assert_eq!(code("stop", json!({"root": base.join("mine"), "instance": "in"})), "denied");
        assert_eq!(code("stop", json!({"root": cfg, "instance": "own"})), "not-found");
        assert_eq!(code("stop", json!({"root": cfg, "instance": "web"})), "not-found", "matches `own` too");
        assert_eq!(code("rm", json!({"root": cfg})), "invalid");
        assert_eq!(code("start", json!({"root": cfg, "instance": null})), "invalid");
        assert!(admit("run", json!({"root": cfg, "sandbox": "web", "env": {}}), &s, &state).is_ok(), "run names none");
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn a_fetch_reaches_the_callers_fleet_root_only() {
        let base = scratch("fetch");
        let root = base.join("fleet/hub");
        for d in ["fleet/hub/roots/h/cfg", "fleet/hub/roots/h/web", "mine/cfg", "mine/web"] {
            std::fs::create_dir_all(base.join(d)).unwrap();
        }
        let state = base.join("state.toml");
        let inst = |name: &str, cfg: &Path, folder: &Path| {
            format!(
                "[instance.{name}]\ninstance_id = \"id-{name}\"\nsandbox = \"web\"\ncontainer = \"devsandbox-{name}\"\n\
                 folder = {:?}\nworkspace = \"/w\"\ncreated_unix = 1\nconfig_dir = {:?}\n",
                folder.to_str().unwrap(),
                cfg.to_str().unwrap()
            )
        };
        let placed = (root.join("roots/h/cfg"), root.join("roots/h/web"));
        let own = (base.join("mine/cfg"), base.join("mine/web"));
        let text = inst("placed", &placed.0, &placed.1) + &inst("own", &own.0, &own.1) + &inst("mixed", &placed.0, &own.1);
        std::fs::write(&state, text).unwrap();
        // The own root is one of this member's roots: a quick call reaches it, a fetch doesn't.
        let r = Reach { own: [own.0.canonicalize().unwrap()].into(), ..fleet(&root) };
        let s = peer(&root);
        let fetch = |name: &str, r: &Reach| admit("instances.fetch", json!({"instance": name}), &s, r, &state);
        assert!(fetch("placed", &r).is_ok());
        assert!(fetch("id-placed", &r).is_ok(), "by id");
        assert!(admit("instances.done", json!({"instance": "own", "done": true}), &s, &r, &state).is_ok());
        for name in ["own", "mixed", "nope"] {
            assert_eq!(fetch(name, &r).unwrap_err().code, "not-found", "{name}");
        }
        assert_eq!(admit("instances.fetch", json!({}), &s, &r, &state).unwrap_err().code, "invalid");
        // Under `full`: any instance.
        let full = Reach { trust: Trust::Full, ..r.clone() };
        assert!(fetch("own", &full).is_ok());
        // `placements.*` is this host's own, under either trust.
        for r in [&r, &full] {
            assert_eq!(admit("placements.fetch", json!({"instance": "x"}), &s, r, &state).unwrap_err().code, "denied");
        }
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn a_verbs_env_is_this_hosts() {
        let base = scratch("env");
        let root = base.join("fleet/hub");
        std::fs::create_dir_all(root.join("cfg")).unwrap();
        let state = state_with(&base, &root);
        let p = json!({"root": root.join("cfg"), "instance": "in", "env": {"PATH": "/hub/bin", "SSH_AUTH_SOCK": "/hub/agent"}});
        let r = fleet(&root);
        let got = admit("stop", p.clone(), &peer(&root), &r, &state).unwrap();
        assert_eq!(got["env"], json!({"PATH": "/worker/bin"}));
        // Missing too: the verb gets it all the same.
        let got = admit("run", json!({"root": root.join("cfg"), "sandbox": "web"}), &peer(&root), &r, &state).unwrap();
        assert_eq!(got["env"], json!({"PATH": "/worker/bin"}));
        // Not a verb: params untouched.
        let got = admit("sandboxes.list", json!({"root": root.join("cfg"), "env": {"A": "b"}}), &peer(&root), &r, &state).unwrap();
        assert_eq!(got["env"], json!({"A": "b"}));
        // `code.haves`: admitted as sent under either trust (the daemon
        // answers it about the peer's own fleet root).
        let haves = json!({"repos": ["0123456789abcdef"]});
        assert_eq!(admit("code.haves", haves.clone(), &peer(&root), &r, &state).unwrap(), haves);
        let full_reach = Reach { trust: Trust::Full, ..r.clone() };
        assert_eq!(admit("code.haves", haves.clone(), &peer(&root), &full_reach, &state).unwrap(), haves);
        // A peer without one: the verb's as sent, under either trust.
        let as_sent = Peer { env: None, ..peer(&root) };
        assert_eq!(admit("stop", p.clone(), &as_sent, &r, &state).unwrap()["env"], p["env"]);
        let full = Reach { trust: Trust::Full, ..r.clone() };
        assert_eq!(admit("stop", p.clone(), &as_sent, &full, &state).unwrap()["env"], p["env"]);
        // `full` still takes the peer's.
        assert_eq!(admit("stop", p.clone(), &peer(&root), &full, &state).unwrap()["env"], json!({"PATH": "/worker/bin"}));
        // A relayed agent: the verb's `SSH_AUTH_SOCK` while it answers.
        let sock = base.join("agent-link-lap.sock");
        let linked = Peer { agent: Some(sock.clone()), ..peer(&root) };
        assert_eq!(admit("stop", p.clone(), &linked, &r, &state).unwrap()["env"], json!({"PATH": "/worker/bin"}), "not bound");
        let _listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
        let want = json!({"PATH": "/worker/bin", "SSH_AUTH_SOCK": sock});
        assert_eq!(admit("stop", p, &linked, &r, &state).unwrap()["env"], want);
        let _ = std::fs::remove_dir_all(&base);
    }

    /// Own roots are reached exactly, beside the fleet root.
    #[test]
    fn worker_admits_own_roots_exactly() {
        let base = scratch("own");
        let root = base.join("fleet/hub");
        std::fs::create_dir_all(root.join("cfg")).unwrap();
        std::fs::create_dir_all(base.join("mine/nested")).unwrap();
        std::fs::create_dir_all(base.join("other")).unwrap();
        let state = state_with(&base, &root);
        let (s, r) = (peer(&root), worker(&root, &[&base.join("mine")]));
        let ok = |m: &str, p: Value| admit(m, p, &s, &r, &state).unwrap();
        let code = |m: &str, p: Value| admit(m, p, &s, &r, &state).unwrap_err().code;
        let mine = base.join("mine");
        assert_eq!(ok("sandboxes.list", json!({"root": mine})), json!({"root": mine}), "an own root");
        assert_eq!(code("sandboxes.list", json!({"root": mine.join("nested")})), "denied", "not what's nested in one");
        assert_eq!(code("sandboxes.list", json!({"root": base.join("other")})), "denied", "nor another path");
        assert_eq!(code("sandboxes.list", json!({"root": mine.join("nested/..")})), "denied", "`..`");
        // Every instance reached: `all` goes (`own` here, `in` under the fleet root).
        assert!(admit("start", json!({"root": mine, "all": true}), &s, &r, &state).is_ok());
        // A peer without a fleet root: `in`'s root is reached as an own root
        // (it's in `state.toml`), and so is `all`.
        let ssh = Reach { fleet_root: None, ..r.clone() };
        let own = own_roots(&State::load_at(&state).unwrap(), None);
        let ssh = Reach { own: ssh.own.union(&own).cloned().collect(), ..ssh };
        assert!(admit("stop", json!({"root": root.join("cfg"), "all": true}), &s, &ssh, &state).is_ok());
        // Without a `Peer.env` its verbs keep the env they sent.
        let attached = Peer { name: "lap".into(), fleet_root: None, env: None, agent: None, key: None, introduced_by: None };
        let sent = json!({"root": mine, "instance": "own", "env": {"SSH_AUTH_SOCK": "/run/agent-machine_lap.sock"}});
        assert_eq!(admit("stop", sent.clone(), &attached, &ssh, &state).unwrap(), sent);
        assert_eq!(admit("config.migrate", json!({"root": mine}), &s, &ssh, &state).unwrap_err().code, "denied");
        // Its instances are named, verbs reach them.
        assert!(admit("instances.done", json!({"instance": "own", "done": true}), &s, &r, &state).is_ok());
        assert!(admit("stop", json!({"root": mine, "instance": "web"}), &s, &r, &state).is_ok(), "both matches reached");
        // Edits of a config: under the fleet root only.
        for m in ["config.migrate", "config.ack"] {
            let e = admit(m, json!({"root": mine}), &s, &r, &state).unwrap_err();
            assert_eq!(e.code, "denied", "{m}");
            assert!(e.message.contains("machine trust full"), "{}", e.message);
            assert!(admit(m, json!({"root": root.join("cfg")}), &s, &r, &state).is_ok(), "{m} under the fleet root");
        }
        assert!(admit("config.findings", json!({"root": mine}), &s, &r, &state).is_ok(), "reading is fine");
        assert_eq!(ok("roots.list", json!({"paths": ["/anywhere"]})), json!({"paths": ["/anywhere"]}));
        let _ = std::fs::remove_dir_all(&base);
    }

    /// `full`: nothing confined, but `member.*`, `membership.*`, `link.*` and `links.*` stay local.
    #[test]
    fn full_skips_the_table_but_not_member_or_link() {
        let base = scratch("full");
        let root = base.join("fleet/hub");
        std::fs::create_dir_all(&root).unwrap();
        let state = base.join("absent.toml");
        let (s, r) = (peer(&root), Reach { trust: Trust::Full, ..fleet(&root) });
        for (m, p) in [
            ("sandboxes.list", json!({"root": "/anywhere/at/all"})),
            ("config.migrate", json!({"root": "/etc"})),
            ("machines.list", json!({})),
            ("shutdown", json!({})),
            ("instances.done", json!({"instance": "nobody"})),
            ("stop", json!({"all": true})),
            ("instances.list", json!({"machine": "m"})),
            ("gc", json!({"root": "/anywhere", "force": true})),
        ] {
            let as_sent = Peer { env: None, ..s.clone() };
            assert_eq!(admit(m, p.clone(), &as_sent, &r, &state).unwrap(), p, "{m}: as sent");
        }
        // `gc`: a verb, so the peer's env; under `worker` refused whatever the root.
        let gc = json!({"root": root, "env": {"PATH": "/hub/bin"}});
        assert_eq!(admit("gc", gc.clone(), &s, &r, &state).unwrap()["env"], json!({"PATH": "/worker/bin"}));
        let e = admit("gc", gc, &s, &fleet(&root), &state).unwrap_err();
        assert_eq!(e.code, "denied");
        assert!(e.message.contains("host maintenance"), "{}", e.message);
        for m in ["member.get", "member.set", "membership.get", "membership.adopt", "membership.sign", "link.attach", "link.anything", "links.inbound", "fleet.leave", "fleet.rm"] {
            for reach in [&r, &fleet(&root)] {
                assert_eq!(admit(m, json!({}), &s, reach, &state).unwrap_err().code, "denied", "{m}");
            }
        }
        let _ = std::fs::remove_dir_all(&base);
    }

    fn sk(n: u8) -> crate::serve::fleet::identity::SigningKey {
        crate::serve::fleet::identity::SigningKey::from_seed([n; 32])
    }

    fn pk(n: u8) -> PublicKey {
        crate::serve::fleet::identity::Signer::public_key(&sk(n))
    }

    /// A peer named `name` that proved key `n`.
    fn proved(name: &str, n: u8) -> Peer {
        Peer { name: name.into(), fleet_root: None, env: None, agent: None, key: Some(pk(n)), introduced_by: None }
    }

    /// `lap` (1) the authority, `box` (2) the hub, `pi` (3) a member; `new`
    /// (5) introduced by `pi`.
    fn fleet_log() -> Stored {
        use crate::serve::fleet::membership::Introduction;
        let mut s = crate::serve::fleet::membership_api::test_support::fleet("lap", &sk(1), "box", &[("box", pk(2)), ("pi", pk(3))]);
        let genesis = s.log.membership().unwrap().genesis;
        s.introduce(Introduction::sign(&genesis, "new", pk(5), "pi", &sk(3))).unwrap();
        s
    }

    /// `fleet.*` goes by the key the peer proved: `leave` / `forget` from
    /// the log's hub (name and key), `rm` and `place` to the hub from a
    /// member (`place` from an introduced one too); never from a local
    /// client, nor from a peer that proved no key.
    /// The key of each member of [`fleet_log`] by name (seeds 1, 2, 3, 5).
    fn own_key(own: &str) -> Option<PublicKey> {
        match own {
            "lap" => Some(pk(1)),
            "box" => Some(pk(2)),
            "pi" => Some(pk(3)),
            "new" => Some(pk(5)),
            _ => None,
        }
    }

    #[test]
    fn fleet_calls_go_by_the_proven_key() {
        let stored = fleet_log();
        // `pi` revoked: what `fleet.leave` / `.forget` / `.rm` follow.
        let mut revoked = stored.clone();
        revoked.log.append(crate::serve::fleet::membership::Op::Revoke { name: "pi".into(), key: pk(3) }, "lap", &sk(1)).unwrap();
        let on = |own| Some(Log { stored: &stored, own, key: own_key(own) });
        let after = |own| Some(Log { stored: &revoked, own, key: own_key(own) });
        let none = json!({});
        let pi = json!({"name": "pi"});
        let code = |m: &str, p: &Peer, log: Option<Log>| admit_fleet(m, &pi, Some(p), log).unwrap_err().code;
        let capped = Peer { introduced_by: Some("pi".into()), ..proved("new", 5) };
        for (m, params) in [("fleet.leave", &none), ("fleet.forget", &pi)] {
            assert_eq!(admit_fleet(m, params, Some(&proved("box", 2)), after("pi")), Ok(()), "{m} from the hub, after the revoke");
            let e = admit_fleet(m, params, Some(&proved("box", 2)), on("pi")).unwrap_err();
            assert!(e.code == "denied" && e.message.contains("follows a revoke"), "{m}: no revoke yet: {}", e.message);
            assert_eq!(code(m, &proved("box", 9), after("pi")), "denied", "{m}: the hub's name, another key");
            assert_eq!(code(m, &proved("lap", 2), after("pi")), "denied", "{m}: the hub's key, another name");
            assert_eq!(code(m, &proved("lap", 1), after("pi")), "denied", "{m}: the authority isn't the hub");
            assert_eq!(code(m, &capped, after("pi")), "denied");
            assert_eq!(code(m, &Peer { key: None, ..proved("box", 2) }, after("pi")), "denied", "{m}: no key");
            assert_eq!(admit_fleet(m, params, Some(&proved("box", 2)), None).unwrap_err().code, "denied", "{m}: no log");
            assert_eq!(admit_fleet(m, params, None, after("pi")).unwrap_err().code, "denied", "{m}: a local client");
        }
        // `fleet.leave` follows a revoke of this host's own key, not another's.
        assert_eq!(code("fleet.leave", &proved("box", 2), after("lap")), "denied");
        assert_eq!(admit_fleet("fleet.forget", &none, Some(&proved("box", 2)), after("lap")).unwrap_err().code, "invalid");
        for m in ["fleet.rm", "fleet.place"] {
            let log = if m == "fleet.rm" { after("box") } else { on("box") };
            assert_eq!(admit_fleet(m, &pi, Some(&proved("pi", 3)), on("box")), Ok(()), "{m} from a member (`rm` of itself)");
            assert_eq!(admit_fleet(m, &pi, Some(&proved("lap", 1)), log), Ok(()), "{m} from the authority");
            let e = admit_fleet(m, &pi, Some(&proved("pi", 3)), on("lap")).unwrap_err();
            assert_eq!((e.code, e.message), ("denied", format!("`{m}` runs on the hub, and this host isn't it")));
            assert_eq!(code(m, &proved("pi", 1), on("box")), "denied", "{m}: a member's name, another's key");
            assert_eq!(code(m, &proved("stranger", 9), on("box")), "denied");
            assert_eq!(code(m, &Peer { key: None, ..proved("pi", 3) }, on("box")), "denied", "{m}: no key");
            assert_eq!(admit_fleet(m, &pi, None, on("box")).unwrap_err().code, "denied");
        }
        // `fleet.rm` of another member: only once the log revokes it.
        let e = admit_fleet("fleet.rm", &pi, Some(&proved("lap", 1)), on("box")).unwrap_err();
        assert!(e.code == "denied" && e.message.contains("isn't revoked in the hub's membership log"), "{}", e.message);
        // A capped member's run is placed; it removes no one.
        assert_eq!(admit_fleet("fleet.place", &none, Some(&capped), on("box")), Ok(()));
        assert_eq!(admit_fleet("fleet.place", &none, Some(&Peer { key: Some(pk(9)), ..capped.clone() }), on("box")).unwrap_err().code, "denied");
        let e = admit_fleet("fleet.rm", &pi, Some(&capped), on("box")).unwrap_err();
        assert_eq!(e.code, "denied");
        assert!(e.message.contains("capped"), "{}", e.message);
        assert_eq!(admit_fleet("fleet.other", &none, Some(&proved("box", 2)), on("pi")).unwrap_err().code, "unknown-method");
    }

    /// The hub is the one the log names at the call: once a `hub` entry
    /// moves it from `box` to `pi`, `box`'s key no longer sends `fleet.forget`
    /// and `pi`'s does; `rm` / `place` / `report` run on `pi`, not `box`.
    #[test]
    fn the_hub_only_calls_follow_the_logs_hub() {
        use crate::serve::fleet::membership::Op;
        let mut before = fleet_log();
        before.log.append(Op::Add { name: "zed".into(), key: pk(4) }, "lap", &sk(1)).unwrap();
        before.log.append(Op::Revoke { name: "zed".into(), key: pk(4) }, "lap", &sk(1)).unwrap();
        let mut moved = before.clone();
        moved.log.append(Op::Hub { name: "pi".into() }, "lap", &sk(1)).unwrap();
        let (zed, none) = (json!({"name": "zed"}), json!({}));
        fn at<'a>(stored: &'a Stored, own: &'a str) -> Option<Log<'a>> {
            Some(Log { stored, own, key: own_key(own) })
        }
        assert_eq!(admit_fleet("fleet.forget", &zed, Some(&proved("box", 2)), at(&before, "lap")), Ok(()));
        assert_eq!(admit_fleet("fleet.forget", &zed, Some(&proved("pi", 3)), at(&before, "lap")).unwrap_err().code, "denied");
        assert_eq!(admit_fleet("fleet.forget", &zed, Some(&proved("pi", 3)), at(&moved, "lap")), Ok(()), "the new hub's key");
        let e = admit_fleet("fleet.forget", &zed, Some(&proved("box", 2)), at(&moved, "lap")).unwrap_err();
        assert!(e.code == "denied" && e.message.contains("`box` isn't it"), "the old hub's key: {}", e.message);
        for (m, params) in [("fleet.rm", &zed), ("fleet.place", &none), ("fleet.report", &none)] {
            assert_eq!(admit_fleet(m, params, Some(&proved("lap", 1)), at(&before, "box")), Ok(()), "{m} on the hub");
            assert_eq!(admit_fleet(m, params, Some(&proved("lap", 1)), at(&moved, "pi")), Ok(()), "{m} on the new hub");
            let e = admit_fleet(m, params, Some(&proved("lap", 1)), at(&moved, "box")).unwrap_err();
            assert_eq!((e.code, e.message), ("denied", format!("`{m}` runs on the hub, and this host isn't it")), "{m} on the old hub");
        }
    }

    /// `fleet.propose` on the authority only (by its own key), from a member
    /// of the log, never a capped one; `fleet.sync` from a member or an
    /// introduced peer, anywhere.
    #[test]
    fn proposals_go_to_the_authority_and_syncs_come_from_members() {
        let stored = fleet_log();
        let on = |own| Some(Log { stored: &stored, own, key: own_key(own) });
        let p = json!({"op": {"kind": "revoke", "name": "pi"}});
        let capped = Peer { introduced_by: Some("pi".into()), ..proved("new", 5) };
        assert_eq!(admit_fleet("fleet.propose", &p, Some(&proved("pi", 3)), on("lap")), Ok(()));
        assert_eq!(admit_fleet("fleet.propose", &p, Some(&proved("box", 2)), on("lap")), Ok(()), "the hub is a member too");
        let e = admit_fleet("fleet.propose", &p, Some(&proved("pi", 3)), on("box")).unwrap_err();
        assert_eq!((e.code, e.message.as_str()), ("denied", "`fleet.propose` goes to the fleet's authority `lap`, and this host isn't it"));
        // The authority's name with another key (a stale `member.toml`).
        let impostor = Some(Log { stored: &stored, own: "lap", key: Some(pk(9)) });
        assert_eq!(admit_fleet("fleet.propose", &p, Some(&proved("pi", 3)), impostor).unwrap_err().code, "denied");
        let e = admit_fleet("fleet.propose", &p, Some(&capped), on("lap")).unwrap_err();
        assert!(e.code == "denied" && e.message.contains("capped"), "{}", e.message);
        assert_eq!(admit_fleet("fleet.propose", &p, Some(&proved("pi", 9)), on("lap")).unwrap_err().code, "denied");
        assert_eq!(admit_fleet("fleet.propose", &p, Some(&proved("stranger", 9)), on("lap")).unwrap_err().code, "denied");
        let sync = json!({"entries": []});
        for own in ["lap", "box", "pi"] {
            assert_eq!(admit_fleet("fleet.sync", &sync, Some(&proved("box", 2)), on(own)), Ok(()), "on {own}");
        }
        assert_eq!(admit_fleet("fleet.sync", &sync, Some(&capped), on("pi")), Ok(()), "from an introduced peer");
        assert_eq!(admit_fleet("fleet.sync", &sync, Some(&proved("stranger", 9)), on("pi")).unwrap_err().code, "denied");
        assert_eq!(admit_fleet("fleet.sync", &sync, None, on("pi")).unwrap_err().code, "denied");
    }

    /// `fleet.report` on the hub only, from a member or a held
    /// introduction by its key; `fleet.graph` anywhere from either.
    #[test]
    fn link_reports_go_to_the_hub_and_graphs_come_from_members() {
        let stored = fleet_log();
        let on = |own| Some(Log { stored: &stored, own, key: own_key(own) });
        let p = json!({});
        let capped = Peer { introduced_by: Some("pi".into()), ..proved("new", 5) };
        for from in [proved("pi", 3), proved("lap", 1), capped.clone()] {
            assert_eq!(admit_fleet("fleet.report", &p, Some(&from), on("box")), Ok(()), "{} to the hub", from.name);
            for own in ["lap", "box", "pi"] {
                assert_eq!(admit_fleet("fleet.graph", &p, Some(&from), on(own)), Ok(()), "{} on {own}", from.name);
            }
        }
        let e = admit_fleet("fleet.report", &p, Some(&proved("pi", 3)), on("lap")).unwrap_err();
        assert_eq!((e.code, e.message.as_str()), ("denied", "`fleet.report` runs on the hub, and this host isn't it"));
        for m in ["fleet.report", "fleet.graph"] {
            let on = if m == "fleet.report" { on("box") } else { on("pi") };
            assert_eq!(admit_fleet(m, &p, Some(&proved("pi", 9)), on).unwrap_err().code, "denied", "{m}: a member's name, another key");
            assert_eq!(admit_fleet(m, &p, Some(&proved("stranger", 9)), on).unwrap_err().code, "denied", "{m}");
            assert_eq!(admit_fleet(m, &p, Some(&Peer { key: None, ..proved("pi", 3) }), on).unwrap_err().code, "denied", "{m}: no key");
            assert_eq!(admit_fleet(m, &p, Some(&proved("pi", 3)), None).unwrap_err().code, "denied", "{m}: no log");
            assert_eq!(admit_fleet(m, &p, None, on).unwrap_err().code, "denied", "{m}: a local client");
        }
        // An introduction's name under another key.
        let e = admit_fleet("fleet.report", &p, Some(&proved("new", 9)), on("box")).unwrap_err();
        assert_eq!(e.code, "denied");
        // `graph.get` is this member's own: never over a link.
        let r = Reach { trust: Trust::Full, fleet_root: None, own: BTreeSet::new() };
        let e = admit("graph.get", json!({}), &proved("pi", 3), &r, Path::new("/nonexistent")).unwrap_err();
        assert_eq!(e.code, "denied");
    }

    #[test]
    fn the_reach_comes_from_member_toml_and_state_toml() {
        let base = scratch("load");
        let root = base.join("fleet/hub");
        std::fs::create_dir_all(root.join("cfg")).unwrap();
        std::fs::create_dir_all(base.join("mine")).unwrap();
        std::fs::create_dir_all(base.join("picked")).unwrap();
        std::fs::create_dir_all(base.join("home/.devsandboxes")).unwrap();
        let state = state_with(&base, &root);
        let files = Files { state, member: Some(base.join("member.toml")), home: Some(base.join("home")) };
        let (r, warn) = Reach::load(&files, Some(&root));
        assert_eq!(warn, None);
        assert_eq!(r.trust, Trust::Worker, "no member.toml");
        let own = |p: &[&str]| p.iter().map(|p| base.join(p)).collect::<BTreeSet<_>>();
        assert_eq!(r.own, [root.join("cfg")].into_iter().chain(own(&["mine", "home/.devsandboxes"])).collect());
        member::write_for_test(
            files.member.as_ref().unwrap(),
            &Member { trust: Trust::Full, roots: vec![base.join("picked"), base.join("gone")], ..Default::default() },
        );
        let (r, warn) = Reach::load(&files, Some(&root));
        assert_eq!((r.trust, warn), (Trust::Full, None));
        assert!(r.own.is_superset(&own(&["picked", "gone"])), "picked ones, a missing one as written");
        // A member.toml that doesn't load: `worker`, no picked roots, said.
        std::fs::write(files.member.as_ref().unwrap(), "trust = 1\n").unwrap();
        let (r, warn) = Reach::load(&files, Some(&root));
        assert_eq!(r.trust, Trust::Worker);
        assert!(!r.own.contains(&base.join("picked")));
        assert!(warn.unwrap().contains("trust = \"worker\""));
        // No data dir: `worker`.
        let (r, _) = Reach::load(&Files { member: None, ..files }, None);
        assert_eq!((r.trust, r.fleet_root), (Trust::Worker, None));
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn rows_are_cut_to_the_fleet_root() {
        let root = Path::new("/nonexistent/fleet/hub");
        let mut snap = json!({
            "instances": [
                {"name": "in", "root": "/nonexistent/fleet/hub/cfg", "instance_id": "i1"},
                {"name": "own", "root": "/nonexistent/mine", "instance_id": "o1"},
                {"name": "sneaky", "root": "/nonexistent/fleet/hub/../../mine"},
                {"name": "old", "root": null},
            ],
            "services": [
                {"name": "db", "used_by": ["in", "own"]},
                {"name": "cache", "scope": "isolated", "used_by": ["in", "own"], "containers": [
                    ["devsandbox-svc-p-i1-cache", {"Running": "Up"}], ["devsandbox-svc-p-o1-cache", {"Running": "Up"}]]},
                {"name": "pg", "scope": "global", "used_by": ["in"], "containers": [["devsandbox-svc-p-pg", {"Running": "Up"}]]},
            ],
            "sandboxes": [{"name": "web"}],
            "thread_children": {"id-own": {"k": "own"}, "id-in": {"k": "in", "j": "own"}},
        });
        let full = Reach { trust: Trust::Full, ..fleet(root) };
        let mut whole = snap.clone();
        filter_snapshot(&mut whole, &full);
        assert_eq!(whole, snap, "nothing cut under `full`");
        let mut own = snap.clone();
        filter_snapshot(&mut own, &worker(root, &[Path::new("/nonexistent/mine")]));
        let names: Vec<&str> = own["instances"].as_array().unwrap().iter().map(|r| r["name"].as_str().unwrap()).collect();
        assert_eq!(names, ["in", "own"], "an own root's rows kept, the others dropped");
        assert_eq!(own["thread_children"], json!({"id-own": {"k": "own"}, "id-in": {"k": "in", "j": "own"}}));
        let root = &fleet(root);
        filter_snapshot(&mut snap, root);
        assert_eq!(snap["instances"], json!([{"name": "in", "root": "/nonexistent/fleet/hub/cfg", "instance_id": "i1"}]));
        assert_eq!(snap["services"][0]["used_by"], json!(["in"]));
        assert_eq!(snap["services"][1]["containers"], json!([["devsandbox-svc-p-i1-cache", {"Running": "Up"}]]), "another root's isolated copy cut");
        assert_eq!(snap["services"][2]["containers"].as_array().unwrap().len(), 1, "a global one kept");
        assert_eq!(snap["thread_children"], json!({"id-in": {"k": "in"}}));
        assert_eq!(snap["sandboxes"], json!([{"name": "web"}]), "the root's own config, as is");

        let resolved = json!({"matches": ["in", "own"], "found": [
            {"name": "in", "root": "/nonexistent/fleet/hub/cfg"}, {"name": "own", "root": "/nonexistent/mine"}]});
        let got = filter_answer("instances.resolve", resolved, root, Path::new("/nonexistent/state.toml")).unwrap();
        assert_eq!(got, json!({"matches": ["in"], "found": [{"name": "in", "root": "/nonexistent/fleet/hub/cfg"}]}));
        let own = json!({"matches": ["own"], "found": [{"name": "own", "root": "/nonexistent/mine"}]});
        assert_eq!(filter_answer("instances.resolve", own, root, Path::new("/nonexistent/state.toml")).unwrap_err().code, "not-found");
        assert_eq!(filter_answer("sandboxes.list", json!({"a": 1}), root, Path::new("/nonexistent/state.toml")).unwrap(), json!({"a": 1}));
    }

    /// A hub's federated push: other machines' rows (tagged, their `root` a
    /// path there) stay, their services untouched; this host's own rows are
    /// cut as ever, and a remote instance of the same name keeps no local
    /// row's service user.
    #[test]
    fn a_federated_push_keeps_other_machines_rows() {
        let root = Path::new("/nonexistent/fleet/hub");
        let mut snap = json!({
            "instances": [
                {"name": "in", "root": "/nonexistent/fleet/hub/cfg", "instance_id": "i1"},
                {"name": "own", "root": "/nonexistent/mine", "instance_id": "o1"},
                {"name": "own", "root": "/x/cfg", "machine": "x", "instance_id": "x1"},
            ],
            "services": [
                {"name": "db", "used_by": ["in", "own"]},
                {"name": "db", "used_by": ["own"], "machine": "x", "root": "/x/cfg"},
            ],
            "machines": [{"name": "x"}],
        });
        filter_snapshot(&mut snap, &fleet(root));
        let rows: Vec<(&str, Option<&str>)> =
            snap["instances"].as_array().unwrap().iter().map(|r| (r["name"].as_str().unwrap(), r["machine"].as_str())).collect();
        assert_eq!(rows, [("in", None), ("own", Some("x"))]);
        assert_eq!(snap["services"][0]["used_by"], json!(["in"]), "x's `own` isn't this host's");
        assert_eq!(snap["services"][1]["used_by"], json!(["own"]), "x's service as x has it");
        assert_eq!(snap["machines"], json!([{"name": "x"}]));
    }

    #[test]
    fn container_rows_are_cut_to_lent_instances_and_their_services() {
        let containers = BTreeSet::from(["devsandbox-in".to_string()]);
        let projects = BTreeSet::from(["aaaa1111".to_string()]);
        let svc = |name: &str, project: &str| json!({"name": name, "labels": {"devsandbox.project": project}});
        let mut list = json!({"rows": [
            {"name": "devsandbox-in", "labels": {}},
            {"name": "devsandbox-own", "labels": {}},
            svc("devsandbox-svc-aaaa1111-db", "aaaa1111"),
            svc("devsandbox-svc-bbbb2222-db", "bbbb2222"),
            // Named like a lent service, labelled otherwise: the label decides.
            svc("devsandbox-svc-aaaa1111-x", "bbbb2222"),
            {"name": "devsandbox-svc-aaaa1111-nolabels"},
            {"labels": {"devsandbox.project": "aaaa1111"}},
        ]});
        cut_containers("containers.list", &mut list, &containers, &projects);
        let names: Vec<&str> = list["rows"].as_array().unwrap().iter().map(|r| r["name"].as_str().unwrap()).collect();
        assert_eq!(names, ["devsandbox-in", "devsandbox-svc-aaaa1111-db"]);

        let row = |name: &str| json!({"name": name, "cpu": "1%", "mem": "2MiB"});
        let mut stats = json!({"rows": [row("devsandbox-in"), row("devsandbox-own"), row("devsandbox-svc-aaaa1111-in-db"),
            row("devsandbox-svc-bbbb2222-db"), row("devsandbox-svc-aaaa11112-db")]});
        cut_containers("containers.stats", &mut stats, &containers, &projects);
        assert_eq!(stats["rows"], json!([row("devsandbox-in"), row("devsandbox-svc-aaaa1111-in-db")]));
    }

    /// The projects come from the lent instances' config roots in `state.toml`.
    #[test]
    fn container_answers_are_cut_by_the_state() {
        let base = scratch("containers");
        let root = base.join("fleet/hub");
        std::fs::create_dir_all(root.join("cfg")).unwrap();
        std::fs::create_dir_all(base.join("mine")).unwrap();
        let state = state_with(&base, &root);
        let lent = crate::commands::services::project_id(&root.join("cfg")).unwrap();
        let mine = crate::commands::services::project_id(&base.join("mine")).unwrap();
        let svc = |p: &str| json!({"name": format!("devsandbox-svc-{p}-db"), "labels": {"devsandbox.project": p}});
        let answer = json!({"rows": [{"name": "devsandbox-in", "labels": {}}, {"name": "devsandbox-own", "labels": {}}, svc(&lent), svc(&mine)]});
        let with_own = filter_answer("containers.list", answer.clone(), &worker(&root, &[&base.join("mine")]), &state).unwrap();
        assert_eq!(with_own, answer, "an own root's instance and services kept");
        let reach = fleet(&root);
        let root = &reach;
        let got = filter_answer("containers.list", answer, root, &state).unwrap();
        assert_eq!(got, json!({"rows": [{"name": "devsandbox-in", "labels": {}}, svc(&lent)]}));
        let stats = json!({"rows": [{"name": "devsandbox-own"}, {"name": format!("devsandbox-svc-{lent}-db")}]});
        let got = filter_answer("containers.stats", stats, root, &state).unwrap();
        assert_eq!(got, json!({"rows": [{"name": format!("devsandbox-svc-{lent}-db")}]}));
        assert_eq!(filter_answer("containers.list", json!({"rows": []}), root, &base.join("bad")).unwrap(), json!({"rows": []}), "no state: none lent");
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn a_peers_roots_listing_gets_its_fleet_root_once() {
        let reach = worker(Path::new("/d/fleet/hub"), &[]);
        let own = json!([{"root": "/own", "sandboxes": [{"name": "web"}], "error": null}]);
        let got = with_fleet_root(own.clone(), &reach);
        assert_eq!(got, json!([own[0], {"root": "/d/fleet/hub", "sandboxes": [], "error": null, "fleet": true}]));
        assert_eq!(with_fleet_root(got.clone(), &reach), got, "listed already");
        // Listed among the own roots already: flagged there.
        let listed = json!([{"root": "/d/fleet/hub", "sandboxes": [], "error": null, "fleet": false}]);
        assert_eq!(with_fleet_root(listed, &reach), json!([{"root": "/d/fleet/hub", "sandboxes": [], "error": null, "fleet": true}]));
        let relay = Reach { fleet_root: None, ..reach.clone() };
        assert_eq!(with_fleet_root(own.clone(), &relay), own, "no fleet root: as is");
        assert_eq!(with_fleet_root(json!({"x": 1}), &reach), json!({"x": 1}), "not a listing");
    }
}