clawft-kernel 0.8.3

WeftOS kernel: boot sequence, process table, service registry, and health subsystem
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
//! Package verification: manifest frame, signatures against pinned anchors,
//! then every listed file by size and BLAKE3.
//!
//! Signatures are checked before any file is read, so an unsigned or
//! mis-signed package never causes file I/O beyond the manifest itself.
//! Each failure class has its own [`VerifyError`] variant and stable
//! [`VerifyError::code`].

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

use ed25519_dalek::{Signature, VerifyingKey};

use crate::workload_kind::{KindRegistry, validate_envelope};

use super::codec::hex_decode_exact;
use super::cognitum;
use super::manifest::{
    CogPackageBody, FileRef, KIND_COG, MANIFEST_FILE, MAX_MANIFEST_BYTES, ManifestEnvelope,
    ManifestError,
};
use super::trust::{KeyOrigin, TrustAnchors};

/// Largest single package file read during verification.
pub const MAX_FILE_BYTES: u64 = 512 * 1024 * 1024;

/// Why a package was rejected.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum VerifyError {
    /// Manifest unreadable or structurally invalid.
    #[error("manifest invalid: {0}")]
    Manifest(String),
    /// No signature entries and no accepted external attestation.
    #[error("package has no signature")]
    MissingSignature,
    /// Signatures exist but none is from a pinned signer.
    #[error("no signature from a pinned signer (saw: {key_ids})")]
    UntrustedSigner {
        /// Key ids seen on the envelope.
        key_ids: String,
    },
    /// A pinned signer's signature does not verify (manifest tampered or
    /// key id / key mismatch).
    #[error("signature from {key_id} does not verify")]
    BadSignature {
        /// The offending key id.
        key_id: String,
    },
    /// A listed file is absent.
    #[error("package file missing: {path}")]
    FileMissing {
        /// Package-relative path.
        path: String,
    },
    /// A listed file's content does not match its pinned hash or size.
    #[error("package file tampered: {path} (expected {expected}, got {actual})")]
    HashMismatch {
        /// Package-relative path.
        path: String,
        /// Pinned value.
        expected: String,
        /// Observed value.
        actual: String,
    },
    /// The Cognitum release record was supplied and rejected.
    #[error("cognitum release record rejected: {0}")]
    CognitumRecord(String),
    /// I/O failure other than a missing file.
    #[error("io error on {path}: {msg}")]
    Io {
        /// Path involved.
        path: String,
        /// Error text.
        msg: String,
    },
}

impl VerifyError {
    /// Stable machine-readable code for CLI output and audit payloads.
    pub fn code(&self) -> &'static str {
        match self {
            Self::Manifest(_) => "manifest-invalid",
            Self::MissingSignature => "missing-signature",
            Self::UntrustedSigner { .. } => "untrusted-signer",
            Self::BadSignature { .. } => "bad-signature",
            Self::FileMissing { .. } => "file-missing",
            Self::HashMismatch { .. } => "file-tampered",
            Self::CognitumRecord(_) => "cognitum-record-rejected",
            Self::Io { .. } => "io-error",
        }
    }
}

impl From<ManifestError> for VerifyError {
    fn from(e: ManifestError) -> Self {
        Self::Manifest(e.to_string())
    }
}

/// Verification options.
#[derive(Debug, Clone, Default)]
pub struct VerifyPolicy {
    /// Opt in to the Cognitum ADR-154/155 release-record verifier. Off by
    /// default; when on, a valid record from a pinned Cognitum key that
    /// binds one of the package binaries counts as a signature.
    pub accept_cognitum_release: bool,
    /// BLAKE3 hashes of `cog.toml` files an operator has reviewed and pins
    /// for **record-only** trust. A Cognitum release record binds the cog id,
    /// version, source commit and binary digest but not the raw `cog.toml`,
    /// so a package trusted through a record alone is accepted only when its
    /// `cog.toml` hash is in this list. Operator-signed packages need no pin
    /// (the envelope signature covers `cog.toml`).
    pub record_cog_toml_pins: Vec<String>,
}

/// A signer whose signature was accepted.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AcceptedSigner {
    /// Key id.
    pub key_id: String,
    /// Anchor set it came from.
    pub origin: KeyOrigin,
}

/// A package that passed verification.
#[derive(Debug, Clone)]
pub struct VerifiedPackage {
    /// BLAKE3 of the signed statement.
    pub package_id: String,
    /// The envelope as read.
    pub envelope: ManifestEnvelope,
    /// Typed cog body.
    pub body: CogPackageBody,
    /// Accepted signers (at least one).
    pub signers: Vec<AcceptedSigner>,
}

/// Where package files are read from.
pub trait FileSource {
    /// Read `file` (the source may use its path or its hash).
    fn read(&self, file: &FileRef) -> Result<Vec<u8>, VerifyError>;
}

/// Reads files from an unpacked package directory.
pub struct DirSource {
    root: PathBuf,
}

impl DirSource {
    /// Source rooted at `root`.
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self { root: root.into() }
    }
}

impl FileSource for DirSource {
    fn read(&self, file: &FileRef) -> Result<Vec<u8>, VerifyError> {
        // Paths were validated as relative and traversal-free; also refuse a
        // symlinked directory that would resolve outside the package.
        let path = self.root.join(&file.path);
        if let (Ok(root), Ok(real)) = (self.root.canonicalize(), path.canonicalize())
            && !real.starts_with(&root)
        {
            return Err(VerifyError::Io {
                path: file.path.clone(),
                msg: "resolves outside the package".into(),
            });
        }
        read_bounded(&path, &file.path, MAX_FILE_BYTES)
    }
}

pub(crate) fn read_bounded(path: &Path, label: &str, max: u64) -> Result<Vec<u8>, VerifyError> {
    let meta = std::fs::symlink_metadata(path).map_err(|e| io_or_missing(e, label))?;
    if !meta.is_file() {
        return Err(VerifyError::Io {
            path: label.into(),
            msg: "not a regular file".into(),
        });
    }
    if meta.len() > max {
        return Err(VerifyError::Io {
            path: label.into(),
            msg: format!("larger than {max} bytes"),
        });
    }
    // Bounded read: the file may grow between the metadata check and here.
    let mut out = Vec::new();
    std::fs::File::open(path)
        .map_err(|e| io_or_missing(e, label))?
        .take(max + 1)
        .read_to_end(&mut out)
        .map_err(|e| io_or_missing(e, label))?;
    if out.len() as u64 > max {
        return Err(VerifyError::Io {
            path: label.into(),
            msg: format!("larger than {max} bytes"),
        });
    }
    Ok(out)
}

fn io_or_missing(e: std::io::Error, label: &str) -> VerifyError {
    if e.kind() == std::io::ErrorKind::NotFound {
        VerifyError::FileMissing { path: label.into() }
    } else {
        VerifyError::Io {
            path: label.into(),
            msg: e.to_string(),
        }
    }
}

/// Verify the package in directory `dir` (manifest at `dir/cogpkg.json`).
pub fn verify_dir(
    dir: &Path,
    anchors: &TrustAnchors,
    policy: &VerifyPolicy,
) -> Result<VerifiedPackage, VerifyError> {
    verify_dir_in(dir, anchors, policy, &KindRegistry::builtin())
}

/// [`verify_dir`] against a caller-supplied kind registry.
pub fn verify_dir_in(
    dir: &Path,
    anchors: &TrustAnchors,
    policy: &VerifyPolicy,
    kinds: &KindRegistry,
) -> Result<VerifiedPackage, VerifyError> {
    let bytes = read_bounded(
        &dir.join(MANIFEST_FILE),
        MANIFEST_FILE,
        MAX_MANIFEST_BYTES as u64,
    )?;
    verify_with_source_in(&bytes, &DirSource::new(dir), anchors, policy, kinds)
}

/// Verify manifest bytes, reading listed files through `source`.
pub fn verify_with_source(
    manifest: &[u8],
    source: &dyn FileSource,
    anchors: &TrustAnchors,
    policy: &VerifyPolicy,
) -> Result<VerifiedPackage, VerifyError> {
    verify_with_source_in(manifest, source, anchors, policy, &KindRegistry::builtin())
}

/// [`verify_with_source`] against a caller-supplied kind registry.
pub fn verify_with_source_in(
    manifest: &[u8],
    source: &dyn FileSource,
    anchors: &TrustAnchors,
    policy: &VerifyPolicy,
    kinds: &KindRegistry,
) -> Result<VerifiedPackage, VerifyError> {
    let (envelope, body, mut signers) = parse_and_check(manifest, anchors, kinds)?;
    // The Cognitum release-record path trusts a registry attestation of a
    // cog binary, so it is defined for the cog kind only. Refuse rather than
    // ignore it: a caller that turned it on for another kind wants a check
    // that does not exist there.
    if policy.accept_cognitum_release && envelope.kind != KIND_COG {
        return Err(VerifyError::Manifest(
            "the Cognitum release verifier applies only to the cog kind".into(),
        ));
    }

    // An attached Cognitum record is checked whenever the verifier is on, also
    // on packages an operator already signed: a forged or mismatched record
    // must not ride along unexamined next to a valid signature.
    let record = if policy.accept_cognitum_release {
        cognitum::check_attached(&body, source, anchors)?
    } else {
        None
    };
    if signers.is_empty()
        && let Some(rec) = record
    {
        // Record-only trust: the record has to bind what it cannot sign.
        cognitum::require_record_only_binding(&body, &rec.facts, policy)?;
        signers.push(rec.signer);
    }
    if signers.is_empty() {
        return Err(no_signer_error(&envelope));
    }

    for file in body.files() {
        check_file(file, &source.read(file)?)?;
    }
    Ok(VerifiedPackage {
        package_id: envelope.package_id()?,
        envelope,
        body,
        signers,
    })
}

/// Verify the manifest envelope and its signatures without reading any
/// listed file (mesh-placement-11).
///
/// Used where file content is proven some other way: the artifact
/// exchange checks every file's size and BLAKE3 while streaming it, so a
/// multi-GB payload never has to sit in memory. Only pinned Ed25519
/// signers count here; the Cognitum release-record path needs a binary
/// and is only available through [`verify_with_source`].
pub fn verify_manifest_signatures(
    manifest: &[u8],
    anchors: &TrustAnchors,
) -> Result<VerifiedPackage, VerifyError> {
    verify_manifest_signatures_in(manifest, anchors, &KindRegistry::builtin())
}

/// [`verify_manifest_signatures`] against a caller-supplied kind registry.
pub fn verify_manifest_signatures_in(
    manifest: &[u8],
    anchors: &TrustAnchors,
    kinds: &KindRegistry,
) -> Result<VerifiedPackage, VerifyError> {
    let (envelope, body, signers) = parse_and_check(manifest, anchors, kinds)?;
    if signers.is_empty() {
        return Err(no_signer_error(&envelope));
    }
    Ok(VerifiedPackage {
        package_id: envelope.package_id()?,
        envelope,
        body,
        signers,
    })
}

type Checked = (ManifestEnvelope, CogPackageBody, Vec<AcceptedSigner>);

fn parse_and_check(
    manifest: &[u8],
    anchors: &TrustAnchors,
    kinds: &KindRegistry,
) -> Result<Checked, VerifyError> {
    let envelope = ManifestEnvelope::from_bytes(manifest)?;
    // The kind must be registered and accept the body. The verified package
    // is still cog-shaped until a kind brings its own verified body, so a
    // registered kind must also parse as a cog body.
    validate_envelope(kinds, &envelope)?;
    let body = envelope.cog_shaped_body()?;
    let signers = check_signatures(&envelope, anchors)?;
    Ok((envelope, body, signers))
}

fn no_signer_error(envelope: &ManifestEnvelope) -> VerifyError {
    if envelope.signatures.is_empty() {
        VerifyError::MissingSignature
    } else {
        let key_ids: Vec<&str> = envelope
            .signatures
            .iter()
            .map(|s| s.key_id.as_str())
            .collect();
        VerifyError::UntrustedSigner {
            key_ids: key_ids.join(","),
        }
    }
}

/// Check one file's size and hash.
pub fn check_file(file: &FileRef, content: &[u8]) -> Result<(), VerifyError> {
    let actual = blake3::hash(content).to_hex().to_string();
    if actual != file.blake3 {
        return Err(VerifyError::HashMismatch {
            path: file.path.clone(),
            expected: file.blake3.clone(),
            actual,
        });
    }
    if content.len() as u64 != file.size {
        return Err(VerifyError::HashMismatch {
            path: file.path.clone(),
            expected: format!("{} bytes", file.size),
            actual: format!("{} bytes", content.len()),
        });
    }
    Ok(())
}

/// Returns accepted pinned signers. A well-formed signature from a pinned
/// key that fails to verify is fatal ([`VerifyError::BadSignature`]);
/// entries from unpinned keys are ignored here and only reported if nothing
/// else is accepted. An entry whose public key or signature is not valid
/// hex of the right length is skipped like an unpinned one: it can neither
/// authenticate the package nor veto a valid signature next to it, so one
/// garbage entry cannot fail the whole verify.
pub(crate) fn check_signatures(
    env: &ManifestEnvelope,
    anchors: &TrustAnchors,
) -> Result<Vec<AcceptedSigner>, VerifyError> {
    let msg = env.signed_statement()?;
    let mut accepted = Vec::new();
    for entry in &env.signatures {
        if entry.algorithm != "ed25519" {
            return Err(VerifyError::Manifest(format!(
                "unsupported algorithm {:?}",
                entry.algorithm
            )));
        }
        let Some(pk) = hex_decode_exact::<32>(&entry.public_key) else {
            continue;
        };
        let Some(pinned) = anchors.signer(&pk) else {
            continue;
        };
        let bad = || VerifyError::BadSignature {
            key_id: entry.key_id.clone(),
        };
        if pinned.key_id != entry.key_id {
            return Err(bad());
        }
        let Some(sig) = hex_decode_exact::<64>(&entry.signature) else {
            continue;
        };
        let vk = VerifyingKey::from_bytes(&pk).map_err(|_| bad())?;
        vk.verify_strict(&msg, &Signature::from_bytes(&sig))
            .map_err(|_| bad())?;
        if !accepted
            .iter()
            .any(|a: &AcceptedSigner| a.key_id == pinned.key_id)
        {
            accepted.push(AcceptedSigner {
                key_id: pinned.key_id.clone(),
                origin: pinned.origin,
            });
        }
    }
    Ok(accepted)
}