cdk-rsx-cli 0.1.1

Build and test Internet Computer canisters with CDK RSX
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
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
//! Canonical build inputs and verification of compiler-emitted policy identities.

use anyhow::{Context, Result, bail, ensure};
use cdk_rsx_compat::{PRODUCER_SCOPE, eligible_scope, hex};
use flate2::read::GzDecoder;
use serde::Deserialize;
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use std::{
    collections::{BTreeMap, BTreeSet},
    fs::{self, File},
    io::{self, Read, Write},
    path::{Path, PathBuf},
};
use walkdir::WalkDir;

const ALIAS_FORMAT: &str = "cdk-rsx-compat-aliases-v1";
const INVENTORY_FORMAT: &str = "cdk-rsx-policy-inputs-v1";
const MAX_ENTRIES: usize = 16_384;
const MAX_DOCUMENT_BYTES: usize = 8 * 1024 * 1024;
const TARGETS: [&str; 2] = ["wasm32-unknown-unknown", "wasm64-unknown-unknown"];
const CRATES_IO: [&str; 2] = [
    "registry+https://github.com/rust-lang/crates.io-index",
    "sparse+https://index.crates.io/",
];
const SDK_REPOSITORY: &str = "https://github.com/3V-Interactive/cdk-rsx";
const PACKAGE_SCOPES: &str = include_str!("../compat/packages.toml");
pub(crate) const APPROVED_ALIASES: &[u8] = include_bytes!("../compat/approved-aliases.json");

pub(crate) struct Admission {
    pub(crate) context: String,
    pub(crate) context_inputs: Value,
    pub(crate) tooling: String,
    pub(crate) tooling_inputs: Value,
    pub(crate) package_roots: BTreeMap<PathBuf, String>,
    pub(crate) package_records: Value,
    pub(crate) aliases: Value,
    pub(crate) inputs: BTreeSet<PathBuf>,
    target: String,
}

impl Admission {
    pub(crate) fn inventory(&self, wasm: &[u8]) -> Result<Value> {
        let inventory = cdk_rsx_wasm::compatibility(wasm)?;
        validate_inventory(&inventory, &self.aliases, &self.context, &self.target)
    }
}

pub(crate) fn materialize_aliases(target: &Path, bytes: &[u8]) -> Result<PathBuf> {
    let key = digest(bytes);
    // Builders of both generations must share the same target lock.
    let lock_id = format!("[\"compatibility-aliases\", \"{key}\"]");
    let lock_name = format!("{}.lock", digest(lock_id.as_bytes()));
    let _lock = crate::cargo::lock(target, &lock_name)?;
    let directory = target.join(".cdk-rsx-compat-aliases");
    ensure!(
        !directory.is_symlink(),
        "compatibility alias cache cannot be a symlink: {}",
        directory.display()
    );
    fs::create_dir_all(&directory)?;
    let path = directory.join(format!("{key}.json"));
    if !path.exists() && !path.is_symlink() {
        let mut temporary = tempfile::Builder::new()
            .prefix(".publish-")
            .tempfile_in(&directory)?;
        temporary.write_all(bytes)?;
        match temporary.persist_noclobber(&path) {
            Ok(_) => {}
            Err(error) if error.error.kind() == io::ErrorKind::AlreadyExists => {}
            Err(error) => return Err(error.error.into()),
        }
    }
    ensure!(
        !path.is_symlink() && path.is_file() && read_document_bytes(&path)? == bytes,
        "compatibility alias cache differs from its digest: {}",
        path.display()
    );
    Ok(path)
}

#[derive(Deserialize)]
struct CargoGraph {
    workspace_root: PathBuf,
    packages: Vec<CargoPackage>,
    resolve: CargoResolve,
}

#[derive(Deserialize)]
struct CargoPackage {
    id: String,
    name: String,
    version: String,
    source: Option<String>,
    repository: Option<String>,
    manifest_path: PathBuf,
    targets: Vec<CargoTarget>,
}

#[derive(Deserialize)]
struct CargoTarget {
    kind: Vec<String>,
}

#[derive(Deserialize)]
struct CargoResolve {
    nodes: Vec<CargoNode>,
}

#[derive(Deserialize)]
struct CargoNode {
    id: String,
    features: Vec<String>,
    dependencies: Vec<String>,
}

#[derive(Deserialize)]
struct CargoLock {
    package: Vec<LockedPackage>,
}

#[derive(Deserialize)]
struct LockedPackage {
    name: String,
    version: String,
    source: Option<String>,
    checksum: Option<String>,
}

pub(crate) fn prepare(
    metadata: &Value,
    target: &str,
    rustflags: &[String],
    compiler: &crate::cargo::Compiler,
    archives: Option<&Path>,
    candidate: Option<&Path>,
    excluded: &[PathBuf],
) -> Result<Admission> {
    let cargo_home = &compiler.home;
    let compiler = &compiler.version;
    ensure!(
        TARGETS.contains(&target),
        "unsupported compatibility target {target}"
    );
    let graph = CargoGraph::deserialize(metadata).context("resolved Cargo metadata")?;
    let lock_path = graph.workspace_root.join("Cargo.lock").canonicalize()?;
    let lock = toml::from_str::<CargoLock>(&fs::read_to_string(&lock_path)?)?;
    let packages: BTreeMap<_, _> = graph.packages.iter().map(|p| (p.id.as_str(), p)).collect();
    let nodes: BTreeMap<_, _> = graph
        .resolve
        .nodes
        .iter()
        .map(|n| (n.id.as_str(), n))
        .collect();
    ensure!(
        nodes
            .values()
            .all(|node| packages.contains_key(node.id.as_str())
                && node
                    .dependencies
                    .iter()
                    .all(|dep| nodes.contains_key(dep.as_str()))),
        "Cargo resolution refers to a missing package"
    );
    let locked: BTreeMap<_, _> = lock
        .package
        .iter()
        .filter_map(|p| {
            p.source.as_deref().map(|source| {
                (
                    (p.name.as_str(), p.version.as_str(), source),
                    p.checksum.as_deref(),
                )
            })
        })
        .collect();
    let scopes = toml::from_str::<BTreeMap<String, String>>(PACKAGE_SCOPES)?;
    let mut inputs = BTreeSet::from([lock_path]);
    let mut package_roots = BTreeMap::new();
    let mut package_records = Vec::new();
    let mut registry_packages = Vec::new();
    let mut closure = Vec::new();

    for node in nodes.values() {
        let package = packages[node.id.as_str()];
        let mut features = node.features.clone();
        features.sort();
        closure
            .push(json!({"name": package.name, "version": package.version, "features": features}));
        let Some(source) = package.source.as_deref() else {
            continue;
        };
        let lock_key = (package.name.as_str(), package.version.as_str(), source);
        let checksum = *locked
            .get(&lock_key)
            .with_context(|| format!("{} is missing from Cargo.lock", package.name))?;
        if source.starts_with("registry+") || source.starts_with("sparse+") {
            check_digest(checksum.context("missing locked registry checksum")?)?;
        }
        let mut deps: Vec<_> = node
            .dependencies
            .iter()
            .map(|id| identity(packages[id.as_str()]))
            .collect();
        deps.sort_by_cached_key(canonical_bytes);
        registry_packages.push(json!({
            "name": package.name, "version": package.version, "source": source,
            "checksum": checksum, "features": features, "dependencies": deps,
        }));
        let Some(scope) = scopes.get(&package.name) else {
            continue;
        };
        if !CRATES_IO.contains(&source) || package.repository.as_deref() != Some(SDK_REPOSITORY) {
            continue;
        }
        let checksum = checksum.context("missing locked SDK package checksum")?;
        let file_name = format!("{}-{}.crate", package.name, package.version);
        let Some(archive) = find_archive(cargo_home, archives, &file_name, checksum)? else {
            // A directory source can be built without the archive. Its package
            // policies stay unqualified until those original bytes are supplied.
            continue;
        };
        let manifest = package.manifest_path.canonicalize()?;
        ensure!(
            manifest == package.manifest_path,
            "noncanonical SDK manifest {}",
            package.manifest_path.display()
        );
        let directory = manifest
            .parent()
            .context("SDK manifest lacks package directory")?;
        inputs.extend(verify_package_source(directory, &archive)?);
        inputs.insert(archive.clone());
        ensure!(
            package_roots
                .insert(directory.to_owned(), scope.clone())
                .is_none(),
            "duplicate SDK package owner {}",
            directory.display()
        );
        package_records.push(json!({
            "name": package.name, "version": package.version, "source": source,
            "archive": {"path": archive, "bytes": archive.metadata()?.len(), "sha256": checksum},
            "scope": scope, "root": directory,
        }));
    }

    let local_tools = local_tooling(&packages, &nodes, excluded, &mut inputs)?;
    registry_packages.sort_by_cached_key(canonical_bytes);
    package_records.sort_by_cached_key(canonical_bytes);
    closure.sort_by_cached_key(canonical_bytes);
    let tooling_inputs = json!({
        "format": "cdk-rsx-cli-tooling-v1", "cli_version": env!("CARGO_PKG_VERSION"),
        "cli_recipe": env!("CDK_RSX_CLI_RECIPE"),
        "registry_packages": registry_packages, "local_producers": local_tools,
    });
    let tooling = digest(&canonical_bytes(&tooling_inputs));
    let flags: Vec<_> = rustflags
        .iter()
        .map(|flag| {
            if flag.starts_with("--remap-path-prefix=") {
                format!(
                    "--remap-path-prefix=<source>={}",
                    flag.rsplit_once('=').unwrap().1
                )
            } else {
                flag.clone()
            }
        })
        .collect();
    let context_inputs = json!({
        "format": "cdk-rsx-compat-context-v1", "target": target,
        "rustflags": flags, "compiler": compiler, "tooling": tooling, "packages": closure,
    });
    let context = digest(&canonical_bytes(&context_inputs));

    // The release stager verifies approval pins and projects the merged payload.
    let approved = rows(&parse_document(APPROVED_ALIASES)?, ALIAS_FORMAT)?;
    let mut aliases = approved.into_values().collect::<Vec<_>>();
    if let Some(candidate) = candidate {
        let candidate = candidate.canonicalize()?;
        let additional = validate_aliases(&load_document(&candidate)?)?;
        aliases.extend(rows(&additional, ALIAS_FORMAT)?.into_values());
        inputs.insert(candidate);
    }
    let aliases = validate_aliases(&json!({"format": ALIAS_FORMAT, "entries": aliases}))?;
    Ok(Admission {
        context,
        context_inputs,
        tooling,
        tooling_inputs,
        package_roots,
        package_records: Value::Array(package_records),
        aliases,
        inputs,
        target: target.into(),
    })
}

fn identity(package: &CargoPackage) -> Value {
    json!({"name": package.name, "version": package.version, "source": package.source})
}

fn local_tooling(
    packages: &BTreeMap<&str, &CargoPackage>,
    nodes: &BTreeMap<&str, &CargoNode>,
    excluded: &[PathBuf],
    inputs: &mut BTreeSet<PathBuf>,
) -> Result<Vec<Value>> {
    let mut pending = nodes
        .values()
        .filter(|node| {
            let package = packages[node.id.as_str()];
            package.source.is_none()
                && (matches!(package.name.as_str(), "cdk-rsx-memory-abi" | "cdk-rsx-wasm")
                    || package
                        .targets
                        .iter()
                        .any(|target| target.kind.iter().any(|kind| kind == "proc-macro")))
        })
        .map(|node| node.id.as_str())
        .collect::<Vec<_>>();
    let mut visited = BTreeSet::new();
    let mut records = Vec::new();
    while let Some(id) = pending.pop() {
        if !visited.insert(id) {
            continue;
        }
        let package = packages[id];
        if package.source.is_some() {
            continue;
        }
        let node = nodes[id];
        pending.extend(node.dependencies.iter().map(String::as_str));
        let manifest = package.manifest_path.canonicalize()?;
        let dir = manifest
            .parent()
            .context("local producer manifest lacks package directory")?;
        let mut files = Vec::new();
        for entry in WalkDir::new(dir)
            .sort_by_file_name()
            .into_iter()
            .filter_entry(|entry| {
                let path = entry.path();
                !excluded.iter().any(|root| path.starts_with(root))
                    && (entry.depth() == 0
                        || !matches!(
                            entry.file_name().to_str(),
                            Some(
                                ".git"
                                    | ".rustup"
                                    | ".cargo-home"
                                    | "node_modules"
                                    | "target"
                                    | "tmp"
                            )
                        ))
            })
        {
            let entry = entry?;
            ensure!(
                !entry.file_type().is_symlink(),
                "symlink in local producer inputs {}",
                entry.path().display()
            );
            if entry.file_type().is_file() {
                let path = entry.path();
                inputs.insert(path.to_owned());
                files.push(json!({
                    "name": path.strip_prefix(dir)?, "sha256": file_sha(path)?, "bytes": path.metadata()?.len(),
                }));
            }
        }
        let mut deps: Vec<_> = node
            .dependencies
            .iter()
            .map(|id| identity(packages[id.as_str()]))
            .collect();
        deps.sort_by_cached_key(canonical_bytes);
        let mut features = node.features.clone();
        features.sort();
        records.push(json!({
            "package": identity(package), "features": features, "dependencies": deps, "files": files,
        }));
    }
    records.sort_by_cached_key(canonical_bytes);
    Ok(records)
}

fn find_archive(
    home: &Path,
    explicit: Option<&Path>,
    filename: &str,
    checksum: &str,
) -> Result<Option<PathBuf>> {
    let candidates = if let Some(root) = explicit {
        let path = root.join(filename);
        ensure!(
            path.is_file(),
            "locked SDK package archive is missing: {}",
            path.display()
        );
        vec![path]
    } else {
        let root = home.join("registry/cache");
        match fs::read_dir(root) {
            Ok(dirs) => {
                let mut candidates = Vec::new();
                for dir in dirs {
                    let path = dir?.path().join(filename);
                    if path.is_file() {
                        candidates.push(path);
                    }
                }
                candidates.sort();
                candidates
            }
            Err(error) if error.kind() == io::ErrorKind::NotFound => Vec::new(),
            Err(error) => return Err(error.into()),
        }
    };
    for path in &candidates {
        if file_sha(path)? == checksum {
            return Ok(Some(path.canonicalize()?));
        }
    }
    if let Some(first) = candidates.first() {
        bail!(
            "SDK package archive checksum differs from Cargo.lock: {}",
            first.display()
        );
    }
    Ok(None)
}

fn verify_package_source(directory: &Path, archive: &Path) -> Result<BTreeSet<PathBuf>> {
    let stem = archive
        .file_stem()
        .and_then(|name| name.to_str())
        .context("SDK archive has invalid name")?;
    let mut bundle = tar::Archive::new(GzDecoder::new(File::open(archive)?));
    let mut files = BTreeSet::new();
    for entry in bundle.entries()? {
        let mut entry = entry?;
        let kind = entry.header().entry_type();
        let name = entry.path_bytes();
        let name = std::str::from_utf8(&name)?;
        let name = if kind.is_dir() {
            name.strip_suffix('/').unwrap_or(name)
        } else {
            name
        };
        let mut parts = name.split('/');
        ensure!(
            parts.next() == Some(stem) && (kind.is_dir() || kind.is_file()),
            "invalid SDK package archive entry {name:?}"
        );
        let mut path = directory.to_owned();
        for part in parts {
            ensure!(
                !matches!(part, "" | "." | ".."),
                "invalid SDK package archive path {name:?}"
            );
            path.push(part);
        }
        if kind.is_dir() {
            continue;
        }
        ensure!(
            path != directory
                && path.is_file()
                && path.canonicalize()? == path
                && files.insert(path.clone()),
            "invalid SDK source entry {}",
            path.display()
        );
        ensure!(
            reader_sha(&mut entry)? == file_sha(&path)?,
            "SDK package source differs from its locked archive: {}",
            path.display()
        );
    }
    ensure!(
        files.contains(&directory.join("Cargo.toml")),
        "SDK archive lacks Cargo.toml: {}",
        archive.display()
    );
    let mut actual = BTreeSet::new();
    for entry in WalkDir::new(directory) {
        let entry = entry?;
        ensure!(
            !entry.file_type().is_symlink(),
            "symlink in SDK package source {}",
            entry.path().display()
        );
        if entry.file_type().is_dir() {
            continue;
        }
        let path = entry.into_path();
        if path.parent() == Some(directory)
            && matches!(
                path.file_name().and_then(|p| p.to_str()),
                Some(".cargo-ok" | ".cargo-checksum.json")
            )
        {
            continue;
        }
        actual.insert(path);
    }
    ensure!(
        actual == files,
        "SDK package files differ from its locked archive: {}",
        directory.display()
    );
    Ok(files)
}

pub(crate) fn digest(bytes: &[u8]) -> String {
    hex(Sha256::digest(bytes).into())
}

fn file_sha(path: &Path) -> Result<String> {
    reader_sha(&mut File::open(path).with_context(|| format!("read {}", path.display()))?)
}

fn reader_sha(input: &mut impl Read) -> Result<String> {
    let mut digest = Sha256::new();
    io::copy(input, &mut digest)?;
    Ok(hex(digest.finalize().into()))
}

fn check_digest(value: &str) -> Result<()> {
    ensure!(
        value.len() == 64
            && value
                .bytes()
                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)),
        "expected lowercase SHA-256 digest"
    );
    Ok(())
}

#[derive(Deserialize, serde::Serialize, PartialEq, Eq, Clone)]
#[serde(deny_unknown_fields)]
struct Row {
    context: String,
    scope: String,
    raw: String,
    identity: String,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Document {
    format: String,
    entries: Vec<Row>,
}

type Rows = BTreeMap<(String, String, String), Row>;

fn rows(value: &Value, format: &str) -> Result<Rows> {
    let document = Document::deserialize(value).context("invalid compatibility document")?;
    ensure!(
        document.format == format,
        "expected compatibility format {format}"
    );
    ensure!(
        document.entries.len() <= MAX_ENTRIES,
        "compatibility entry bound exceeded"
    );
    let mut found = BTreeMap::new();
    for row in document.entries {
        ensure!(
            eligible_scope(&row.scope),
            "ineligible compatibility scope {}",
            row.scope
        );
        for hash in [&row.context, &row.raw, &row.identity] {
            check_digest(hash)?;
        }
        let key = (row.context.clone(), row.scope.clone(), row.raw.clone());
        if let Some(previous) = found.insert(key, row.clone()) {
            ensure!(
                previous == row,
                "conflicting compatibility identity for {}",
                row.scope
            );
        }
    }
    Ok(found)
}

pub(crate) fn validate_aliases(value: &Value) -> Result<Value> {
    let entries = rows(value, ALIAS_FORMAT)?;
    for row in entries.values() {
        ensure!(
            row.context.bytes().any(|b| b != b'0'),
            "alias context cannot use the unqualified zero sentinel"
        );
        let target = (row.context.clone(), row.scope.clone(), row.identity.clone());
        ensure!(
            entries
                .get(&target)
                .is_none_or(|next| next.identity == row.identity),
            "compatibility aliases cannot chain"
        );
    }
    Ok(json!({"format": ALIAS_FORMAT, "entries": entries.into_values().collect::<Vec<_>>()}))
}

pub(crate) fn validate_inventory(
    value: &Value,
    aliases: &Value,
    context: &str,
    target: &str,
) -> Result<Value> {
    ensure!(
        TARGETS.contains(&target),
        "unsupported compatibility target {target}"
    );
    check_digest(context)?;
    ensure!(
        context.bytes().any(|b| b != b'0'),
        "unqualified inventory context"
    );
    let entries = rows(value, INVENTORY_FORMAT)?;
    let approved = rows(&validate_aliases(aliases)?, ALIAS_FORMAT)?;
    let compiler = format!("compiler/{target}");
    let mut has_compiler = false;
    let mut has_producer = false;
    for (key, row) in &entries {
        ensure!(
            row.context == context,
            "actual Wasm context differs from the canonical build"
        );
        let expected = approved
            .get(key)
            .map(|row| row.identity.as_str())
            .unwrap_or(&row.raw);
        ensure!(
            row.identity == expected,
            "actual Wasm identity differs from exact alias payload for {}",
            row.scope
        );
        if row.scope.starts_with("compiler/") {
            ensure!(
                row.scope == compiler,
                "actual Wasm inventory contains a different compiler target"
            );
            has_compiler = true;
        }
        has_producer |= row.scope == PRODUCER_SCOPE;
    }
    ensure!(
        has_compiler && has_producer,
        "rooted artifact lacks compiler or source-policy inventory"
    );
    Ok(json!({"format": INVENTORY_FORMAT, "entries": entries.into_values().collect::<Vec<_>>()}))
}

pub(crate) fn canonical_bytes(value: &Value) -> Vec<u8> {
    // The published v1 receipt contract uses ASCII-escaped, sorted JSON and
    // includes a trailing newline. Do not depend on serde's map feature flags.
    fn write(value: &Value, out: &mut String) {
        match value {
            Value::Object(object) => {
                out.push('{');
                let sorted: BTreeMap<_, _> = object.iter().collect();
                for (i, (key, value)) in sorted.into_iter().enumerate() {
                    if i != 0 {
                        out.push(',')
                    }
                    string(key, out);
                    out.push(':');
                    write(value, out);
                }
                out.push('}');
            }
            Value::Array(values) => {
                out.push('[');
                for (i, value) in values.iter().enumerate() {
                    if i != 0 {
                        out.push(',')
                    }
                    write(value, out);
                }
                out.push(']');
            }
            Value::String(value) => string(value, out),
            value => out.push_str(&value.to_string()),
        }
    }
    fn string(value: &str, out: &mut String) {
        use std::fmt::Write;
        for ch in serde_json::to_string(value)
            .expect("JSON string serialization")
            .chars()
        {
            if ch < '\u{7f}' {
                out.push(ch);
            } else {
                for unit in ch.encode_utf16(&mut [0; 2]) {
                    write!(out, "\\u{unit:04x}").unwrap();
                }
            }
        }
    }
    let mut out = String::new();
    write(value, &mut out);
    out.push('\n');
    out.into_bytes()
}

pub(crate) fn load_document(path: &Path) -> Result<Value> {
    let bytes = read_document_bytes(path)?;
    parse_document(&bytes).with_context(|| format!("invalid document {}", path.display()))
}

pub(crate) fn read_document_bytes(path: &Path) -> Result<Vec<u8>> {
    let mut bytes = Vec::new();
    File::open(path)
        .with_context(|| format!("read {}", path.display()))?
        .take((MAX_DOCUMENT_BYTES + 1) as u64)
        .read_to_end(&mut bytes)?;
    ensure!(
        bytes.len() <= MAX_DOCUMENT_BYTES,
        "document exceeds byte bound: {}",
        path.display()
    );
    Ok(bytes)
}

pub(crate) fn parse_document(bytes: &[u8]) -> Result<Value> {
    use serde::de::{Error, MapAccess, SeqAccess, Visitor};
    struct Strict(Value);
    struct ReadStrict;
    impl<'de> Deserialize<'de> for Strict {
        fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
            de.deserialize_any(ReadStrict).map(Strict)
        }
    }
    impl<'de> Visitor<'de> for ReadStrict {
        type Value = Value;
        fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            f.write_str("a JSON value")
        }
        fn visit_map<M: MapAccess<'de>>(self, mut map: M) -> Result<Value, M::Error> {
            let mut fields = serde_json::Map::new();
            while let Some((key, Strict(value))) = map.next_entry::<String, Strict>()? {
                if fields.insert(key.clone(), value).is_some() {
                    return Err(M::Error::custom(format_args!(
                        "duplicate JSON field {key:?}"
                    )));
                }
            }
            Ok(Value::Object(fields))
        }
        fn visit_seq<S: SeqAccess<'de>>(self, mut seq: S) -> Result<Value, S::Error> {
            let mut array = Vec::new();
            while let Some(Strict(value)) = seq.next_element()? {
                array.push(value);
            }
            Ok(Value::Array(array))
        }
        fn visit_bool<E: Error>(self, value: bool) -> Result<Value, E> {
            Ok(value.into())
        }
        fn visit_i64<E: Error>(self, value: i64) -> Result<Value, E> {
            Ok(value.into())
        }
        fn visit_u64<E: Error>(self, value: u64) -> Result<Value, E> {
            Ok(value.into())
        }
        fn visit_f64<E: Error>(self, value: f64) -> Result<Value, E> {
            serde_json::Number::from_f64(value)
                .map(Value::Number)
                .ok_or_else(|| E::custom("invalid JSON number"))
        }
        fn visit_str<E: Error>(self, value: &str) -> Result<Value, E> {
            Ok(value.into())
        }
        fn visit_unit<E: Error>(self) -> Result<Value, E> {
            Ok(Value::Null)
        }
    }
    ensure!(
        bytes.len() <= MAX_DOCUMENT_BYTES,
        "compatibility document exceeds byte bound"
    );
    Ok(serde_json::from_slice::<Strict>(bytes)?.0)
}

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

    #[test]
    fn canonical_aliases_and_strict_receipt_json() -> Result<()> {
        let canonical = canonical_bytes(&validate_aliases(&parse_document(APPROVED_ALIASES)?)?);
        assert_eq!(APPROVED_ALIASES, canonical);
        assert_eq!(
            canonical_bytes(&json!({"é": "🚀", "a": "\u{7f}"})),
            b"{\"a\":\"\\u007f\",\"\\u00e9\":\"\\ud83d\\ude80\"}\n"
        );
        assert!(parse_document(br#"{"meta":{"x":true,"x":false}}"#).is_err());
        Ok(())
    }

    #[test]
    fn content_addressed_aliases_reuse_the_same_file_and_reject_changes() -> Result<()> {
        let target = tempfile::tempdir()?;
        let first = materialize_aliases(target.path(), APPROVED_ALIASES)?;
        assert_eq!(first, materialize_aliases(target.path(), APPROVED_ALIASES)?);
        fs::write(&first, b"changed")?;
        assert!(materialize_aliases(target.path(), APPROVED_ALIASES).is_err());
        assert_eq!(fs::read(first)?, b"changed");
        Ok(())
    }

    #[test]
    fn archive_matches_the_complete_resolved_source() -> Result<()> {
        let temporary = tempfile::tempdir()?;
        let source = temporary.path().join("source");
        fs::create_dir(&source)?;
        fs::write(
            source.join("Cargo.toml"),
            b"[package]\nname = \"example\"\n",
        )?;
        fs::write(source.join("lib.rs"), b"pub fn run() {}\n")?;
        fs::write(source.join(".cargo-ok"), b"")?;
        let path = temporary.path().join("example-1.0.0.crate");
        let encoder =
            flate2::write::GzEncoder::new(File::create(&path)?, flate2::Compression::fast());
        let mut archive = tar::Builder::new(encoder);
        for name in ["Cargo.toml", "lib.rs"] {
            archive.append_path_with_name(source.join(name), format!("example-1.0.0/{name}"))?;
        }
        archive.into_inner()?.finish()?;
        assert_eq!(verify_package_source(&source, &path)?.len(), 2);
        fs::write(source.join("untracked.rs"), b"")?;
        assert!(verify_package_source(&source, &path).is_err());
        fs::remove_file(source.join("untracked.rs"))?;
        fs::write(source.join("lib.rs"), b"pub fn changed() {}\n")?;
        assert!(verify_package_source(&source, &path).is_err());
        Ok(())
    }
}