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
//! Which host opens a container's URL (docs/architecture/daemon/fleet.md,
//! *Opening URLs*): the instance's host's opener, routing each admitted
//! `open` record to where the user last attached from, and the receiving
//! member's `open.deliver` check.
//!
//! - **Sending** ([`opener`], the bridges' `bridge::Opener`): on a thread of
//!   its own, the record becomes an `open::OpenJob` (`open::prepare`: the
//!   profile to send), then [`route`] over the instance's latest attach
//!   (`serve::attaches`): this host ([`Route::Here`]) opens it with
//!   `open::open_here`; a member ([`Route::Member`]) gets `open.deliver`
//!   ([`DeliverParams`]). A failed delivery (the member's refusal included)
//!   is a `serve.log` line and a failed `opens.done` here, never a local
//!   open: the user is at that member, not here.
//! - **Feedback** ([`DoneParams`]): every open ends in one `opens.done`,
//!   from the host that knows: the bridges' sink for a refusal at intake,
//!   [`send`] for a failed delivery, `open::open_here` on the opening host
//!   for the rest. A receiver's refusal goes back to the sender as the
//!   call's error, so it is the sender's failed delivery.
//! - **Receiving** ([`receive`], the daemon's `open.deliver`, from a fleet
//!   peer only): strict params (`instance` an instance name), `open::decide`'s
//!   characters, scheme and limit again (per `(peer, instance)`; the TTL was
//!   the sender's), and only for an instance this host
//!   attached to itself on that peer within `open::OPEN_ATTACH_WINDOW`, so
//!   no member can drive this desktop by naming an instance it was never
//!   asked to open. Only the profile's *name* comes over: the command is
//!   this host's `profiles.toml`'s.

use std::path::PathBuf;
use std::sync::Arc;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use super::api::ApiError;
use super::attaches::Origin;
use super::forwards;
use crate::devsbd::bridge::Opener;
use crate::open::{self, ForwardTarget, Forwarder, Loopback, OnDone, OpenDone, OpenJob, Outcome};

/// Opens a job on this host (`open::open_here` on a thread of its own, in
/// production); a seam so the daemon's tests record the job instead.
pub type OpenHere = Arc<dyn Fn(OpenJob) + Send + Sync>;

/// `method` with `params` on fleet member `name`: its result, or why not.
pub type CallMember = Arc<dyn Fn(&str, &str, Value) -> Result<Value, String> + Send + Sync>;

/// `open.deliver`'s params: the instance by its current name and config
/// root on the sending host (the receiver's loopback forwards go into it),
/// the URL as the container gave it, and the profile name the sender chose
/// (`open::profile_to_send`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DeliverParams {
    pub instance: String,
    pub root: PathBuf,
    pub url: String,
    pub profile: Option<String>,
}

/// Where an instance's open goes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Route {
    Here,
    Member(String),
}

/// The last attach decides: none (none yet, or a member's that ended
/// `open::OPEN_ATTACH_WINDOW` ago or more: `Attaches::latest` drops it, as
/// that member would refuse the delivery), or this host's own, opens here;
/// a member's goes to that member.
pub fn route(latest: Option<Origin>) -> Route {
    match latest {
        None | Some(Origin::Here) => Route::Here,
        Some(Origin::Member(m)) => Route::Member(m),
    }
}

/// What the sending side runs on.
#[derive(Clone)]
pub struct Sender {
    /// `(instance, instance_id, url)` → the job (`open::prepare`).
    pub prepare: Arc<dyn Fn(&str, &str, &str) -> OpenJob + Send + Sync>,
    /// The latest attach to an instance id that still counts
    /// (`Attaches::latest` at the current time).
    pub latest: Arc<dyn Fn(&str) -> Option<Origin> + Send + Sync>,
    pub call_member: CallMember,
    pub open_here: OpenHere,
    /// Told of a failed delivery (`opens.done`).
    pub done: OnDone,
    pub log: fn(&str),
}

/// `opens.done`'s params: an [`OpenDone`] on the wire, `line` so clients
/// show it without composing text (like `inbox.shown`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DoneParams {
    pub instance: String,
    pub url: String,
    pub profile: Option<String>,
    /// `opened`, `refused` or `failed`.
    pub outcome: &'static str,
    pub why: Option<String>,
    pub line: String,
}

impl DoneParams {
    pub fn new(done: &OpenDone) -> DoneParams {
        DoneParams {
            instance: done.instance.clone(),
            url: done.url.clone(),
            profile: done.profile.clone(),
            outcome: done.kind(),
            why: done.why(),
            line: done.line(),
        }
    }
}

fn failed(instance: &str, url: &str, profile: Option<String>, why: String) -> OpenDone {
    OpenDone { instance: instance.to_string(), url: url.to_string(), profile, outcome: Outcome::Failed(why) }
}

/// The bridges' opener: [`send`] on a thread of its own per record, so the
/// bridge's handler never waits on state, a link or a browser.
pub fn opener(sender: Sender) -> Opener {
    Arc::new(move |instance: &str, instance_id: &str, url: &str| {
        let (log, done) = (sender.log, Arc::clone(&sender.done));
        let (s, i, id, u) = (sender.clone(), instance.to_string(), instance_id.to_string(), url.to_string());
        let spawned = std::thread::Builder::new().name("serve-open".into()).spawn(move || send(&s, &i, &id, &u));
        if let Err(e) = spawned {
            log(&format!("cannot start an open's thread: {e}"));
            done(failed(instance, url, None, format!("cannot start an open's thread: {e}")));
        }
    })
}

/// One admitted `open` record from `instance` (`instance_id`): prepared,
/// routed, opened here or delivered (a failed delivery told to `done`).
pub fn send(s: &Sender, instance: &str, instance_id: &str, url: &str) {
    let job = (s.prepare)(instance, instance_id, url);
    match route((s.latest)(instance_id)) {
        Route::Here => (s.open_here)(job),
        Route::Member(m) => {
            let delivered = deliver_params(&job).and_then(|p| {
                let params = serde_json::to_value(p).map_err(|e| e.to_string())?;
                (s.call_member)(&m, "open.deliver", params)
            });
            if let Err(why) = delivered {
                // The member's error is its own text: one line here.
                let why = open::printable(&why);
                (s.log)(&format!("{instance}: cannot deliver {url} to {m}: {why}"));
                (s.done)(failed(instance, url, job.profile, format!("cannot deliver to {m}: {why}")));
            }
        }
    }
}

/// `open.deliver`'s params for `job` (its target is the local instance:
/// its state key and config root), or why it can't go.
fn deliver_params(job: &OpenJob) -> Result<DeliverParams, String> {
    let target = job.target.as_ref().map_err(Clone::clone)?;
    Ok(DeliverParams { instance: target.instance.clone(), root: target.dir.clone(), url: job.url.clone(), profile: job.profile.clone() })
}

/// The longest `open.deliver` URL taken: an `open` record's own cap.
const MAX_URL: usize = crate::devsbd::notify::MAX_RECORD;

/// The longest instance name taken.
const MAX_INSTANCE: usize = 256;

/// The longest profile name taken.
const MAX_PROFILE: usize = 64;

/// Whether `name` can be an instance name in `open.deliver`: ASCII
/// `[A-Za-z0-9][A-Za-z0-9_.-]*` (what `run` names instances; a rename that
/// strays outside it can't open on another member). It ends up in this
/// host's log and status lines.
fn valid_instance(name: &str) -> bool {
    let mut chars = name.chars();
    chars.next().is_some_and(|c| c.is_ascii_alphanumeric())
        && chars.all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c))
}

/// `open.deliver` `params` from fleet peer `peer`, checked in order: the
/// params (strict: a `machine` or any other key is refused; `instance` an
/// instance name, [`valid_instance`]; a URL with no control character or
/// whitespace), `attached` (whether this host attached to `instance` on
/// `peer` within the window), then `open::decide` at `now` (unix seconds)
/// for its scheme and `limit` (spends this `(peer, instance)`'s token): the
/// TTL was the sender's, so `now` is the record's time too. The job to open
/// here: `instance` as `peer` named it and its root there as the forward
/// target.
pub fn receive(
    params: Value,
    peer: &str,
    now: u64,
    limit: impl FnOnce(&str) -> bool,
    attached: impl FnOnce(&str) -> bool,
) -> Result<OpenJob, ApiError> {
    let p: DeliverParams = super::api::parse(params)?;
    if p.instance.is_empty() || p.instance.len() > MAX_INSTANCE {
        return Err(ApiError::invalid(format!("`instance`: 1 to {MAX_INSTANCE} bytes")));
    }
    if !valid_instance(&p.instance) {
        return Err(ApiError::invalid(format!("`instance`: not an instance name: {}", open::printable(&p.instance))));
    }
    if p.url.len() > MAX_URL {
        return Err(ApiError::invalid(format!("`url`: at most {MAX_URL} bytes")));
    }
    // Before `attached`, whose refusal quotes the URL.
    if open::has_bad_chars(&p.url) {
        return Err(ApiError::invalid(open::Verdict::BadChars.log_line(&p.instance, &p.url).unwrap_or_default()));
    }
    if !p.root.is_absolute() {
        return Err(ApiError::invalid(format!("`root` must be absolute: {}", p.root.display())));
    }
    if let Some(profile) = &p.profile {
        if profile.len() > MAX_PROFILE {
            return Err(ApiError::invalid(format!("`profile`: at most {MAX_PROFILE} bytes")));
        }
        crate::config::check_profile_name(profile).map_err(|e| ApiError::invalid(format!("{e:#}")))?;
    }
    // Before the policy: a request for an instance this host never asked
    // about spends none of that instance's limit.
    if !attached(&p.instance) {
        return Err(ApiError::denied(format!(
            "`{peer}` asked to open {} for `{}`, which this host hasn't attached to in the last {} min",
            p.url,
            p.instance,
            open::OPEN_ATTACH_WINDOW.as_secs() / 60
        )));
    }
    let verdict = open::decide(&p.url, now, now, || limit(&p.instance));
    if let Some(line) = verdict.log_line(&p.instance, &p.url) {
        let code = if matches!(verdict, open::Verdict::BadScheme(_) | open::Verdict::BadChars) { "invalid" } else { "denied" };
        return Err(ApiError { code, message: line });
    }
    let target = ForwardTarget { machine: Some(peer.to_string()), dir: p.root, instance: p.instance.clone() };
    Ok(OpenJob { instance: p.instance, url: p.url, profile: p.profile, target: Ok(target) })
}

/// The opener's [`Forwarder`]: the registry's open forwards
/// (`forwards::Handle::open_forward`), an instance on another member's
/// `machine` handed through. A callback port the registry couldn't bind is
/// `Err(None)`: its status line already said which port blocked it.
pub fn forwarder(forwards: Option<forwards::Handle>) -> Forwarder {
    Arc::new(move |target: &ForwardTarget, lb: Loopback| {
        let Some(forwards) = &forwards else { return Err(Some("no forwards registry in this daemon".into())) };
        let req = forwards::OpenRequest {
            machine: target.machine.clone(),
            dir: target.dir.clone(),
            instance: target.instance.clone(),
            container_port: lb.port,
            callback: lb.callback,
        };
        forwards
            .open_forward(req)
            .map(|o| o.host_port)
            .map_err(|e| (!(lb.callback && e.code == "bind-failed")).then_some(e.message))
    })
}

/// The production [`OpenHere`]: `open::open_here` through `forward`, on a
/// thread of its own, its outcome told to `done`.
pub fn open_here(forward: Forwarder, log: fn(&str), done: OnDone) -> OpenHere {
    Arc::new(move |job: OpenJob| {
        let (forward, d) = (Arc::clone(&forward), Arc::clone(&done));
        let (instance, url, profile) = (job.instance.clone(), job.url.clone(), job.profile.clone());
        let spawned = std::thread::Builder::new().name("serve-open".into()).spawn(move || open::open_here(job, &forward, log, &d));
        if let Err(e) = spawned {
            log(&format!("cannot start an open's thread: {e}"));
            done(failed(&instance, &url, profile, format!("cannot start an open's thread: {e}")));
        }
    })
}

#[cfg(test)]
mod tests {
    use std::sync::Mutex;

    use serde_json::json;

    use super::*;

    #[test]
    fn the_last_attach_decides() {
        assert_eq!(route(None), Route::Here, "nothing attached yet");
        assert_eq!(route(Some(Origin::Here)), Route::Here);
        assert_eq!(route(Some(Origin::Member("lap".into()))), Route::Member("lap".into()));
    }

    fn job(target: Result<ForwardTarget, String>) -> OpenJob {
        OpenJob { instance: "web-1".into(), url: "http://localhost:3000/".into(), profile: Some("work".into()), target }
    }

    fn local() -> ForwardTarget {
        ForwardTarget { machine: None, dir: "/cfg".into(), instance: "web-1".into() }
    }

    type Calls = Arc<Mutex<Vec<(String, String, Value)>>>;

    type Dones = Arc<Mutex<Vec<OpenDone>>>;

    /// A sender over fakes: `latest` is the instance's latest attach,
    /// `answer` every member call's. Records the calls, the local opens and
    /// the outcomes told; log lines go to `LINES`.
    fn sender(
        target: Result<ForwardTarget, String>,
        latest: Option<Origin>,
        answer: Result<Value, String>,
    ) -> (Sender, Calls, Arc<Mutex<Vec<OpenJob>>>, Dones) {
        let (calls, opened, dones): (Calls, Arc<Mutex<Vec<OpenJob>>>, Dones) = Default::default();
        let (c, o, d) = (Arc::clone(&calls), Arc::clone(&opened), Arc::clone(&dones));
        let s = Sender {
            prepare: Arc::new(move |_, _, _| job(target.clone())),
            latest: Arc::new(move |id| {
                assert_eq!(id, "id-1");
                latest.clone()
            }),
            call_member: Arc::new(move |m, method, params| {
                c.lock().unwrap().push((m.into(), method.into(), params));
                answer.clone()
            }),
            open_here: Arc::new(move |j| o.lock().unwrap().push(j)),
            done: Arc::new(move |done| d.lock().unwrap().push(done)),
            log: record,
        };
        (s, calls, opened, dones)
    }

    static LINES: Mutex<Vec<String>> = Mutex::new(Vec::new());

    fn record(line: &str) {
        LINES.lock().unwrap().push(line.to_string());
    }

    fn logged(needle: &str) -> bool {
        LINES.lock().unwrap().iter().any(|l| l.contains(needle))
    }

    #[test]
    fn an_open_with_no_member_attach_opens_here() {
        for latest in [None, Some(Origin::Here)] {
            let (s, calls, opened, dones) = sender(Ok(local()), latest, Ok(json!({"ok": true})));
            send(&s, "web-1", "id-1", "http://localhost:3000/");
            assert_eq!(*opened.lock().unwrap(), vec![job(Ok(local()))]);
            assert!(calls.lock().unwrap().is_empty());
            assert!(dones.lock().unwrap().is_empty(), "`open_here` tells its own");
        }
    }

    #[test]
    fn an_open_after_a_member_attach_is_delivered_there() {
        let (s, calls, opened, dones) = sender(Ok(local()), Some(Origin::Member("lap".into())), Ok(json!({"ok": true})));
        send(&s, "web-1", "id-1", "http://localhost:3000/");
        let want = json!({"instance": "web-1", "root": "/cfg", "url": "http://localhost:3000/", "profile": "work"});
        assert_eq!(*calls.lock().unwrap(), vec![("lap".to_string(), "open.deliver".to_string(), want)]);
        assert!(opened.lock().unwrap().is_empty());
        assert!(dones.lock().unwrap().is_empty(), "taken: the member tells its own");
    }

    #[test]
    fn a_failed_delivery_is_logged_and_never_opens_here() {
        let (s, _, opened, dones) =
            sender(Ok(local()), Some(Origin::Member("lap".into())), Err("open.deliver: nope (denied)".into()));
        send(&s, "web-1", "id-1", "https://a.example/");
        assert!(logged("web-1: cannot deliver https://a.example/ to lap: open.deliver: nope (denied)"));
        assert!(opened.lock().unwrap().is_empty(), "no fallback");
        let told = dones.lock().unwrap().clone();
        assert_eq!(
            told,
            vec![OpenDone {
                instance: "web-1".into(),
                url: "https://a.example/".into(),
                profile: Some("work".into()),
                outcome: Outcome::Failed("cannot deliver to lap: open.deliver: nope (denied)".into()),
            }]
        );
        assert_eq!(told[0].line(), "web-1: open failed: cannot deliver to lap: open.deliver: nope (denied)");

        let (s, calls, opened, dones) = sender(Err("not in state.toml".into()), Some(Origin::Member("lap".into())), Ok(json!({})));
        send(&s, "gone", "id-1", "https://b.example/");
        assert!(logged("gone: cannot deliver https://b.example/ to lap: not in state.toml"));
        assert!(calls.lock().unwrap().is_empty() && opened.lock().unwrap().is_empty());
        assert_eq!(dones.lock().unwrap()[0].line(), "gone: open failed: cannot deliver to lap: not in state.toml");
    }

    fn params() -> Value {
        json!({"instance": "web-1", "root": "/home/u/cfg", "url": "http://localhost:3000/", "profile": "work"})
    }

    fn with_none() -> Value {
        Value::Null
    }

    fn take(params: Value) -> Result<OpenJob, ApiError> {
        receive(params, "box", 1_790_000_000, |_| true, |i| i == "web-1")
    }

    #[test]
    fn a_delivery_for_an_attached_instance_is_taken() {
        let target = ForwardTarget { machine: Some("box".into()), dir: "/home/u/cfg".into(), instance: "web-1".into() };
        assert_eq!(
            take(params()).unwrap(),
            OpenJob {
                instance: "web-1".into(),
                url: "http://localhost:3000/".into(),
                profile: Some("work".into()),
                target: Ok(target)
            }
        );
        let mut p = params();
        p["profile"] = Value::Null;
        assert_eq!(take(p).unwrap().profile, None);
    }

    #[test]
    fn a_delivery_is_checked_in_order() {
        let code = |p: Value| take(p).unwrap_err().code;
        assert_eq!(code(with_none()), "invalid", "no params");
        let with = |k: &str, v: Value| {
            let mut p = params();
            p[k] = v;
            p
        };
        assert_eq!(code(with("machine", json!("lap"))), "invalid", "strict: no `machine`");
        assert_eq!(code(with("extra", json!(1))), "invalid");
        assert_eq!(code(json!({"instance": "web-1"})), "invalid");
        assert_eq!(code(with("instance", json!(""))), "invalid");
        assert_eq!(code(with("root", json!("rel"))), "invalid");
        assert_eq!(code(with("profile", json!("Work Profile"))), "invalid");
        assert_eq!(code(with("profile", json!("x".repeat(65)))), "invalid");
        assert_eq!(code(with("url", json!(format!("https://x/{}", "a".repeat(MAX_URL))))), "invalid");
        let e = take(with("url", json!("ssh://x"))).unwrap_err();
        assert_eq!((e.code, e.message.as_str()), ("invalid", "web-1: open refused, scheme `ssh` (http and https only): ssh://x"));
        let e = receive(params(), "box", 1, |_| false, |_| true).unwrap_err();
        assert_eq!(e.code, "denied", "rate-limited: {}", e.message);
        let e = take(with("instance", json!("web-2"))).unwrap_err();
        assert_eq!(
            (e.code, e.message.as_str()),
            ("denied", "`box` asked to open http://localhost:3000/ for `web-2`, which this host hasn't attached to in the last 10 min")
        );
        // The limit isn't spent on a refused scheme, nor on an instance
        // never attached to.
        receive(with("url", json!("ssh://x")), "box", 1, |_| panic!("not asked"), |_| true).unwrap_err();
        receive(params(), "box", 1, |_| panic!("not asked"), |_| false).unwrap_err();
    }

    #[test]
    fn a_delivery_takes_only_an_instance_name_and_a_clean_url() {
        let with = |k: &str, v: Value| {
            let mut p = params();
            p[k] = v;
            p
        };
        for name in ["web 1", "-web", ".web", "_web", "web\n1", "wéb", "web/1", "web\u{1b}[2J"] {
            let e = take(with("instance", json!(name))).unwrap_err();
            assert_eq!(e.code, "invalid", "{name:?}");
            assert!(!e.message.contains(['\n', '\u{1b}']), "{:?}", e.message);
        }
        for name in ["web-1", "Web_2.x", "9"] {
            let e = receive(with("instance", json!(name)), "box", 1_790_000_000, |_| true, |_| false).unwrap_err();
            assert_eq!(e.code, "denied", "{name}: a name, just not attached");
        }
        // A URL with a control character: refused before `attached`, whose
        // refusal would quote it, and escaped in the message.
        let e = receive(with("url", json!("https://x/\r\nweb-1: opened")), "box", 1, |_| panic!("not asked"), |_| panic!("not asked"))
            .unwrap_err();
        assert_eq!(
            (e.code, e.message.as_str()),
            ("invalid", "web-1: open refused, control characters or whitespace in the URL: https://x/\\r\\nweb-1: opened")
        );
        assert_eq!(take(with("url", json!("https://x/a b"))).unwrap_err().code, "invalid");
    }

    #[test]
    fn a_members_error_is_one_line_here() {
        let (s, _, _, dones) = sender(Ok(local()), Some(Origin::Member("lap".into())), Err("nope\nweb-1: opened https://evil".into()));
        send(&s, "web-1", "id-1", "https://c.example/");
        assert!(logged("web-1: cannot deliver https://c.example/ to lap: nope\\nweb-1: opened https://evil"));
        assert!(!dones.lock().unwrap()[0].line().contains('\n'));
    }
}