devsandbox 0.11.1

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
//! `member.toml`, next to `state.toml`: this host as a fleet member
//! (docs/architecture/daemon/fleet.md, *Member file*): the name it goes by,
//! its fleet's control plane, its trust, the config roots it shows the fleet, its
//! `[allow]`, and the hand-edited `[caps]` and `dev-builds`. Next to it,
//! `member.key` ([`key_path`]) is this member's private key
//! (`fleet::identity::FileKeyStore`), whose public half `member.get` answers.
//!
//! Written by the daemon only (decision 3 of the fleet plan), through
//! `member.set` ([`call`]; `devsandbox machine trust`, `machine roots` and
//! `machine allow` are its clients), with [`update`]: under the sibling
//! `member.lock`, a temp file and a rename (`serve::locked_file`). `control_plane`
//! has no call: it's written from an accepted membership log
//! (`membership.adopt`, `super::membership_api`) and cleared on leaving,
//! both through [`set_fleet`].
//! `member.*` is local only (`fleet::lent` admits none of it over a link):
//! `[allow]` is this host's own grant, never a peer's or the control
//! plane's to set (gpus plan decision 7). `[caps]` and `dev-builds` have
//! no call: they're edited by hand. All of it is re-read at each use
//! (`worker_policy` reads `trust` and `[allow]` itself, on every
//! platform), so nothing is cached to invalidate. The `[[agent]]` grants have no
//! `member.*` call either: `machines.set {agent}` and `machines.add
//! {agent}` write them (`super::grants`), read at each `AGENT` stream.

use std::ffi::OsString;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::serve::api::{ApiError, parse as parse_params};
use crate::serve::fleet::identity::{FileKeyStore, KeyStore, PublicKey};
use crate::serve::fleet::membership_api::KeyInfo;
use crate::serve::machines::check_name;
pub use crate::worker_policy::{Allow, Trust};

type Answer = Result<Value, ApiError>;

/// The file. Unknown keys are ignored, as in `daemon.config.toml`: an
/// allowance a newer binary knows is one an older one doesn't grant.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "kebab-case")]
pub struct Member {
    /// The name this host goes by in the fleet; empty is [`default_name`]
    /// of the hostname.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub name: String,
    /// The fleet's control plane ([`Member::control_plane`]): `self` on the control plane, else the control plane's
    /// member name; empty is in no fleet (fleet plan decision 1).
    #[serde(rename = "control_plane", skip_serializing_if = "String::is_empty")]
    pub control_plane: String,
    /// What a remote caller reaches here (`worker_policy::Trust`).
    pub trust: Trust,
    /// Take the fleet's pinned dev build from a peer that has it
    /// (`fleet::update::Decision::Receive`): code the authority chooses, run
    /// outside a container. Edited by hand, as `[allow]` is; `full` implies
    /// it ([`Member::takes_dev_builds`]).
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub dev_builds: bool,
    /// Config roots this host shows the fleet besides those its
    /// `state.toml` has instances in (picked at `machine add`; decision 17
    /// of the fleet plan). Absolute.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub roots: Vec<PathBuf>,
    /// The worker policy's allowances (`worker_policy`, which reads them
    /// itself from this file).
    pub allow: Allow,
    /// Soft caps, reported in this host's capacity
    /// (`serve::capacity::Capacity::caps`); never enforced.
    #[serde(skip_serializing_if = "SoftCaps::is_empty")]
    pub caps: SoftCaps,
    /// `[[agent]]`: the members this host's ssh-agent is granted to, by
    /// name and key (fleet plan decision 65; `super::grants`). None by
    /// default; one per name.
    #[serde(rename = "agent", skip_serializing_if = "Vec::is_empty")]
    pub agent: Vec<Grant>,
}

/// One `[[agent]]` grant: member `name`, as it proved `key` when granted
/// (`ed25519:<hex>`). It holds for `key` and the keys the membership log
/// rotates it to under `name` (`super::grants::granted`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Grant {
    pub name: String,
    pub key: PublicKey,
}

/// `[caps]`: what this host means to give the fleet (fleet plan, *Placement*). All
/// optional; sizes as `16G`, `512M`, `1.5T` (binary units) or bytes.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct SoftCaps {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cpus: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mem: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub disk: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instances: Option<u64>,
}

impl SoftCaps {
    pub fn is_empty(&self) -> bool {
        *self == SoftCaps::default()
    }

    /// `mem` and `disk` must be sizes.
    pub fn check(&self) -> Result<()> {
        for (key, size) in [("mem", &self.mem), ("disk", &self.disk)] {
            if let Some(size) = size {
                crate::serve::capacity::parse_size(size).with_context(|| format!("`caps.{key}`"))?;
            }
        }
        Ok(())
    }
}

/// `control_plane` in `member.toml`, typed.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum ControlPlane {
    /// In no fleet.
    #[default]
    None,
    /// This host is the control plane (`self`).
    This,
    /// The control plane is the member of this name.
    Other(String),
}

/// The `control_plane` value naming this host.
pub const CONTROL_PLANE_SELF: &str = "self";

impl ControlPlane {
    /// The file's `control_plane` value read (`""`: none). Unchecked: [`check`] is.
    pub fn of(field: &str) -> ControlPlane {
        match field {
            "" => ControlPlane::None,
            CONTROL_PLANE_SELF => ControlPlane::This,
            name => ControlPlane::Other(name.to_string()),
        }
    }

    /// What the file and `member.get` say: `None` in no fleet.
    pub fn field(&self) -> Option<String> {
        match self {
            ControlPlane::None => None,
            ControlPlane::This => Some(CONTROL_PLANE_SELF.into()),
            ControlPlane::Other(name) => Some(name.clone()),
        }
    }

    pub fn is_this(&self) -> bool {
        *self == ControlPlane::This
    }
}

/// A member name: a valid machine name but `self`, which `control_plane = "self"`
/// reads as this host.
pub fn check_member_name(name: &str) -> Result<()> {
    check_name(name)?;
    if name == CONTROL_PLANE_SELF {
        bail!("`{CONTROL_PLANE_SELF}` is reserved (`control_plane = \"{CONTROL_PLANE_SELF}\"` means this host)");
    }
    Ok(())
}

/// `control_plane` is empty, `self` or a valid machine name.
fn check_control_plane(control_plane: &str) -> Result<()> {
    if !control_plane.is_empty() && control_plane != CONTROL_PLANE_SELF {
        check_name(control_plane).context("`control_plane`")?;
    }
    Ok(())
}

impl Member {
    pub fn control_plane(&self) -> ControlPlane {
        ControlPlane::of(&self.control_plane)
    }

    /// Whether a pinned dev build is taken (fleet plan, *Versions*:
    /// `dev-builds`, or `full`).
    pub fn takes_dev_builds(&self) -> bool {
        self.dev_builds || self.trust == Trust::Full
    }

    /// Whether placed work may use this host's GPU (`[allow] gpus`, or
    /// `full`, under which no worker policy applies): the capacity
    /// report's `gpu.lent`.
    pub fn lends_gpu(&self) -> bool {
        self.allow.gpus || self.trust == Trust::Full
    }

    /// `name`, else [`default_name`] of `hostname`.
    pub fn name_or(&self, hostname: &str) -> Result<String> {
        match self.name.as_str() {
            "" => default_name(hostname),
            name => Ok(name.to_string()),
        }
    }
}

/// [`path_from`] over the process env.
pub fn path() -> Result<PathBuf> {
    path_from(std::env::var_os("XDG_DATA_HOME"), std::env::var_os("HOME"))
}

/// `<data>/devsandbox/member.toml`.
pub fn path_from(xdg_data_home: Option<OsString>, home: Option<OsString>) -> Result<PathBuf> {
    Ok(crate::daemon_config::data_dir_from(xdg_data_home, home)?.join("member.toml"))
}

/// `member.key` next to the `member.toml` at `member_toml`: this member's
/// private key (`fleet::identity::FileKeyStore`).
pub fn key_path(member_toml: &Path) -> PathBuf {
    member_toml.with_file_name(crate::daemon_config::MEMBER_KEY)
}

/// `text` as a [`Member`], [`check`]ed.
pub fn parse(text: &str) -> Result<Member> {
    let member: Member = toml::from_str(text)?;
    check(&member)?;
    Ok(member)
}

/// A `name` that's set is a valid member name, `roots` are absolute, and
/// `[caps]` and `[allow]` are well-formed.
pub fn check(member: &Member) -> Result<()> {
    if !member.name.is_empty() {
        check_member_name(&member.name).context("`name`")?;
    }
    check_control_plane(&member.control_plane)?;
    if let Some(bad) = member.roots.iter().find(|r| !r.is_absolute()) {
        bail!("`roots`: `{}` is not an absolute path", bad.display());
    }
    member.caps.check()?;
    let mut names = std::collections::BTreeSet::new();
    for g in &member.agent {
        check_member_name(&g.name).with_context(|| format!("`agent`: `{}`", g.name))?;
        if !names.insert(&g.name) {
            bail!("`agent`: two grants for `{}`", g.name);
        }
    }
    member.allow.check()
}

pub fn serialize(member: &Member) -> Result<String> {
    toml::to_string_pretty(member).context("cannot serialize member.toml")
}

/// Read-modify-write of the file at `path` under its lock (a missing file is
/// the default); saved only when `f` changed it. A file that doesn't parse
/// fails the update rather than being overwritten.
pub fn update<T>(path: &Path, f: impl FnOnce(&mut Member) -> T) -> Result<T> {
    crate::serve::locked_file::update(path, |p| Ok(load(p)?.unwrap_or_default()), serialize, f)
}

/// The file at `path`; a missing file is `None` (the defaults).
pub fn load(path: &Path) -> Result<Option<Member>> {
    match std::fs::read_to_string(path) {
        Ok(text) => parse(&text).map(Some).with_context(|| format!("invalid {}", path.display())),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(e).with_context(|| format!("cannot read {}", path.display())),
    }
}

/// The name a member goes by without `name`: the hostname's first label
/// (`lap.local` → `lap`), if it's a valid member name.
pub fn default_name(hostname: &str) -> Result<String> {
    let label = hostname.split('.').next().unwrap_or_default();
    match check_member_name(label) {
        Ok(()) => Ok(label.to_string()),
        Err(e) => bail!("cannot name this host after hostname `{hostname}` ({e:#}); set `name` in member.toml (next to state.toml)"),
    }
}

/// `member.get`'s answer (and `member.set`'s, after the change).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MemberInfo {
    /// `member.toml`'s `name`, else the hostname's first label; `None`
    /// when neither is a valid name.
    pub name: Option<String>,
    /// `control_plane` as the file says: `self` on the control plane, else the control plane's member
    /// name; `None` in no fleet.
    pub control_plane: Option<String>,
    pub trust: Trust,
    /// `dev-builds` as the file says (`full` takes dev builds either way).
    pub dev_builds: bool,
    pub roots: Vec<PathBuf>,
    /// `[allow]`, every key present.
    pub allow: AllowInfo,
    /// This member's public key (`ed25519:<hex>`), from `member.key`,
    /// created on first ask.
    pub key: PublicKey,
    /// [`PublicKey::fingerprint`] of `key`.
    pub fingerprint: String,
    /// A pending rotation's next key (`member.key.next`, `machine key
    /// rotate`), the key once a membership log listing it is taken; `None`
    /// when none is pending.
    pub next: Option<KeyInfo>,
    /// While this host is `worker` and exposed through another machine
    /// (`fleet::graph::exposed_workers`, over this host's link graph): the
    /// chain from the control plane, its last but one dialing this host (a shell
    /// here). `None` otherwise.
    pub exposed_by: Option<Vec<String>>,
    /// On the fleet's authority: why the daemon's last try didn't pin this
    /// build (`machines::changes::BuildSigned::Skipped`, the control
    /// plane's platform guard), until a pin is signed or none is due.
    /// `None` otherwise.
    #[serde(default)]
    pub pin_skipped: Option<String>,
}

/// `[allow]` on the wire: the TOML keys in snake case, as the rest of
/// `member.*` names its fields, every one present.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct AllowInfo {
    pub privileged: bool,
    pub runtime_socket: bool,
    pub host_network: bool,
    pub global_services: bool,
    pub dispatcher: bool,
    pub inbox: bool,
    pub initialize_command: bool,
    pub publish: bool,
    pub gpus: bool,
    pub local_env: Vec<String>,
    pub binds: Vec<PathBuf>,
}

impl AllowInfo {
    /// The on/off allowances by wire name, in the file's order.
    pub fn flags(&self) -> [(&'static str, bool); 9] {
        [
            ("privileged", self.privileged),
            ("runtime_socket", self.runtime_socket),
            ("host_network", self.host_network),
            ("global_services", self.global_services),
            ("dispatcher", self.dispatcher),
            ("inbox", self.inbox),
            ("initialize_command", self.initialize_command),
            ("publish", self.publish),
            ("gpus", self.gpus),
        ]
    }
}

impl From<&Allow> for AllowInfo {
    fn from(a: &Allow) -> Self {
        AllowInfo {
            privileged: a.privileged,
            runtime_socket: a.runtime_socket,
            host_network: a.host_network,
            global_services: a.global_services,
            dispatcher: a.dispatcher,
            inbox: a.inbox,
            initialize_command: a.initialize_command,
            publish: a.publish,
            gpus: a.gpus,
            local_env: a.local_env.clone(),
            binds: a.binds.clone(),
        }
    }
}

/// `member.set`'s `allow`: each allowance given is set, the rest kept;
/// list entries added (once) or removed (one not there is no error).
/// Serialized as `machines.add` forwards it to the machine's `member.set`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct AllowPatch {
    pub privileged: Option<bool>,
    pub runtime_socket: Option<bool>,
    pub host_network: Option<bool>,
    pub global_services: Option<bool>,
    pub dispatcher: Option<bool>,
    pub inbox: Option<bool>,
    pub initialize_command: Option<bool>,
    pub publish: Option<bool>,
    pub gpus: Option<bool>,
    /// Absolute paths.
    pub binds_add: Vec<PathBuf>,
    pub binds_rm: Vec<PathBuf>,
    /// Env var names ([`check_env_name`]).
    pub local_env_add: Vec<String>,
    pub local_env_rm: Vec<String>,
}

impl AllowPatch {
    /// What `apply` would refuse, checked against no allowances (pure):
    /// `machines.add` checks it before any write.
    pub fn check(&self) -> Result<(), ApiError> {
        self.apply(&mut Allow::default())
    }

    fn apply(&self, a: &mut Allow) -> Result<(), ApiError> {
        let flags = [
            (self.privileged, &mut a.privileged),
            (self.runtime_socket, &mut a.runtime_socket),
            (self.host_network, &mut a.host_network),
            (self.global_services, &mut a.global_services),
            (self.dispatcher, &mut a.dispatcher),
            (self.inbox, &mut a.inbox),
            (self.initialize_command, &mut a.initialize_command),
            (self.publish, &mut a.publish),
            (self.gpus, &mut a.gpus),
        ];
        for (want, have) in flags {
            if let Some(want) = want {
                *have = want;
            }
        }
        for bind in &self.binds_add {
            if !bind.is_absolute() {
                return Err(ApiError::invalid(format!("`allow.binds_add`: `{}` is not an absolute path", bind.display())));
            }
            if !a.binds.contains(bind) {
                a.binds.push(bind.clone());
            }
        }
        a.binds.retain(|b| !self.binds_rm.contains(b));
        for name in &self.local_env_add {
            check_env_name(name).map_err(|e| ApiError::invalid(format!("`allow.local_env_add`: {e:#}")))?;
            if !a.local_env.contains(name) {
                a.local_env.push(name.clone());
            }
        }
        a.local_env.retain(|n| !self.local_env_rm.contains(n));
        Ok(())
    }
}

/// A name `${localEnv:NAME}` can say and an env var can have: not empty,
/// no `:` (the default's separator), `}`, `=` or NUL.
pub fn check_env_name(name: &str) -> Result<()> {
    if name.is_empty() {
        bail!("empty env var name");
    }
    if let Some(c) = name.chars().find(|c| matches!(c, ':' | '}' | '=' | '\0')) {
        bail!("`{name}`: an env var name has no `{}`", c.escape_default());
    }
    Ok(())
}

/// The [`MemberInfo::exposed_by`] chain of the member of this name at this
/// trust (the daemon's link graph).
pub type Exposure<'a> = &'a dyn Fn(&str, Trust) -> Option<Vec<String>>;

/// `member.set`'s params: each one present is changed, the rest kept.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SetParams {
    /// A machine name; `""` clears it (the hostname's first label).
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub trust: Option<Trust>,
    /// Absolute paths added to `roots` (one already there is kept once).
    #[serde(default)]
    pub roots_add: Vec<PathBuf>,
    /// Paths taken out of `roots` (one not there is no error).
    #[serde(default)]
    pub roots_rm: Vec<PathBuf>,
    /// `[allow]` changes (`devsandbox machine allow`).
    #[serde(default)]
    pub allow: Option<AllowPatch>,
}

/// `member` with `p` applied, checked (pure).
pub fn merge(mut member: Member, p: &SetParams) -> Result<Member, ApiError> {
    if let Some(name) = &p.name {
        if !name.is_empty() {
            check_member_name(name).map_err(|e| ApiError::invalid(format!("`name`: {e:#}")))?;
        }
        member.name = name.clone();
    }
    if let Some(trust) = p.trust {
        member.trust = trust;
    }
    for root in &p.roots_add {
        if !root.is_absolute() {
            return Err(ApiError::invalid(format!("`roots_add`: `{}` is not an absolute path", root.display())));
        }
        if !member.roots.contains(root) {
            member.roots.push(root.clone());
        }
    }
    member.roots.retain(|r| !p.roots_rm.contains(r));
    if let Some(allow) = &p.allow {
        allow.apply(&mut member.allow)?;
    }
    check(&member).map_err(|e| ApiError::invalid(format!("{e:#}")))?;
    Ok(member)
}

/// The answer for `member`, its key loaded (or created) from `member.key`
/// next to `path`.
fn info(member: &Member, path: &Path, hostname: &str, exposure: Exposure, pin_skipped: Option<&str>) -> Result<MemberInfo, ApiError> {
    let key = FileKeyStore::new(key_path(path)).public_key().map_err(ApiError::internal)?;
    let next = crate::serve::fleet::membership_api::pending_next(path)?;
    let name = member.name_or(hostname).ok();
    Ok(MemberInfo {
        next,
        exposed_by: name.as_deref().and_then(|n| exposure(n, member.trust)),
        pin_skipped: pin_skipped.map(str::to_string),
        name,
        control_plane: member.control_plane().field(),
        trust: member.trust,
        dev_builds: member.dev_builds,
        roots: member.roots.clone(),
        allow: AllowInfo::from(&member.allow),
        fingerprint: key.fingerprint(),
        key,
    })
}

/// `member.get` over the file at `path`; `hostname` names this host when
/// the file doesn't. The first one creates `member.key`. `pin_skipped` is
/// the daemon's ([`MemberInfo::pin_skipped`]).
pub fn get(path: &Path, hostname: &str, exposure: Exposure, pin_skipped: Option<&str>) -> Result<MemberInfo, ApiError> {
    let member = load(path).map_err(ApiError::internal)?.unwrap_or_default();
    info(&member, path, hostname, exposure, pin_skipped)
}

/// `member.set`: `p` merged into the file, checked, written. Nothing else
/// follows it: a peer link reads the name at its next dial
/// (`fleet::dialer::member_name`), the rest is read at each use. The
/// answer's `exposed_by` is at the new trust.
pub fn set(path: &Path, hostname: &str, p: &SetParams, exposure: Exposure, pin_skipped: Option<&str>) -> Result<MemberInfo, ApiError> {
    let after = update(path, |cur| -> Result<Member, ApiError> {
        *cur = merge(cur.clone(), p)?;
        Ok(cur.clone())
    })
    .map_err(ApiError::internal)??;
    info(&after, path, hostname, exposure, pin_skipped)
}

/// `control_plane` written as `control_plane` (from an accepted membership log, or
/// [`ControlPlane::None`] on leaving), and with it `name` when given (the name the
/// log knows this host by, pinned). Not an API call: the daemon follows a
/// change itself (`daemon::Shared::set_control_plane`).
pub fn set_fleet(path: &Path, name: Option<&str>, control_plane: &ControlPlane) -> Result<Member> {
    update(path, |cur| -> Result<Member> {
        let mut next = cur.clone();
        if let Some(name) = name {
            next.name = name.to_string();
        }
        next.control_plane = control_plane.field().unwrap_or_default();
        check(&next)?;
        *cur = next;
        Ok(cur.clone())
    })?
}

/// Run `method` if it's a `member.*` one; `None` otherwise.
pub fn call(method: &str, params: Value, path: &Path, hostname: &str, exposure: Exposure, pin_skipped: Option<&str>) -> Option<Answer> {
    let to_value = |info: MemberInfo| serde_json::to_value(info).map_err(|e| ApiError::internal(e.into()));
    let answer = match method {
        "member.get" => get(path, hostname, exposure, pin_skipped).and_then(to_value),
        "member.set" => parse_params(params).and_then(|p: SetParams| set(path, hostname, &p, exposure, pin_skipped)).and_then(to_value),
        _ => return None,
    };
    Some(answer)
}

/// Write `member` at `path` (tests: what an earlier `member.set` or a hand
/// edit left).
#[cfg(test)]
pub fn write_for_test(path: &Path, member: &Member) {
    update(path, |m| *m = member.clone()).unwrap();
}

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

    use super::*;
    use crate::serve::fleet::identity::Signer as _;

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

    #[test]
    fn the_path_is_next_to_state_toml() {
        assert_eq!(path_from(Some("/xdg".into()), None).unwrap(), PathBuf::from("/xdg/devsandbox/member.toml"));
        assert_eq!(
            path_from(None, Some("/home/u".into())).unwrap(),
            PathBuf::from("/home/u/.local/share/devsandbox/member.toml")
        );
    }

    #[test]
    fn parses() {
        let m = parse("name = \"lap\"\ntrust = \"full\"\nroots = [\"/srv/cfg\"]\n").unwrap();
        assert_eq!(m, Member { name: "lap".into(), trust: Trust::Full, roots: vec!["/srv/cfg".into()], ..Default::default() });
        assert_eq!(parse("").unwrap(), Member::default(), "empty: the defaults");
        assert_eq!(Member::default().trust, Trust::Worker);
        assert!(parse("trust = \"worker\"\nlater = 1\n").is_ok(), "unknown keys are ignored");
        assert!(parse("trust = \"most\"\n").is_err());
        assert!(parse("name = \"a/b\"\n").is_err());
        assert!(parse("name = \"self\"\n").is_err(), "`self` is reserved");
        assert!(parse("roots = [\"rel\"]\n").is_err(), "roots are absolute");
        let a = parse("[allow]\nprivileged = true\nbinds = [\"/srv/x\"]\nlater = true\n").unwrap().allow;
        assert_eq!(a, Allow { privileged: true, binds: vec!["/srv/x".into()], ..Default::default() });
        assert!(parse("[allow]\nbinds = [\"x\"]\n").is_err(), "binds are absolute");
        assert_eq!(
            serialize(&Member { allow: a, ..Default::default() }).unwrap(),
            "trust = \"worker\"\n\n[allow]\nprivileged = true\nbinds = [\"/srv/x\"]\n"
        );
        // Soft caps: sizes checked, unset ones left out of the file.
        let caps = parse("[caps]\ncpus = 4\nmem = \"16G\"\ninstances = 3\n").unwrap().caps;
        assert_eq!(caps, SoftCaps { cpus: Some(4), mem: Some("16G".into()), disk: None, instances: Some(3) });
        assert_eq!(
            serialize(&Member { caps, ..Default::default() }).unwrap(),
            "trust = \"worker\"\n\n[allow]\n\n[caps]\ncpus = 4\nmem = \"16G\"\ninstances = 3\n"
        );
        assert!(!serialize(&Member::default()).unwrap().contains("caps"));
        let bad = parse("[caps]\ndisk = \"lots\"\n").unwrap_err();
        assert!(format!("{bad:#}").contains("caps.disk"), "{bad:#}");
        assert!(parse("[caps]\ncpus = -1\n").is_err());
        // `dev-builds`: off unless set, left out of the file while off.
        assert!(!parse("").unwrap().dev_builds);
        let dev = parse("dev-builds = true\n").unwrap();
        assert!(dev.dev_builds);
        assert_eq!(serialize(&dev).unwrap(), "trust = \"worker\"\ndev-builds = true\n\n[allow]\n");
        assert!(!serialize(&Member::default()).unwrap().contains("dev-builds"));
        // Roots go before the tables.
        let rooted = Member { roots: vec!["/a".into()], ..Default::default() };
        assert_eq!(parse(&serialize(&rooted).unwrap()).unwrap(), rooted);
    }

    #[test]
    fn control_plane_is_self_a_name_or_none() {
        assert_eq!(parse("").unwrap().control_plane(), ControlPlane::None);
        assert_eq!(parse("control_plane = \"self\"\n").unwrap().control_plane(), ControlPlane::This);
        assert_eq!(parse("control_plane = \"box\"\n").unwrap().control_plane(), ControlPlane::Other("box".into()));
        assert!(parse("control_plane = \"a/b\"\n").is_err());
        assert!(parse("control_plane = \"-x\"\n").is_err());
        assert_eq!(serialize(&Member { control_plane: "self".into(), ..Default::default() }).unwrap(), "control_plane = \"self\"\ntrust = \"worker\"\n\n[allow]\n");
        assert!(!serialize(&Member::default()).unwrap().contains("control_plane"), "no fleet: left out");
        assert_eq!((ControlPlane::None.field(), ControlPlane::This.field(), ControlPlane::Other("k".into()).field()), (None, Some("self".into()), Some("k".into())));
        assert!(ControlPlane::This.is_this() && !ControlPlane::Other("self2".into()).is_this());
    }

    #[test]
    fn dev_builds_or_full_take_dev_builds() {
        assert!(!Member::default().takes_dev_builds());
        assert!(Member { dev_builds: true, ..Default::default() }.takes_dev_builds());
        assert!(Member { trust: Trust::Full, ..Default::default() }.takes_dev_builds());
    }

    #[test]
    fn allow_gpus_or_full_lend_the_gpu() {
        assert!(!Member::default().lends_gpu());
        assert!(!Member { dev_builds: true, ..Default::default() }.lends_gpu());
        assert!(Member { allow: Allow { gpus: true, ..Default::default() }, ..Default::default() }.lends_gpu());
        assert!(Member { trust: Trust::Full, ..Default::default() }.lends_gpu());
        let m = parse("[allow]\ngpus = true\n").unwrap();
        assert!(m.lends_gpu(), "from the file");
    }

    #[test]
    fn default_names_take_the_first_label() {
        assert_eq!(default_name("lap.local").unwrap(), "lap");
        assert_eq!(default_name("box").unwrap(), "box");
        assert!(default_name("").is_err());
        assert!(default_name("a b").is_err());
        assert!(default_name("self.local").is_err(), "`self` is reserved");
        let m = Member { name: "mine".into(), ..Default::default() };
        assert_eq!(m.name_or("a b").unwrap(), "mine");
        assert_eq!(Member::default().name_or("lap.local").unwrap(), "lap");
    }

    #[test]
    fn merge_checks_what_it_changes() {
        let p = |v: Value| -> SetParams { serde_json::from_value(v).unwrap() };
        let named = merge(Member::default(), &p(json!({"name": "lap", "trust": "full"}))).unwrap();
        assert_eq!((named.name.as_str(), named.trust), ("lap", Trust::Full));
        let kept = merge(named.clone(), &p(json!({"roots_add": ["/a", "/b", "/a/"]}))).unwrap();
        assert_eq!((kept.name.as_str(), kept.trust), ("lap", Trust::Full), "the rest kept");
        assert_eq!(kept.roots, [PathBuf::from("/a"), PathBuf::from("/b")], "deduped");
        let rm = merge(kept.clone(), &p(json!({"roots_rm": ["/a", "/gone"], "roots_add": ["/c"]}))).unwrap();
        assert_eq!(rm.roots, [PathBuf::from("/b"), PathBuf::from("/c")]);
        assert_eq!(merge(rm, &p(json!({"name": ""}))).unwrap().name, "", "cleared");
        let code = |v: Value| merge(named.clone(), &p(v)).unwrap_err().code;
        assert_eq!(code(json!({"name": "a/b"})), "invalid");
        assert_eq!(code(json!({"name": "self"})), "invalid");
        assert_eq!(code(json!({"roots_add": ["rel"]})), "invalid");
        // Hand-edited parts aren't settable, nor `control_plane` (only an accepted
        // membership log writes it).
        for bad in [json!({"trust": "most"}), json!({"dev_builds": true}), json!({"caps": {}}), json!({"control_plane": "self"})] {
            assert!(serde_json::from_value::<SetParams>(bad.clone()).is_err(), "{bad}");
        }
    }

    #[test]
    fn allow_patches_change_only_what_they_name() {
        let p = |v: Value| -> SetParams { serde_json::from_value(v).unwrap() };
        let start = Member { trust: Trust::Full, allow: Allow { publish: true, binds: vec!["/x".into()], ..Default::default() }, ..Default::default() };
        let m = merge(start.clone(), &p(json!({"allow": {"gpus": true, "runtime_socket": true, "publish": false}}))).unwrap();
        let want = Allow { gpus: true, runtime_socket: true, binds: vec!["/x".into()], ..Default::default() };
        assert_eq!((m.allow.clone(), m.trust), (want, Trust::Full), "the rest kept");
        assert_eq!(merge(m.clone(), &p(json!({"allow": {}}))).unwrap(), m, "an empty patch");
        let lists = json!({"allow": {"binds_add": ["/a", "/x", "/a"], "binds_rm": ["/x", "/gone"], "local_env_add": ["TOKEN", "HOME", "TOKEN"]}});
        let l = merge(m.clone(), &p(lists)).unwrap();
        assert_eq!(l.allow.binds, [PathBuf::from("/a")]);
        assert_eq!(l.allow.local_env, ["TOKEN", "HOME"], "deduped");
        let l = merge(l, &p(json!({"allow": {"local_env_rm": ["TOKEN", "NOPE"]}}))).unwrap();
        assert_eq!(l.allow.local_env, ["HOME"]);
        let code = |v: Value| merge(start.clone(), &p(v)).unwrap_err().code;
        assert_eq!(code(json!({"allow": {"binds_add": ["rel"]}})), "invalid");
        for bad in ["", "A:B", "A}", "A=B"] {
            assert_eq!(code(json!({"allow": {"local_env_add": [bad]}})), "invalid", "{bad:?}");
        }
        // Unknown keys and the TOML's kebab names aren't the wire's.
        for bad in [json!({"allow": {"nope": true}}), json!({"allow": {"runtime-socket": true}}), json!({"allow": {"binds": ["/a"]}}), json!({"allow": {"gpus": "on"}})] {
            assert!(serde_json::from_value::<SetParams>(bad.clone()).is_err(), "{bad}");
        }
    }

    #[test]
    fn the_wire_matches_the_typings() {
        use crate::serve::dts::{assert_matches, prop_type, union_members};
        let key = crate::serve::fleet::identity::SigningKey::from_seed([1; 32]).public_key();
        let info = MemberInfo {
            name: Some("lap".into()),
            control_plane: Some("self".into()),
            trust: Trust::Full,
            dev_builds: true,
            roots: vec!["/srv/cfg".into()],
            allow: AllowInfo { gpus: true, local_env: vec!["TOKEN".into()], binds: vec!["/srv/x".into()], ..Default::default() },
            fingerprint: key.fingerprint(),
            key,
            next: Some(KeyInfo::of(&key)),
            exposed_by: Some(vec!["box".into(), "lap".into()]),
            pin_skipped: Some("dev build 0.9.0 (dev, abc) not pinned: it runs on linux/x86_64, the control plane on macos/aarch64".into()),
        };
        assert_matches("MemberInfo", &serde_json::to_value(&info).unwrap());
        assert_eq!(serde_json::to_value(&info).unwrap()["exposed_by"], json!(["box", "lap"]));
        assert_matches("MembershipKey", &serde_json::to_value(&info).unwrap()["next"]);
        assert_matches("MemberAllow", &serde_json::to_value(&info).unwrap()["allow"]);
        assert_matches("MemberInfo", &serde_json::to_value(MemberInfo { control_plane: None, ..info }).unwrap());
        assert_eq!(union_members("MemberTrust"), ["'worker'", "'full'"]);
        assert!(prop_type("ApiMethods", "member.get").is_some());
        assert!(prop_type("ApiMethods", "member.set").is_some());
    }

    #[test]
    fn get_and_set_go_through_the_file() {
        let dir = scratch("api");
        let path = dir.join("member.toml");
        let host = "lap.local";
        // Exposed while `worker`, as the daemon's graph would say.
        let exposure = |name: &str, trust: Trust| (trust == Trust::Worker).then(|| vec!["k".to_string(), name.to_string()]);
        let call = |method: &str, params: Value| super::call(method, params, &path, host, &exposure, Some("not pinned: x"));
        let mut got = call("member.get", Value::Null).unwrap().unwrap();
        assert!(!path.exists(), "a get writes no member.toml");
        // The first get makes the key; every answer says the same one.
        let key = FileKeyStore::new(key_path(&path)).public_key().unwrap();
        assert_eq!(key_path(&path), dir.join("member.key"));
        let key_fields = json!({"key": key.to_string(), "fingerprint": key.fingerprint()});
        for f in ["key", "fingerprint"] {
            assert_eq!(got.as_object_mut().unwrap().remove(f).unwrap(), key_fields[f], "{f}");
        }
        assert_eq!(
            got,
            json!({"name": "lap", "control_plane": null, "trust": "worker", "dev_builds": false, "roots": [], "next": null, "exposed_by": ["k", "lap"], "pin_skipped": "not pinned: x",
                "allow": {"privileged": false, "runtime_socket": false, "host_network": false, "global_services": false, "dispatcher": false,
                    "inbox": false, "initialize_command": false, "publish": false, "gpus": false, "local_env": [], "binds": []}})
        );
        // A pending rotation shows.
        let next = FileKeyStore::new(key_path(&path)).next_key().unwrap().public_key();
        let got = call("member.get", Value::Null).unwrap().unwrap();
        assert_eq!((&got["key"], &got["next"]), (&key_fields["key"], &json!({"key": next, "fingerprint": next.fingerprint()})));
        std::fs::remove_file(FileKeyStore::new(key_path(&path)).next_path()).unwrap();

        let set = call("member.set", json!({"trust": "full", "roots_add": ["/srv/cfg"]})).unwrap().unwrap();
        assert_eq!((&set["key"], &set["fingerprint"]), (&key_fields["key"], &key_fields["fingerprint"]));
        assert_eq!((&set["trust"], &set["roots"]), (&json!("full"), &json!(["/srv/cfg"])));
        assert_eq!(set["exposed_by"], Value::Null, "at the new trust");
        assert_eq!(load(&path).unwrap().unwrap().trust, Trust::Full, "written");
        assert!(dir.join("member.lock").exists(), "written through locked_file");

        let set = call("member.set", json!({"name": "box"}));
        assert_eq!(set.unwrap().unwrap()["name"], "box");
        let set = call("member.set", json!({"allow": {"gpus": true, "binds_add": ["/srv/x"]}})).unwrap().unwrap();
        assert_eq!((&set["allow"]["gpus"], &set["allow"]["binds"], &set["allow"]["publish"]), (&json!(true), &json!(["/srv/x"]), &json!(false)));
        // What the worker policy reads, on its next check.
        let (_, allow) = crate::worker_policy::load_member(&path).unwrap();
        assert_eq!(allow, Allow { gpus: true, binds: vec!["/srv/x".into()], ..Default::default() });
        assert_eq!(call("member.set", json!({"allow": {"gpus": 1}})).unwrap().unwrap_err().code, "invalid");
        assert_eq!(call("member.set", json!({"control_plane": "self"})).unwrap().unwrap_err().code, "invalid");
        // The log's control plane, written internally; the name pinned with it.
        set_fleet(&path, Some("box2"), &ControlPlane::This).unwrap();
        let m = load(&path).unwrap().unwrap();
        assert_eq!((m.control_plane(), m.name.as_str()), (ControlPlane::This, "box2"), "written");
        assert!(set_fleet(&path, Some("a/b"), &ControlPlane::None).is_err());
        set_fleet(&path, None, &ControlPlane::Other("k".into())).unwrap();
        assert_eq!(call("member.get", Value::Null).unwrap().unwrap()["control_plane"], "k");
        set_fleet(&path, Some("box"), &ControlPlane::None).unwrap();
        assert_eq!(load(&path).unwrap().unwrap().control_plane(), ControlPlane::None, "cleared");

        // Hand edits survive a set; a refused set changes nothing.
        update(&path, |m| m.dev_builds = true).unwrap();
        let bad = call("member.set", json!({"name": "a/b"}));
        assert_eq!(bad.unwrap().unwrap_err().code, "invalid");
        assert_eq!(call("member.set", json!({"nope": 1})).unwrap().unwrap_err().code, "invalid");
        let m = load(&path).unwrap().unwrap();
        assert_eq!((m.name.as_str(), m.dev_builds, m.trust), ("box", true, Trust::Full));
        assert!(call("member.nope", Value::Null).is_none());

        // A file that doesn't parse isn't overwritten.
        std::fs::write(&path, "trust = 1\n").unwrap();
        assert_eq!(call("member.get", Value::Null).unwrap().unwrap_err().code, "internal");
        assert!(call("member.set", json!({"trust": "worker"})).unwrap().is_err());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "trust = 1\n");
        let _ = std::fs::remove_dir_all(&dir);
    }
}