rill-runtime 1.0.0-rc.3

Signed-model local runtime and IPC server for RillML.
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
//! Common safe-archive skeleton shared by model packs (`.rillpack`) and
//! handler packs (`.rillhandler`).
//!
//! Both pack formats use the same ZIP structure: a manifest, one payload file,
//! a checksums file, and an Ed25519 signature. This module centralises the
//! path validation, size limits, checksum verification and signature logic so
//! that the two pack types cannot drift apart.

use std::{
    collections::{BTreeMap, BTreeSet},
    io::{Cursor, Read, Seek, Write},
};

use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use rill_runtime_protocol::ReleaseIndexPayload;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};
use thiserror::Error;
use zip::{ZipArchive, ZipWriter, write::SimpleFileOptions};

const MANIFEST_PATH: &str = "manifest.json";
const CHECKSUMS_PATH: &str = "checksums.json";
const SIGNATURE_PATH: &str = "META-INF/signature.ed25519";

#[derive(Debug, Default, Clone)]
pub struct TrustStore(pub BTreeMap<String, VerifyingKey>);

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub(crate) struct Checksums {
    schema_version: u32,
    files: BTreeMap<String, String>,
}

#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ArchiveError {
    #[error("zip error: {0}")]
    Zip(#[from] zip::result::ZipError),
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),
    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),
    #[error("unsafe package path {0}")]
    UnsafePath(String),
    #[error("forbidden package file {0}")]
    Forbidden(String),
    #[error("duplicate package file {0}")]
    Duplicate(String),
    #[error("package exceeded {0} limit")]
    Limit(&'static str),
    #[error("missing package file {0}")]
    Missing(&'static str),
    #[error("missing package file {0}")]
    MissingOwned(String),
    #[error("checksum coverage does not exactly match the payload")]
    ChecksumCoverage,
    #[error("checksum mismatch for {0}")]
    Digest(String),
    #[error("unknown publisher key")]
    UnknownKey,
    #[error("signature verification failed")]
    Signature,
}

#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ReleaseIndexError {
    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),
    #[error("invalid release index: {0}")]
    Manifest(String),
    #[error("unknown release-index publisher key")]
    UnknownKey,
    #[error("release-index signature verification failed")]
    Signature,
    #[error("canonical JSON error: {0}")]
    Canonical(ArchiveError),
}

/// Limits for a specific pack type.
#[derive(Debug, Clone, Copy)]
pub(crate) struct ArchiveLimits {
    pub max_files: usize,
    pub max_file_bytes: u64,
    pub max_total_bytes: u64,
    pub max_compressed_total_bytes: u64,
    pub max_compression_ratio: u64,
}

/// The canonical paths every pack must contain.
pub(crate) struct PackPaths {
    pub manifest: &'static str,
    pub checksums: &'static str,
    pub signature: &'static str,
}

pub(crate) const DEFAULT_PATHS: PackPaths = PackPaths {
    manifest: MANIFEST_PATH,
    checksums: CHECKSUMS_PATH,
    signature: SIGNATURE_PATH,
};

pub fn canonical_json(bytes: &[u8]) -> Result<Vec<u8>, ArchiveError> {
    fn canonical(value: Value) -> Value {
        match value {
            Value::Object(map) => {
                // Explicitly sort object keys via BTreeMap so canonicalisation
                // does not depend on serde_json's feature flags (preserve_order).
                let sorted: BTreeMap<String, Value> = map
                    .into_iter()
                    .map(|(key, value)| (key, canonical(value)))
                    .collect();
                Value::Object(sorted.into_iter().collect())
            }
            Value::Array(items) => Value::Array(items.into_iter().map(canonical).collect()),
            other => other,
        }
    }
    let value: Value = serde_json::from_slice(bytes)?;
    Ok(serde_json::to_vec(&canonical(value))?)
}

pub fn sign_release_index(
    payload: ReleaseIndexPayload,
    signing_key: &SigningKey,
) -> Result<rill_runtime_protocol::SignedReleaseIndex, ReleaseIndexError> {
    validate_release_payload(&payload)?;
    let serialized = serde_json::to_vec(&payload)?;
    let canonical = canonical_json(&serialized).map_err(ReleaseIndexError::Canonical)?;
    let signature = hex::encode(signing_key.sign(&canonical).to_bytes());
    Ok(rill_runtime_protocol::SignedReleaseIndex { payload, signature })
}

pub fn verify_release_index(
    index: &rill_runtime_protocol::SignedReleaseIndex,
    trust: &TrustStore,
) -> Result<(), ReleaseIndexError> {
    validate_release_payload(&index.payload)?;
    let signature_bytes =
        hex::decode(&index.signature).map_err(|_| ReleaseIndexError::Signature)?;
    let signature =
        Signature::from_slice(&signature_bytes).map_err(|_| ReleaseIndexError::Signature)?;
    let key = trust
        .0
        .get(&index.payload.publisher_key_id)
        .ok_or(ReleaseIndexError::UnknownKey)?;
    let serialized = serde_json::to_vec(&index.payload)?;
    let canonical = canonical_json(&serialized).map_err(ReleaseIndexError::Canonical)?;
    key.verify(&canonical, &signature)
        .map_err(|_| ReleaseIndexError::Signature)
}

fn validate_release_payload(payload: &ReleaseIndexPayload) -> Result<(), ReleaseIndexError> {
    payload
        .validate_shape()
        .map_err(|message| ReleaseIndexError::Manifest(message.into()))?;
    let mut identities = BTreeSet::new();
    for artifact in &payload.artifacts {
        semver::Version::parse(&artifact.version).map_err(|error| {
            ReleaseIndexError::Manifest(format!("invalid artifact version: {error}"))
        })?;
        let identity = (
            artifact.kind.clone(),
            artifact.id.clone(),
            artifact.target_os.clone(),
            artifact.target_arch.clone(),
            artifact.handler_api_version,
        );
        if !identities.insert(identity) {
            return Err(ReleaseIndexError::Manifest(
                "duplicate release artifact identity".into(),
            ));
        }
    }
    Ok(())
}

/// Read a ZIP archive and validate paths, file count, and size limits.
/// Returns a map of file name → bytes for every non-directory entry.
pub(crate) fn read_archive<R: Read + Seek>(
    reader: R,
    allowed: &[&str],
    limits: ArchiveLimits,
) -> Result<BTreeMap<String, Vec<u8>>, ArchiveError> {
    let mut archive = ZipArchive::new(reader)?;
    if archive.len() > limits.max_files {
        return Err(ArchiveError::Limit("file count"));
    }
    let mut total = 0u64;
    let mut compressed_total = 0u64;
    let mut files = BTreeMap::new();
    for index in 0..archive.len() {
        let mut entry = archive.by_index(index)?;
        if entry.is_dir() {
            continue;
        }
        let name = entry.name().to_string();
        validate_path(&name)?;
        if !allowed.iter().any(|allowed| *allowed == name) {
            return Err(ArchiveError::Forbidden(name));
        }
        if entry.size() > limits.max_file_bytes {
            return Err(ArchiveError::Limit("file size"));
        }
        let compressed = entry.compressed_size();
        // Use checked multiplication instead of integer division so the
        // comparison is exact: ``size / compressed`` truncates and would
        // accept an entry whose true ratio is just above the limit
        // (e.g. size=10, compressed=3, limit=3 → 10/3=3, accepted even
        // though 10 > 3*3). ``size > compressed * ratio`` avoids both the
        // truncation and any floating-point rounding, and the checked
        // product guards against u64 overflow on adversarial inputs.
        if compressed > 0 {
            let cap = compressed
                .checked_mul(limits.max_compression_ratio)
                .ok_or(ArchiveError::Limit("compression ratio"))?;
            if entry.size() > cap {
                return Err(ArchiveError::Limit("compression ratio"));
            }
        }
        total = total
            .checked_add(entry.size())
            .ok_or(ArchiveError::Limit("total size"))?;
        if total > limits.max_total_bytes {
            return Err(ArchiveError::Limit("total size"));
        }
        compressed_total = compressed_total
            .checked_add(compressed)
            .ok_or(ArchiveError::Limit("compressed total size"))?;
        if compressed_total > limits.max_compressed_total_bytes {
            return Err(ArchiveError::Limit("compressed total size"));
        }
        let mut bytes = Vec::with_capacity(entry.size() as usize);
        entry.read_to_end(&mut bytes)?;
        if files.insert(name.clone(), bytes).is_some() {
            return Err(ArchiveError::Duplicate(name));
        }
    }
    Ok(files)
}

/// Verify checksums and signature for a pack.
///
/// `checksum_files` lists the payload file names that checksums.json must
/// cover, in canonical order.
pub(crate) fn verify_checksums_and_signature(
    files: &BTreeMap<String, Vec<u8>>,
    paths: &PackPaths,
    checksum_payload_names: &[&str],
    publisher_key_id: &str,
    trust: &TrustStore,
) -> Result<(), ArchiveError> {
    let checksum_bytes = files
        .get(paths.checksums)
        .ok_or(ArchiveError::Missing(paths.checksums))?;
    let checksums: Checksums = serde_json::from_slice(checksum_bytes)?;
    if checksums.schema_version != 1 {
        return Err(ArchiveError::Missing("checksum schema version"));
    }
    let mut expected_names: Vec<String> = checksum_payload_names
        .iter()
        .map(|s| s.to_string())
        .collect();
    expected_names.sort();
    let actual_names: Vec<String> = checksums.files.keys().cloned().collect();
    if actual_names != expected_names {
        return Err(ArchiveError::ChecksumCoverage);
    }
    for (name, expected) in &checksums.files {
        let bytes = files
            .get(name)
            .ok_or_else(|| ArchiveError::MissingOwned(name.clone()))?;
        let actual = hex::encode(Sha256::digest(bytes));
        if &actual != expected {
            return Err(ArchiveError::Digest(name.clone()));
        }
    }
    let raw_signature = files
        .get(paths.signature)
        .ok_or(ArchiveError::Missing(paths.signature))?;
    let signature = Signature::from_slice(raw_signature).map_err(|_| ArchiveError::Signature)?;
    let key = trust
        .0
        .get(publisher_key_id)
        .ok_or(ArchiveError::UnknownKey)?;
    let manifest_bytes = files
        .get(paths.manifest)
        .ok_or(ArchiveError::Missing(paths.manifest))?;
    let mut message = canonical_json(manifest_bytes)?;
    message.push(b'\n');
    message.extend(canonical_json(checksum_bytes)?);
    key.verify(&message, &signature)
        .map_err(|_| ArchiveError::Signature)
}

/// Build a signed ZIP archive from manifest bytes, payload bytes, and a
/// signing key. Returns the complete archive bytes.
pub(crate) fn build_signed_archive(
    manifest_bytes: &[u8],
    payload_name: &str,
    payload_bytes: &[u8],
    signing_key: &SigningKey,
) -> Result<Vec<u8>, ArchiveError> {
    let checksums = Checksums {
        schema_version: 1,
        files: BTreeMap::from([
            (
                MANIFEST_PATH.into(),
                hex::encode(Sha256::digest(manifest_bytes)),
            ),
            (
                payload_name.into(),
                hex::encode(Sha256::digest(payload_bytes)),
            ),
        ]),
    };
    let checksum_bytes = serde_json::to_vec_pretty(&checksums)?;
    let mut message = canonical_json(manifest_bytes)?;
    message.push(b'\n');
    message.extend(canonical_json(&checksum_bytes)?);
    let signature = signing_key.sign(&message).to_bytes();

    let mut output = Cursor::new(Vec::new());
    {
        let mut archive = ZipWriter::new(&mut output);
        let options = SimpleFileOptions::default()
            .compression_method(zip::CompressionMethod::Deflated)
            .unix_permissions(0o644);
        for (name, bytes) in [
            (MANIFEST_PATH, manifest_bytes),
            (payload_name, payload_bytes),
            (CHECKSUMS_PATH, checksum_bytes.as_slice()),
            (SIGNATURE_PATH, signature.as_slice()),
        ] {
            archive.start_file(name, options)?;
            archive.write_all(bytes)?;
        }
        archive.finish()?;
    }
    Ok(output.into_inner())
}

fn validate_path(name: &str) -> Result<(), ArchiveError> {
    if name.starts_with('/')
        || name.contains('\\')
        || name
            .split('/')
            .any(|part| part.is_empty() || part == "." || part == "..")
    {
        return Err(ArchiveError::UnsafePath(name.into()));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    /// CRC-32 of `data` (matching the value stored in each ZIP local header
    /// and central-directory record).
    fn crc32(data: &[u8]) -> u32 {
        let mut crc: u32 = 0xFFFFFFFF;
        for &byte in data {
            crc ^= byte as u32;
            for _ in 0..8 {
                crc = (crc >> 1) ^ (0xEDB88320 & (0u32.wrapping_sub(crc & 1)));
            }
        }
        !crc
    }

    /// Build a minimal stored (uncompressed) ZIP archive whose single entry
    /// reports `uncompressed_size` and `compressed_size` independently in
    /// both the local file header and the central directory.
    ///
    /// The zip crate's `ZipWriter` always sets both fields to `data.len()`,
    /// which makes it impossible to exercise the compression-ratio check.
    /// Writing the bytes by hand lets the tests pretend the entry compressed
    /// to a different size than its payload.
    fn build_zip_with_sizes(
        name: &str,
        data: &[u8],
        uncompressed_size: u32,
        compressed_size: u32,
    ) -> Vec<u8> {
        let crc = crc32(data);
        let mut buf = Vec::new();
        let local_offset = 0u32;

        // Local file header.
        buf.extend_from_slice(&[0x50, 0x4b, 0x03, 0x04]);
        buf.extend_from_slice(&20u16.to_le_bytes()); // version needed
        buf.extend_from_slice(&0u16.to_le_bytes()); // flags
        buf.extend_from_slice(&0u16.to_le_bytes()); // method = stored
        buf.extend_from_slice(&0u16.to_le_bytes()); // mod time
        buf.extend_from_slice(&0u16.to_le_bytes()); // mod date
        buf.extend_from_slice(&crc.to_le_bytes());
        buf.extend_from_slice(&compressed_size.to_le_bytes());
        buf.extend_from_slice(&uncompressed_size.to_le_bytes());
        buf.extend_from_slice(&(name.len() as u16).to_le_bytes());
        buf.extend_from_slice(&0u16.to_le_bytes()); // extra length
        buf.extend_from_slice(name.as_bytes());
        buf.extend_from_slice(data);

        let cd_start = buf.len() as u32;

        // Central directory file header.
        buf.extend_from_slice(&[0x50, 0x4b, 0x01, 0x02]);
        buf.extend_from_slice(&20u16.to_le_bytes()); // version made by
        buf.extend_from_slice(&20u16.to_le_bytes()); // version needed
        buf.extend_from_slice(&0u16.to_le_bytes()); // flags
        buf.extend_from_slice(&0u16.to_le_bytes()); // method
        buf.extend_from_slice(&0u16.to_le_bytes()); // mod time
        buf.extend_from_slice(&0u16.to_le_bytes()); // mod date
        buf.extend_from_slice(&crc.to_le_bytes());
        buf.extend_from_slice(&compressed_size.to_le_bytes());
        buf.extend_from_slice(&uncompressed_size.to_le_bytes());
        buf.extend_from_slice(&(name.len() as u16).to_le_bytes());
        buf.extend_from_slice(&0u16.to_le_bytes()); // extra length
        buf.extend_from_slice(&0u16.to_le_bytes()); // comment length
        buf.extend_from_slice(&0u16.to_le_bytes()); // disk number
        buf.extend_from_slice(&0u16.to_le_bytes()); // internal attrs
        buf.extend_from_slice(&0u32.to_le_bytes()); // external attrs
        buf.extend_from_slice(&local_offset.to_le_bytes());
        buf.extend_from_slice(name.as_bytes());

        let cd_size = buf.len() as u32 - cd_start;

        // End of central directory record.
        buf.extend_from_slice(&[0x50, 0x4b, 0x05, 0x06]);
        buf.extend_from_slice(&0u16.to_le_bytes()); // disk number
        buf.extend_from_slice(&0u16.to_le_bytes()); // disk with CD
        buf.extend_from_slice(&1u16.to_le_bytes()); // entries on this disk
        buf.extend_from_slice(&1u16.to_le_bytes()); // total entries
        buf.extend_from_slice(&cd_size.to_le_bytes());
        buf.extend_from_slice(&cd_start.to_le_bytes());
        buf.extend_from_slice(&0u16.to_le_bytes()); // comment length

        buf
    }

    fn limits_with_ratio(ratio: u64) -> ArchiveLimits {
        ArchiveLimits {
            max_files: 10,
            max_file_bytes: 1024 * 1024,
            max_total_bytes: 1024 * 1024,
            max_compressed_total_bytes: 1024 * 1024,
            max_compression_ratio: ratio,
        }
    }

    #[test]
    fn compression_ratio_accepts_exact_boundary() {
        // size = compressed * ratio exactly. The previous integer-division
        // implementation accepted this case, and the new checked-multiplication
        // implementation must continue to accept it so the limit remains the
        // boundary, not `ratio - 1`.
        //
        // For stored (uncompressed) entries the zip crate reads
        // `compressed_size` bytes from the local header, so the data buffer
        // must be exactly that long. `uncompressed_size` is reported
        // independently by `entry.size()` and is what the ratio check uses.
        let data = b"0123456789"; // 10 bytes
        let zip = build_zip_with_sizes("payload.bin", data, 1000, 10);
        let files = read_archive(
            std::io::Cursor::new(&zip),
            &["payload.bin"],
            limits_with_ratio(100),
        )
        .expect("exact boundary must be accepted");
        assert_eq!(files.get("payload.bin").map(Vec::as_slice), Some(&data[..]));
    }

    #[test]
    fn compression_ratio_rejects_one_byte_over_boundary() {
        // Regression for the integer-division truncation bug: with the old
        // `size / compressed > ratio` check, size=1001/compressed=10/ratio=100
        // evaluated to `100 > 100` = false and was accepted even though the
        // true ratio is 100.1. The new check must reject it.
        let data = b"0123456789"; // 10 bytes
        let zip = build_zip_with_sizes("payload.bin", data, 1001, 10);
        let result = read_archive(
            std::io::Cursor::new(&zip),
            &["payload.bin"],
            limits_with_ratio(100),
        );
        assert!(
            matches!(result, Err(ArchiveError::Limit("compression ratio"))),
            "expected compression-ratio rejection, got: {result:?}"
        );
    }

    #[test]
    fn compression_ratio_skips_zero_compressed_size() {
        // A zero compressed_size must not divide by zero or trigger the
        // ratio check. The entry is accepted (the size limit still applies).
        let zip = build_zip_with_sizes("payload.bin", b"", 0, 0);
        let files = read_archive(
            std::io::Cursor::new(&zip),
            &["payload.bin"],
            limits_with_ratio(100),
        )
        .expect("zero-size entry must be accepted");
        assert!(files.get("payload.bin").map(Vec::is_empty).unwrap_or(false));
    }

    #[test]
    fn compression_ratio_rejects_overflowing_product() {
        // Adversarial compressed_size * ratio that overflows u64 must be
        // rejected via checked_mul rather than wrapping around to a small
        // value that would let the attack through.
        //
        // compressed_size = 2 (data buffer is 2 bytes), ratio = u64::MAX.
        // 2 * u64::MAX overflows u64; without checked_mul the wrapping
        // product would be u64::MAX - 1, and `entry.size() > u64::MAX - 1`
        // would be false for any small size, letting the attack through.
        let data = b"xy"; // 2 bytes
        let zip = build_zip_with_sizes("payload.bin", data, 2, 2);
        let limits = ArchiveLimits {
            max_files: 10,
            max_file_bytes: 1024 * 1024,
            max_total_bytes: 1024 * 1024,
            max_compressed_total_bytes: 1024 * 1024,
            max_compression_ratio: u64::MAX,
        };
        let result = read_archive(std::io::Cursor::new(&zip), &["payload.bin"], limits);
        assert!(
            matches!(result, Err(ArchiveError::Limit("compression ratio"))),
            "expected overflow rejection, got: {result:?}"
        );
    }
}