OXYGENHUB
# e20897216221 oxygenflow / crates / flow-core / src / pipeline.rs
60.7 KiB · Rust · last changed Approval gates in the pipeline: approval { by; others-only; expires } 20 days ago source blame history raw
1
//! `.flow/pipeline.kdl`: the M0 subset of spec §3 (docs/m0.md §1), parsed
2
//! from KDL 2.0 and validated before anything runs. Every problem is
3
//! reported with its line, and all of them at once.
4
5
use serde::{Deserialize, Serialize};
6
use std::collections::{BTreeMap, BTreeSet};
7
use std::fmt;
8
9
/// Where a pipeline lives in the state being built.
10
pub const PIPELINE_PATH: &str = ".flow/pipeline.kdl";
11
12
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
13
pub struct Pipeline {
14
    pub schema_version: u32,
15
    /// By name.
16
    pub sandboxes: BTreeMap<String, Sandbox>,
17
    /// By name.
18
    pub jobs: BTreeMap<String, Job>,
19
    /// When the pipeline's jobs run, unless a job says (oxygenflow#24);
20
    /// absent: on every push and from "Run pipeline".
21
    #[serde(default, skip_serializing_if = "Option::is_none")]
22
    pub on: Option<On>,
23
}
24
25
/// What starts a job (`on { push "main"; tag "v*"; manual; schedule "0 3 * * *" }`).
26
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
27
pub struct On {
28
    /// Bookmark globs a push runs it for; `Some(vec![])`: any bookmark.
29
    #[serde(default, skip_serializing_if = "Option::is_none")]
30
    pub push: Option<Vec<String>>,
31
    /// Tag globs a pushed tag runs it for; `Some(vec![])`: any tag.
32
    #[serde(default, skip_serializing_if = "Option::is_none")]
33
    pub tag: Option<Vec<String>>,
34
    /// From "Run pipeline" (and `oh run start`).
35
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
36
    pub manual: bool,
37
    /// Five-field cron lines, on the hub's clock, for the default bookmark.
38
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
39
    pub schedule: Vec<String>,
40
}
41
42
/// Why a run started, for [`On::matches`].
43
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44
pub enum Event<'a> {
45
    /// A push moved this bookmark.
46
    Push(&'a str),
47
    /// This tag was pushed.
48
    Tag(&'a str),
49
    /// "Run pipeline", `oh run start`.
50
    Manual,
51
    /// A `schedule` line came due.
52
    Schedule,
53
}
54
55
impl On {
56
    /// What a job without any `on` runs for: every push, and by hand.
57
    pub fn default_on() -> On {
58
        On { push: Some(vec![]), tag: None, manual: true, schedule: vec![] }
59
    }
60
61
    pub fn matches(&self, event: Event<'_>) -> bool {
62
        let any = |globs: &Option<Vec<String>>, name: &str| match globs {
63
            None => false,
64
            Some(g) if g.is_empty() => true,
65
            Some(g) => g.iter().any(|p| globset::Glob::new(p).is_ok_and(|p| p.compile_matcher().is_match(name))),
66
        };
67
        match event {
68
            Event::Push(b) => any(&self.push, b),
69
            Event::Tag(t) => any(&self.tag, t),
70
            Event::Manual => self.manual,
71
            Event::Schedule => !self.schedule.is_empty(),
72
        }
73
    }
74
}
75
76
impl Pipeline {
77
    /// When `job` runs: its own `on`, else the pipeline's, else the default.
78
    pub fn on_of(&self, job: &Job) -> On {
79
        job.on.clone().or_else(|| self.on.clone()).unwrap_or_else(On::default_on)
80
    }
81
}
82
83
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
84
#[serde(rename_all = "lowercase")]
85
pub enum Runtime {
86
    /// Tier 0 (spec §4.1); refused in M0.
87
    Wasm,
88
    /// Tier 1 (spec §4.2): namespaces, Landlock, seccomp, cgroups.
89
    Syscall,
90
    /// Tier 2 (spec §4.3), the default.
91
    Microvm,
92
}
93
94
impl Runtime {
95
    pub fn as_str(self) -> &'static str {
96
        match self {
97
            Runtime::Wasm => "wasm",
98
            Runtime::Syscall => "syscall",
99
            Runtime::Microvm => "microvm",
100
        }
101
    }
102
}
103
104
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
105
#[serde(rename_all = "lowercase")]
106
pub enum Network {
107
    Isolated,
108
    Loopback,
109
    Egress,
110
}
111
112
impl Network {
113
    pub fn as_str(self) -> &'static str {
114
        match self {
115
            Network::Isolated => "isolated",
116
            Network::Loopback => "loopback",
117
            Network::Egress => "egress",
118
        }
119
    }
120
}
121
122
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
123
pub struct Sandbox {
124
    pub name: String,
125
    pub runtime: Runtime,
126
    /// BLAKE3 of the rootfs image, hex.
127
    pub rootfs: String,
128
    pub memory_mib: u32,
129
    pub cpus: u32,
130
    pub network: Network,
131
    /// Environment every job in this sandbox starts from; a job's own `env`
132
    /// overrides it.
133
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
134
    pub env: BTreeMap<String, String>,
135
    /// Labels a runner must have to run jobs here (`runs-on`), sorted.
136
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
137
    pub runs_on: Vec<String>,
138
    /// The hosts a `network "egress"` sandbox may reach (oxygenflow#55):
139
    /// names, or `*.` and a domain for any name under it; sorted. Its jobs
140
    /// reach them through the runner's proxy, and nothing else.
141
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
142
    pub egress_allow: Vec<String>,
143
    /// How long each job here may run, in seconds (`timeout "2h"`), when
144
    /// the job does not say; the hub caps it at the site's maximum.
145
    #[serde(default, skip_serializing_if = "Option::is_none")]
146
    pub timeout_s: Option<u64>,
147
    /// The architecture the jobs need (`arch "riscv64"`, spec §11.3);
148
    /// without it, the rootfs image's.
149
    #[serde(default, skip_serializing_if = "Option::is_none")]
150
    pub arch: Option<String>,
151
}
152
153
/// An architecture name as runners report it: `x86_64`, `aarch64`, `riscv64`.
154
pub fn arch_ok(a: &str) -> bool {
155
    (2..=16).contains(&a.len()) && a.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
156
}
157
158
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
159
pub struct Job {
160
    pub name: String,
161
    pub sandbox: String,
162
    /// Glob patterns over repository paths (spec §6.2).
163
    pub scope: Vec<String>,
164
    /// Sorted.
165
    pub depends_on: Vec<String>,
166
    pub env: BTreeMap<String, String>,
167
    /// Executed as is: no shell, no expansion (spec §2.2 I2).
168
    pub exec: Vec<String>,
169
    /// Ephemeral scratch mounts, sorted by target (spec §3.1 `mount`).
170
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
171
    pub mounts: Vec<Mount>,
172
    /// Files the job produces, sorted by name (spec §5.2 `output`).
173
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
174
    pub outputs: Vec<Output>,
175
    /// Artifacts of jobs this one depends on, put in its workspace before it
176
    /// starts (oxygenflow#58), sorted by path. The runner checks each against
177
    /// the producing job's receipt; this job's receipt lists them as inputs.
178
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
179
    pub inputs: Vec<Input>,
180
    /// Wait for a person before running (oxygenflow#57): `approval { by
181
    /// "maintain"; others-only #true; expires "24h" }`.
182
    #[serde(default, skip_serializing_if = "Option::is_none")]
183
    pub approval: Option<Approval>,
184
    /// Secrets the job mounts, sorted by name (spec §9 `secret`): the hub
185
    /// supplies each by name, the runner mounts it as a file.
186
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
187
    pub secrets: Vec<Secret>,
188
    /// Identities the job asks the hub for (oxygenhub#103): an OIDC token
189
    /// for an audience, mounted as a file like a secret.
190
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
191
    pub identities: Vec<Identity>,
192
    /// Labels a runner must have to take this job (`runs-on`), sorted;
193
    /// with its sandbox's, what the hub matches against a runner's.
194
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
195
    pub runs_on: Vec<String>,
196
    /// How long the job may run, in seconds (`timeout "90m"`); its
197
    /// sandbox's when absent, else the site's default (oxygenflow#23).
198
    #[serde(default, skip_serializing_if = "Option::is_none")]
199
    pub timeout_s: Option<u64>,
200
    /// When it runs, over the pipeline's `on` (oxygenflow#24).
201
    #[serde(default, skip_serializing_if = "Option::is_none")]
202
    pub on: Option<On>,
203
}
204
205
impl Job {
206
    /// The job's environment on top of its sandbox's: what it runs with.
207
    pub fn in_sandbox(&self, sandbox: &Sandbox) -> Job {
208
        let mut job = self.clone();
209
        for (k, v) in &sandbox.env {
210
            job.env.entry(k.clone()).or_insert_with(|| v.clone());
211
        }
212
        job.runs_on.extend(sandbox.runs_on.iter().cloned());
213
        job.runs_on.sort();
214
        job.runs_on.dedup();
215
        job.timeout_s = job.timeout_s.or(sandbox.timeout_s);
216
        job
217
    }
218
219
    /// The job with variables that tell it what it builds (`FLOW_STATE`,
220
    /// `FLOW_BOOKMARK` …) added to its environment; a variable the pipeline
221
    /// sets itself keeps the pipeline's value.
222
    pub fn with_flow_env(&self, vars: &[(String, String)]) -> Job {
223
        let mut job = self.clone();
224
        for (k, v) in vars {
225
            job.env.entry(k.clone()).or_insert_with(|| v.clone());
226
        }
227
        job
228
    }
229
}
230
231
/// An ephemeral scratch mount: empty at the start of every job and gone
232
/// after it, so it cannot carry anything between jobs (spec §2.2 I4) --
233
/// unless it names a `cache` (spec §5.4, #28): then a disk kept from an
234
/// earlier passing job may start it, and the receipt says which.
235
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
236
pub struct Mount {
237
    pub source: MountSource,
238
    /// An absolute path under `/src` or `/tmp`.
239
    pub target: String,
240
    pub size_mib: u32,
241
    /// `cache "name"`: keep this disk after a passing job and start later
242
    /// jobs from it (disk mounts only).
243
    #[serde(default, skip_serializing_if = "Option::is_none")]
244
    pub cache: Option<String>,
245
    /// `key "Cargo.lock" ...`: files whose content picks the cache entry.
246
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
247
    pub key: Vec<String>,
248
}
249
250
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
251
#[serde(rename_all = "lowercase")]
252
pub enum MountSource {
253
    /// `ephemeral://tmpfs`: memory in the sandbox, counted against its memory-limit.
254
    Tmpfs,
255
    /// `ephemeral://disk`: a fresh sparse disk on the runner, for large build trees.
256
    Disk,
257
}
258
259
impl MountSource {
260
    pub fn as_str(self) -> &'static str {
261
        match self {
262
            MountSource::Tmpfs => "ephemeral://tmpfs",
263
            MountSource::Disk => "ephemeral://disk",
264
        }
265
    }
266
}
267
268
/// A file a job produces (spec §5.2): read from the job's disks when it
269
/// ends, kept in the repository as a blob, and named by its receipt.
270
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
271
pub struct Output {
272
    /// The artifact's name, unique in the job.
273
    pub name: String,
274
    /// A clean absolute path under `/src`, not on a tmpfs mount.
275
    pub path: String,
276
    /// `when "always"`: kept from a failing job too, such as a test report
277
    /// (oxygenflow#37). From a failing job it is never in the receipt.
278
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
279
    pub always: bool,
280
    /// An artifact is one file; a report is a directory with a
281
    /// `report.toml`, kept file by file with a manifest (oxygenhub#127).
282
    #[serde(default, skip_serializing_if = "OutputKind::is_artifact")]
283
    pub kind: OutputKind,
284
}
285
286
/// An artifact a job takes from a job it depends on (oxygenflow#58):
287
/// `input { artifact "tfplan" from "plan"; path "/src/tfplan" }`.
288
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
289
pub struct Input {
290
    /// The producing job's artifact.
291
    pub artifact: String,
292
    /// The producing job: one this job depends on.
293
    pub from: String,
294
    /// Where it is put: a clean absolute path under `/src`.
295
    pub path: String,
296
}
297
298
/// Who must approve a job before it runs, and for how long it waits
299
/// (oxygenflow#57).
300
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
301
pub struct Approval {
302
    /// The least role that approves: `write`, `maintain` (the default) or `admin`.
303
    pub by: String,
304
    /// Not the person whose push started the run.
305
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
306
    pub others_only: bool,
307
    /// How long it waits once the jobs it depends on are done, in seconds.
308
    pub expires_s: u64,
309
}
310
311
/// The longest a job waits for approval: 30 days.
312
const MAX_APPROVAL_S: u64 = 30 * 24 * 3600;
313
314
/// The most inputs a job takes.
315
const MAX_INPUTS: usize = 8;
316
317
/// What an [`Output`] is.
318
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
319
#[serde(rename_all = "lowercase")]
320
pub enum OutputKind {
321
    #[default]
322
    Artifact,
323
    Report,
324
}
325
326
impl OutputKind {
327
    pub fn is_artifact(&self) -> bool {
328
        *self == OutputKind::Artifact
329
    }
330
331
    pub fn word(&self) -> &'static str {
332
        match self {
333
            OutputKind::Artifact => "artifact",
334
            OutputKind::Report => "report",
335
        }
336
    }
337
}
338
339
/// A secret the job reads as a file (spec §9): never in the environment.
340
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
341
pub struct Secret {
342
    /// Which secret, as the hub names it; unique in the job.
343
    pub name: String,
344
    /// A clean absolute path under `/run/secrets/`, unique in the job;
345
    /// the file is 0400, the job's user's, on an in-memory mount.
346
    pub mount_path: String,
347
}
348
349
/// An OIDC token the hub mints for the job (oxygenhub#103), naming the
350
/// repository, bookmark, run and job, for `audience`; read as a file.
351
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
352
pub struct Identity {
353
    /// Who the token is for (`sts.amazonaws.com`, a Vault role's audience, …).
354
    pub audience: String,
355
    /// A clean absolute path under `/run/secrets/`, unique among the
356
    /// job's secrets and identities.
357
    pub mount_path: String,
358
}
359
360
/// A secret's mount path: under `/run/secrets/`, no `.` or `..`.
361
pub fn secret_path_ok(p: &str) -> bool {
362
    p.strip_prefix("/run/secrets/").is_some_and(|rest| !rest.is_empty() && rest.split('/').all(|c| !c.is_empty() && c != "." && c != ".."))
363
}
364
365
/// Artifacts a job may declare.
366
pub const MAX_OUTPUTS: usize = 16;
367
368
/// Whether `p` is a clean absolute path strictly under `/src`, with nothing
369
/// a debugfs command line would have to quote.
370
fn output_path_ok(p: &str) -> bool {
371
    p.strip_prefix("/src/").is_some_and(|rest| {
372
        !rest.is_empty()
373
            && rest.split('/').all(|c| !c.is_empty() && c != "." && c != "..")
374
            && p.bytes().all(|b| b.is_ascii_graphic() && b != b'"' && b != b'\\')
375
    })
376
}
377
378
/// Mounts a job may declare.
379
pub const MAX_MOUNTS: usize = 4;
380
/// The most secrets a job may mount.
381
pub const MAX_SECRETS: usize = 8;
382
/// The most identities a job may ask for.
383
pub const MAX_IDENTITIES: usize = 4;
384
/// Sizes a mount may have: 16 MiB to 64 GiB.
385
pub const MIN_MOUNT_MIB: u64 = 16;
386
pub const MAX_MOUNT_MIB: u64 = 64 * 1024;
387
388
/// Whether `t` is a clean absolute path strictly under `/src` or `/tmp`.
389
fn mount_target_ok(t: &str) -> bool {
390
    let under = t.strip_prefix("/src/").or_else(|| t.strip_prefix("/tmp/"));
391
    under.is_some_and(|rest| !rest.is_empty() && rest.split('/').all(|c| !c.is_empty() && c != "." && c != ".."))
392
}
393
394
/// One problem in a pipeline, at a 1-based line.
395
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
396
pub struct Problem {
397
    pub line: usize,
398
    pub message: String,
399
}
400
401
impl fmt::Display for Problem {
402
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
403
        write!(f, "line {}: {}", self.line, self.message)
404
    }
405
}
406
407
/// Every problem found, in line order.
408
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
409
pub struct Problems(pub Vec<Problem>);
410
411
impl fmt::Display for Problems {
412
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
413
        let lines: Vec<String> = self.0.iter().map(|p| p.to_string()).collect();
414
        f.write_str(&lines.join("\n"))
415
    }
416
}
417
418
const MIN_MEMORY_MIB: u64 = 64;
419
const MAX_MEMORY_MIB: u64 = 16 * 1024;
420
const MAX_CPUS: i128 = 16;
421
422
/// Nodes of the full spec that M0 recognises and refuses.
423
const LATER_TOP: &[&str] = &["publish", "secret"];
424
const LATER_JOB: &[&str] = &["attest"];
425
426
struct Ctx<'a> {
427
    src: &'a str,
428
    problems: Vec<Problem>,
429
}
430
431
impl Ctx<'_> {
432
    fn line(&self, span: SourceSpan) -> usize {
433
        let at = span.offset().min(self.src.len());
434
        self.src[..at].bytes().filter(|b| *b == b'\n').count() + 1
435
    }
436
437
    fn err(&mut self, span: SourceSpan, message: impl Into<String>) {
438
        let line = self.line(span);
439
        self.problems.push(Problem { line, message: message.into() });
440
    }
441
442
    /// The node's arguments as strings; properties and other types are errors.
443
    fn strings(&mut self, node: &KdlNode) -> Vec<String> {
444
        let mut out = Vec::new();
445
        for e in node.entries() {
446
            if let Some(k) = e.name() {
447
                self.err(e.span(), format!("`{}` takes no property `{}`", node.name().value(), k.value()));
448
                continue;
449
            }
450
            match e.value() {
451
                KdlValue::String(s) => out.push(s.clone()),
452
                other => self.err(e.span(), format!("`{}` takes strings, not {}", node.name().value(), kind_of(other))),
453
            }
454
        }
455
        out
456
    }
457
458
    /// Exactly one string argument.
459
    fn one_string(&mut self, node: &KdlNode) -> Option<String> {
460
        let v = self.strings(node);
461
        if v.len() != 1 {
462
            self.err(node.span(), format!("`{}` takes one string", node.name().value()));
463
            return None;
464
        }
465
        v.into_iter().next()
466
    }
467
468
    fn one_integer(&mut self, node: &KdlNode) -> Option<i128> {
469
        match node.entries() {
470
            [e] if e.name().is_none() => match e.value() {
471
                KdlValue::Integer(n) => Some(*n),
472
                other => {
473
                    self.err(e.span(), format!("`{}` takes an integer, not {}", node.name().value(), kind_of(other)));
474
                    None
475
                }
476
            },
477
            _ => {
478
                self.err(node.span(), format!("`{}` takes one integer", node.name().value()));
479
                None
480
            }
481
        }
482
    }
483
484
    fn no_children(&mut self, node: &KdlNode) {
485
        if node.children().is_some() {
486
            self.err(node.span(), format!("`{}` takes no block", node.name().value()));
487
        }
488
    }
489
490
    fn name_ok(&mut self, span: SourceSpan, what: &str, name: &str) -> bool {
491
        let ok = !name.is_empty() && name.len() <= 64 && name.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b));
492
        if !ok {
493
            self.err(span, format!("{what} name {name:?} must be 1 to 64 of A-Z a-z 0-9 . _ -"));
494
        }
495
        ok
496
    }
497
}
498
499
use kdl::{KdlDocument, KdlNode, KdlValue};
500
use miette::SourceSpan;
501
502
fn kind_of(v: &KdlValue) -> &'static str {
503
    match v {
504
        KdlValue::String(_) => "a string",
505
        KdlValue::Integer(_) => "an integer",
506
        KdlValue::Float(_) => "a number",
507
        KdlValue::Bool(_) => "a boolean",
508
        KdlValue::Null => "null",
509
    }
510
}
511
512
/// `"512MiB"`, `"4GiB"`, `"65536KiB"` to MiB.
513
fn parse_memory(s: &str) -> Option<u64> {
514
    let (num, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit())?);
515
    let n: u64 = num.parse().ok()?;
516
    let mib = match unit {
517
        "KiB" => n.is_multiple_of(1024).then_some(n / 1024)?,
518
        "MiB" => n,
519
        "GiB" => n.checked_mul(1024)?,
520
        _ => return None,
521
    };
522
    Some(mib)
523
}
524
525
/// The line of the first escape KDL 2.0 does not have but shells and C
526
/// do (`\0NN`, `\e`, `\xNN`), as someone colouring output writes them.
527
fn foreign_escape_line(src: &str) -> Option<usize> {
528
    src.lines()
529
        .position(|l| {
530
            let b = l.as_bytes();
531
            b.windows(2).enumerate().any(|(i, w)| {
532
                w[0] == b'\\'
533
                    && (i == 0 || b[i - 1] != b'\\')
534
                    && (w[1] == b'e' || w[1] == b'x' || (w[1] == b'0' && b.get(i + 2).is_some_and(u8::is_ascii_digit)))
535
            })
536
        })
537
        .map(|i| i + 1)
538
}
539
540
impl Pipeline {
541
    /// Parse and validate a pipeline document.
542
    pub fn parse(src: &str) -> Result<Pipeline, Problems> {
543
        let doc = match KdlDocument::parse_v2(src) {
544
            Ok(d) => d,
545
            Err(e) => {
546
                let mut ctx = Ctx { src, problems: Vec::new() };
547
                for d in &e.diagnostics {
548
                    let msg = d.message.clone().or_else(|| d.label.clone()).unwrap_or_else(|| "not valid KDL 2.0".into());
549
                    ctx.err(d.span, msg);
550
                }
551
                if ctx.problems.is_empty() {
552
                    ctx.problems.push(Problem { line: 1, message: "not valid KDL 2.0".into() });
553
                }
554
                if let Some(line) = foreign_escape_line(src) {
555
                    ctx.problems.push(Problem {
556
                        line,
557
                        message: "KDL strings have no \\033, \\e or \\x escapes: write ESC (for ANSI colours) as \\u{1b}".into(),
558
                    });
559
                }
560
                return Err(Problems(ctx.problems));
561
            }
562
        };
563
        let mut ctx = Ctx { src, problems: Vec::new() };
564
        let mut schema = None;
565
        let mut sandboxes = BTreeMap::new();
566
        let mut jobs: BTreeMap<String, (Job, SourceSpan)> = BTreeMap::new();
567
        let mut on = None;
568
        for node in doc.nodes() {
569
            match node.name().value() {
570
                "on" => {
571
                    if on.is_some() {
572
                        ctx.err(node.span(), "`on` is given twice");
573
                    }
574
                    on = Some(parse_on(&mut ctx, node));
575
                }
576
                "schema-version" => {
577
                    ctx.no_children(node);
578
                    match ctx.one_integer(node) {
579
                        Some(1) => schema = Some(1),
580
                        Some(n) => ctx.err(node.span(), format!("schema-version {n} is not supported; this runner reads 1")),
581
                        None => {}
582
                    }
583
                }
584
                "sandbox" => {
585
                    if let Some(sb) = parse_sandbox(&mut ctx, node) {
586
                        if sandboxes.contains_key(&sb.name) {
587
                            ctx.err(node.span(), format!("sandbox {:?} is declared twice", sb.name));
588
                        } else {
589
                            sandboxes.insert(sb.name.clone(), sb);
590
                        }
591
                    }
592
                }
593
                "job" => {
594
                    if let Some(job) = parse_job(&mut ctx, node) {
595
                        if jobs.contains_key(&job.name) {
596
                            ctx.err(node.span(), format!("job {:?} is declared twice", job.name));
597
                        } else {
598
                            jobs.insert(job.name.clone(), (job, node.span()));
599
                        }
600
                    }
601
                }
602
                n if LATER_TOP.contains(&n) => ctx.err(node.span(), format!("`{n}` is not in M0 yet")),
603
                n => ctx.err(node.span(), format!("unknown node `{n}`; expected schema-version, on, sandbox or job")),
604
            }
605
        }
606
        if schema.is_none() && !ctx.problems.iter().any(|p| p.message.contains("schema-version")) {
607
            ctx.problems.push(Problem { line: 1, message: "`schema-version 1` is required".into() });
608
        }
609
        if jobs.is_empty() && ctx.problems.is_empty() {
610
            ctx.problems.push(Problem { line: 1, message: "a pipeline needs at least one job".into() });
611
        }
612
        // References and cycles.
613
        for (job, span) in jobs.values() {
614
            if !job.sandbox.is_empty() && !sandboxes.contains_key(&job.sandbox) {
615
                ctx.err(*span, format!("job {:?} uses sandbox {:?}, which is not declared", job.name, job.sandbox));
616
            }
617
            for d in &job.depends_on {
618
                if !jobs.contains_key(d) {
619
                    ctx.err(*span, format!("job {:?} depends on {:?}, which is not declared", job.name, d));
620
                } else if d == &job.name {
621
                    ctx.err(*span, format!("job {:?} depends on itself", job.name));
622
                }
623
            }
624
            // Inputs come from a job this one depends on, which declares
625
            // that artifact (oxygenflow#58).
626
            for i in &job.inputs {
627
                let Some((producer, _)) = jobs.get(&i.from) else {
628
                    ctx.err(*span, format!("job {:?} takes an input from {:?}, which is not declared", job.name, i.from));
629
                    continue;
630
                };
631
                if !job.depends_on.contains(&i.from) {
632
                    ctx.err(*span, format!("job {:?} takes {:?} from {:?}: add depends-on \"{}\"", job.name, i.artifact, i.from, i.from));
633
                }
634
                match producer.outputs.iter().find(|o| o.name == i.artifact) {
635
                    Some(o) if o.kind == OutputKind::Artifact => {}
636
                    Some(_) => ctx.err(*span, format!("{:?} of job {:?} is a report; inputs are artifacts", i.artifact, i.from)),
637
                    None => ctx.err(*span, format!("job {:?} declares no artifact {:?}", i.from, i.artifact)),
638
                }
639
            }
640
        }
641
        let graph: BTreeMap<&str, Vec<&str>> =
642
            jobs.values().map(|(j, _)| (j.name.as_str(), j.depends_on.iter().map(String::as_str).collect())).collect();
643
        if let Some(cycle) = find_cycle(&graph) {
644
            let span = jobs[cycle[0]].1;
645
            ctx.err(span, format!("jobs depend on each other in a cycle: {}", cycle.join(" → ")));
646
        }
647
        if !ctx.problems.is_empty() {
648
            ctx.problems.sort_by_key(|p| p.line);
649
            return Err(Problems(ctx.problems));
650
        }
651
        Ok(Pipeline { schema_version: 1, sandboxes, jobs: jobs.into_iter().map(|(k, (j, _))| (k, j)).collect(), on })
652
    }
653
654
    /// Jobs in an order where each comes after what it depends on (ties by name).
655
    pub fn order(&self) -> Vec<&Job> {
656
        let mut done: BTreeSet<&str> = BTreeSet::new();
657
        let mut out = Vec::with_capacity(self.jobs.len());
658
        while out.len() < self.jobs.len() {
659
            let before = out.len();
660
            for j in self.jobs.values() {
661
                if !done.contains(j.name.as_str()) && j.depends_on.iter().all(|d| done.contains(d.as_str())) {
662
                    out.push(j);
663
                }
664
            }
665
            for j in &out[before..] {
666
                done.insert(j.name.as_str());
667
            }
668
            if out.len() == before {
669
                break; // validated pipelines have no cycles
670
            }
671
        }
672
        out
673
    }
674
675
    /// Each job's depth: 0 without dependencies, else one more than its deepest dependency.
676
    pub fn depths(&self) -> BTreeMap<&str, usize> {
677
        let mut depth: BTreeMap<&str, usize> = BTreeMap::new();
678
        for j in self.order() {
679
            let d = j.depends_on.iter().map(|x| depth.get(x.as_str()).copied().unwrap_or(0) + 1).max().unwrap_or(0);
680
            depth.insert(j.name.as_str(), d);
681
        }
682
        depth
683
    }
684
}
685
686
fn find_cycle<'a>(graph: &BTreeMap<&'a str, Vec<&'a str>>) -> Option<Vec<&'a str>> {
687
    #[derive(Clone, Copy, PartialEq)]
688
    enum Mark {
689
        Visiting,
690
        Done,
691
    }
692
    fn visit<'a>(
693
        n: &'a str,
694
        graph: &BTreeMap<&'a str, Vec<&'a str>>,
695
        marks: &mut BTreeMap<&'a str, Mark>,
696
        stack: &mut Vec<&'a str>,
697
    ) -> Option<Vec<&'a str>> {
698
        match marks.get(n) {
699
            Some(Mark::Done) => return None,
700
            Some(Mark::Visiting) => {
701
                let at = stack.iter().position(|s| *s == n).unwrap_or(0);
702
                let mut c = stack[at..].to_vec();
703
                c.push(n);
704
                return Some(c);
705
            }
706
            None => {}
707
        }
708
        marks.insert(n, Mark::Visiting);
709
        stack.push(n);
710
        for d in graph.get(n).into_iter().flatten() {
711
            if graph.contains_key(d) && *d != n {
712
                if let Some(c) = visit(d, graph, marks, stack) {
713
                    return Some(c);
714
                }
715
            }
716
        }
717
        stack.pop();
718
        marks.insert(n, Mark::Done);
719
        None
720
    }
721
    let mut marks = BTreeMap::new();
722
    for n in graph.keys() {
723
        let mut stack = Vec::new();
724
        if let Some(c) = visit(n, graph, &mut marks, &mut stack) {
725
            return Some(c);
726
        }
727
    }
728
    None
729
}
730
731
fn block<'a>(ctx: &mut Ctx, node: &'a KdlNode) -> &'a [KdlNode] {
732
    match node.children() {
733
        Some(d) => d.nodes(),
734
        None => {
735
            ctx.err(node.span(), format!("`{}` needs a block {{ … }}", node.name().value()));
736
            &[]
737
        }
738
    }
739
}
740
741
fn parse_sandbox(ctx: &mut Ctx, node: &KdlNode) -> Option<Sandbox> {
742
    let name = ctx.one_string(node)?;
743
    let named = ctx.name_ok(node.span(), "sandbox", &name);
744
    let (mut runtime, mut rootfs, mut memory, mut cpus, mut network) =
745
        (Some(Runtime::Microvm), None, Some(1024u32), Some(1u32), Some(Network::Isolated));
746
    let mut seen = BTreeSet::new();
747
    let mut env = BTreeMap::new();
748
    let mut runs_on = Vec::new();
749
    let mut timeout_s = None;
750
    let mut arch: Option<String> = None;
751
    let mut egress_allow = Vec::new();
752
    for c in block(ctx, node) {
753
        let key = c.name().value();
754
        if key != "runs-on" && !seen.insert(key.to_string()) {
755
            ctx.err(c.span(), format!("`{key}` is given twice"));
756
        }
757
        if key == "env" {
758
            parse_env(ctx, c, &mut env);
759
            continue;
760
        }
761
        if key == "runs-on" {
762
            ctx.no_children(c);
763
            parse_labels(ctx, c, &mut runs_on);
764
            continue;
765
        }
766
        if key != "network" {
767
            ctx.no_children(c);
768
        }
769
        match key {
770
            "runtime" => {
771
                runtime = match ctx.one_string(c).as_deref() {
772
                    Some("microvm") => Some(Runtime::Microvm),
773
                    Some("syscall") | Some("gvisor") => Some(Runtime::Syscall),
774
                    Some("wasm") => {
775
                        ctx.err(c.span(), "runtime \"wasm\" is not in M0 yet; use \"microvm\" or \"syscall\"");
776
                        None
777
                    }
778
                    Some(other) => {
779
                        ctx.err(c.span(), format!("runtime {other:?}: expected \"microvm\", \"syscall\" or \"wasm\""));
780
                        None
781
                    }
782
                    None => None,
783
                }
784
            }
785
            "rootfs" => {
786
                rootfs = match ctx.one_string(c) {
787
                    Some(r) => match r.strip_prefix("cas://blob/") {
788
                        Some(h) if h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) => {
789
                            Some(h.to_string())
790
                        }
791
                        _ => {
792
                            ctx.err(c.span(), format!("rootfs {r:?}: expected \"cas://blob/\" and 64 lower-case hex digits"));
793
                            None
794
                        }
795
                    },
796
                    None => None,
797
                }
798
            }
799
            "arch" => {
800
                arch = match ctx.one_string(c) {
801
                    Some(a) if arch_ok(&a) => Some(a),
802
                    Some(a) => {
803
                        ctx.err(c.span(), format!("arch {a:?} is not an architecture name such as x86_64, aarch64 or riscv64"));
804
                        None
805
                    }
806
                    None => None,
807
                }
808
            }
809
            "memory-limit" => {
810
                memory = match ctx.one_string(c) {
811
                    Some(m) => match parse_memory(&m) {
812
                        Some(mib) if (MIN_MEMORY_MIB..=MAX_MEMORY_MIB).contains(&mib) => Some(mib as u32),
813
                        Some(_) => {
814
                            ctx.err(c.span(), format!("memory-limit {m:?} must be from 64MiB to 16GiB"));
815
                            None
816
                        }
817
                        None => {
818
                            ctx.err(c.span(), format!("memory-limit {m:?}: expected a whole number of KiB, MiB or GiB, as \"4GiB\""));
819
                            None
820
                        }
821
                    },
822
                    None => None,
823
                }
824
            }
825
            "cpu-limit" => {
826
                cpus = match ctx.one_integer(c) {
827
                    Some(n) if (1..=MAX_CPUS).contains(&n) => Some(n as u32),
828
                    Some(n) => {
829
                        ctx.err(c.span(), format!("cpu-limit {n} must be from 1 to {MAX_CPUS}"));
830
                        None
831
                    }
832
                    None => None,
833
                }
834
            }
835
            "network" => {
836
                let kind = ctx.one_string(c);
837
                if kind.as_deref() != Some("egress") {
838
                    ctx.no_children(c);
839
                }
840
                network = match kind.as_deref() {
841
                    Some("isolated") => Some(Network::Isolated),
842
                    // Loopback only: the guest's `lo` comes up, and it still has
843
                    // no device that reaches anything outside it.
844
                    Some("loopback") => Some(Network::Loopback),
845
                    // Allow-listed egress (oxygenflow#55): still no network
846
                    // device; a proxy in the guest relays to the runner, which
847
                    // lets through only the hosts named here.
848
                    Some("egress") => {
849
                        egress_allow = parse_egress(ctx, c);
850
                        Some(Network::Egress)
851
                    }
852
                    Some(other) => {
853
                        ctx.err(c.span(), format!("network {other:?}: expected \"isolated\", \"loopback\" or \"egress\""));
854
                        None
855
                    }
856
                    None => None,
857
                }
858
            }
859
            "timeout" => timeout_s = parse_timeout(ctx, c),
860
            other => ctx.err(c.span(), format!("unknown sandbox setting `{other}`")),
861
        }
862
    }
863
    if rootfs.is_none() && !seen.contains("rootfs") {
864
        ctx.err(node.span(), format!("sandbox {name:?} needs a rootfs"));
865
    }
866
    if network == Some(Network::Egress) {
867
        if runtime == Some(Runtime::Syscall) {
868
            ctx.err(node.span(), format!("sandbox {name:?}: network \"egress\" needs runtime \"microvm\""));
869
        }
870
        // Only a runner that allows egress offers this label.
871
        if !runs_on.iter().any(|l| l == EGRESS_LABEL) {
872
            runs_on.push(EGRESS_LABEL.to_string());
873
            runs_on.sort();
874
        }
875
    }
876
    if !named {
877
        return None;
878
    }
879
    Some(Sandbox {
880
        name,
881
        runtime: runtime?,
882
        rootfs: rootfs?,
883
        memory_mib: memory?,
884
        cpus: cpus?,
885
        network: network?,
886
        env,
887
        runs_on,
888
        egress_allow,
889
        timeout_s,
890
        arch,
891
    })
892
}
893
894
/// The label a runner offers when it allows egress, and an egress sandbox
895
/// needs (oxygenflow#55).
896
pub const EGRESS_LABEL: &str = "egress";
897
898
/// The most hosts one sandbox may name.
899
const MAX_EGRESS_HOSTS: usize = 32;
900
901
/// Whether `pattern` is a host name, or `*.` and a domain: lower-case
902
/// letters, digits, `-` and dots, at least two labels.
903
pub fn egress_pattern_ok(pattern: &str) -> bool {
904
    let name = pattern.strip_prefix("*.").unwrap_or(pattern);
905
    let labels: Vec<&str> = name.split('.').collect();
906
    name.len() <= 253
907
        && labels.len() >= 2
908
        && labels.iter().all(|l| {
909
            !l.is_empty()
910
                && l.len() <= 63
911
                && !l.starts_with('-')
912
                && !l.ends_with('-')
913
                && l.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
914
        })
915
}
916
917
/// Whether `host` is one `patterns` allow: a name exactly, or a name under
918
/// a `*.` domain (not the domain itself). Case and a final dot are ignored.
919
pub fn egress_allows(patterns: &[String], host: &str) -> bool {
920
    let host = host.trim_end_matches('.').to_ascii_lowercase();
921
    patterns.iter().any(|p| match p.strip_prefix("*.") {
922
        Some(domain) => host.len() > domain.len() + 1 && host.ends_with(domain) && host[..host.len() - domain.len()].ends_with('.'),
923
        None => host == *p,
924
    })
925
}
926
927
/// `network "egress" { allow "*.googleapis.com" "registry.opentofu.org" }`.
928
fn parse_egress(ctx: &mut Ctx, node: &KdlNode) -> Vec<String> {
929
    let mut out = Vec::new();
930
    for c in block(ctx, node) {
931
        ctx.no_children(c);
932
        if c.name().value() != "allow" {
933
            ctx.err(c.span(), format!("unknown egress setting `{}`; egress takes `allow \"host\"...`", c.name().value()));
934
            continue;
935
        }
936
        for h in ctx.strings(c) {
937
            if egress_pattern_ok(&h) {
938
                out.push(h);
939
            } else {
940
                ctx.err(
941
                    c.span(),
942
                    format!("allow {h:?}: expected a lower-case host name such as \"registry.opentofu.org\", or \"*.\" and a domain"),
943
                );
944
            }
945
        }
946
    }
947
    out.sort();
948
    out.dedup();
949
    if out.is_empty() {
950
        ctx.err(node.span(), "network \"egress\" needs at least one `allow \"host\"`");
951
    } else if out.len() > MAX_EGRESS_HOSTS {
952
        ctx.err(node.span(), format!("network \"egress\" may allow at most {MAX_EGRESS_HOSTS} hosts"));
953
    }
954
    out
955
}
956
957
/// An `on` block: `push` and `tag` with globs (none: any), `manual`,
958
/// `schedule` with five-field cron lines.
959
fn parse_on(ctx: &mut Ctx, node: &KdlNode) -> On {
960
    let mut on = On::default();
961
    if !node.entries().is_empty() {
962
        ctx.err(node.span(), "`on` takes a block: on { push \"main\"; tag \"v*\"; manual }");
963
    }
964
    let globs = |ctx: &mut Ctx, c: &KdlNode| -> Vec<String> {
965
        let g = ctx.strings(c);
966
        for p in &g {
967
            if let Err(e) = globset::Glob::new(p) {
968
                ctx.err(c.span(), format!("{p:?}: {e}"));
969
            }
970
        }
971
        g
972
    };
973
    for c in block(ctx, node) {
974
        ctx.no_children(c);
975
        match c.name().value() {
976
            "push" => on.push.get_or_insert_with(Vec::new).extend(globs(ctx, c)),
977
            "tag" => on.tag.get_or_insert_with(Vec::new).extend(globs(ctx, c)),
978
            "manual" => on.manual = true,
979
            "schedule" => {
980
                for line in ctx.strings(c) {
981
                    if crate::cron::Cron::parse(&line).is_some() {
982
                        on.schedule.push(line);
983
                    } else {
984
                        ctx.err(
985
                            c.span(),
986
                            format!("schedule {line:?}: expected five cron fields (minute hour day month weekday), as \"0 3 * * *\""),
987
                        );
988
                    }
989
                }
990
            }
991
            other => ctx.err(c.span(), format!("unknown `on` event `{other}`; expected push, tag, manual or schedule")),
992
        }
993
    }
994
    if on.push.is_none() && on.tag.is_none() && !on.manual && on.schedule.is_empty() {
995
        ctx.err(node.span(), "`on` names no event, so nothing would run it");
996
    }
997
    on
998
}
999
1000
/// The longest a pipeline may ask a job to run.
1001
pub const MAX_TIMEOUT_S: u64 = 24 * 3600;
1002
1003
/// A duration: whole hours, minutes and seconds in that order, each
1004
/// optional, as "90m", "2h", "1h30m" or "45s".
1005
pub fn parse_duration(s: &str) -> Option<u64> {
1006
    let (mut total, mut num, mut last) = (0u64, String::new(), 0u8);
1007
    for ch in s.chars() {
1008
        if ch.is_ascii_digit() {
1009
            num.push(ch);
1010
            continue;
1011
        }
1012
        let (unit, mult) = match ch {
1013
            'h' => (1, 3600),
1014
            'm' => (2, 60),
1015
            's' => (3, 1),
1016
            _ => return None,
1017
        };
1018
        // Each unit once, largest first, each with its number.
1019
        if num.is_empty() || unit <= last {
1020
            return None;
1021
        }
1022
        last = unit;
1023
        total = total.checked_add(num.parse::<u64>().ok()?.checked_mul(mult)?)?;
1024
        num.clear();
1025
    }
1026
    (num.is_empty() && total > 0).then_some(total)
1027
}
1028
1029
/// A `timeout` line: one duration, from a minute to a day.
1030
fn parse_timeout(ctx: &mut Ctx, c: &KdlNode) -> Option<u64> {
1031
    let t = ctx.one_string(c)?;
1032
    match parse_duration(&t) {
1033
        Some(secs) if (60..=MAX_TIMEOUT_S).contains(&secs) => Some(secs),
1034
        Some(_) => {
1035
            ctx.err(c.span(), format!("timeout {t:?} must be from 1m to 24h"));
1036
            None
1037
        }
1038
        None => {
1039
            ctx.err(c.span(), format!("timeout {t:?}: expected hours, minutes and seconds, as \"90m\" or \"1h30m\""));
1040
            None
1041
        }
1042
    }
1043
}
1044
1045
/// The labels of a `runs-on` line: lower-case letters, digits, `-`, `_`
1046
/// and `.`, at most 64 bytes each; into `into`, sorted, once each.
1047
fn parse_labels(ctx: &mut Ctx, c: &KdlNode, into: &mut Vec<String>) {
1048
    let labels = ctx.strings(c);
1049
    if labels.is_empty() {
1050
        ctx.err(c.span(), "`runs-on` needs one or more labels, as runs-on \"riscv64\"");
1051
    }
1052
    for l in labels {
1053
        let ok = !l.is_empty()
1054
            && l.len() <= 64
1055
            && l.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'-' | b'_' | b'.'));
1056
        if ok {
1057
            into.push(l);
1058
        } else {
1059
            ctx.err(c.span(), format!("runs-on {l:?}: a label is lower-case letters, digits, -, _ and ., at most 64"));
1060
        }
1061
    }
1062
    into.sort();
1063
    into.dedup();
1064
}
1065
1066
/// An `env` block of `NAME "value"` lines, into `env`.
1067
fn parse_env(ctx: &mut Ctx, c: &KdlNode, env: &mut BTreeMap<String, String>) {
1068
    if !c.entries().is_empty() {
1069
        ctx.err(c.span(), "`env` takes a block of NAME \"value\" lines");
1070
    }
1071
    for e in block(ctx, c) {
1072
        let k = e.name().value().to_string();
1073
        let valid =
1074
            !k.is_empty() && !k.starts_with(|c: char| c.is_ascii_digit()) && k.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_');
1075
        if !valid {
1076
            ctx.err(e.span(), format!("environment name {k:?} must be letters, digits and _"));
1077
            continue;
1078
        }
1079
        ctx.no_children(e);
1080
        if let Some(v) = ctx.one_string(e) {
1081
            if env.insert(k.clone(), v).is_some() {
1082
                ctx.err(e.span(), format!("environment {k} is set twice"));
1083
            }
1084
        }
1085
    }
1086
}
1087
1088
/// `mount { source "ephemeral://disk"; target "/src/target"; size "8GiB" }`.
1089
fn parse_mount(ctx: &mut Ctx, node: &KdlNode) -> Option<Mount> {
1090
    let (mut source, mut target, mut size) = (None, None, None);
1091
    let (mut cache, mut keys) = (None, Vec::new());
1092
    let mut seen = BTreeSet::new();
1093
    for c in block(ctx, node) {
1094
        let key = c.name().value();
1095
        if !seen.insert(key.to_string()) {
1096
            ctx.err(c.span(), format!("`{key}` is given twice"));
1097
            continue;
1098
        }
1099
        ctx.no_children(c);
1100
        match key {
1101
            "source" => {
1102
                source = match ctx.one_string(c).as_deref() {
1103
                    Some("ephemeral://tmpfs") => Some(MountSource::Tmpfs),
1104
                    Some("ephemeral://disk") => Some(MountSource::Disk),
1105
                    Some(other) => {
1106
                        ctx.err(
1107
                            c.span(),
1108
                            format!("mount source {other:?} is not in M0 yet; M0 mounts \"ephemeral://tmpfs\" or \"ephemeral://disk\""),
1109
                        );
1110
                        None
1111
                    }
1112
                    None => None,
1113
                }
1114
            }
1115
            "target" => {
1116
                target = match ctx.one_string(c) {
1117
                    Some(t) if mount_target_ok(&t) => Some(t),
1118
                    Some(t) => {
1119
                        ctx.err(
1120
                            c.span(),
1121
                            format!("mount target {t:?} must be an absolute path under /src or /tmp, without . or .. or a trailing /"),
1122
                        );
1123
                        None
1124
                    }
1125
                    None => None,
1126
                }
1127
            }
1128
            "size" => {
1129
                size = match ctx.one_string(c) {
1130
                    Some(m) => match parse_memory(&m) {
1131
                        Some(mib) if (MIN_MOUNT_MIB..=MAX_MOUNT_MIB).contains(&mib) => Some(mib as u32),
1132
                        Some(_) => {
1133
                            ctx.err(c.span(), format!("mount size {m:?} must be from 16MiB to 64GiB"));
1134
                            None
1135
                        }
1136
                        None => {
1137
                            ctx.err(c.span(), format!("mount size {m:?}: expected a whole number of KiB, MiB or GiB, as \"8GiB\""));
1138
                            None
1139
                        }
1140
                    },
1141
                    None => None,
1142
                }
1143
            }
1144
            "cache" => {
1145
                cache = match ctx.one_string(c) {
1146
                    Some(n) if !n.is_empty() && n.len() <= 64 && n.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b)) => {
1147
                        Some(n)
1148
                    }
1149
                    Some(n) => {
1150
                        ctx.err(c.span(), format!("cache name {n:?}: letters, digits, '.', '_' and '-', at most 64"));
1151
                        None
1152
                    }
1153
                    None => None,
1154
                }
1155
            }
1156
            "key" => {
1157
                keys = ctx.strings(c);
1158
                if keys.is_empty() {
1159
                    ctx.err(c.span(), "`key` names one or more files, as \"Cargo.lock\"");
1160
                }
1161
                for k in &keys {
1162
                    if k.starts_with('/') || k.split('/').any(|p| p.is_empty() || p == "." || p == "..") {
1163
                        ctx.err(c.span(), format!("key file {k:?} must be a path in the repository, without . or .."));
1164
                    }
1165
                }
1166
            }
1167
            "readonly" | "include" => ctx.err(c.span(), format!("mount `{key}` is not in M0 yet")),
1168
            other => ctx.err(c.span(), format!("unknown mount setting `{other}`")),
1169
        }
1170
    }
1171
    for (name, missing) in [("source", source.is_none()), ("target", target.is_none()), ("size", size.is_none())] {
1172
        if missing && !seen.contains(name) {
1173
            ctx.err(node.span(), format!("a mount needs a {name}"));
1174
        }
1175
    }
1176
    if source == Some(MountSource::Tmpfs) && cache.is_some() {
1177
        ctx.err(node.span(), "only an ephemeral://disk mount can be a cache");
1178
    }
1179
    if !keys.is_empty() && cache.is_none() {
1180
        ctx.err(node.span(), "`key` goes with `cache`");
1181
    }
1182
    Some(Mount { source: source?, target: target?, size_mib: size?, cache, key: keys })
1183
}
1184
1185
/// `output { artifact "name" { path "/src/target/release/tool" } }`.
1186
/// `secret "deploy-token" { mount-path "/run/secrets/token" }` (spec §9.1).
1187
/// The hub is the vault: the secret of that name set for the repository,
1188
/// its organisation or the site. `vault-ref` is not in this slice.
1189
fn parse_secret(ctx: &mut Ctx, node: &KdlNode, job: &mut Job) {
1190
    let Some(name) = ctx.one_string(node) else {
1191
        ctx.err(node.span(), "`secret` takes a name and a block with mount-path");
1192
        return;
1193
    };
1194
    if !ctx.name_ok(node.span(), "secret", &name) {
1195
        return;
1196
    }
1197
    let mut path = None;
1198
    for c in block(ctx, node) {
1199
        ctx.no_children(c);
1200
        match c.name().value() {
1201
            "mount-path" => match ctx.one_string(c) {
1202
                Some(p) if secret_path_ok(&p) => path = Some(p),
1203
                Some(p) => {
1204
                    ctx.err(c.span(), format!("secret mount-path {p:?} must be an absolute path under /run/secrets/, without . or .."))
1205
                }
1206
                None => {}
1207
            },
1208
            "vault-ref" => ctx.err(c.span(), "`vault-ref` is not in M0; the hub supplies the secret of that name"),
1209
            other => ctx.err(c.span(), format!("unknown secret setting `{other}`")),
1210
        }
1211
    }
1212
    let Some(mount_path) = path else {
1213
        ctx.err(node.span(), format!("secret {name:?} needs a mount-path"));
1214
        return;
1215
    };
1216
    if job.secrets.iter().any(|s| s.name == name) {
1217
        ctx.err(node.span(), format!("secret {name:?} is given twice"));
1218
    } else if job.secrets.iter().any(|s| s.mount_path == mount_path) || job.identities.iter().any(|i| i.mount_path == mount_path) {
1219
        ctx.err(node.span(), format!("two files mount at {mount_path:?}"));
1220
    } else if job.secrets.len() == MAX_SECRETS {
1221
        ctx.err(node.span(), format!("a job has at most {MAX_SECRETS} secrets"));
1222
    } else {
1223
        job.secrets.push(Secret { name, mount_path });
1224
    }
1225
}
1226
1227
/// `identity "sts.amazonaws.com" { mount-path "/run/secrets/aws-token" }`:
1228
/// the hub mints an OIDC token for that audience and the runner mounts it
1229
/// as a file (oxygenhub#103).
1230
fn parse_identity(ctx: &mut Ctx, node: &KdlNode, job: &mut Job) {
1231
    let Some(audience) = ctx.one_string(node) else {
1232
        ctx.err(node.span(), "`identity` takes an audience and a block with mount-path");
1233
        return;
1234
    };
1235
    let aud_ok = !audience.is_empty() && audience.len() <= 255 && !audience.chars().any(|c| c.is_whitespace() || c.is_control());
1236
    if !aud_ok {
1237
        ctx.err(node.span(), format!("identity audience {audience:?} must be 1 to 255 characters without spaces"));
1238
        return;
1239
    }
1240
    let mut path = None;
1241
    for c in block(ctx, node) {
1242
        ctx.no_children(c);
1243
        match c.name().value() {
1244
            "mount-path" => match ctx.one_string(c) {
1245
                Some(p) if secret_path_ok(&p) => path = Some(p),
1246
                Some(p) => {
1247
                    ctx.err(c.span(), format!("identity mount-path {p:?} must be an absolute path under /run/secrets/, without . or .."))
1248
                }
1249
                None => {}
1250
            },
1251
            other => ctx.err(c.span(), format!("unknown identity setting `{other}`")),
1252
        }
1253
    }
1254
    let Some(mount_path) = path else {
1255
        ctx.err(node.span(), format!("identity {audience:?} needs a mount-path"));
1256
        return;
1257
    };
1258
    if job.identities.iter().any(|i| i.audience == audience) {
1259
        ctx.err(node.span(), format!("identity {audience:?} is given twice"));
1260
    } else if job.identities.iter().any(|i| i.mount_path == mount_path) || job.secrets.iter().any(|s| s.mount_path == mount_path) {
1261
        ctx.err(node.span(), format!("two files mount at {mount_path:?}"));
1262
    } else if job.identities.len() == MAX_IDENTITIES {
1263
        ctx.err(node.span(), format!("a job has at most {MAX_IDENTITIES} identities"));
1264
    } else {
1265
        job.identities.push(Identity { audience, mount_path });
1266
    }
1267
}
1268
1269
fn parse_output(ctx: &mut Ctx, node: &KdlNode, job: &mut Job) {
1270
    if !node.entries().is_empty() {
1271
        ctx.err(node.span(), "`output` takes a block of artifacts and reports");
1272
    }
1273
    for a in block(ctx, node) {
1274
        let kind = match a.name().value() {
1275
            "artifact" => OutputKind::Artifact,
1276
            "report" => OutputKind::Report,
1277
            other => {
1278
                ctx.err(
1279
                    a.span(),
1280
                    format!("unknown output `{other}`; outputs are `artifact \"name\" {{ path \"/src/file\" }}` and `report \"name\" {{ path \"/src/dir\" }}`"),
1281
                );
1282
                continue;
1283
            }
1284
        };
1285
        let word = kind.word();
1286
        let Some(name) = ctx.one_string(a) else { continue };
1287
        if !ctx.name_ok(a.span(), word, &name) {
1288
            continue;
1289
        }
1290
        let mut path = None;
1291
        let mut always = false;
1292
        for c in block(ctx, a) {
1293
            ctx.no_children(c);
1294
            match c.name().value() {
1295
                "path" => match ctx.one_string(c) {
1296
                    Some(p) if output_path_ok(&p) => path = Some(p),
1297
                    Some(p) => ctx
1298
                        .err(c.span(), format!("{word} path {p:?} must be an absolute path under /src, without . or .., quotes or spaces")),
1299
                    None => {}
1300
                },
1301
                "format" if kind == OutputKind::Artifact => {
1302
                    if ctx.one_string(c).as_deref() != Some("blob") {
1303
                        ctx.err(c.span(), "artifact format is \"blob\"");
1304
                    }
1305
                }
1306
                "when" => match ctx.one_string(c).as_deref() {
1307
                    Some("passed") => always = false,
1308
                    Some("always") => always = true,
1309
                    Some(_) => ctx.err(c.span(), format!("{word} `when` is \"passed\" (the default) or \"always\"")),
1310
                    None => {}
1311
                },
1312
                other => ctx.err(c.span(), format!("unknown {word} setting `{other}`")),
1313
            }
1314
        }
1315
        let Some(path) = path else {
1316
            ctx.err(a.span(), format!("{word} {name:?} needs a path"));
1317
            continue;
1318
        };
1319
        if job.outputs.iter().any(|o| o.name == name) {
1320
            ctx.err(a.span(), format!("output {name:?} is given twice (artifacts and reports share names)"));
1321
        } else if job.outputs.len() == MAX_OUTPUTS {
1322
            ctx.err(a.span(), format!("a job has at most {MAX_OUTPUTS} artifacts and reports"));
1323
        } else {
1324
            job.outputs.push(Output { name, path, always, kind });
1325
        }
1326
    }
1327
}
1328
1329
/// `approval { by "maintain"; others-only #true; expires "24h" }`, each
1330
/// optional: `maintain`, anyone with the role, 24 hours.
1331
fn parse_approval(ctx: &mut Ctx, node: &KdlNode) -> Option<Approval> {
1332
    if !node.entries().is_empty() {
1333
        ctx.err(node.span(), "`approval` takes a block: approval { by \"maintain\"; others-only #true; expires \"24h\" }");
1334
    }
1335
    let mut a = Approval { by: "maintain".into(), others_only: false, expires_s: 24 * 3600 };
1336
    let Some(children) = node.children() else { return Some(a) };
1337
    for c in children.nodes() {
1338
        ctx.no_children(c);
1339
        match c.name().value() {
1340
            "by" => match ctx.one_string(c).as_deref() {
1341
                Some(r @ ("write" | "maintain" | "admin")) => a.by = r.to_string(),
1342
                Some(r) => ctx.err(c.span(), format!("approval by {r:?}: expected \"write\", \"maintain\" or \"admin\"")),
1343
                None => {}
1344
            },
1345
            "others-only" => match c.entries() {
1346
                [e] if e.name().is_none() => match e.value() {
1347
                    KdlValue::Bool(b) => a.others_only = *b,
1348
                    _ => ctx.err(c.span(), "`others-only` takes #true or #false"),
1349
                },
1350
                _ => ctx.err(c.span(), "`others-only` takes #true or #false"),
1351
            },
1352
            "expires" => {
1353
                let Some(t) = ctx.one_string(c) else { continue };
1354
                match parse_duration(&t) {
1355
                    Some(secs) if (60..=MAX_APPROVAL_S).contains(&secs) => a.expires_s = secs,
1356
                    Some(_) => ctx.err(c.span(), format!("expires {t:?} must be from 1m to 720h")),
1357
                    None => ctx.err(c.span(), format!("expires {t:?}: expected hours, minutes and seconds, as \"24h\"")),
1358
                }
1359
            }
1360
            other => ctx.err(c.span(), format!("unknown approval setting `{other}`; approval takes `by`, `others-only` and `expires`")),
1361
        }
1362
    }
1363
    Some(a)
1364
}
1365
1366
/// `input { artifact "NAME" from "JOB"; path "/src/FILE" }`.
1367
fn parse_input(ctx: &mut Ctx, node: &KdlNode, job: &mut Job) {
1368
    if !node.entries().is_empty() {
1369
        ctx.err(node.span(), "`input` takes a block: input { artifact \"tfplan\" from \"plan\"; path \"/src/tfplan\" }");
1370
    }
1371
    let (mut artifact, mut from, mut path) = (None, None, None);
1372
    for c in block(ctx, node) {
1373
        ctx.no_children(c);
1374
        match c.name().value() {
1375
            "artifact" => match ctx.strings(c).as_slice() {
1376
                [name, word, producer] if word == "from" => {
1377
                    if ctx.name_ok(c.span(), "artifact", name) && ctx.name_ok(c.span(), "job", producer) {
1378
                        artifact = Some(name.clone());
1379
                        from = Some(producer.clone());
1380
                    }
1381
                }
1382
                _ => ctx.err(c.span(), "`artifact` names the artifact and its job: artifact \"tfplan\" from \"plan\""),
1383
            },
1384
            "path" => match ctx.one_string(c) {
1385
                Some(p) if output_path_ok(&p) => path = Some(p),
1386
                Some(p) => {
1387
                    ctx.err(c.span(), format!("input path {p:?} must be an absolute path under /src, without . or .., quotes or spaces"))
1388
                }
1389
                None => {}
1390
            },
1391
            other => ctx.err(c.span(), format!("unknown input setting `{other}`; an input has `artifact` and `path`")),
1392
        }
1393
    }
1394
    match (artifact, from, path) {
1395
        (Some(artifact), Some(from), Some(path)) => {
1396
            if job.inputs.iter().any(|i| i.path == path) {
1397
                ctx.err(node.span(), format!("two inputs are put at {path:?}"));
1398
            } else if job.inputs.len() == MAX_INPUTS {
1399
                ctx.err(node.span(), format!("a job takes at most {MAX_INPUTS} inputs"));
1400
            } else {
1401
                job.inputs.push(Input { artifact, from, path });
1402
            }
1403
        }
1404
        (a, _, p) => {
1405
            if a.is_some() && p.is_none() {
1406
                ctx.err(node.span(), "an input needs a `path`");
1407
            } else if a.is_none() && p.is_some() {
1408
                ctx.err(node.span(), "an input needs `artifact \"NAME\" from \"JOB\"`");
1409
            }
1410
        }
1411
    }
1412
}
1413
1414
fn parse_job(ctx: &mut Ctx, node: &KdlNode) -> Option<Job> {
1415
    let name = ctx.one_string(node)?;
1416
    let named = ctx.name_ok(node.span(), "job", &name);
1417
    let mut job = Job {
1418
        name: name.clone(),
1419
        sandbox: String::new(),
1420
        scope: vec![],
1421
        depends_on: vec![],
1422
        env: BTreeMap::new(),
1423
        exec: vec![],
1424
        mounts: vec![],
1425
        secrets: vec![],
1426
        identities: vec![],
1427
        outputs: vec![],
1428
        inputs: vec![],
1429
        approval: None,
1430
        runs_on: vec![],
1431
        timeout_s: None,
1432
        on: None,
1433
    };
1434
    let mut seen = BTreeSet::new();
1435
    let mut outputs_at = None;
1436
    for c in block(ctx, node) {
1437
        let key = c.name().value();
1438
        if key != "scope"
1439
            && key != "depends-on"
1440
            && key != "mount"
1441
            && key != "secret"
1442
            && key != "identity"
1443
            && key != "runs-on"
1444
            && !seen.insert(key.to_string())
1445
        {
1446
            ctx.err(c.span(), format!("`{key}` is given twice"));
1447
        }
1448
        match key {
1449
            "sandbox" => {
1450
                ctx.no_children(c);
1451
                job.sandbox = ctx.one_string(c).unwrap_or_default();
1452
            }
1453
            "scope" => {
1454
                ctx.no_children(c);
1455
                for g in ctx.strings(c) {
1456
                    match globset::Glob::new(&g) {
1457
                        Ok(_) => job.scope.push(g),
1458
                        Err(e) => ctx.err(c.span(), format!("scope {g:?}: {e}")),
1459
                    }
1460
                }
1461
            }
1462
            "depends-on" => {
1463
                ctx.no_children(c);
1464
                job.depends_on.extend(ctx.strings(c));
1465
            }
1466
            "runs-on" => {
1467
                ctx.no_children(c);
1468
                parse_labels(ctx, c, &mut job.runs_on);
1469
            }
1470
            "timeout" => {
1471
                ctx.no_children(c);
1472
                job.timeout_s = parse_timeout(ctx, c);
1473
            }
1474
            "on" => job.on = Some(parse_on(ctx, c)),
1475
            "env" => parse_env(ctx, c, &mut job.env),
1476
            "exec" => {
1477
                ctx.no_children(c);
1478
                job.exec = ctx.strings(c);
1479
                if job.exec.is_empty() {
1480
                    ctx.err(c.span(), "`exec` needs a program and its arguments");
1481
                } else if job.exec.iter().any(|a| a.contains('\0')) {
1482
                    ctx.err(c.span(), "`exec` arguments cannot contain NUL");
1483
                }
1484
            }
1485
            "mount" => {
1486
                if !c.entries().is_empty() {
1487
                    ctx.err(c.span(), "`mount` takes a block of source, target and size");
1488
                }
1489
                if let Some(m) = parse_mount(ctx, c) {
1490
                    if job.mounts.len() == MAX_MOUNTS {
1491
                        ctx.err(c.span(), format!("a job has at most {MAX_MOUNTS} mounts"));
1492
                    } else if let Some(other) = job.mounts.iter().find(|o| {
1493
                        o.target == m.target
1494
                            || m.target.starts_with(&format!("{}/", o.target))
1495
                            || o.target.starts_with(&format!("{}/", m.target))
1496
                    }) {
1497
                        ctx.err(c.span(), format!("mount {:?} overlaps mount {:?}", m.target, other.target));
1498
                    } else {
1499
                        job.mounts.push(m);
1500
                    }
1501
                }
1502
            }
1503
            "output" => {
1504
                outputs_at = Some(c.span());
1505
                parse_output(ctx, c, &mut job);
1506
            }
1507
            "input" => parse_input(ctx, c, &mut job),
1508
            "approval" => job.approval = parse_approval(ctx, c),
1509
            "secret" => parse_secret(ctx, c, &mut job),
1510
            "identity" => parse_identity(ctx, c, &mut job),
1511
            n if LATER_JOB.contains(&n) => ctx.err(c.span(), format!("`{n}` is not in M0 yet")),
1512
            other => ctx.err(c.span(), format!("unknown job setting `{other}`")),
1513
        }
1514
    }
1515
    job.mounts.sort_by(|a, b| a.target.cmp(&b.target));
1516
    job.outputs.sort_by(|a, b| a.name.cmp(&b.name));
1517
    job.inputs.sort_by(|a, b| a.path.cmp(&b.path));
1518
    job.secrets.sort_by(|a, b| a.name.cmp(&b.name));
1519
    job.identities.sort_by(|a, b| a.audience.cmp(&b.audience));
1520
    // A tmpfs is gone when the job ends; nothing on it can be kept.
1521
    for o in &job.outputs {
1522
        if let Some(m) = job.mounts.iter().find(|m| m.source == MountSource::Tmpfs && o.path.starts_with(&format!("{}/", m.target))) {
1523
            ctx.err(
1524
                outputs_at.unwrap_or(node.span()),
1525
                format!(
1526
                    "artifact {:?} is on the tmpfs mount {:?}, which is gone when the job ends; use ephemeral://disk",
1527
                    o.name, m.target
1528
                ),
1529
            );
1530
        }
1531
    }
1532
    if job.sandbox.is_empty() && !seen.contains("sandbox") {
1533
        ctx.err(node.span(), format!("job {name:?} needs a sandbox"));
1534
    }
1535
    if job.exec.is_empty() && !seen.contains("exec") {
1536
        ctx.err(node.span(), format!("job {name:?} needs an exec"));
1537
    }
1538
    job.depends_on.sort();
1539
    job.depends_on.dedup();
1540
    // Kept even when incomplete, so its references are checked too; the
1541
    // problems above already make the pipeline invalid.
1542
    named.then_some(job)
1543
}