lenso-plugin-bundle 0.1.1

Immutable Lenso Plugin Release manifests, bundle materialization, and verification.
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
//! Immutable Plugin Release manifests, source materialization, and Bundle verification.

mod model;

use std::{
    collections::{BTreeMap, BTreeSet},
    fmt, fs,
    path::{Component, Path, PathBuf},
};

pub use model::*;
use serde::{Deserialize, de::DeserializeOwned};
use serde_json::Value;
use sha2::{Digest, Sha256};

/// The only manifest filename accepted in a materialized Plugin Bundle.
pub const MANIFEST_FILE: &str = "lenso-plugin.json";

/// A source Artifact selected while materializing one Release.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ArtifactSource {
    pub artifact_id: String,
    pub path: PathBuf,
}

/// Exact input to one fail-closed Bundle build.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BundleBuild {
    pub template: PathBuf,
    pub output: PathBuf,
    pub artifact_sources: Vec<ArtifactSource>,
}

/// Canonical Plugin Manifest plus its content identity.
#[derive(Clone, Debug)]
pub struct ManifestDocument {
    value: PluginManifest,
    bytes: Vec<u8>,
    digest: String,
}

impl ManifestDocument {
    /// Strictly parses and validates one publisher Manifest.
    pub fn parse(input: &[u8]) -> Result<Self, BundleError> {
        let value = strict_json::<PluginManifest>(input)?;
        Self::from_value(value)
    }

    /// Validates and canonicalizes one typed publisher Manifest.
    pub fn from_value(value: PluginManifest) -> Result<Self, BundleError> {
        validate_manifest(&value)?;
        let json = serde_json::to_value(&value)
            .map_err(|error| BundleError::InvalidManifest(error.to_string()))?;
        validate_json_value(&json)?;
        let bytes = serde_json::to_vec(&json)
            .map_err(|error| BundleError::InvalidManifest(error.to_string()))?;
        let digest = sha256_digest(&bytes);
        Ok(Self {
            value,
            bytes,
            digest,
        })
    }

    pub const fn value(&self) -> &PluginManifest {
        &self.value
    }

    pub fn bytes(&self) -> &[u8] {
        &self.bytes
    }

    pub fn digest(&self) -> &str {
        &self.digest
    }
}

/// Verified closure of one immutable Plugin Release.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct VerifiedBundle {
    pub plugin_id: String,
    pub release_version: String,
    pub manifest_digest: String,
    pub artifact_digests: Vec<String>,
    pub product_metadata_digests: Vec<String>,
}

/// A Plugin authoring or immutable Bundle invariant failed closed.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BundleError {
    InvalidManifest(String),
    InvalidBundle(String),
    DigestMismatch(String),
    Io(String),
    Wasm(String),
}

impl fmt::Display for BundleError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidManifest(detail) => write!(formatter, "invalid Plugin Manifest: {detail}"),
            Self::InvalidBundle(detail) => write!(formatter, "invalid Plugin Bundle: {detail}"),
            Self::DigestMismatch(subject) => write!(formatter, "digest mismatch for {subject}"),
            Self::Io(detail) => formatter.write_str(detail),
            Self::Wasm(detail) => write!(
                formatter,
                "failed to encode WebAssembly Component: {detail}"
            ),
        }
    }
}

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

/// Builds an immutable Bundle directory without executing publisher code.
pub fn build_bundle(build: &BundleBuild) -> Result<VerifiedBundle, BundleError> {
    if build.output.exists() {
        return invalid_bundle(format!(
            "output `{}` already exists",
            build.output.display()
        ));
    }
    let template = read_regular_file(&build.template, "Plugin Manifest template")?;
    let mut manifest = ManifestDocument::parse(&template)?.value;
    let template_root = build.template.parent().unwrap_or_else(|| Path::new("."));
    let sources = build
        .artifact_sources
        .iter()
        .map(|source| (source.artifact_id.as_str(), source.path.as_path()))
        .collect::<BTreeMap<_, _>>();
    if sources.len() != build.artifact_sources.len() {
        return invalid_bundle("Artifact source IDs must be unique");
    }
    if sources
        .keys()
        .any(|id| !manifest.artifacts.iter().any(|artifact| artifact.id == *id))
    {
        return invalid_bundle("Artifact source references an unknown Artifact ID");
    }

    let output_parent = build.output.parent().unwrap_or_else(|| Path::new("."));
    fs::create_dir_all(output_parent).map_err(io_error)?;
    let staging = tempfile::Builder::new()
        .prefix(".lenso-plugin-")
        .tempdir_in(output_parent)
        .map_err(io_error)?;
    let mut files = BTreeMap::new();
    for artifact in &mut manifest.artifacts {
        validate_relative_path(&artifact.path)?;
        let source = sources
            .get(artifact.id.as_str())
            .copied()
            .map_or_else(|| template_root.join(&artifact.path), Path::to_path_buf);
        let source_bytes = read_regular_file(&source, &format!("Artifact `{}`", artifact.id))?;
        let bytes = if artifact.kind == ArtifactKind::WasmComponent {
            wit_component::ComponentEncoder::default()
                .module(&source_bytes)
                .map_err(|error| BundleError::Wasm(error.to_string()))?
                .validate(true)
                .encode()
                .map_err(|error| BundleError::Wasm(error.to_string()))?
        } else {
            source_bytes
        };
        artifact.digest = sha256_digest(&bytes);
        artifact.size = u64::try_from(bytes.len())
            .map_err(|_| BundleError::InvalidBundle("Artifact size exceeds u64".to_owned()))?;
        write_bundle_file(staging.path(), &artifact.path, &bytes)?;
        files.insert(artifact.path.clone(), bytes);
    }
    for metadata in &mut manifest.product_metadata {
        validate_relative_path(&metadata.path)?;
        let bytes = read_regular_file(
            &template_root.join(&metadata.path),
            &format!("Product Metadata `{}`", metadata.id),
        )?;
        metadata.digest = sha256_digest(&bytes);
        write_bundle_file(staging.path(), &metadata.path, &bytes)?;
        files.insert(metadata.path.clone(), bytes);
    }

    let document = ManifestDocument::from_value(manifest)?;
    fs::write(staging.path().join(MANIFEST_FILE), document.bytes()).map_err(io_error)?;
    let verified = verify_bundle_files(&document, &files)?;
    fs::rename(staging.path(), &build.output).map_err(io_error)?;
    Ok(verified)
}

/// Verifies an already materialized directory as an exact immutable Bundle closure.
pub fn verify_bundle_directory(root: &Path) -> Result<VerifiedBundle, BundleError> {
    let manifest_path = root.join(MANIFEST_FILE);
    let manifest = ManifestDocument::parse(&read_regular_file(&manifest_path, "Plugin Manifest")?)?;
    let mut files = BTreeMap::new();
    collect_bundle_files(root, root, &mut files)?;
    files.remove(MANIFEST_FILE);
    verify_bundle_files(&manifest, &files)
}

/// Verifies exact declared bytes without performing admission or granting authority.
pub fn verify_bundle_files(
    manifest: &ManifestDocument,
    files: &BTreeMap<String, Vec<u8>>,
) -> Result<VerifiedBundle, BundleError> {
    let declared_paths = manifest
        .value()
        .artifacts
        .iter()
        .map(|artifact| artifact.path.as_str())
        .chain(
            manifest
                .value()
                .product_metadata
                .iter()
                .map(|metadata| metadata.path.as_str()),
        )
        .collect::<BTreeSet<_>>();
    if declared_paths.len()
        != manifest.value().artifacts.len() + manifest.value().product_metadata.len()
    {
        return invalid_bundle("Manifest declares a duplicate Bundle path");
    }
    if files.len() != declared_paths.len()
        || files
            .keys()
            .any(|path| !declared_paths.contains(path.as_str()))
    {
        return invalid_bundle("Bundle files do not exactly close over declared paths");
    }
    let mut artifact_digests = Vec::new();
    for artifact in &manifest.value().artifacts {
        let bytes = files.get(&artifact.path).ok_or_else(|| {
            BundleError::InvalidBundle(format!("missing Artifact `{}`", artifact.id))
        })?;
        if u64::try_from(bytes.len()).unwrap_or(u64::MAX) != artifact.size {
            return invalid_bundle(format!("Artifact `{}` size does not match", artifact.id));
        }
        if sha256_digest(bytes) != artifact.digest {
            return Err(BundleError::DigestMismatch(format!(
                "Artifact `{}`",
                artifact.id
            )));
        }
        artifact_digests.push(artifact.digest.clone());
    }
    artifact_digests.sort();
    artifact_digests.dedup();
    let mut product_metadata_digests = Vec::new();
    for metadata in &manifest.value().product_metadata {
        let bytes = files.get(&metadata.path).ok_or_else(|| {
            BundleError::InvalidBundle(format!("missing Product Metadata `{}`", metadata.id))
        })?;
        if sha256_digest(bytes) != metadata.digest {
            return Err(BundleError::DigestMismatch(format!(
                "Product Metadata `{}`",
                metadata.id
            )));
        }
        product_metadata_digests.push(metadata.digest.clone());
    }
    product_metadata_digests.sort();
    product_metadata_digests.dedup();
    Ok(VerifiedBundle {
        plugin_id: manifest.value().plugin_id.clone(),
        release_version: manifest.value().release_version.clone(),
        manifest_digest: manifest.digest().to_owned(),
        artifact_digests,
        product_metadata_digests,
    })
}

/// Validates publisher-owned Manifest semantics independently of Host policy.
#[allow(clippy::too_many_lines)]
pub fn validate_manifest(manifest: &PluginManifest) -> Result<(), BundleError> {
    if manifest.schema_version != 1 {
        return invalid_manifest("unsupported schema version");
    }
    if manifest.plugin_id.is_empty() || semver::Version::parse(&manifest.release_version).is_err() {
        return invalid_manifest("Plugin identity or Release version is invalid");
    }
    let artifact_ids = manifest
        .artifacts
        .iter()
        .map(|artifact| artifact.id.as_str())
        .collect::<Vec<_>>();
    let contribution_ids = manifest
        .module_contributions
        .iter()
        .map(|contribution| contribution.id.as_str())
        .collect::<Vec<_>>();
    let data_ids = manifest
        .data_contributions
        .iter()
        .map(|contribution| contribution.id.as_str())
        .collect::<Vec<_>>();
    let permission_ids = manifest
        .permission_requests
        .iter()
        .map(|request| request.id.as_str())
        .collect::<Vec<_>>();
    let feature_ids = manifest
        .features
        .iter()
        .map(|feature| feature.id.as_str())
        .collect::<Vec<_>>();
    let metadata_ids = manifest
        .product_metadata
        .iter()
        .map(|metadata| metadata.id.as_str())
        .collect::<Vec<_>>();
    ensure_sorted_unique(&artifact_ids, "Artifact ID")?;
    ensure_sorted_unique(&contribution_ids, "Module contribution ID")?;
    ensure_sorted_unique(&data_ids, "Data contribution ID")?;
    ensure_sorted_unique(&permission_ids, "permission request ID")?;
    ensure_sorted_unique(&feature_ids, "Feature ID")?;
    ensure_sorted_unique(&metadata_ids, "Product Metadata ID")?;
    let artifact_set = artifact_ids.iter().copied().collect::<BTreeSet<_>>();
    let contribution_set = contribution_ids.iter().copied().collect::<BTreeSet<_>>();
    let data_set = data_ids.iter().copied().collect::<BTreeSet<_>>();
    let permission_set = permission_ids.iter().copied().collect::<BTreeSet<_>>();
    let metadata_set = metadata_ids.iter().copied().collect::<BTreeSet<_>>();
    for artifact in &manifest.artifacts {
        digest_component(&artifact.digest)?;
        validate_relative_path(&artifact.path)?;
        if artifact.id.is_empty() || artifact.media_type.is_empty() || artifact.targets.is_empty() {
            return invalid_manifest("Artifact identity, media type, and targets must be explicit");
        }
        ensure_sorted_unique(&artifact.targets, "Artifact target")?;
    }
    for contribution in &manifest.module_contributions {
        digest_component(&contribution.configuration_schema_digest)?;
        if contribution.id.is_empty()
            || contribution.package_id.is_empty()
            || contribution.implementations.is_empty()
        {
            return invalid_manifest(
                "Module contribution identity and implementations are required",
            );
        }
        let provided = contribution
            .provides
            .iter()
            .map(|capability| capability.capability_id.as_str())
            .collect::<Vec<_>>();
        ensure_sorted_unique(&provided, "provided Capability")?;
        for capability in &contribution.provides {
            digest_component(&capability.descriptor_digest)?;
            validate_semver(
                &capability.descriptor_version,
                "Capability Descriptor version",
            )?;
            ensure_sorted_unique(&capability.request_operations, "Capability Operation")?;
            if capability
                .operation_kinds
                .keys()
                .any(|operation| !capability.request_operations.contains(operation))
            {
                return invalid_manifest(
                    "Capability interaction kind references an unknown Operation",
                );
            }
        }
        let required = contribution
            .requires
            .iter()
            .map(|capability| capability.capability_id.as_str())
            .collect::<Vec<_>>();
        ensure_sorted_unique(&required, "required Capability")?;
        for capability in &contribution.requires {
            validate_semver(
                &capability.descriptor_version,
                "required Capability Descriptor version",
            )?;
        }
        ensure_sorted_unique(
            &contribution.permission_request_ids,
            "Module permission request",
        )?;
        if contribution
            .permission_request_ids
            .iter()
            .any(|request| !permission_set.contains(request.as_str()))
        {
            return invalid_manifest(
                "Module contribution references an unknown permission request",
            );
        }
        if let Some(state) = &contribution.state {
            if state.state_schema_id.is_empty() {
                return invalid_manifest("state Schema identity is empty");
            }
            digest_component(&state.state_schema_digest)?;
        }
        let variants = contribution
            .implementations
            .iter()
            .map(|variant| variant.id.as_str())
            .collect::<Vec<_>>();
        ensure_sorted_unique(&variants, "implementation variant ID")?;
        for variant in &contribution.implementations {
            if variant.artifact.is_some() == variant.built_in_factory.is_some() {
                return invalid_manifest("implementation must select exactly one execution input");
            }
            if variant.built_in_factory.is_some()
                && variant.execution_class != "lenso.native-rust@1"
            {
                return invalid_manifest("only native Rust may select a built-in factory");
            }
            if variant
                .artifact
                .as_deref()
                .is_some_and(|artifact| !artifact_set.contains(artifact))
            {
                return invalid_manifest("implementation references an unknown Artifact");
            }
            if variant.entrypoint.is_empty()
                || variant.execution_class.is_empty()
                || variant.targets.is_empty()
                || variant.profiles.is_empty()
            {
                return invalid_manifest(
                    "implementation entrypoint, class, targets, and Profiles are required",
                );
            }
            ensure_sorted_unique(&variant.targets, "implementation target")?;
            ensure_sorted_unique(&variant.profiles, "implementation Profile")?;
        }
    }
    for contribution in &manifest.data_contributions {
        if !artifact_set.contains(contribution.artifact.as_str())
            || contribution.media_type.is_empty()
            || contribution.content_schema_id.is_empty()
        {
            return invalid_manifest("Data contribution references incomplete authority");
        }
        digest_component(&contribution.content_schema_digest)?;
        digest_component(&contribution.product_metadata_digest)?;
    }
    for request in &manifest.permission_requests {
        if request.id.is_empty()
            || request.resource_kind.is_empty()
            || request.explanation_key.is_empty()
        {
            return invalid_manifest("permission request identity is incomplete");
        }
    }
    for metadata in &manifest.product_metadata {
        if metadata.id.is_empty() || metadata.namespace.is_empty() || metadata.schema_id.is_empty()
        {
            return invalid_manifest("Product Metadata identity is incomplete");
        }
        validate_relative_path(&metadata.path)?;
        digest_component(&metadata.digest)?;
    }
    for feature in &manifest.features {
        validate_refs(
            &feature.module_contribution_ids,
            &contribution_set,
            "Module contribution",
        )?;
        validate_refs(
            &feature.data_contribution_ids,
            &data_set,
            "Data contribution",
        )?;
        validate_refs(&feature.artifact_ids, &artifact_set, "Artifact")?;
        validate_refs(
            &feature.permission_request_ids,
            &permission_set,
            "permission request",
        )?;
        validate_refs(
            &feature.product_metadata_ids,
            &metadata_set,
            "Product Metadata",
        )?;
    }
    for template in &manifest.binding_templates {
        if !contribution_set.contains(template.consumer_contribution_id.as_str())
            || !contribution_set.contains(template.provider_contribution_id.as_str())
            || template.capability_id.is_empty()
        {
            return invalid_manifest("binding template references unknown contribution authority");
        }
        let consumer = manifest
            .module_contributions
            .iter()
            .find(|value| value.id == template.consumer_contribution_id)
            .expect("validated contribution");
        let provider = manifest
            .module_contributions
            .iter()
            .find(|value| value.id == template.provider_contribution_id)
            .expect("validated contribution");
        if !consumer
            .requires
            .iter()
            .any(|value| value.capability_id == template.capability_id)
            || !provider
                .provides
                .iter()
                .any(|value| value.capability_id == template.capability_id)
        {
            return invalid_manifest("binding template Capability is not required and provided");
        }
    }
    Ok(())
}

/// Computes the canonical digest syntax used by Plugin Release documents and files.
pub fn sha256_digest(bytes: &[u8]) -> String {
    format!("sha256:{}", hex::encode(Sha256::digest(bytes)))
}

fn strict_json<T: DeserializeOwned>(input: &[u8]) -> Result<T, BundleError> {
    let mut deserializer = serde_json::Deserializer::from_slice(input);
    let strict = StrictValue::deserialize(&mut deserializer)
        .map_err(|error| BundleError::InvalidManifest(error.to_string()))?;
    deserializer
        .end()
        .map_err(|error| BundleError::InvalidManifest(error.to_string()))?;
    validate_json_value(&strict.0)?;
    serde_json::from_value(strict.0)
        .map_err(|error| BundleError::InvalidManifest(error.to_string()))
}

#[derive(Clone, Debug)]
struct StrictValue(Value);

impl<'de> Deserialize<'de> for StrictValue {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_any(StrictVisitor)
    }
}

struct StrictVisitor;

impl<'de> serde::de::Visitor<'de> for StrictVisitor {
    type Value = StrictValue;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("strict Plugin Manifest JSON")
    }

    fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E> {
        Ok(StrictValue(Value::Bool(value)))
    }

    fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> {
        Ok(StrictValue(Value::Number(value.into())))
    }

    fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        u64::try_from(value)
            .map_err(|_| E::custom("negative integers are forbidden"))
            .and_then(|value| self.visit_u64(value))
    }

    fn visit_f64<E>(self, _: f64) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Err(E::custom("floating-point values are forbidden"))
    }

    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> {
        Ok(StrictValue(Value::String(value.to_owned())))
    }

    fn visit_string<E>(self, value: String) -> Result<Self::Value, E> {
        Ok(StrictValue(Value::String(value)))
    }

    fn visit_none<E>(self) -> Result<Self::Value, E> {
        Ok(StrictValue(Value::Null))
    }

    fn visit_unit<E>(self) -> Result<Self::Value, E> {
        Ok(StrictValue(Value::Null))
    }

    fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
    where
        A: serde::de::SeqAccess<'de>,
    {
        let mut values = Vec::new();
        while let Some(value) = sequence.next_element::<StrictValue>()? {
            values.push(value.0);
        }
        Ok(StrictValue(Value::Array(values)))
    }

    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
    where
        A: serde::de::MapAccess<'de>,
    {
        let mut keys = BTreeSet::new();
        let mut values = serde_json::Map::new();
        while let Some(key) = map.next_key::<String>()? {
            if !keys.insert(key.clone()) {
                return Err(serde::de::Error::custom(format!("duplicate field `{key}`")));
            }
            values.insert(key, map.next_value::<StrictValue>()?.0);
        }
        Ok(StrictValue(Value::Object(values)))
    }
}

fn validate_json_value(value: &Value) -> Result<(), BundleError> {
    match value {
        Value::Number(number) if !number.is_u64() => {
            invalid_manifest("numbers must be non-negative integers")
        }
        Value::Array(values) => values.iter().try_for_each(validate_json_value),
        Value::Object(values) => values.values().try_for_each(validate_json_value),
        _ => Ok(()),
    }
}

fn validate_relative_path(path: &str) -> Result<(), BundleError> {
    if path.is_empty() || path.contains('\\') {
        return invalid_manifest("Bundle path is empty or platform-ambiguous");
    }
    let path = Path::new(path);
    if path.is_absolute()
        || path
            .components()
            .any(|part| !matches!(part, Component::Normal(_)))
    {
        return invalid_manifest("Bundle path must contain only normalized relative segments");
    }
    Ok(())
}

fn digest_component(digest: &str) -> Result<&str, BundleError> {
    let Some(value) = digest.strip_prefix("sha256:") else {
        return invalid_manifest("digest does not use sha256 prefix");
    };
    if value.len() != 64
        || !value
            .bytes()
            .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
    {
        return invalid_manifest("digest is not 64 lowercase hexadecimal characters");
    }
    Ok(value)
}

fn validate_semver(value: &str, kind: &str) -> Result<(), BundleError> {
    semver::Version::parse(value)
        .map(|_| ())
        .map_err(|_| BundleError::InvalidManifest(format!("{kind} is not SemVer")))
}

fn ensure_sorted_unique<T: Ord + fmt::Display>(
    values: &[T],
    kind: &str,
) -> Result<(), BundleError> {
    if values.windows(2).any(|pair| pair[0] >= pair[1]) {
        return invalid_manifest(format!("{kind} entries must be sorted and unique"));
    }
    Ok(())
}

fn validate_refs<'a>(
    values: &'a [String],
    known: &BTreeSet<&'a str>,
    kind: &str,
) -> Result<(), BundleError> {
    ensure_sorted_unique(values, kind)?;
    if values.iter().any(|value| !known.contains(value.as_str())) {
        return invalid_manifest(format!("Feature references an unknown {kind}"));
    }
    Ok(())
}

fn read_regular_file(path: &Path, kind: &str) -> Result<Vec<u8>, BundleError> {
    let metadata = fs::symlink_metadata(path)
        .map_err(|error| BundleError::Io(format!("failed to inspect {kind}: {error}")))?;
    if !metadata.is_file() || metadata.file_type().is_symlink() {
        return invalid_bundle(format!("{kind} is not a regular file"));
    }
    fs::read(path).map_err(io_error)
}

fn write_bundle_file(root: &Path, relative: &str, bytes: &[u8]) -> Result<(), BundleError> {
    let path = root.join(relative);
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).map_err(io_error)?;
    }
    fs::write(path, bytes).map_err(io_error)
}

fn collect_bundle_files(
    root: &Path,
    directory: &Path,
    files: &mut BTreeMap<String, Vec<u8>>,
) -> Result<(), BundleError> {
    let metadata = fs::symlink_metadata(directory).map_err(io_error)?;
    if !metadata.is_dir() || metadata.file_type().is_symlink() {
        return invalid_bundle("Bundle root contains a non-regular directory");
    }
    let mut entries = fs::read_dir(directory)
        .map_err(io_error)?
        .collect::<Result<Vec<_>, _>>()
        .map_err(io_error)?;
    entries.sort_by_key(std::fs::DirEntry::file_name);
    for entry in entries {
        let path = entry.path();
        let metadata = fs::symlink_metadata(&path).map_err(io_error)?;
        if metadata.file_type().is_symlink() {
            return invalid_bundle("Bundle contains a symbolic link");
        }
        if metadata.is_dir() {
            collect_bundle_files(root, &path, files)?;
            continue;
        }
        if !metadata.is_file() {
            return invalid_bundle("Bundle contains a non-regular file");
        }
        let relative = path
            .strip_prefix(root)
            .map_err(|_| BundleError::InvalidBundle("Bundle path escaped root".to_owned()))?
            .to_str()
            .ok_or_else(|| BundleError::InvalidBundle("Bundle path is not UTF-8".to_owned()))?
            .replace(std::path::MAIN_SEPARATOR, "/");
        validate_relative_path(&relative)?;
        files.insert(relative, fs::read(path).map_err(io_error)?);
    }
    Ok(())
}

fn invalid_manifest<T>(detail: impl Into<String>) -> Result<T, BundleError> {
    Err(BundleError::InvalidManifest(detail.into()))
}

fn invalid_bundle<T>(detail: impl Into<String>) -> Result<T, BundleError> {
    Err(BundleError::InvalidBundle(detail.into()))
}

fn io_error(error: impl fmt::Display) -> BundleError {
    BundleError::Io(error.to_string())
}

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

    const ZERO_DIGEST: &str =
        "sha256:0000000000000000000000000000000000000000000000000000000000000000";

    fn template() -> PluginManifest {
        PluginManifest {
            schema_version: 1,
            plugin_id: "example.quickjs".to_owned(),
            release_version: "1.0.0".to_owned(),
            artifacts: vec![ArtifactDeclaration {
                id: "script".to_owned(),
                kind: ArtifactKind::QuickJsModule,
                digest: ZERO_DIGEST.to_owned(),
                size: 0,
                media_type: "text/javascript".to_owned(),
                path: "plugin.mjs".to_owned(),
                targets: vec!["aarch64-macos".to_owned()],
            }],
            module_contributions: Vec::new(),
            data_contributions: Vec::new(),
            permission_requests: Vec::new(),
            features: Vec::new(),
            binding_templates: Vec::new(),
            product_metadata: Vec::new(),
        }
    }

    #[test]
    fn build_materializes_and_verifies_an_exact_bundle() {
        let source = tempfile::tempdir().unwrap();
        let template_path = source.path().join("lenso-plugin.template.json");
        fs::write(&template_path, serde_json::to_vec(&template()).unwrap()).unwrap();
        fs::write(
            source.path().join("source.mjs"),
            b"export const ready = true;\n",
        )
        .unwrap();
        let output = source.path().join("dist/plugin");
        let built = build_bundle(&BundleBuild {
            template: template_path,
            output: output.clone(),
            artifact_sources: vec![ArtifactSource {
                artifact_id: "script".to_owned(),
                path: source.path().join("source.mjs"),
            }],
        })
        .unwrap();
        assert_eq!(built, verify_bundle_directory(&output).unwrap());
        assert_ne!(built.artifact_digests, [ZERO_DIGEST]);
    }

    #[test]
    fn verification_rejects_tampering_and_undeclared_files() {
        let mut manifest = template();
        let bytes = b"ready".to_vec();
        manifest.artifacts[0].digest = sha256_digest(&bytes);
        manifest.artifacts[0].size = u64::try_from(bytes.len()).unwrap();
        let document = ManifestDocument::from_value(manifest).unwrap();
        let mut files = BTreeMap::from([("plugin.mjs".to_owned(), bytes)]);
        verify_bundle_files(&document, &files).unwrap();
        files.insert("extra".to_owned(), Vec::new());
        assert!(verify_bundle_files(&document, &files).is_err());
    }

    #[test]
    fn parsing_rejects_duplicate_fields_and_path_escape() {
        assert!(ManifestDocument::parse(br#"{"schema_version":1,"schema_version":1}"#).is_err());
        let mut manifest = template();
        manifest.artifacts[0].path = "../plugin.mjs".to_owned();
        assert!(ManifestDocument::from_value(manifest).is_err());
    }
}