summaryrefslogtreecommitdiffstats
path: root/src/config.rs
blob: 7818e4b4a880159963fdafafd07970c8772cbf65 (plain)
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
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

/// The image a build runs in when the config does not say. Only this module
/// resolves it, so it is not part of the crate's interface.
const DEFAULT_SANDBOX_IMAGE: &str = "aur-build-sandbox:latest";

#[derive(Clone, Default, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)]
pub enum Sandbox {
    #[default]
    Loopback,
    Remote {
        listen: String,
        /// Rendezvous secret. Deploy it like a credential.
        token: String,
        #[serde(default)]
        shared_workspace: bool,
    },
    AgentSandbox {
        api: String,
        namespace: String,
        /// Never logged.
        bearer: String,
        image: String,
        listen: String,
        token: String,
        #[serde(default)]
        shared_workspace: bool,
    },
}

impl std::fmt::Debug for Sandbox {
    // Hand-written so the rendezvous token and cluster bearer cannot ride into
    // a log line, a panic message, or an audit payload.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Sandbox::Loopback => f.write_str("Sandbox::Loopback"),
            Sandbox::Remote { listen, shared_workspace, .. } => f
                .debug_struct("Sandbox::Remote")
                .field("listen", listen)
                .field("shared_workspace", shared_workspace)
                .field("token", &"[redacted]")
                .finish(),
            Sandbox::AgentSandbox { api, namespace, image, listen, shared_workspace, .. } => f
                .debug_struct("Sandbox::AgentSandbox")
                .field("api", api)
                .field("namespace", namespace)
                .field("image", image)
                .field("listen", listen)
                .field("shared_workspace", shared_workspace)
                .field("token", &"[redacted]")
                .field("bearer", &"[redacted]")
                .finish(),
        }
    }
}

impl Sandbox {
    pub fn kind(&self) -> &'static str {
        match self {
            Sandbox::Loopback => "loopback",
            Sandbox::Remote { .. } => "remote",
            Sandbox::AgentSandbox { .. } => "agent-sandbox",
        }
    }

    pub fn listen(&self) -> Option<&str> {
        match self {
            Sandbox::Remote { listen, .. } => Some(listen),
            Sandbox::AgentSandbox { listen, .. } => Some(listen),
            Sandbox::Loopback => None,
        }
    }

    /// Never log this.
    pub fn token(&self) -> Option<&str> {
        match self {
            Sandbox::Remote { token, .. } => Some(token),
            Sandbox::AgentSandbox { token, .. } => Some(token),
            Sandbox::Loopback => None,
        }
    }

    pub fn image(&self) -> Option<&str> {
        match self {
            Sandbox::AgentSandbox { image, .. } => Some(image),
            _ => None,
        }
    }

    /// Validation consults it; the fixture-bound tests that assert it are the only outside readers.
    ///
    /// Module-internal in a production build, `pub` only under `test-support`:
    /// one body behind two visibility declarations, exactly one of which compiles.
    #[cfg(feature = "test-support")]
    pub fn shared_workspace(&self) -> bool {
        Self::shared_workspace_impl(self)
    }

    #[cfg(not(feature = "test-support"))]
    fn shared_workspace(&self) -> bool {
        Self::shared_workspace_impl(self)
    }

    fn shared_workspace_impl(&self) -> bool {
        match self {
            Sandbox::Loopback => true,
            Sandbox::Remote { shared_workspace, .. } => *shared_workspace,
            Sandbox::AgentSandbox { shared_workspace, .. } => *shared_workspace,
        }
    }

    /// The accepted values, so a test can assert that an unknown kind names
    /// the whole valid set rather than one example of it. Serde builds the
    /// rejection message itself, so nothing in production reads this list.
    #[cfg(test)]
    const KINDS: [&'static str; 3] = ["loopback", "remote", "agent-sandbox"];
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
    pub root: PathBuf,
    pub repo_name: String,
    pub arch: String,
    pub signing_key_id: String,
    pub bind: String,
    pub password: String,
    pub base_url: String,
    pub build_profile: String,
    pub makepkg_bin: String,
    pub pacman_bin: String,
    pub repo_add_bin: String,
    pub gpg_bin: String,
    pub sandbox: Sandbox,
    #[cfg(feature = "test-support")]
    #[serde(default, skip_serializing_if = "TestHooks::is_empty")]
    pub hooks: TestHooks,
    pub max_concurrent_builds: usize,
    pub lease_secs: i64,
    pub min_free_disk_mb: u64,
    pub max_transient_attempts: i64,
    pub dispatch_tick_secs: u64,
}

/// Test-tier only, and already half-gated: the `hooks` field that holds one and
/// the `Default` line that fills it are both behind `test-support`, so without
/// the gate below this type compiles into a release binary that can never
/// construct, read, or deserialize it.
#[cfg(feature = "test-support")]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct TestHooks {
    pub path_prepend: Option<PathBuf>,
    pub shim_manifest: Option<PathBuf>,
    pub shim_dir: Option<PathBuf>,
    pub publish_fault: Option<String>,
    pub shim_fail: Option<String>,
    pub shim_kill_parent: Option<String>,
    pub shim_plant_link: Option<String>,
}

#[cfg(feature = "test-support")]
impl TestHooks {
    pub fn is_empty(&self) -> bool {
        self.path_prepend.is_none()
            && self.shim_manifest.is_none()
            && self.shim_dir.is_none()
            && self.publish_fault.is_none()
            && self.shim_fail.is_none()
            && self.shim_kill_parent.is_none()
            && self.shim_plant_link.is_none()
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            root: PathBuf::from("/var/lib/aur-build"),
            repo_name: "aur-build".into(),
            arch: "x86_64".into(),
            signing_key_id: String::new(),
            bind: "127.0.0.1:8484".into(),
            password: String::new(),
            base_url: "http://127.0.0.1:8484".into(),
            build_profile: "extra-x86_64".into(),
            makepkg_bin: "makepkg".into(),
            pacman_bin: "pacman".into(),
            repo_add_bin: "repo-add".into(),
            gpg_bin: "gpg".into(),
            sandbox: Sandbox::default(),
            #[cfg(feature = "test-support")]
            hooks: TestHooks::default(),
            max_concurrent_builds: 1,
            lease_secs: 90,
            min_free_disk_mb: 1024,
            max_transient_attempts: 3,
            dispatch_tick_secs: 2,
        }
    }
}

impl Config {
    pub fn sandbox_image(&self) -> String {
        self.sandbox
            .image()
            .unwrap_or(DEFAULT_SANDBOX_IMAGE)
            .to_string()
    }

    pub fn validate(&self) -> crate::error::Result<()> {
        let require = |field: &str, value: &str| -> crate::error::Result<()> {
            if value.trim().is_empty() {
                return Err(crate::error::Error::invalid(format!(
                    "sandbox kind \"{}\" needs a non-empty \"{field}\"",
                    self.sandbox.kind()
                )));
            }
            Ok(())
        };
        match &self.sandbox {
            Sandbox::Loopback => {}
            Sandbox::Remote { listen, token, .. } => {
                require("listen", listen)?;
                require("token", token)?;
            }
            Sandbox::AgentSandbox { api, namespace, bearer, image, listen, token, .. } => {
                for (field, value) in [
                    ("api", api),
                    ("namespace", namespace),
                    ("bearer", bearer),
                    ("image", image),
                    ("listen", listen),
                    ("token", token),
                ] {
                    require(field, value)?;
                }
            }
        }
        if self.sandbox.shared_workspace() {
            return Ok(());
        }
        Err(crate::error::Error::invalid(format!(
            concat!(
                "sandbox kind \"{}\" was not told that hub and sandbox share a filesystem: ",
                "set \"shared_workspace\": true in the sandbox object. The build workspace is ",
                "not shipped to a remote sandbox — `Run` frames carry a hub-side working ",
                "directory — so a remote build only works where the staging directory is ",
                "visible at the same path on both sides. Asserting it here is what keeps a ",
                "remote configuration from silently building on the hub it was meant to leave."
            ),
            self.sandbox.kind()
        )))
    }

    pub fn load(root: &Path) -> crate::error::Result<Self> {
        let dir = absolute(root)?;
        let p = dir.join("config.json");
        if !p.exists() {
            return Err(crate::error::Error::not_found(format!(
                "no config at {}; run `aur-build init`",
                p.display()
            )));
        }
        let s = std::fs::read_to_string(&p)?;
        let v: serde_json::Value = serde_json::from_str(&s)?;
        check_retired_sandbox_keys(&v)?;
        let mut cfg: Config = serde_json::from_value(v)?;
        cfg.root = dir;
        Ok(cfg)
    }

    pub fn save(&self) -> crate::error::Result<()> {
        std::fs::create_dir_all(&self.root)?;
        let mut out = self.clone();
        out.root = absolute(&self.root)?;
        std::fs::write(
            self.root.join("config.json"),
            serde_json::to_string_pretty(&out)? + "\n",
        )?;
        Ok(())
    }

    // Everything this assembles comes from the `test-support`-gated `hooks`
    // field, so in a release build the argument and the vector are both unused.
    #[cfg_attr(not(feature = "test-support"), allow(unused_variables))]
    pub fn child_env_pairs(&self) -> Vec<(String, String)> {
        #[cfg_attr(not(feature = "test-support"), allow(unused_mut))]
        let mut pairs = Vec::new();
        #[cfg(feature = "test-support")]
        {
            let h = &self.hooks;
            if let Some(dir) = &h.path_prepend {
                let path = std::env::var("PATH").unwrap_or_default();
                pairs.push(("PATH".to_string(), format!("{}:{path}", dir.display())));
            }
            if let Some(m) = &h.shim_manifest {
                pairs.push(("AUR_SHIM_MANIFEST".to_string(), m.display().to_string()));
            }
            if let Some(d) = &h.shim_dir {
                pairs.push(("AUR_SHIM_DIR".to_string(), d.display().to_string()));
            }
            if let Some(f) = &h.shim_fail {
                pairs.push(("AUR_SHIM_FAIL".to_string(), f.clone()));
            }
            if let Some(k) = &h.shim_kill_parent {
                pairs.push(("AUR_SHIM_KILL_PARENT".to_string(), k.clone()));
            }
            if let Some(l) = &h.shim_plant_link {
                pairs.push(("AUR_SHIM_PLANT_LINK".to_string(), l.clone()));
            }
        }
        pairs
    }

    pub fn child_env(&self, cmd: &mut std::process::Command) {
        for (k, v) in self.child_env_pairs() {
            cmd.env(k, v);
        }
    }

    pub fn ensure_dirs(&self) -> crate::error::Result<()> {
        for d in [
            self.root.clone(),
            self.mirrors_dir(),
            self.vcs_cache_dir(),
            self.source_cache_dir(),
            self.staging_dir(),
            self.store_dir(),
            self.log_dir(),
            self.repo_dir(),
        ] {
            std::fs::create_dir_all(d)?;
        }
        std::fs::create_dir_all(self.repo_arch_dir())?;
        Ok(())
    }

    pub fn db_path(&self) -> PathBuf {
        self.root.join("aur-build.db")
    }
    fn mirrors_dir(&self) -> PathBuf {
        self.root.join("mirrors")
    }
    pub fn mirror_path(&self, pkgbase: &str) -> PathBuf {
        self.mirrors_dir().join(format!("{pkgbase}.git"))
    }
    pub fn vcs_cache_dir(&self) -> PathBuf {
        self.root.join("vcs_cache")
    }
    pub fn vcs_cache_path(&self, url: &str) -> PathBuf {
        let h = crate::hash::short(url.as_bytes(), 16);
        self.vcs_cache_dir().join(format!("{}-{}.git", slug(url), h))
    }
    pub fn source_cache_dir(&self) -> PathBuf {
        self.root.join("source_cache")
    }
    pub fn source_cache_path(&self, digest: &str) -> PathBuf {
        self.source_cache_dir().join(&digest[..2.min(digest.len())]).join(digest)
    }
    pub fn staging_dir(&self) -> PathBuf {
        self.root.join("staging")
    }
    pub fn staging_build_dir(&self, build_id: &str) -> PathBuf {
        self.staging_dir().join(build_id)
    }
    /// The content-addressed store layout is this module's own business; a test pins where a blob lands.
    ///
    /// Module-internal in a production build, `pub` only under `test-support`:
    /// one body behind two visibility declarations, exactly one of which compiles.
    #[cfg(feature = "test-support")]
    pub fn store_dir(&self) -> PathBuf {
        Self::store_dir_impl(self)
    }

    #[cfg(not(feature = "test-support"))]
    fn store_dir(&self) -> PathBuf {
        Self::store_dir_impl(self)
    }

    fn store_dir_impl(&self) -> PathBuf {
        self.root.join("store")
    }
    pub fn store_path(&self, digest: &str) -> PathBuf {
        self.store_dir().join(&digest[..2.min(digest.len())]).join(digest)
    }
    fn log_dir(&self) -> PathBuf {
        self.root.join("logs")
    }
    pub fn build_log_path(&self, build_id: &str) -> PathBuf {
        self.log_dir().join(format!("{build_id}.log"))
    }
    fn repo_dir(&self) -> PathBuf {
        self.root.join("repo")
    }
    pub fn repo_arch_dir(&self) -> PathBuf {
        self.repo_dir()
            .join(&self.repo_name)
            .join("os")
            .join(&self.arch)
    }
    pub fn repo_db_name(&self) -> String {
        format!("{}.db", self.repo_name)
    }
}

fn retired_key_is_inert(key: &str, value: &str) -> bool {
    match key {
        "sandbox_backend" => value == "loopback",
        "sandbox_image" => value.is_empty() || value == DEFAULT_SANDBOX_IMAGE,
        _ => value.is_empty(),
    }
}

fn check_retired_sandbox_keys(v: &serde_json::Value) -> crate::error::Result<()> {
    const RETIRED: [&str; 4] = ["sandbox_backend", "agent_listen", "agent_token", "sandbox_image"];
    let named: Vec<String> = RETIRED
        .iter()
        .filter(|k| {
        let key: &str = k;
        match v.get(key) {
            None => false,
            Some(serde_json::Value::String(s)) => !retired_key_is_inert(key, s),
            Some(_) => true,
        }
        })
        .map(|k| format!("\"{k}\""))
        .collect();
    if named.is_empty() {
        return Ok(());
    }
    let example = concat!(
        "replace them with a single \"sandbox\" object: ",
        "{\"kind\":\"loopback\"}, ",
        "{\"kind\":\"remote\",\"listen\":…,\"token\":…}, or ",
        "{\"kind\":\"agent-sandbox\",\"api\":…,\"namespace\":…,\"bearer\":…,\"image\":…,\"listen\":…,\"token\":…}"
    );
    Err(crate::error::Error::invalid(format!(
        "{} are retired sandbox keys; {example}",
        named.join(", ")
    )))
}

fn absolute(p: &Path) -> crate::error::Result<PathBuf> {
    Ok(std::path::absolute(p)?)
}

fn slug(url: &str) -> String {
    url.chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() {
                c.to_ascii_lowercase()
            } else {
                '-'
            }
        })
        .collect::<String>()
        .trim_matches('-')
        .chars()
        .take(32)
        .collect()
}
#[cfg(test)]
mod tests {
    use super::*;

    // `Config::load` takes a directory, so parsing a config means having a file
    // on disk somewhere. The tempdir below is plumbing for that signature, not
    // something these tests are about: none of them touches the database, the
    // fixture corpus, or a subprocess.
    fn load_sandbox(sandbox: &str) -> Result<Config, String> {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(
            tmp.path().join("config.json"),
            format!("{{\n  \"sandbox\": {sandbox}\n}}\n"),
        )
        .unwrap();
        Config::load(tmp.path()).map_err(|e| e.to_string())
    }

    fn load_raw(body: &str) -> Result<Config, String> {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("config.json"), body).unwrap();
        Config::load(tmp.path()).map_err(|e| e.to_string())
    }

    // Moved verbatim from tests/config.rs: these eleven exercise parsing,
    // validation and Debug redaction of the config itself.

    #[test]
    fn each_sandbox_kind_parses_with_its_required_fields() {
        match load_sandbox(r#"{"kind":"loopback"}"#).unwrap().sandbox {
            Sandbox::Loopback => {}
            other => panic!("expected loopback, got {other:?}"),
        }

        let remote = load_sandbox(
            r#"{"kind":"remote","listen":"127.0.0.1:8787","token":"s3cr3t"}"#,
        )
        .unwrap();
        match &remote.sandbox {
            Sandbox::Remote { listen, token, shared_workspace } => {
                assert_eq!(listen, "127.0.0.1:8787");
                assert_eq!(token, "s3cr3t");
                assert!(!*shared_workspace, "sharing the filesystem is asserted, never assumed");
            }
            other => panic!("expected remote, got {other:?}"),
        }

        let abs = load_sandbox(
            r#"{"kind":"agent-sandbox","api":"https://k8s:6443","namespace":"builds",
                 "bearer":"kube-token","image":"aur-build-sandbox:latest",
                 "listen":"0.0.0.0:8787","token":"s3cr3t","shared_workspace":true}"#,
        )
        .unwrap();
        match &abs.sandbox {
            Sandbox::AgentSandbox { api, namespace, bearer, image, .. } => {
                assert_eq!(api, "https://k8s:6443");
                assert_eq!(namespace, "builds");
                assert_eq!(bearer, "kube-token");
                assert_eq!(image, "aur-build-sandbox:latest");
            }
            other => panic!("expected agent-sandbox, got {other:?}"),
        }
        assert_eq!(abs.sandbox_image(), "aur-build-sandbox:latest");
    }

    #[test]
    fn a_missing_required_field_names_the_field() {
        let err = load_sandbox(r#"{"kind":"remote","listen":"127.0.0.1:8787"}"#).unwrap_err();
        assert!(err.contains("token"), "the error must name the missing field: {err}");

        let err = load_sandbox(r#"{"kind":"remote","token":"t"}"#).unwrap_err();
        assert!(err.contains("listen"), "the error must name the missing field: {err}");

        for missing in ["api", "namespace", "bearer", "image", "listen", "token"] {
            let mut fields = vec![
                r#""api":"https://k8s:6443""#.to_string(),
                r#""namespace":"builds""#.to_string(),
                r#""bearer":"kube""#.to_string(),
                r#""image":"img""#.to_string(),
                r#""listen":"0.0.0.0:1""#.to_string(),
                r#""token":"t""#.to_string(),
            ];
            fields.retain(|f| !f.starts_with(&format!("\"{missing}\"")));
            let err = load_sandbox(&format!("{{\"kind\":\"agent-sandbox\",{}}}", fields.join(",")))
                .unwrap_err();
            assert!(err.contains(missing), "dropping {missing} must name it: {err}");
        }
    }

    #[test]
    fn a_misspelled_field_is_refused_not_ignored() {
        let err = load_sandbox(r#"{"kind":"remote","listn":"127.0.0.1:1","token":"t"}"#).unwrap_err();
        assert!(err.contains("listn"), "a typo'd field name must be named: {err}");
    }

    #[test]
    fn an_unknown_kind_names_the_value_and_the_valid_set() {
        let err = load_sandbox(r#"{"kind":"kata"}"#).unwrap_err();
        assert!(err.contains("kata"), "must name the bad value: {err}");
        for kind in Sandbox::KINDS {
            assert!(err.contains(kind), "must name the valid set ({kind} missing): {err}");
        }
    }

    #[test]
    fn a_config_with_no_sandbox_object_is_the_local_backend() {
        let cfg = load_raw("{\n  \"repo_name\": \"aur\"\n}\n").unwrap();
        assert!(matches!(cfg.sandbox, Sandbox::Loopback));
        assert_eq!(cfg.repo_name, "aur", "the rest of the config is untouched");
        assert_eq!(cfg.sandbox_image(), DEFAULT_SANDBOX_IMAGE);
        assert!(cfg.sandbox.shared_workspace(), "loopback shares the filesystem by construction");
    }

    #[test]
    fn a_config_init_wrote_before_the_enum_still_loads() {
        let cfg = load_raw(
            r#"{
      "root": "/var/lib/aur-build",
      "repo_name": "aur",
      "arch": "x86_64",
      "signing_key_id": "",
      "bind": "127.0.0.1:8484",
      "password": "",
      "base_url": "http://127.0.0.1:8484",
      "build_profile": "extra-x86_64",
      "git_bin": "git",
      "makepkg_bin": "makepkg",
      "pacman_bin": "pacman",
      "repo_add_bin": "repo-add",
      "gpg_bin": "gpg",
      "build_user": "",
      "sandbox_backend": "loopback",
      "agent_listen": "",
      "agent_token": "",
      "sandbox_image": "aur-build-sandbox:latest",
      "max_concurrent_builds": 1,
      "lease_secs": 90,
      "min_free_disk_mb": 1024,
      "max_transient_attempts": 3,
      "dispatch_tick_secs": 2
    }"#,
        )
        .unwrap();
        assert!(matches!(cfg.sandbox, Sandbox::Loopback));
        assert_eq!(cfg.lease_secs, 90);
    }

    #[test]
    fn retired_sandbox_keys_that_mean_something_are_refused() {
        let err = load_raw(r#"{ "sandbox_backend": "remote", "agent_listen": "0.0.0.0:1", "agent_token": "t" }"#)
            .unwrap_err();
        assert!(err.contains("sandbox_backend"), "must name the retired key: {err}");
        assert!(err.contains("sandbox"), "must point at the replacement: {err}");

        let err = load_raw(r#"{ "sandbox_backend": "kata" }"#).unwrap_err();
        assert!(err.contains("sandbox_backend"), "{err}");

        assert!(load_raw(r#"{ "sandbox_backend": "loopback", "agent_token": "" }"#).is_ok());
    }

    #[test]
    fn the_rendezvous_secrets_never_reach_debug() {
        let cfg = load_sandbox(
            r#"{"kind":"agent-sandbox","api":"https://k8s:6443","namespace":"builds",
                 "bearer":"kube-token","image":"img","listen":"0.0.0.0:1","token":"s3cr3t"}"#,
        )
        .unwrap();
        let shown = format!("{cfg:?}");
        assert!(!shown.contains("s3cr3t"), "the rendezvous token leaked into Debug");
        assert!(!shown.contains("kube-token"), "the cluster bearer leaked into Debug");
        assert!(shown.contains("builds"), "the non-secret fields are still visible: {shown}");
    }

    #[test]
    fn a_field_that_is_present_but_empty_is_refused() {
        let cfg = load_sandbox(r#"{"kind":"remote","listen":"","token":"t","shared_workspace":true}"#)
            .unwrap();
        let err = cfg.validate().unwrap_err().to_string();
        assert!(err.contains("listen"), "must name the empty field: {err}");

        let cfg = load_sandbox(r#"{"kind":"remote","listen":"127.0.0.1:1","token":"  ","shared_workspace":true}"#)
            .unwrap();
        let err = cfg.validate().unwrap_err().to_string();
        assert!(err.contains("token"), "whitespace is not a token: {err}");

        for blank in ["api", "namespace", "bearer", "image", "listen", "token"] {
            let mut fields = std::collections::BTreeMap::from([
                ("api", "https://k8s:6443"),
                ("namespace", "builds"),
                ("bearer", "kube"),
                ("image", "img"),
                ("listen", "0.0.0.0:1"),
                ("token", "t"),
            ]);
            fields.insert(blank, "");
            let body: Vec<String> =
                fields.iter().map(|(k, v)| format!("\"{k}\":\"{v}\"")).collect();
            let cfg = load_sandbox(&format!("{{\"kind\":\"agent-sandbox\",{}}}", body.join(","))).unwrap();
            let err = cfg.validate().unwrap_err().to_string();
            assert!(err.contains(blank), "blank {blank} must be named: {err}");
        }
    }

    #[test]
    fn a_remote_backend_must_assert_the_shared_workspace() {
        let cfg = load_sandbox(r#"{"kind":"remote","listen":"127.0.0.1:1","token":"t"}"#).unwrap();
        let err = cfg.validate().unwrap_err().to_string();
        assert!(err.contains("shared_workspace"), "must name the missing assertion: {err}");
        assert!(err.contains("workspace"), "must explain what is missing: {err}");
        assert!(err.contains("remote"), "must say which kind: {err}");

        let cfg = load_sandbox(
            r#"{"kind":"agent-sandbox","api":"https://k8s:6443","namespace":"b","bearer":"k",
                 "image":"img","listen":"0.0.0.0:1","token":"t"}"#,
        )
        .unwrap();
        let err = cfg.validate().unwrap_err().to_string();
        assert!(err.contains("shared_workspace"), "{err}");
        assert!(err.contains("agent-sandbox"), "{err}");

        assert!(load_sandbox(
            r#"{"kind":"remote","listen":"127.0.0.1:1","token":"t","shared_workspace":true}"#
        )
        .unwrap()
        .validate()
        .is_ok());
    }

    #[test]
    fn the_local_backend_needs_no_assertion_at_all() {
        assert!(load_sandbox(r#"{"kind":"loopback"}"#).unwrap().validate().is_ok());
        assert!(load_raw("{}\n").unwrap().validate().is_ok());
    }
}