vela-cli 0.940.9

The vela command-line tool: build, check, sign, replay, and publish scientific frontier state.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
//! Bounded, symlink-safe reads for files retained inside a frontier.
//!
//! The read happens through one already-open descriptor. Path identity is
//! checked before and after the bounded read, so a concurrent rename or
//! symlink swap cannot substitute different bytes after validation on the
//! supported Unix and Windows targets.

use std::io::Read;
use std::path::{Component, Path};

pub(crate) const RECEIPT_MAX_BYTES: u64 = 8 * 1024 * 1024;
pub(crate) const PUBLIC_ARTIFACT_MAX_BYTES: u64 = 8 * 1024 * 1024;
pub(crate) const PUBLIC_ARTIFACT_TOTAL_MAX_BYTES: u64 = 64 * 1024 * 1024;

#[derive(Debug)]
pub(crate) struct BoundedFileError {
    pub(crate) code: &'static str,
    pub(crate) message: String,
    /// True only when a descriptor was successfully opened. Tests use this to
    /// prove pagination selects IDs before it touches retained material.
    pub(crate) opened: bool,
}

impl BoundedFileError {
    fn new(code: &'static str, message: impl Into<String>, opened: bool) -> Self {
        Self {
            code,
            message: message.into(),
            opened,
        }
    }
}

impl std::fmt::Display for BoundedFileError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(&self.message)
    }
}

/// Read one explicitly supplied file without allowing its path to swap to a
/// symlink or different inode while Vela is reading it. Unlike
/// [`read_bounded_frontier_file`], this accepts a path outside the frontier so
/// portable Receipt v1 files can be landed directly.
pub(crate) fn read_bounded_file(
    path: &Path,
    max_bytes: u64,
    label: &str,
) -> Result<Vec<u8>, BoundedFileError> {
    let metadata = std::fs::symlink_metadata(path).map_err(|error| {
        BoundedFileError::new(
            if error.kind() == std::io::ErrorKind::NotFound {
                "missing"
            } else {
                "inspect_failed"
            },
            format!("inspect {label} {}: {error}", path.display()),
            false,
        )
    })?;
    if metadata.file_type().is_symlink() {
        return Err(BoundedFileError::new(
            "symlink",
            format!("{label} must not be a symlink: {}", path.display()),
            false,
        ));
    }
    if !metadata.is_file() {
        return Err(BoundedFileError::new(
            "not_regular",
            format!("{label} must be a regular file: {}", path.display()),
            false,
        ));
    }
    if metadata.len() > max_bytes {
        return Err(BoundedFileError::new(
            "oversized",
            format!(
                "{label} {} exceeds the {max_bytes}-byte limit",
                path.display()
            ),
            false,
        ));
    }

    let inspected_identity = same_file::Handle::from_path(path).map_err(|error| {
        BoundedFileError::new(
            "inspect_failed",
            format!("identify {label} {}: {error}", path.display()),
            false,
        )
    })?;
    let file = std::fs::File::open(path).map_err(|error| {
        BoundedFileError::new(
            "open_failed",
            format!("open {label} {}: {error}", path.display()),
            false,
        )
    })?;
    let opened = file.metadata().map_err(|error| {
        BoundedFileError::new(
            "inspect_open_failed",
            format!("inspect open {label} {}: {error}", path.display()),
            true,
        )
    })?;
    if !opened.is_file() {
        return Err(BoundedFileError::new(
            "not_regular",
            format!("{label} must be a regular file: {}", path.display()),
            true,
        ));
    }
    let opened_identity = same_file::Handle::from_file(file.try_clone().map_err(|error| {
        BoundedFileError::new(
            "inspect_open_failed",
            format!("clone open {label} {}: {error}", path.display()),
            true,
        )
    })?)
    .map_err(|error| {
        BoundedFileError::new(
            "inspect_open_failed",
            format!("identify open {label} {}: {error}", path.display()),
            true,
        )
    })?;
    verify_handle_identity(&inspected_identity, &opened_identity, path, label, true)?;
    if opened.len() > max_bytes {
        return Err(BoundedFileError::new(
            "oversized",
            format!(
                "{label} {} exceeds the {max_bytes}-byte limit",
                path.display()
            ),
            true,
        ));
    }
    verify_named_path_identity(path, &opened_identity, label, true)?;

    let mut bytes = Vec::new();
    file.take(max_bytes.saturating_add(1))
        .read_to_end(&mut bytes)
        .map_err(|error| {
            BoundedFileError::new(
                "read_failed",
                format!("read {label} {}: {error}", path.display()),
                true,
            )
        })?;
    if bytes.len() as u64 > max_bytes {
        return Err(BoundedFileError::new(
            "oversized",
            format!(
                "{label} {} exceeds the {max_bytes}-byte limit",
                path.display()
            ),
            true,
        ));
    }
    verify_named_path_identity(path, &opened_identity, label, true)?;
    Ok(bytes)
}

pub(crate) fn read_bounded_frontier_file(
    frontier: &Path,
    relative: &Path,
    max_bytes: u64,
    label: &str,
) -> Result<Vec<u8>, BoundedFileError> {
    if relative.is_absolute()
        || !relative
            .components()
            .all(|component| matches!(component, Component::Normal(_)))
    {
        return Err(BoundedFileError::new(
            "path_invalid",
            format!(
                "{label} path must be normalized and frontier-relative: {}",
                relative.display()
            ),
            false,
        ));
    }
    let root = frontier.canonicalize().map_err(|error| {
        BoundedFileError::new(
            "frontier_unresolvable",
            format!("canonicalize frontier for {label}: {error}"),
            false,
        )
    })?;
    let components = relative.components().collect::<Vec<_>>();
    let mut current = root.clone();
    let mut inspected_identity = None;
    for (index, component) in components.iter().enumerate() {
        let Component::Normal(component) = component else {
            unreachable!("relative components were validated")
        };
        current.push(component);
        let metadata = match std::fs::symlink_metadata(&current) {
            Ok(metadata) => metadata,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                return Err(BoundedFileError::new(
                    "missing",
                    format!("{label} is missing: {}", current.display()),
                    false,
                ));
            }
            Err(error) => {
                return Err(BoundedFileError::new(
                    "inspect_failed",
                    format!("inspect {label} {}: {error}", current.display()),
                    false,
                ));
            }
        };
        if metadata.file_type().is_symlink() {
            return Err(BoundedFileError::new(
                "symlink",
                format!("{label} path traverses a symlink: {}", current.display()),
                false,
            ));
        }
        let is_leaf = index + 1 == components.len();
        if is_leaf {
            if !metadata.is_file() {
                return Err(BoundedFileError::new(
                    "not_regular",
                    format!("{label} must be a regular file: {}", current.display()),
                    false,
                ));
            }
            if metadata.len() > max_bytes {
                return Err(BoundedFileError::new(
                    "oversized",
                    format!(
                        "{label} {} exceeds the {max_bytes}-byte limit",
                        current.display()
                    ),
                    false,
                ));
            }
            inspected_identity = Some(same_file::Handle::from_path(&current).map_err(|error| {
                BoundedFileError::new(
                    "inspect_failed",
                    format!("identify {label} {}: {error}", current.display()),
                    false,
                )
            })?);
        } else if !metadata.is_dir() {
            return Err(BoundedFileError::new(
                "ancestor_not_directory",
                format!(
                    "{label} ancestor must be a directory: {}",
                    current.display()
                ),
                false,
            ));
        }
    }

    let file = std::fs::File::open(&current).map_err(|error| {
        BoundedFileError::new(
            "open_failed",
            format!("open {label} {}: {error}", current.display()),
            false,
        )
    })?;
    let opened = file.metadata().map_err(|error| {
        BoundedFileError::new(
            "inspect_open_failed",
            format!("inspect open {label} {}: {error}", current.display()),
            true,
        )
    })?;
    if !opened.is_file() {
        return Err(BoundedFileError::new(
            "not_regular",
            format!("{label} must be a regular file: {}", current.display()),
            true,
        ));
    }
    let inspected_identity = inspected_identity.ok_or_else(|| {
        BoundedFileError::new(
            "path_invalid",
            format!(
                "{label} path must name a frontier-relative file: {}",
                relative.display()
            ),
            true,
        )
    })?;
    let opened_identity = same_file::Handle::from_file(file.try_clone().map_err(|error| {
        BoundedFileError::new(
            "inspect_open_failed",
            format!("clone open {label} {}: {error}", current.display()),
            true,
        )
    })?)
    .map_err(|error| {
        BoundedFileError::new(
            "inspect_open_failed",
            format!("identify open {label} {}: {error}", current.display()),
            true,
        )
    })?;
    verify_handle_identity(&inspected_identity, &opened_identity, &current, label, true)?;
    if opened.len() > max_bytes {
        return Err(BoundedFileError::new(
            "oversized",
            format!(
                "{label} {} exceeds the {max_bytes}-byte limit",
                current.display()
            ),
            true,
        ));
    }
    verify_open_path_identity(&root, &current, &opened_identity, label, true)?;

    let mut bytes = Vec::new();
    file.take(max_bytes.saturating_add(1))
        .read_to_end(&mut bytes)
        .map_err(|error| {
            BoundedFileError::new(
                "read_failed",
                format!("read {label} {}: {error}", current.display()),
                true,
            )
        })?;
    if bytes.len() as u64 > max_bytes {
        return Err(BoundedFileError::new(
            "oversized",
            format!(
                "{label} {} exceeds the {max_bytes}-byte limit",
                current.display()
            ),
            true,
        ));
    }
    verify_open_path_identity(&root, &current, &opened_identity, label, true)?;
    Ok(bytes)
}

fn verify_open_path_identity(
    root: &Path,
    current: &Path,
    opened: &same_file::Handle,
    label: &str,
    descriptor_opened: bool,
) -> Result<(), BoundedFileError> {
    verify_named_path_identity(current, opened, label, descriptor_opened)?;
    let canonical = current.canonicalize().map_err(|error| {
        BoundedFileError::new(
            "path_changed",
            format!("canonicalize {label} {}: {error}", current.display()),
            descriptor_opened,
        )
    })?;
    if !canonical.starts_with(root) {
        return Err(BoundedFileError::new(
            "path_escape",
            format!(
                "{label} resolved outside the frontier: {}",
                canonical.display()
            ),
            descriptor_opened,
        ));
    }
    Ok(())
}

fn verify_named_path_identity(
    current: &Path,
    opened: &same_file::Handle,
    label: &str,
    descriptor_opened: bool,
) -> Result<(), BoundedFileError> {
    let linked = std::fs::symlink_metadata(current).map_err(|error| {
        BoundedFileError::new(
            "path_changed",
            format!("reinspect {label} {}: {error}", current.display()),
            descriptor_opened,
        )
    })?;
    if linked.file_type().is_symlink() || !linked.is_file() {
        return Err(BoundedFileError::new(
            "path_changed",
            format!(
                "{label} path must remain a non-symlink regular file: {}",
                current.display()
            ),
            descriptor_opened,
        ));
    }
    let named = same_file::Handle::from_path(current).map_err(|error| {
        BoundedFileError::new(
            "path_changed",
            format!("reinspect named {label} {}: {error}", current.display()),
            descriptor_opened,
        )
    })?;
    verify_handle_identity(&named, opened, current, label, descriptor_opened)
}

fn verify_handle_identity(
    inspected: &same_file::Handle,
    opened: &same_file::Handle,
    current: &Path,
    label: &str,
    descriptor_opened: bool,
) -> Result<(), BoundedFileError> {
    if inspected != opened {
        return Err(BoundedFileError::new(
            "path_changed",
            format!("{label} path changed while open: {}", current.display()),
            descriptor_opened,
        ));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::path::PathBuf;

    #[test]
    fn reads_a_valid_normalized_frontier_relative_file() {
        let frontier = tempfile::tempdir().unwrap();
        let relative = Path::new("records/receipts/receipt.json");
        let absolute = frontier.path().join(relative);
        fs::create_dir_all(absolute.parent().unwrap()).unwrap();
        fs::write(&absolute, b"bounded receipt bytes").unwrap();

        let bytes = read_bounded_frontier_file(
            frontier.path(),
            relative,
            b"bounded receipt bytes".len() as u64,
            "receipt",
        )
        .unwrap();

        assert_eq!(bytes, b"bounded receipt bytes");
    }

    #[test]
    fn standalone_reader_accepts_an_absolute_file_and_rejects_size_before_open() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("receipt.json");
        fs::write(&path, b"bounded receipt bytes").unwrap();
        assert_eq!(
            read_bounded_file(&path, b"bounded receipt bytes".len() as u64, "receipt").unwrap(),
            b"bounded receipt bytes"
        );

        let error = read_bounded_file(&path, 4, "receipt").unwrap_err();
        assert_eq!(error.code, "oversized");
        assert!(!error.opened);
    }

    #[cfg(unix)]
    #[test]
    fn standalone_reader_rejects_a_symlink_leaf_before_open() {
        use std::os::unix::fs::symlink;

        let directory = tempfile::tempdir().unwrap();
        let real = directory.path().join("real.json");
        let linked = directory.path().join("linked.json");
        fs::write(&real, b"receipt").unwrap();
        symlink(&real, &linked).unwrap();

        let error = read_bounded_file(&linked, 128, "receipt").unwrap_err();
        assert_eq!(error.code, "symlink");
        assert!(!error.opened);
    }

    #[test]
    fn inspected_leaf_identity_must_match_the_open_descriptor() {
        let directory = tempfile::tempdir().unwrap();
        let inspected_path = directory.path().join("inspected.json");
        let substituted_path = directory.path().join("substituted.json");
        fs::write(&inspected_path, b"inspected").unwrap();
        fs::write(&substituted_path, b"substituted").unwrap();
        let inspected = same_file::Handle::from_path(&inspected_path).unwrap();
        let substituted = same_file::Handle::from_path(&substituted_path).unwrap();

        let error =
            verify_handle_identity(&inspected, &substituted, &inspected_path, "receipt", true)
                .unwrap_err();
        assert_eq!(error.code, "path_changed");
        assert!(error.opened);
    }

    #[test]
    fn rejects_oversized_input_before_opening_a_descriptor() {
        let frontier = tempfile::tempdir().unwrap();
        let relative = Path::new("records/receipt.json");
        let absolute = frontier.path().join(relative);
        fs::create_dir_all(absolute.parent().unwrap()).unwrap();
        fs::write(&absolute, b"12345").unwrap();

        let error =
            read_bounded_frontier_file(frontier.path(), relative, 4, "receipt").unwrap_err();

        assert_eq!(error.code, "oversized");
        assert!(!error.opened, "size metadata must reject before File::open");
    }

    #[cfg(unix)]
    #[test]
    fn rejects_a_symlink_leaf_before_opening_a_descriptor() {
        use std::os::unix::fs::symlink;

        let frontier = tempfile::tempdir().unwrap();
        fs::write(frontier.path().join("real.json"), b"real bytes").unwrap();
        symlink("real.json", frontier.path().join("receipt.json")).unwrap();

        let error =
            read_bounded_frontier_file(frontier.path(), Path::new("receipt.json"), 128, "receipt")
                .unwrap_err();

        assert_eq!(error.code, "symlink");
        assert!(!error.opened);
    }

    #[cfg(unix)]
    #[test]
    fn rejects_a_symlink_ancestor_before_opening_a_descriptor() {
        use std::os::unix::fs::symlink;

        let frontier = tempfile::tempdir().unwrap();
        let real_directory = frontier.path().join("real-records");
        fs::create_dir(&real_directory).unwrap();
        fs::write(real_directory.join("receipt.json"), b"real bytes").unwrap();
        symlink("real-records", frontier.path().join("records")).unwrap();

        let error = read_bounded_frontier_file(
            frontier.path(),
            Path::new("records/receipt.json"),
            128,
            "receipt",
        )
        .unwrap_err();

        assert_eq!(error.code, "symlink");
        assert!(!error.opened);
    }

    #[test]
    fn accepts_only_normalized_frontier_relative_paths() {
        let frontier = tempfile::tempdir().unwrap();
        let absolute = frontier.path().join("receipt.json");
        fs::write(&absolute, b"receipt").unwrap();
        let invalid = [
            PathBuf::from("./receipt.json"),
            PathBuf::from("records/../receipt.json"),
            absolute,
        ];

        for path in invalid {
            let error =
                read_bounded_frontier_file(frontier.path(), &path, 128, "receipt").unwrap_err();
            assert_eq!(error.code, "path_invalid", "path: {}", path.display());
            assert!(!error.opened, "path: {}", path.display());
        }
    }
}