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