verirun-core 0.2.0

Deterministic core for verirun covering RFC 8785 canonical JSON, domain-separated SHA-256 digest framing, DAG validation, and Merkle manifests with std only.
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
//! Core error types.
//!
//! Every error carries the concrete diagnostic context a person needs to
//! act: byte offsets, the offending text, and expected versus actual
//! values where a comparison failed. A bare variant name is never the
//! whole message (docs/ARCHITECTURE.md section 11).

use core::fmt;

use crate::digest::Digest;

/// The class of a [`CanonicalError`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CanonicalErrorKind {
    /// The number is NaN or an infinity. RFC 8785 has no encoding for it.
    NonFiniteNumber,
    /// The number is integral in value and its magnitude exceeds the
    /// IEEE 754 safe integer bound of 9007199254740991.
    IntegerOutOfSafeRange,
    /// An object was constructed or encoded with a duplicate key.
    DuplicateKey,
    /// A programmatically built value nests deeper than the depth
    /// limit the parser enforces, so encoding it would recurse
    /// without bound.
    DepthLimitExceeded,
}

/// A canonicalization failure: a domain rejection from the number rules
/// or from object construction or encoding.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CanonicalError {
    kind: CanonicalErrorKind,
    offset: Option<usize>,
    detail: String,
}

impl CanonicalError {
    /// Creates an error with no source offset.
    #[must_use]
    pub const fn new(kind: CanonicalErrorKind, detail: String) -> Self {
        Self {
            kind,
            offset: None,
            detail,
        }
    }

    /// Creates an error tied to a byte offset in a parsed source.
    #[must_use]
    pub const fn at_offset(kind: CanonicalErrorKind, offset: usize, detail: String) -> Self {
        Self {
            kind,
            offset: Some(offset),
            detail,
        }
    }

    /// The error class.
    #[must_use]
    pub const fn kind(&self) -> CanonicalErrorKind {
        self.kind
    }

    /// The byte offset in the source, when the error came from parsing.
    #[must_use]
    pub const fn offset(&self) -> Option<usize> {
        self.offset
    }

    /// The human-readable diagnostic detail.
    #[must_use]
    pub fn detail(&self) -> &str {
        &self.detail
    }
}

impl fmt::Display for CanonicalError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.offset {
            Some(offset) => write!(
                f,
                "canonicalization error at byte {offset}: {}",
                self.detail
            ),
            None => write!(f, "canonicalization error: {}", self.detail),
        }
    }
}

impl std::error::Error for CanonicalError {}

/// The class of a [`ParseError`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ParseErrorKind {
    /// The input is empty.
    EmptyInput,
    /// A byte that cannot start or continue the expected token.
    UnexpectedByte,
    /// The input ended in the middle of a value.
    UnexpectedEnd,
    /// A literal other than `true`, `false`, or `null`.
    InvalidLiteral,
    /// A number that violates the JSON number grammar.
    InvalidNumber,
    /// A number literal that overflows f64 to an infinity.
    NumberOutOfRange,
    /// A number whose integral value exceeds the safe integer bound.
    IntegerOutOfSafeRange,
    /// An object key that already appeared in the same object.
    DuplicateKey,
    /// Nesting deeper than the parser depth limit.
    DepthLimit,
    /// A `\u` escape holding a surrogate with no valid partner.
    LoneSurrogate,
    /// An unknown escape character after a backslash.
    InvalidEscape,
    /// A `\u` escape that is not four hexadecimal digits.
    InvalidUnicodeEscape,
    /// A raw control character (below U+0020) inside a string.
    ControlCharacterInString,
    /// The input is not valid UTF-8.
    InvalidUtf8,
    /// Non-whitespace bytes after the top-level value.
    TrailingBytes,
}

/// A parse failure. Always carries the byte offset of the failure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseError {
    kind: ParseErrorKind,
    offset: usize,
    detail: String,
}

impl ParseError {
    /// Creates a parse error at a byte offset.
    #[must_use]
    pub const fn new(kind: ParseErrorKind, offset: usize, detail: String) -> Self {
        Self {
            kind,
            offset,
            detail,
        }
    }

    /// The error class.
    #[must_use]
    pub const fn kind(&self) -> ParseErrorKind {
        self.kind
    }

    /// The byte offset of the failure in the input.
    #[must_use]
    pub const fn offset(&self) -> usize {
        self.offset
    }

    /// The human-readable diagnostic detail.
    #[must_use]
    pub fn detail(&self) -> &str {
        &self.detail
    }
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "parse error at byte {}: {}", self.offset, self.detail)
    }
}

impl std::error::Error for ParseError {}

/// The class of a [`DigestError`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DigestErrorKind {
    /// The hex text has the wrong length for a 32-byte digest.
    InvalidLength,
    /// The hex text holds a character that is not a lowercase hex digit.
    InvalidCharacter,
}

/// A failure to parse a [`crate::digest::Digest`] from hex text.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DigestError {
    kind: DigestErrorKind,
    detail: String,
}

impl DigestError {
    /// Creates a digest error.
    #[must_use]
    pub const fn new(kind: DigestErrorKind, detail: String) -> Self {
        Self { kind, detail }
    }

    /// The error class.
    #[must_use]
    pub const fn kind(&self) -> DigestErrorKind {
        self.kind
    }

    /// The human-readable diagnostic detail.
    #[must_use]
    pub fn detail(&self) -> &str {
        &self.detail
    }
}

impl fmt::Display for DigestError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "digest error: {}", self.detail)
    }
}

impl std::error::Error for DigestError {}

/// The class of a [`PathError`]: the sandbox path rule a declared
/// path broke (docs/ARCHITECTURE.md section 8.4).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PathErrorKind {
    /// The path is empty, or nothing remains after dot and empty
    /// components are normalized away.
    Empty,
    /// The path is absolute: a leading separator, or a Windows
    /// drive prefix of one ASCII letter and a colon.
    Absolute,
    /// The path contains a backslash, a separator spelling this
    /// system does not use.
    BackslashSeparator,
    /// The path contains a `..` component.
    ParentTraversal,
}

/// A sandbox path rule failure. Carries the declared path exactly
/// as written and the rule it broke.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PathError {
    kind: PathErrorKind,
    declared: String,
    detail: String,
}

impl PathError {
    /// Creates a path error for a declared path.
    #[must_use]
    pub const fn new(kind: PathErrorKind, declared: String, detail: String) -> Self {
        Self {
            kind,
            declared,
            detail,
        }
    }

    /// The rule the path broke.
    #[must_use]
    pub const fn kind(&self) -> PathErrorKind {
        self.kind
    }

    /// The declared path, exactly as written in the spec.
    #[must_use]
    pub fn declared(&self) -> &str {
        &self.declared
    }

    /// The human-readable diagnostic detail.
    #[must_use]
    pub fn detail(&self) -> &str {
        &self.detail
    }
}

impl fmt::Display for PathError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "invalid sandbox path {:?}: {}",
            self.declared, self.detail
        )
    }
}

impl std::error::Error for PathError {}

/// A DAG validation failure (docs/ARCHITECTURE.md section 7.1).
///
/// Validation checks run in a fixed order, so for a given spec
/// exactly one of these is ever the reported error, and it is the
/// same on every host and every run.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DagError {
    /// A task object, or the run file itself, violates the schema
    /// of section 3.2. `task_id` names the task when the violation
    /// is inside one and the id could be read.
    Schema {
        /// The task holding the violation, when identifiable.
        task_id: Option<String>,
        /// What the schema requires and what was found.
        detail: String,
    },
    /// Two tasks share a `task_id`. The error names the id.
    DuplicateTaskId {
        /// The duplicated task id.
        task_id: String,
    },
    /// A `depends_on` entry names no task in the run.
    UnknownDependency {
        /// The task declaring the dependency.
        task_id: String,
        /// The dependency id that names no task.
        missing: String,
    },
    /// A normalized output path is claimed by two tasks, or twice
    /// by one task.
    CollidingOutput {
        /// The normalized colliding path.
        path: String,
        /// The first task that claimed the path.
        first_task: String,
        /// The second task that claimed the path.
        second_task: String,
    },
    /// A task declares the same normalized input path more than
    /// once.
    DuplicateInput {
        /// The task declaring the input.
        task_id: String,
        /// The normalized input path declared more than once.
        path: String,
    },
    /// A declared input or output path breaks a sandbox path rule.
    InvalidPath {
        /// The task declaring the path.
        task_id: String,
        /// The path failure, carrying the declared path.
        source: PathError,
    },
    /// The graph does not fully order under Kahn's algorithm.
    Cycle {
        /// The tasks left with nonzero indegree, sorted.
        remnants: Vec<String>,
    },
}

impl fmt::Display for DagError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Schema { task_id, detail } => match task_id {
                Some(task_id) => write!(f, "schema violation in task {task_id:?}: {detail}"),
                None => write!(f, "schema violation: {detail}"),
            },
            Self::DuplicateTaskId { task_id } => {
                write!(f, "duplicate task id {task_id:?}")
            }
            Self::UnknownDependency { task_id, missing } => {
                write!(f, "task {task_id:?} depends on unknown task {missing:?}")
            }
            Self::CollidingOutput {
                path,
                first_task,
                second_task,
            } => write!(
                f,
                "output path {path:?} is claimed by both {first_task:?} and {second_task:?}"
            ),
            Self::DuplicateInput { task_id, path } => {
                write!(f, "task {task_id:?} declares input {path:?} more than once")
            }
            Self::InvalidPath { task_id, source } => {
                write!(f, "task {task_id:?} declares an invalid path: {source}")
            }
            Self::Cycle { remnants } => write!(
                f,
                "dependency cycle: tasks left unordered are {}",
                remnants.join(", ")
            ),
        }
    }
}

impl std::error::Error for DagError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::InvalidPath { source, .. } => Some(source),
            _ => None,
        }
    }
}

/// A failure to interpret a value as a manifest or a task record
/// (docs/ARCHITECTURE.md section 9.1).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ManifestError {
    /// The `format` field names a different manifest format.
    WrongFormat {
        /// The format string found.
        found: String,
    },
    /// A required field is absent.
    MissingField {
        /// The absent field's name.
        field: &'static str,
    },
    /// A field holds a value of the wrong JSON type.
    WrongType {
        /// The field's name.
        field: &'static str,
        /// The type the field must hold.
        expected: &'static str,
    },
    /// A digest field holds text that is not a valid digest.
    InvalidDigest {
        /// The field's name.
        field: &'static str,
        /// The digest parse failure.
        source: DigestError,
    },
    /// A status field names no known task status.
    UnknownStatus {
        /// The status string found.
        found: String,
    },
    /// A numeric field holds a value outside its domain: a
    /// negative or fractional byte length, or an exit code outside
    /// the `i32` range.
    InvalidNumber {
        /// The field's name.
        field: &'static str,
        /// What the number must satisfy and what was found.
        detail: String,
    },
    /// Two task records in one manifest share a task id. No run
    /// can produce that, and consumers keyed by task id would
    /// silently drop one of the records.
    DuplicateTaskId {
        /// The duplicated task id.
        task_id: String,
    },
    /// One task record names the same artifact path twice. No
    /// run can produce that, because collection holds one entry
    /// per declared output.
    DuplicateArtifactPath {
        /// The task holding the record.
        task_id: String,
        /// The artifact path named twice.
        path: String,
    },
}

impl fmt::Display for ManifestError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::WrongFormat { found } => {
                write!(
                    f,
                    "manifest format is {found:?}, expected \"verirun-manifest/1\""
                )
            }
            Self::MissingField { field } => write!(f, "manifest field {field:?} is missing"),
            Self::WrongType { field, expected } => {
                write!(f, "manifest field {field:?} must be {expected}")
            }
            Self::InvalidDigest { field, source } => {
                write!(
                    f,
                    "manifest field {field:?} is not a valid digest: {source}"
                )
            }
            Self::UnknownStatus { found } => write!(f, "unknown task status {found:?}"),
            Self::InvalidNumber { field, detail } => {
                write!(
                    f,
                    "manifest field {field:?} holds an invalid number: {detail}"
                )
            }
            Self::DuplicateTaskId { task_id } => {
                write!(f, "manifest holds two records for task {task_id:?}")
            }
            Self::DuplicateArtifactPath { task_id, path } => {
                write!(
                    f,
                    "manifest record for task {task_id:?} names artifact {path:?} more than once"
                )
            }
        }
    }
}

impl std::error::Error for ManifestError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::InvalidDigest { source, .. } => Some(source),
            _ => None,
        }
    }
}

/// A manifest verification failure (docs/ARCHITECTURE.md
/// section 9.3).
///
/// Every variant carries the expected and actual digests, and the
/// referencing task and path where a blob is involved. The CLI
/// maps every variant to exit code 2.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VerifyError {
    /// The requested manifest digest names no object in the store.
    ManifestMissing {
        /// The requested manifest digest.
        digest: Digest,
    },
    /// The manifest object exists but could not be read, for a
    /// reason other than absence or corruption, such as a
    /// permission failure.
    ManifestUnreadable {
        /// The requested manifest digest.
        digest: Digest,
        /// The store failure that prevented the read.
        detail: String,
    },
    /// The manifest blob does not hash to the requested digest.
    ManifestDigestMismatch {
        /// The requested digest.
        expected: Digest,
        /// The digest the blob actually hashes to.
        actual: Digest,
    },
    /// The manifest bytes are not the canonical encoding of their
    /// own content.
    NonCanonicalManifest {
        /// What re-encoding changed.
        detail: String,
    },
    /// The manifest bytes do not parse into a manifest.
    MalformedManifest {
        /// The manifest parse failure.
        source: ManifestError,
    },
    /// The stored Merkle root differs from the root recomputed
    /// from the record fields.
    RootMismatch {
        /// The root stored in the manifest.
        stored: Digest,
        /// The root recomputed from the records.
        recomputed: Digest,
    },
    /// A blob the manifest names is absent from the store.
    BlobMissing {
        /// The missing blob digest.
        digest: Digest,
        /// One task that references the blob.
        task_id: String,
        /// The artifact path that references it, or `stdout` or
        /// `stderr` for a log blob.
        path: String,
    },
    /// A blob the manifest names exists but could not be read,
    /// for a reason other than absence or corruption, such as a
    /// permission failure.
    BlobUnreadable {
        /// The unreadable blob digest.
        digest: Digest,
        /// One task that references the blob.
        task_id: String,
        /// The artifact path that references it, or `stdout` or
        /// `stderr` for a log blob.
        path: String,
        /// The store failure that prevented the read.
        detail: String,
    },
    /// A blob the manifest names does not hash to its digest.
    BlobMismatch {
        /// The digest the manifest names.
        expected: Digest,
        /// The digest the content actually hashes to.
        actual: Digest,
        /// One task that references the blob.
        task_id: String,
        /// The artifact path that references it, or `stdout` or
        /// `stderr` for a log blob.
        path: String,
    },
    /// An artifact record's declared byte length differs from the
    /// verified byte length of the blob it names.
    ArtifactSizeMismatch {
        /// The blob digest the artifact record names.
        digest: Digest,
        /// The byte length recorded in the manifest.
        expected: u64,
        /// The actual byte length of the verified blob.
        actual: u64,
        /// The task holding the inconsistent artifact record.
        task_id: String,
        /// The artifact path holding the inconsistent byte length.
        path: String,
    },
}

impl fmt::Display for VerifyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ManifestMissing { digest } => {
                write!(f, "no manifest object {digest} in the store")
            }
            Self::ManifestUnreadable { digest, detail } => {
                write!(f, "manifest object {digest} could not be read: {detail}")
            }
            Self::ManifestDigestMismatch { expected, actual } => write!(
                f,
                "manifest digest mismatch: requested {expected}, content hashes to {actual}"
            ),
            Self::NonCanonicalManifest { detail } => {
                write!(f, "manifest is not in canonical form: {detail}")
            }
            Self::MalformedManifest { source } => write!(f, "malformed manifest: {source}"),
            Self::RootMismatch { stored, recomputed } => write!(
                f,
                "merkle root mismatch: stored {stored}, recomputed {recomputed}"
            ),
            Self::BlobMissing {
                digest,
                task_id,
                path,
            } => write!(
                f,
                "blob {digest} referenced by task {task_id:?} at {path:?} is missing"
            ),
            Self::BlobUnreadable {
                digest,
                task_id,
                path,
                detail,
            } => write!(
                f,
                "blob {digest} referenced by task {task_id:?} at {path:?} could not be read: {detail}"
            ),
            Self::BlobMismatch {
                expected,
                actual,
                task_id,
                path,
            } => write!(
                f,
                "blob mismatch for task {task_id:?} at {path:?}: expected {expected}, content hashes to {actual}"
            ),
            Self::ArtifactSizeMismatch {
                digest,
                expected,
                actual,
                task_id,
                path,
            } => write!(
                f,
                "artifact size mismatch for task {task_id:?} at {path:?} (blob {digest}): manifest records {expected} bytes, blob has {actual} bytes"
            ),
        }
    }
}

impl std::error::Error for VerifyError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::MalformedManifest { source } => Some(source),
            _ => None,
        }
    }
}