apoc 0.9.1

Agentic process control for LLMs
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
//! Offline verification for isolated VM image bundles.

use std::collections::{BTreeSet, HashMap};
use std::fs::{self, File};
use std::io::Read;
use std::os::unix::fs::MetadataExt as _;
use std::path::{Component, Path, PathBuf};
use std::sync::{Mutex, OnceLock};

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

pub const MANIFEST_FILE: &str = "bundle-manifest.json";

/// Point-in-time integrity state for one VM bundle.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum VerificationStatus {
    Verified,
    LegacyUnverified,
    Invalid,
}

/// One immutable artifact declared by a VM bundle manifest.
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
pub struct ManifestArtifact {
    pub role: String,
    pub path: String,
    pub size_bytes: u64,
    pub sha256: String,
}

/// Guest platform declared by the bundle manifest.
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
pub struct ManifestGuest {
    pub os: String,
    pub architecture: String,
}

/// Immutable VM configuration declared by the bundle manifest.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, JsonSchema)]
pub struct ManifestConfig {
    pub cpu_count: i64,
    pub memory_mb: i64,
    pub guest_agent_port: u32,
    pub guest_connect_timeout_ms: i64,
    pub kernel_command_line: String,
    pub resources: ImmutableResources,
}

/// Immutable boot resources declared by a VM bundle.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, JsonSchema)]
pub struct ImmutableResources {
    pub kernel: String,
    pub initrd: Option<String>,
    pub disk: String,
}

/// Reproducible build inputs recorded by the bundle producer.
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
pub struct BuildProvenance {
    pub source_revision: Option<String>,
    pub source_dirty: bool,
    pub build_script_sha256: String,
    pub docker_platform: String,
    pub base_image: String,
    pub base_image_digest: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rr_software_counters_revision: Option<String>,
}

/// Structured result of verifying one image reference without booting a VM.
#[derive(Clone, Debug, Serialize, JsonSchema)]
pub struct VerificationReport {
    pub schema_version: u32,
    pub status: VerificationStatus,
    pub bundle_path: String,
    pub image_digest: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub guest: Option<ManifestGuest>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub config: Option<ManifestConfig>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub build: Option<BuildProvenance>,
    pub artifacts: Vec<ManifestArtifact>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

#[derive(Debug, Deserialize)]
struct BundleManifest {
    schema_version: u32,
    guest: ManifestGuest,
    config: ManifestConfig,
    build: BuildProvenance,
    artifacts: Vec<ManifestArtifact>,
}

#[derive(Debug, Deserialize)]
struct BundleConfig {
    #[serde(rename = "cpuCount")]
    cpu_count: i64,
    #[serde(rename = "memoryMB")]
    memory_mb: i64,
    #[serde(rename = "guestAgentPort")]
    guest_agent_port: u32,
    #[serde(rename = "guestConnectTimeoutMS")]
    guest_connect_timeout_ms: i64,
    #[serde(rename = "imageDigest")]
    image_digest: Option<String>,
    #[serde(rename = "kernelCommandLine")]
    kernel_command_line: String,
    resources: BundleResources,
}

#[derive(Debug, Deserialize)]
struct BundleResources {
    kernel: String,
    initrd: Option<String>,
    disk: Option<String>,
}

impl BundleConfig {
    fn immutable(&self) -> Result<ManifestConfig, String> {
        Ok(ManifestConfig {
            cpu_count: self.cpu_count,
            memory_mb: self.memory_mb,
            guest_agent_port: self.guest_agent_port,
            guest_connect_timeout_ms: self.guest_connect_timeout_ms,
            kernel_command_line: self.kernel_command_line.clone(),
            resources: ImmutableResources {
                kernel: self.resources.kernel.clone(),
                initrd: self.resources.initrd.clone(),
                disk: self
                    .resources
                    .disk
                    .clone()
                    .ok_or_else(|| "config resources.disk is required".to_string())?,
            },
        })
    }
}

/// Resolves and verifies one local, path, or digest image reference.
pub fn verify_reference(raw: &str) -> Result<VerificationReport, String> {
    let (bundle_path, expected_digest) = resolve_reference(raw)?;
    Ok(verify_bundle(&bundle_path, expected_digest.as_deref()))
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct ImmutableFileStamp {
    path: String,
    device: u64,
    inode: u64,
    size: u64,
    modified_seconds: i64,
    modified_nanoseconds: i64,
    changed_seconds: i64,
    changed_nanoseconds: i64,
    regular: bool,
    symlink: bool,
}

#[derive(Clone)]
struct CachedVerification {
    expected_digest: Option<String>,
    stamps: Vec<ImmutableFileStamp>,
    report: VerificationReport,
}

static VERIFICATION_CACHE: OnceLock<Mutex<HashMap<PathBuf, CachedVerification>>> = OnceLock::new();

/// Resolves and verifies one image reference, reusing a successful report only
/// while every identity-bearing file retains the same Unix metadata stamp.
pub fn verify_reference_cached(raw: &str) -> Result<VerificationReport, String> {
    let (bundle_path, expected_digest) = resolve_reference(raw)?;
    let cached = verification_cache()
        .lock()
        .map_err(|_| "Image verification cache is poisoned".to_string())?
        .get(&bundle_path)
        .cloned();
    if let Some(cached) = cached
        && cached.expected_digest == expected_digest
        && immutable_file_stamps(&bundle_path, &cached.report.artifacts)
            .ok()
            .as_ref()
            == Some(&cached.stamps)
    {
        return Ok(cached.report);
    }

    let report = verify_bundle(&bundle_path, expected_digest.as_deref());
    let mut cache = verification_cache()
        .lock()
        .map_err(|_| "Image verification cache is poisoned".to_string())?;
    if report.status == VerificationStatus::Verified {
        let stamps = immutable_file_stamps(&bundle_path, &report.artifacts)?;
        cache.insert(
            bundle_path,
            CachedVerification {
                expected_digest,
                stamps,
                report: report.clone(),
            },
        );
    } else {
        cache.remove(&bundle_path);
    }
    Ok(report)
}

fn verification_cache() -> &'static Mutex<HashMap<PathBuf, CachedVerification>> {
    VERIFICATION_CACHE.get_or_init(|| Mutex::new(HashMap::new()))
}

fn immutable_file_stamps(
    bundle_path: &Path,
    artifacts: &[ManifestArtifact],
) -> Result<Vec<ImmutableFileStamp>, String> {
    std::iter::once("config.json")
        .chain(std::iter::once(MANIFEST_FILE))
        .chain(artifacts.iter().map(|artifact| artifact.path.as_str()))
        .map(|relative| {
            let metadata = fs::symlink_metadata(bundle_path.join(relative)).map_err(|error| {
                format!("Cannot inspect immutable image file {relative}: {error}")
            })?;
            Ok(ImmutableFileStamp {
                path: relative.to_string(),
                device: metadata.dev(),
                inode: metadata.ino(),
                size: metadata.size(),
                modified_seconds: metadata.mtime(),
                modified_nanoseconds: metadata.mtime_nsec(),
                changed_seconds: metadata.ctime(),
                changed_nanoseconds: metadata.ctime_nsec(),
                regular: metadata.file_type().is_file(),
                symlink: metadata.file_type().is_symlink(),
            })
        })
        .collect()
}

/// Successful import of one verified immutable bundle into apoc's image store.
pub(crate) struct ImportedImage {
    pub source_bundle: String,
    pub target_bundle: String,
    pub image_digest: String,
    pub files: u64,
    pub bytes: u64,
    pub already_present: bool,
}

/// Copies only identity-bearing image files into the digest-addressed apoc store.
pub(crate) fn import_verified_bundle(
    source: &Path,
    image_store: &Path,
) -> Result<ImportedImage, String> {
    let source = fs::canonicalize(source).map_err(|error| {
        format!(
            "Image bundle does not exist at {}: {error}",
            source.display()
        )
    })?;
    let report = verify_bundle(&source, None);
    if report.status != VerificationStatus::Verified {
        return Err(report
            .error
            .unwrap_or_else(|| "Image bundle is not verified".to_string()));
    }
    let image_digest = report
        .image_digest
        .clone()
        .ok_or_else(|| "Verified image has no digest".to_string())?;
    let digest = image_digest
        .strip_prefix("sha256:")
        .ok_or_else(|| "Verified image digest is not canonical".to_string())?;
    let store = image_store.join("sha256");
    let target = store.join(digest);
    let files = u64::try_from(report.artifacts.len() + 2)
        .map_err(|_| "Image file count is outside u64".to_string())?;
    let bytes = immutable_bundle_bytes(&source, &report.artifacts)?;

    if target.exists() {
        let existing = verify_bundle(&target, Some(&image_digest));
        if existing.status != VerificationStatus::Verified {
            return Err(format!(
                "Digest-addressed image target is already present but invalid: {}",
                target.display()
            ));
        }
        return Ok(ImportedImage {
            source_bundle: source.to_string_lossy().into_owned(),
            target_bundle: target.to_string_lossy().into_owned(),
            image_digest,
            files,
            bytes,
            already_present: true,
        });
    }

    fs::create_dir_all(&store)
        .map_err(|error| format!("Cannot create image store {}: {error}", store.display()))?;
    let staging = store.join(format!(".import-{}", uuid::Uuid::now_v7()));
    let copied = (|| {
        fs::create_dir(&staging)
            .map_err(|error| format!("Cannot create image import staging directory: {error}"))?;
        for relative in std::iter::once("config.json")
            .chain(std::iter::once(MANIFEST_FILE))
            .chain(
                report
                    .artifacts
                    .iter()
                    .map(|artifact| artifact.path.as_str()),
            )
        {
            copy_immutable_file(&source, &staging, relative)?;
        }
        let staged = verify_bundle(&staging, None);
        if staged.status != VerificationStatus::Verified
            || staged.image_digest.as_deref() != Some(image_digest.as_str())
        {
            return Err(staged.error.unwrap_or_else(|| {
                "Imported image staging bundle does not match the verified source".to_string()
            }));
        }
        fs::rename(&staging, &target)
            .map_err(|error| format!("Cannot publish imported image atomically: {error}"))?;
        Ok(())
    })();
    if copied.is_err() {
        let _ = fs::remove_dir_all(&staging);
    }
    copied?;

    Ok(ImportedImage {
        source_bundle: source.to_string_lossy().into_owned(),
        target_bundle: target.to_string_lossy().into_owned(),
        image_digest,
        files,
        bytes,
        already_present: false,
    })
}

fn immutable_bundle_bytes(source: &Path, artifacts: &[ManifestArtifact]) -> Result<u64, String> {
    std::iter::once("config.json")
        .chain(std::iter::once(MANIFEST_FILE))
        .chain(artifacts.iter().map(|artifact| artifact.path.as_str()))
        .try_fold(0_u64, |total, relative| {
            let metadata = fs::symlink_metadata(source.join(relative)).map_err(|error| {
                format!("Cannot inspect immutable image file {relative}: {error}")
            })?;
            if !metadata.file_type().is_file() || metadata.file_type().is_symlink() {
                return Err(format!(
                    "Immutable image file is not a regular file: {relative}"
                ));
            }
            total
                .checked_add(metadata.len())
                .ok_or_else(|| "Immutable image byte count overflowed".to_string())
        })
}

fn copy_immutable_file(source: &Path, target: &Path, relative: &str) -> Result<(), String> {
    let source_file = source.join(relative);
    let metadata = fs::symlink_metadata(&source_file)
        .map_err(|error| format!("Cannot inspect immutable image file {relative}: {error}"))?;
    if !metadata.file_type().is_file() || metadata.file_type().is_symlink() {
        return Err(format!(
            "Immutable image file is not a regular file: {relative}"
        ));
    }
    let target_file = target.join(relative);
    if let Some(parent) = target_file.parent() {
        fs::create_dir_all(parent)
            .map_err(|error| format!("Cannot create image artifact directory: {error}"))?;
    }
    fs::copy(&source_file, &target_file)
        .map_err(|error| format!("Cannot copy immutable image file {relative}: {error}"))?;
    Ok(())
}

fn resolve_reference(raw: &str) -> Result<(PathBuf, Option<String>), String> {
    let (path, expected_digest) = if raw == "local" {
        (
            resolve_local_bundle().ok_or_else(|| {
                "Local image is unavailable; install vm-bundle beside apoc or set APOC_EXECUTOR_VM_BUNDLE"
                    .to_string()
            })?,
            None,
        )
    } else if let Some(digest) = raw.strip_prefix("sha256:") {
        validate_digest_hex(digest)
            .map_err(|error| format!("Invalid sha256 image reference: {error}"))?;
        (
            image_store()?.join("sha256").join(digest),
            Some(format!("sha256:{digest}")),
        )
    } else {
        (PathBuf::from(raw), None)
    };

    let canonical = fs::canonicalize(&path)
        .map_err(|error| format!("Image bundle does not exist at {}: {error}", path.display()))?;
    if !canonical.is_dir() {
        return Err(format!(
            "Image bundle is not a directory: {}",
            canonical.display()
        ));
    }
    Ok((canonical, expected_digest))
}

fn resolve_local_bundle() -> Option<PathBuf> {
    let configured = std::env::var_os("APOC_EXECUTOR_VM_BUNDLE").map(PathBuf::from);
    let sibling = std::env::current_exe()
        .ok()
        .and_then(|path| path.parent().map(|parent| parent.join("vm-bundle")));
    let repository = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    configured
        .into_iter()
        .chain(sibling)
        .chain([
            repository.join("extensions/macos-native/.build/vm-bundle"),
            repository.join("extensions/macos-native/vm-bundle"),
        ])
        .find(|path| path.is_dir())
}

pub(crate) fn image_store() -> Result<PathBuf, String> {
    if let Some(path) = std::env::var_os("APOC_IMAGE_STORE") {
        return Ok(PathBuf::from(path));
    }
    if let Some(path) = std::env::var_os("APOC_HOME") {
        return Ok(PathBuf::from(path).join("images"));
    }
    let home = std::env::var_os("HOME")
        .ok_or_else(|| "HOME, APOC_HOME, and APOC_IMAGE_STORE are unset".to_string())?;
    Ok(PathBuf::from(home).join(".local/share/apoc/images"))
}

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

    #[test]
    fn imports_only_verified_immutable_bundle_files() {
        let store = tempfile::tempdir().unwrap();
        let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/image-v1");
        let imported = import_verified_bundle(&source, store.path()).unwrap();

        assert!(!imported.already_present);
        assert_eq!(imported.files, 5);
        assert!(
            Path::new(&imported.target_bundle)
                .join(MANIFEST_FILE)
                .is_file()
        );
        assert_eq!(
            verify_reference(&imported.target_bundle).unwrap().status,
            VerificationStatus::Verified
        );
    }

    #[test]
    fn cached_verification_invalidates_when_an_artifact_changes() {
        let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/image-v1");
        let bundle = tempfile::tempdir().unwrap();
        let initial = verify_reference(&source.to_string_lossy()).unwrap();
        for relative in std::iter::once("config.json")
            .chain(std::iter::once(MANIFEST_FILE))
            .chain(
                initial
                    .artifacts
                    .iter()
                    .map(|artifact| artifact.path.as_str()),
            )
        {
            let destination = bundle.path().join(relative);
            if let Some(parent) = destination.parent() {
                fs::create_dir_all(parent).unwrap();
            }
            fs::copy(source.join(relative), destination).unwrap();
        }

        let reference = bundle.path().to_string_lossy();
        let first = verify_reference_cached(&reference).unwrap();
        assert_eq!(first.status, VerificationStatus::Verified);

        let artifact = &first.artifacts[0];
        let path = bundle.path().join(&artifact.path);
        let mut bytes = fs::read(&path).unwrap();
        bytes.push(0);
        fs::write(path, bytes).unwrap();

        let second = verify_reference_cached(&reference).unwrap();
        assert_eq!(second.status, VerificationStatus::Invalid);
    }
}

fn verify_bundle(bundle_path: &Path, expected_digest: Option<&str>) -> VerificationReport {
    let display_path = bundle_path.to_string_lossy().into_owned();
    match verify_bundle_inner(bundle_path, expected_digest) {
        Ok(VerifiedBundle::Verified(verified)) => VerificationReport {
            schema_version: 1,
            status: VerificationStatus::Verified,
            bundle_path: display_path,
            image_digest: Some(verified.image_digest),
            guest: Some(verified.guest),
            config: Some(verified.config),
            build: Some(verified.build),
            artifacts: verified.artifacts,
            error: None,
        },
        Ok(VerifiedBundle::Legacy) => VerificationReport {
            schema_version: 1,
            status: VerificationStatus::LegacyUnverified,
            bundle_path: display_path,
            image_digest: None,
            guest: None,
            config: None,
            build: None,
            artifacts: Vec::new(),
            error: Some("bundle-manifest.json is missing".to_string()),
        },
        Err(error) => VerificationReport {
            schema_version: 1,
            status: VerificationStatus::Invalid,
            bundle_path: display_path,
            image_digest: None,
            guest: None,
            config: None,
            build: None,
            artifacts: Vec::new(),
            error: Some(error),
        },
    }
}

enum VerifiedBundle {
    Verified(Box<VerifiedImage>),
    Legacy,
}

struct VerifiedImage {
    image_digest: String,
    guest: ManifestGuest,
    config: ManifestConfig,
    build: BuildProvenance,
    artifacts: Vec<ManifestArtifact>,
}

fn verify_bundle_inner(
    bundle_path: &Path,
    expected_digest: Option<&str>,
) -> Result<VerifiedBundle, String> {
    let config_bytes = fs::read(bundle_path.join("config.json"))
        .map_err(|error| format!("Cannot read config.json: {error}"))?;
    let config: BundleConfig = serde_json::from_slice(&config_bytes)
        .map_err(|error| format!("Cannot decode config.json: {error}"))?;

    let manifest_path = bundle_path.join(MANIFEST_FILE);
    let manifest_bytes = match fs::read(&manifest_path) {
        Ok(bytes) => bytes,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            if expected_digest.is_some() {
                return Err("Digest-addressed bundles require bundle-manifest.json".to_string());
            }
            return Ok(VerifiedBundle::Legacy);
        }
        Err(error) => return Err(format!("Cannot read {MANIFEST_FILE}: {error}")),
    };

    let manifest_digest = format!("sha256:{:x}", Sha256::digest(&manifest_bytes));
    if config.image_digest.as_deref() != Some(manifest_digest.as_str()) {
        return Err(format!(
            "config imageDigest does not match {MANIFEST_FILE}: expected {manifest_digest}"
        ));
    }
    if let Some(expected) = expected_digest {
        if expected != manifest_digest {
            return Err(format!(
                "Image reference does not match {MANIFEST_FILE}: expected {expected}, found {manifest_digest}"
            ));
        }
        if bundle_path.file_name().and_then(|value| value.to_str())
            != expected.strip_prefix("sha256:")
        {
            return Err("Image-store directory does not match the requested digest".to_string());
        }
    }

    let manifest: BundleManifest = serde_json::from_slice(&manifest_bytes)
        .map_err(|error| format!("Cannot decode {MANIFEST_FILE}: {error}"))?;
    if manifest.schema_version != 1 {
        return Err(format!(
            "Unsupported bundle manifest schema version: {}",
            manifest.schema_version
        ));
    }
    if manifest.guest.os != "linux" || manifest.guest.architecture != "arm64" {
        return Err(format!(
            "Unsupported guest platform: {}/{}",
            manifest.guest.os, manifest.guest.architecture
        ));
    }
    if manifest.config != config.immutable()? {
        return Err("Manifest configuration does not match config.json".to_string());
    }
    validate_build_provenance(&manifest.build)?;
    validate_artifacts(bundle_path, &manifest.config.resources, &manifest.artifacts)?;

    Ok(VerifiedBundle::Verified(Box::new(VerifiedImage {
        image_digest: manifest_digest,
        guest: manifest.guest,
        config: manifest.config,
        build: manifest.build,
        artifacts: manifest.artifacts,
    })))
}

fn validate_build_provenance(build: &BuildProvenance) -> Result<(), String> {
    validate_prefixed_digest(&build.build_script_sha256, "build.build_script_sha256")?;
    if let Some(digest) = &build.base_image_digest {
        validate_prefixed_digest(digest, "build.base_image_digest")?;
    }
    if build.source_revision.as_deref() == Some("") {
        return Err("build.source_revision must not be empty when present".to_string());
    }
    if let Some(revision) = &build.rr_software_counters_revision
        && (revision.len() != 40
            || !revision
                .bytes()
                .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()))
    {
        return Err(
            "build.rr_software_counters_revision must be a 40-character lowercase Git commit"
                .to_string(),
        );
    }
    if build.docker_platform.is_empty() || build.base_image.is_empty() {
        return Err("Build platform and base image must not be empty".to_string());
    }
    Ok(())
}

fn validate_artifacts(
    bundle_path: &Path,
    resources: &ImmutableResources,
    artifacts: &[ManifestArtifact],
) -> Result<(), String> {
    let mut roles = BTreeSet::new();
    let mut paths = BTreeSet::new();
    for artifact in artifacts {
        if !matches!(artifact.role.as_str(), "kernel" | "initrd" | "rootfs") {
            return Err(format!("Unsupported artifact role: {}", artifact.role));
        }
        if !roles.insert(artifact.role.as_str()) {
            return Err(format!("Duplicate artifact role: {}", artifact.role));
        }
        if !paths.insert(artifact.path.as_str()) {
            return Err(format!("Duplicate artifact path: {}", artifact.path));
        }
        validate_prefixed_digest(&artifact.sha256, "artifact sha256")?;
        let path = confined_regular_file(bundle_path, &artifact.path)?;
        let metadata = fs::metadata(&path)
            .map_err(|error| format!("Cannot inspect artifact {}: {error}", artifact.path))?;
        if metadata.len() != artifact.size_bytes {
            return Err(format!(
                "Artifact size mismatch for {}: expected {}, found {}",
                artifact.path,
                artifact.size_bytes,
                metadata.len()
            ));
        }
        let actual = hash_file(&path)
            .map_err(|error| format!("Cannot hash artifact {}: {error}", artifact.path))?;
        if actual != artifact.sha256 {
            return Err(format!(
                "Artifact digest mismatch for {}: expected {}, found {}",
                artifact.path, artifact.sha256, actual
            ));
        }
    }

    let expected = [
        ("kernel", Some(resources.kernel.as_str())),
        ("rootfs", Some(resources.disk.as_str())),
        ("initrd", resources.initrd.as_deref()),
    ];
    for (role, path) in expected {
        match path {
            Some(path) => {
                let artifact = artifacts
                    .iter()
                    .find(|artifact| artifact.role == role)
                    .ok_or_else(|| format!("Missing required artifact role: {role}"))?;
                if artifact.path != path {
                    return Err(format!(
                        "Artifact path for {role} does not match config: expected {path}, found {}",
                        artifact.path
                    ));
                }
            }
            None if roles.contains(role) => {
                return Err(format!("Unexpected artifact role: {role}"));
            }
            None => {}
        }
    }
    Ok(())
}

fn confined_regular_file(bundle_path: &Path, relative: &str) -> Result<PathBuf, String> {
    let canonical_bundle = fs::canonicalize(bundle_path)
        .map_err(|error| format!("Cannot resolve bundle path: {error}"))?;
    let path = Path::new(relative);
    if relative.is_empty()
        || relative
            .split('/')
            .any(|component| component.is_empty() || component == "." || component == "..")
        || path
            .components()
            .any(|component| !matches!(component, Component::Normal(_)))
    {
        return Err(format!(
            "Artifact path must be normalized and relative: {relative}"
        ));
    }

    let mut current = canonical_bundle.clone();
    for component in path.components() {
        let Component::Normal(value) = component else {
            unreachable!();
        };
        current.push(value);
        let metadata = fs::symlink_metadata(&current)
            .map_err(|error| format!("Cannot inspect artifact path {relative}: {error}"))?;
        if metadata.file_type().is_symlink() {
            return Err(format!(
                "Artifact path must not contain symlinks: {relative}"
            ));
        }
    }
    let canonical = fs::canonicalize(&current)
        .map_err(|error| format!("Cannot resolve artifact path {relative}: {error}"))?;
    if !canonical.starts_with(&canonical_bundle) {
        return Err(format!("Artifact path escapes the bundle: {relative}"));
    }
    let metadata = fs::metadata(&canonical)
        .map_err(|error| format!("Cannot inspect artifact {relative}: {error}"))?;
    if !metadata.is_file() {
        return Err(format!("Artifact is not a regular file: {relative}"));
    }
    Ok(canonical)
}

fn hash_file(path: &Path) -> Result<String, String> {
    let mut file = File::open(path).map_err(|error| error.to_string())?;
    let mut hasher = Sha256::new();
    let mut buffer = [0_u8; 1024 * 1024];
    loop {
        let count = file.read(&mut buffer).map_err(|error| error.to_string())?;
        if count == 0 {
            break;
        }
        hasher.update(&buffer[..count]);
    }
    Ok(format!("sha256:{:x}", hasher.finalize()))
}

fn validate_prefixed_digest(value: &str, field: &str) -> Result<(), String> {
    let digest = value
        .strip_prefix("sha256:")
        .ok_or_else(|| format!("{field} must use sha256:<digest>"))?;
    validate_digest_hex(digest).map_err(|error| format!("Invalid {field}: {error}"))
}

fn validate_digest_hex(value: &str) -> Result<(), String> {
    if value.len() != 64
        || !value
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
    {
        return Err("Digest must contain 64 lowercase hexadecimal characters".to_string());
    }
    Ok(())
}

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

    #[test]
    fn digest_validation_is_canonical() {
        assert!(validate_digest_hex(&"a".repeat(64)).is_ok());
        assert!(validate_digest_hex(&"A".repeat(64)).is_err());
        assert!(validate_digest_hex("abc").is_err());
    }

    #[test]
    fn artifact_paths_are_normalized() {
        let directory = tempfile::tempdir().unwrap();
        fs::write(directory.path().join("kernel"), b"bytes").unwrap();
        assert!(confined_regular_file(directory.path(), "kernel").is_ok());
        assert!(confined_regular_file(directory.path(), "../kernel").is_err());
        assert!(confined_regular_file(directory.path(), "./kernel").is_err());
        assert!(confined_regular_file(directory.path(), "path//kernel").is_err());
    }

    #[test]
    fn rr_software_counter_provenance_requires_a_canonical_commit() {
        let build = |revision| BuildProvenance {
            source_revision: None,
            source_dirty: false,
            build_script_sha256: format!("sha256:{}", "a".repeat(64)),
            docker_platform: "linux/arm64".to_string(),
            base_image: "debian:trixie-slim".to_string(),
            base_image_digest: None,
            rr_software_counters_revision: revision,
        };

        assert!(validate_build_provenance(&build(Some("a".repeat(40)))).is_ok());
        assert!(validate_build_provenance(&build(Some("A".repeat(40)))).is_err());
        assert!(validate_build_provenance(&build(Some("a".repeat(39)))).is_err());
    }
}