Skip to main content

rpi_cli/
prebuilt_extensions.rs

1//! Versioned prebuilt extension distribution (rpi-extension.json v1).
2//! Repository discovery uses crates.io metadata. Release tags and library
3//! paths are protocol fields, never guessed from asset names or repository latest.
4
5use std::collections::BTreeMap;
6use std::io::{Cursor, Read};
7use std::path::{Component, Path, PathBuf};
8
9use serde::{Deserialize, Serialize};
10use sha2::{Digest, Sha256};
11
12const CRATES_API: &str = "https://crates.io/api/v1/crates";
13const MAX_METADATA: u64 = 8 * 1024 * 1024;
14const MAX_MANIFEST: u64 = 256 * 1024;
15const MAX_ARCHIVE: u64 = 256 * 1024 * 1024;
16const MAX_LIBRARY: u64 = 128 * 1024 * 1024;
17const MAX_ENTRIES: usize = 128;
18/// Optional archive index for sidecar files beside the library. Archives
19/// without it are the legacy single-library layout.
20const RUNTIME_ASSETS_FILE: &str = "runtime-assets.json";
21/// Largest accepted `runtime-assets.json`, in bytes.
22const MAX_ASSET_INDEX: u64 = 256 * 1024;
23/// Longest accepted sidecar path, in bytes.
24const MAX_ASSET_PATH: usize = 512;
25
26#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
27pub struct PrebuiltRecord {
28    pub repository: String,
29    pub target: String,
30    pub manifest_sha256: String,
31    pub source_commit: String,
32    pub sdk_version: String,
33    pub plugin_abi: u32,
34    pub archive_sha256: String,
35    pub library_sha256: String,
36    /// Explicit repository installs discover versions from package-specific tags.
37    #[serde(default)]
38    pub custom_repository: bool,
39    /// Sidecar files installed beside the library, as verified against the
40    /// archive index. Empty for single-library archives, so their records are unchanged.
41    #[serde(default, skip_serializing_if = "Vec::is_empty")]
42    pub assets: Vec<PrebuiltAsset>,
43}
44
45/// One verified sidecar file, relative to the extension store directory.
46#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
47pub struct PrebuiltAsset {
48    pub path: String,
49    pub sha256: String,
50}
51
52/// The sidecar index inside a package archive: `runtime-assets.json`.
53#[derive(Debug, Deserialize)]
54struct RuntimeAssetIndex {
55    schema_version: u32,
56    assets: Vec<RuntimeAsset>,
57}
58
59#[derive(Debug, Deserialize)]
60struct RuntimeAsset {
61    path: String,
62    size: u64,
63    sha256: String,
64}
65
66/// Size caps for one archive: each file, and every expanded byte together.
67#[derive(Debug, Clone, Copy)]
68pub(crate) struct ArchiveLimits {
69    pub per_file: u64,
70    pub total: u64,
71}
72
73impl ArchiveLimits {
74    pub(crate) const PREBUILT: Self = Self {
75        per_file: MAX_LIBRARY,
76        total: MAX_ARCHIVE,
77    };
78}
79
80/// A sidecar whose bytes match the archive index.
81pub(crate) struct VerifiedAsset {
82    pub path: String,
83    pub sha256: String,
84    pub bytes: Vec<u8>,
85}
86
87/// Verified archive contents. `assets` follow the order of the archive index.
88pub(crate) struct PrebuiltContents {
89    pub library: Vec<u8>,
90    pub assets: Vec<VerifiedAsset>,
91}
92
93#[derive(Debug, Deserialize)]
94struct RegistryPackage {
95    #[serde(rename = "crate")]
96    metadata: RegistryMetadata,
97    versions: Vec<RegistryVersion>,
98}
99
100#[derive(Debug, Deserialize)]
101struct RegistryMetadata {
102    id: String,
103    repository: Option<String>,
104}
105
106#[derive(Debug, Deserialize)]
107struct RegistryVersion {
108    num: String,
109    yanked: bool,
110}
111
112#[derive(Debug, Deserialize)]
113struct Manifest {
114    schema_version: u32,
115    name: String,
116    version: String,
117    repository: String,
118    tag: String,
119    source_commit: String,
120    sdk: Sdk,
121    targets: BTreeMap<String, Distribution>,
122}
123
124#[derive(Debug, Deserialize)]
125struct Sdk {
126    version: String,
127    plugin_abi: u32,
128}
129
130#[derive(Debug, Deserialize)]
131struct Distribution {
132    url: String,
133    format: String,
134    size: u64,
135    sha256: String,
136    library: Library,
137}
138
139#[derive(Debug, Deserialize)]
140struct Library {
141    path: String,
142    sha256: String,
143}
144
145struct ResolvedPackage {
146    name: String,
147    version: String,
148    repository: String,
149    custom_repository: bool,
150}
151
152#[derive(Deserialize)]
153struct GitReference {
154    #[serde(rename = "ref")]
155    reference: String,
156}
157
158fn stable_tag_version(refs: &[GitReference], name: &str) -> Result<String, String> {
159    let prefix = format!("refs/tags/{name}-v");
160    refs.iter().filter_map(|r| r.reference.strip_prefix(&prefix))
161        .filter_map(|v| semver::Version::parse(v).ok()).filter(|v| v.pre.is_empty())
162        .max().map(|v| v.to_string()).ok_or_else(|| format!("no stable {name}-v<version> tag exists in this repository; specify --version explicitly"))
163}
164
165async fn repository_version(
166    client: &reqwest::Client,
167    api: &str,
168    name: &str,
169    repository: &str,
170) -> Result<String, String> {
171    let repository = canonical_repository(repository)?;
172    let repo = repository
173        .strip_prefix("https://github.com/")
174        .ok_or("invalid GitHub repository")?;
175    let response = client
176        .get(format!(
177            "{api}/repos/{repo}/git/matching-refs/tags/{name}-v"
178        ))
179        .header(reqwest::header::ACCEPT, "application/vnd.github+json")
180        .send()
181        .await
182        .map_err(|e| format!("GitHub tag lookup failed: {e}"))?;
183    if !response.status().is_success() {
184        return Err(format!("GitHub tag lookup returned {}", response.status()));
185    }
186    let refs: Vec<GitReference> =
187        serde_json::from_slice(&body_limited(response, MAX_METADATA).await?)
188            .map_err(|e| format!("invalid GitHub tag metadata: {e}"))?;
189    stable_tag_version(&refs, name)
190}
191
192/// Supported triples are deliberately exact: GNU/musl and MSVC/GNU are
193/// different native-library distributions.
194pub fn host_target() -> Result<&'static str, String> {
195    match (std::env::consts::OS, std::env::consts::ARCH) {
196        ("windows", "x86_64") if cfg!(target_env = "msvc") => Ok("x86_64-pc-windows-msvc"),
197        ("linux", "x86_64") if cfg!(target_env = "gnu") => Ok("x86_64-unknown-linux-gnu"),
198        ("linux", "x86_64") if cfg!(target_env = "musl") => Ok("x86_64-unknown-linux-musl"),
199        ("linux", "aarch64") if cfg!(target_env = "gnu") => Ok("aarch64-unknown-linux-gnu"),
200        ("macos", "x86_64") => Ok("x86_64-apple-darwin"),
201        ("macos", "aarch64") => Ok("aarch64-apple-darwin"),
202        _ => Err(
203            "no supported prebuilt target for this host; use --build to compile explicitly".into(),
204        ),
205    }
206}
207
208fn valid_segment(value: &str) -> bool {
209    !value.is_empty()
210        && !matches!(value, "." | "..")
211        && value
212            .bytes()
213            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
214}
215
216/// Accept an explicit owner/repo override or repository metadata URLs,
217/// including Cargo's common .git / git+https forms and GitHub tree subpaths.
218pub(crate) fn canonical_repository(value: &str) -> Result<String, String> {
219    let value = value.trim().strip_prefix("git+").unwrap_or(value.trim());
220    let value = if value.contains("://") {
221        value.to_string()
222    } else {
223        format!("https://github.com/{value}")
224    };
225    let url = reqwest::Url::parse(&value).map_err(|_| "invalid GitHub repository".to_string())?;
226    if url.scheme() != "https"
227        || url.host_str() != Some("github.com")
228        || !url.username().is_empty()
229        || url.password().is_some()
230        || url.port().is_some()
231    {
232        return Err("prebuilt repository must be an HTTPS GitHub repository; use --build for other repositories".into());
233    }
234    let segments: Vec<_> = url
235        .path_segments()
236        .ok_or("invalid GitHub repository path")?
237        .collect();
238    if segments.len() < 2 || !valid_segment(segments[0]) {
239        return Err("repository must identify a GitHub owner and repository".into());
240    }
241    let repo = segments[1].strip_suffix(".git").unwrap_or(segments[1]);
242    if !valid_segment(repo) {
243        return Err("invalid GitHub repository name".into());
244    }
245    if segments.len() > 2
246        && !segments[2..].iter().all(|s| s.is_empty())
247        && !matches!(segments[2], "tree" | "blob")
248    {
249        return Err("unsupported GitHub repository URL path".into());
250    }
251    Ok(format!(
252        "https://github.com/{}/{}",
253        segments[0].to_ascii_lowercase(),
254        repo.to_ascii_lowercase()
255    ))
256}
257
258fn release_url(repository: &str, name: &str, version: &str, file: &str) -> Result<String, String> {
259    let mut url = reqwest::Url::parse(repository).map_err(|e| e.to_string())?;
260    url.path_segments_mut()
261        .map_err(|_| "invalid release repository")?
262        .push("releases")
263        .push("download")
264        .push(&format!("{name}-v{version}"))
265        .push(file);
266    Ok(url.into())
267}
268
269fn select_version(versions: &[RegistryVersion], requested: Option<&str>) -> Result<String, String> {
270    if let Some(requested) = requested {
271        let version = semver::Version::parse(requested)
272            .map_err(|_| "--version requires an exact semantic version".to_string())?;
273        return versions
274            .iter()
275            .find(|v| !v.yanked && v.num == version.to_string())
276            .map(|v| v.num.clone())
277            .ok_or_else(|| format!("version {requested} is absent or yanked on crates.io"));
278    }
279    versions
280        .iter()
281        .filter(|v| !v.yanked)
282        .filter_map(|v| semver::Version::parse(&v.num).ok())
283        .filter(|v| v.pre.is_empty())
284        .max()
285        .map(|v| v.to_string())
286        .ok_or_else(|| "no non-yanked stable version is available".into())
287}
288
289pub(crate) async fn body_limited(
290    mut response: reqwest::Response,
291    limit: u64,
292) -> Result<Vec<u8>, String> {
293    if response.content_length().is_some_and(|n| n > limit) {
294        return Err("download exceeds size limit".into());
295    }
296    let mut bytes = Vec::new();
297    while let Some(chunk) = response
298        .chunk()
299        .await
300        .map_err(|e| format!("download failed: {e}"))?
301    {
302        if bytes.len() as u64 + chunk.len() as u64 > limit {
303            return Err("download exceeds size limit".into());
304        }
305        bytes.extend_from_slice(&chunk);
306    }
307    Ok(bytes)
308}
309
310async fn resolve_package(
311    client: &reqwest::Client,
312    api: &str,
313    name: &str,
314    version: Option<&str>,
315    repository: Option<&str>,
316) -> Result<ResolvedPackage, String> {
317    // An explicit repository + version also supports unpublished third-party extensions.
318    if let Some(repository) = repository {
319        let repository = canonical_repository(repository)?;
320        let version = match version {
321            Some(version) => semver::Version::parse(version)
322                .map_err(|_| "--version requires an exact semantic version".to_string())?
323                .to_string(),
324            None => repository_version(client, "https://api.github.com", name, &repository).await?,
325        };
326        return Ok(ResolvedPackage {
327            name: name.into(),
328            version,
329            repository,
330            custom_repository: true,
331        });
332    }
333    let response = client
334        .get(format!("{api}/{name}"))
335        .send()
336        .await
337        .map_err(|e| format!("crates.io lookup failed: {e}"))?;
338    if !response.status().is_success() {
339        return Err(format!(
340            "crates.io lookup for {name} returned {}",
341            response.status()
342        ));
343    }
344    let data: RegistryPackage =
345        serde_json::from_slice(&body_limited(response, MAX_METADATA).await?)
346            .map_err(|e| format!("invalid crates.io metadata: {e}"))?;
347    if !data
348        .metadata
349        .id
350        .replace('-', "_")
351        .eq_ignore_ascii_case(&name.replace('-', "_"))
352    {
353        return Err("crates.io metadata identifies a different package".into());
354    }
355    let version = select_version(&data.versions, version)?;
356    let repository = repository
357        .or(data.metadata.repository.as_deref())
358        .ok_or("crate has no repository metadata; use --github owner/repo or --build")?;
359    Ok(ResolvedPackage {
360        name: data.metadata.id,
361        version,
362        repository: canonical_repository(repository)?,
363        custom_repository: false,
364    })
365}
366
367pub(crate) fn hash(bytes: &[u8]) -> String {
368    format!("{:x}", Sha256::digest(bytes))
369}
370
371pub(crate) fn check_hash(bytes: &[u8], expected: &str) -> Result<(), String> {
372    if expected.len() != 64
373        || !expected
374            .bytes()
375            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
376    {
377        return Err("manifest SHA-256 must be 64 lowercase hexadecimal characters".into());
378    }
379    if hash(bytes) != expected {
380        return Err("SHA-256 mismatch".into());
381    }
382    Ok(())
383}
384
385fn validate_manifest<'a>(
386    manifest: &'a Manifest,
387    package: &ResolvedPackage,
388    target: &str,
389) -> Result<&'a Distribution, String> {
390    if manifest.schema_version != 1 {
391        return Err(format!(
392            "unsupported prebuilt manifest schema {}",
393            manifest.schema_version
394        ));
395    }
396    if manifest.name != package.name
397        || manifest.version != package.version
398        || manifest.tag != format!("{}-v{}", package.name, package.version)
399        || canonical_repository(&manifest.repository)? != package.repository
400    {
401        return Err("prebuilt manifest package, version, repository or tag does not match the requested package".into());
402    }
403    if manifest.source_commit.len() != 40
404        || !manifest
405            .source_commit
406            .bytes()
407            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
408    {
409        return Err("manifest source_commit must be a full Git commit SHA".into());
410    }
411    semver::Version::parse(&manifest.sdk.version).map_err(|_| "invalid SDK version in manifest")?;
412    if manifest.sdk.plugin_abi != rpi_plugin_sdk::RPI_PLUGIN_ABI_VERSION_UNIFIED {
413        return Err(format!(
414            "extension SDK ABI {} is incompatible with host ABI {}",
415            manifest.sdk.plugin_abi,
416            rpi_plugin_sdk::RPI_PLUGIN_ABI_VERSION_UNIFIED
417        ));
418    }
419    let distribution = manifest.targets.get(target).ok_or_else(|| {
420        format!(
421            "no prebuilt extension for exact target {target}; use --build to compile explicitly"
422        )
423    })?;
424    if distribution.size == 0
425        || distribution.size > MAX_ARCHIVE
426        || !matches!(distribution.format.as_str(), "zip" | "tar.gz")
427    {
428        return Err("unsupported archive format or size in manifest".into());
429    }
430    let name = &distribution.library.path;
431    let extension = if target.contains("windows") {
432        ".dll"
433    } else if target.contains("apple") {
434        ".dylib"
435    } else {
436        ".so"
437    };
438    if name.is_empty()
439        || !name.ends_with(extension)
440        || name.contains(['/', '\\', ':'])
441        || !name
442            .bytes()
443            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
444        || matches!(name.as_str(), "." | "..")
445    {
446        return Err(
447            "manifest library.path must be a flat library filename for the selected target".into(),
448        );
449    }
450    for expected in [&distribution.sha256, &distribution.library.sha256] {
451        if expected.len() != 64
452            || !expected
453                .bytes()
454                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
455        {
456            return Err("invalid SHA-256 in manifest".into());
457        }
458    }
459    validate_release_asset_url(&distribution.url, &package.repository, &manifest.tag)?;
460    Ok(distribution)
461}
462
463pub(crate) fn validate_release_asset_url(
464    value: &str,
465    repository: &str,
466    tag: &str,
467) -> Result<(), String> {
468    let url = reqwest::Url::parse(value).map_err(|_| "invalid archive URL")?;
469    let segments: Vec<String> = url
470        .path_segments()
471        .ok_or("archive URL has no path")?
472        .map(|s| {
473            percent_encoding::percent_decode_str(s)
474                .decode_utf8()
475                .map(|s| s.into_owned())
476                .map_err(|_| "invalid encoded archive URL")
477        })
478        .collect::<Result<_, _>>()?;
479    if url.scheme() != "https"
480        || url.host_str() != Some("github.com")
481        || url.port().is_some()
482        || !url.username().is_empty()
483        || url.password().is_some()
484        || url.query().is_some()
485        || url.fragment().is_some()
486        || segments.len() != 6
487        || segments[2] != "releases"
488        || segments[3] != "download"
489        || segments[4] != tag
490        || canonical_repository(&format!(
491            "https://github.com/{}/{}",
492            segments[0], segments[1]
493        ))? != repository
494        || segments[5].is_empty()
495        || matches!(segments[5].as_str(), "." | "..")
496        || !segments[5]
497            .bytes()
498            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'+'))
499    {
500        return Err(
501            "archive URL must belong to the same GitHub repository and package Release".into(),
502        );
503    }
504    Ok(())
505}
506
507async fn fetch_manifest(
508    client: &reqwest::Client,
509    package: &ResolvedPackage,
510) -> Result<(Manifest, Vec<u8>), String> {
511    let url = release_url(
512        &package.repository,
513        &package.name,
514        &package.version,
515        "rpi-extension.json",
516    )?;
517    let response = client
518        .get(&url)
519        .send()
520        .await
521        .map_err(|e| format!("prebuilt manifest request failed: {e}"))?;
522    read_manifest_response(response, package).await
523}
524
525async fn read_manifest_response(
526    response: reqwest::Response,
527    package: &ResolvedPackage,
528) -> Result<(Manifest, Vec<u8>), String> {
529    if response.status() == reqwest::StatusCode::NOT_FOUND {
530        return Err(format!("prebuilt release for {} {} is not ready (rpi-extension.json is missing); retry later or use --build explicitly", package.name, package.version));
531    }
532    if !response.status().is_success() {
533        return Err(format!(
534            "prebuilt manifest request returned {}",
535            response.status()
536        ));
537    }
538    let bytes = body_limited(response, MAX_MANIFEST).await?;
539    let manifest =
540        serde_json::from_slice(&bytes).map_err(|e| format!("invalid rpi-extension.json: {e}"))?;
541    Ok((manifest, bytes))
542}
543
544/// Only advertise an update when its exact platform manifest is available and compatible.
545pub async fn latest_compatible_version(
546    client: &reqwest::Client,
547    package: &crate::install::InstalledNativePackage,
548) -> Result<Option<String>, String> {
549    let Some(record) = &package.prebuilt else {
550        return Ok(None);
551    };
552    let repository = record
553        .custom_repository
554        .then_some(record.repository.as_str());
555    let resolved = resolve_package(client, CRATES_API, &package.name, None, repository).await?;
556    if resolved.repository != record.repository {
557        return Err(
558            "extension repository changed; reinstall explicitly to select a new publisher".into(),
559        );
560    }
561    if !crate::updates::is_newer(&package.version, &resolved.version) {
562        return Ok(Some(resolved.version));
563    }
564    let (manifest, _) = fetch_manifest(client, &resolved).await?;
565    validate_manifest(&manifest, &resolved, host_target()?)?;
566    Ok(Some(resolved.version))
567}
568
569pub async fn install(
570    name: &str,
571    version: Option<&str>,
572    repository: Option<&str>,
573    force: bool,
574    cdn_base: Option<&reqwest::Url>,
575) -> Result<(), String> {
576    let records = crate::install::installed_native_packages_strict()?;
577    let existing = records.iter().find(|p| p.name == name);
578    let target = host_target()?;
579    let client = reqwest::Client::builder()
580        .timeout(std::time::Duration::from_secs(15))
581        .user_agent(format!("rpi/{}", crate::VERSION))
582        .build()
583        .map_err(|e| e.to_string())?;
584    let repository = repository.or_else(|| {
585        existing
586            .and_then(|p| p.prebuilt.as_ref())
587            .filter(|record| record.custom_repository)
588            .map(|r| r.repository.as_str())
589    });
590    let package = resolve_package(&client, CRATES_API, name, version, repository).await?;
591    if let Some(record) = existing.and_then(|p| p.prebuilt.as_ref()) {
592        if repository.is_none() && record.repository != package.repository {
593            return Err(
594                "extension repository changed; select the new repository explicitly with --github"
595                    .into(),
596            );
597        }
598    }
599    if !crate::install::should_install_version(
600        name,
601        existing.map(|p| p.version.as_str()),
602        &package.version,
603        force,
604    )? {
605        crate::install::print_already_installed(name, &package.version);
606        return Ok(());
607    }
608    println!(
609        "downloading prebuilt {} {} for {target}",
610        package.name, package.version
611    );
612    let (manifest, manifest_bytes) = fetch_manifest(&client, &package).await?;
613    let distribution = validate_manifest(&manifest, &package, target)?;
614    let cdn_url = cdn_base
615        .map(|base| {
616            crate::cdn::archive_url(base, &package.repository, &manifest.tag, &distribution.url)
617        })
618        .transpose()?
619        .flatten();
620    let archive = crate::cdn::download_with_fallback(
621        &client,
622        cdn_url.as_ref(),
623        &distribution.url,
624        distribution.size,
625        &distribution.sha256,
626        "archive",
627    )
628    .await?;
629    let agent_dir = crate::config::agent_dir().map_err(|e| e.to_string())?;
630    let agent_dir_for_gc = agent_dir.clone();
631    let target = target.to_string();
632    let installed = tokio::task::spawn_blocking(move || {
633        install_archive_at(
634            &package,
635            &manifest,
636            &manifest_bytes,
637            &archive,
638            &target,
639            &agent_dir,
640            force,
641        )
642    })
643    .await
644    .map_err(|e| format!("prebuilt installation failed: {e}"))??;
645    for path in installed {
646        println!("installed {}", path.display());
647    }
648    if matches!(
649        crate::install::gc_retired_native_artifacts(&agent_dir_for_gc),
650        crate::install::RetiredGcOutcome::Deferred
651    ) {
652        eprintln!(
653            "warning: stale native extension artifacts were not cleaned up because the resource lease could not be acquired (a running rpi host or lease setup failure); they will be ignored at startup and retried on a later install"
654        );
655    }
656    println!("rpi will validate the plugin entrypoint/SDK API size and load this extension on the next start.");
657    Ok(())
658}
659
660fn install_archive_at(
661    package: &ResolvedPackage,
662    manifest: &Manifest,
663    manifest_bytes: &[u8],
664    archive: &[u8],
665    target: &str,
666    agent_dir: &Path,
667    force: bool,
668) -> Result<Vec<PathBuf>, String> {
669    let distribution = validate_manifest(manifest, package, target)?;
670    if archive.len() as u64 != distribution.size {
671        return Err("archive byte length does not match manifest".into());
672    }
673    check_hash(archive, &distribution.sha256)?;
674    // Everything is verified in memory before the extension store is touched.
675    let contents = extract_contents(archive, &distribution.format, &distribution.library.path)?;
676    check_hash(&contents.library, &distribution.library.sha256)?;
677    validate_library_target(&contents.library, target)?;
678    let provenance = PrebuiltRecord {
679        repository: package.repository.clone(),
680        target: target.into(),
681        manifest_sha256: hash(manifest_bytes),
682        source_commit: manifest.source_commit.clone(),
683        sdk_version: manifest.sdk.version.clone(),
684        plugin_abi: manifest.sdk.plugin_abi,
685        archive_sha256: distribution.sha256.clone(),
686        library_sha256: distribution.library.sha256.clone(),
687        custom_repository: package.custom_repository,
688        assets: contents
689            .assets
690            .iter()
691            .map(|asset| PrebuiltAsset {
692                path: asset.path.clone(),
693                sha256: asset.sha256.clone(),
694            })
695            .collect(),
696    };
697    let temporary = tempfile::tempdir().map_err(|e| e.to_string())?;
698    let artifact = temporary.path().join(&distribution.library.path);
699    std::fs::write(&artifact, &contents.library).map_err(|e| e.to_string())?;
700    let assets: Vec<crate::install::NativeAssetFile> = contents
701        .assets
702        .into_iter()
703        .map(|asset| crate::install::NativeAssetFile {
704            path: asset.path,
705            bytes: asset.bytes,
706        })
707        .collect();
708    let record = crate::install::InstalledNativePackage {
709        name: package.name.clone(),
710        version: package.version.clone(),
711        // Older hosts regard this as a non-registry source and will not rebuild it.
712        source: Some(format!("prebuilt:{}", package.repository)),
713        prebuilt: Some(provenance),
714        artifacts: Vec::new(),
715    };
716    crate::install::install_native_package_with_assets_at(
717        &agent_dir.join("extensions"),
718        &agent_dir.join("native-packages.json"),
719        record,
720        &[artifact],
721        &assets,
722        force,
723    )
724}
725
726fn safe_entry_name(name: &str) -> Result<PathBuf, String> {
727    if name.contains(['\\', ':'])
728        || Path::new(name).components().any(|p| {
729            matches!(
730                p,
731                Component::ParentDir | Component::RootDir | Component::Prefix(_)
732            )
733        })
734    {
735        return Err("unsafe archive entry path".into());
736    }
737    Ok(Path::new(name)
738        .components()
739        .filter(|c| !matches!(c, Component::CurDir))
740        .collect())
741}
742
743fn read_library(reader: impl Read) -> Result<Vec<u8>, String> {
744    let mut bytes = Vec::new();
745    reader
746        .take(MAX_LIBRARY + 1)
747        .read_to_end(&mut bytes)
748        .map_err(|e| e.to_string())?;
749    if bytes.len() as u64 > MAX_LIBRARY {
750        return Err("extracted library exceeds size limit".into());
751    }
752    Ok(bytes)
753}
754
755#[derive(Clone, Copy, PartialEq, Eq)]
756enum EntryKind {
757    Directory,
758    File,
759}
760
761/// Visit every entry of a prebuilt archive in archive order. Unsafe names, links,
762/// more than `MAX_ENTRIES` entries and more than `total` expanded bytes are rejected
763/// here, for every archive. Visitors decide what to read.
764fn walk_archive(
765    archive: &[u8],
766    format: &str,
767    total: u64,
768    mut visit: impl FnMut(&Path, EntryKind, &mut dyn Read) -> Result<(), String>,
769) -> Result<(), String> {
770    let mut expanded = 0u64;
771    match format {
772        "zip" => {
773            let mut zip = zip::ZipArchive::new(Cursor::new(archive)).map_err(|e| e.to_string())?;
774            if zip.len() > MAX_ENTRIES {
775                return Err("too many archive entries".into());
776            }
777            for i in 0..zip.len() {
778                let mut file = zip.by_index(i).map_err(|e| e.to_string())?;
779                let path = safe_entry_name(file.name())?;
780                if file
781                    .unix_mode()
782                    .is_some_and(|mode| mode & 0o170000 == 0o120000)
783                {
784                    return Err("archive symlinks are not allowed".into());
785                }
786                expanded = expanded
787                    .checked_add(file.size())
788                    .ok_or("archive size overflow")?;
789                if expanded > total {
790                    return Err("expanded archive exceeds size limit".into());
791                }
792                let kind = if file.is_dir() {
793                    EntryKind::Directory
794                } else {
795                    EntryKind::File
796                };
797                visit(&path, kind, &mut file)?;
798            }
799        }
800        "tar.gz" => {
801            let decoder = flate2::read::GzDecoder::new(Cursor::new(archive)).take(total + 1);
802            let mut tar = tar::Archive::new(decoder);
803            for (i, entry) in tar.entries().map_err(|e| e.to_string())?.enumerate() {
804                if i >= MAX_ENTRIES {
805                    return Err("too many archive entries".into());
806                }
807                let mut file = entry.map_err(|e| e.to_string())?;
808                let name = file
809                    .path()
810                    .map_err(|e| e.to_string())?
811                    .to_string_lossy()
812                    .into_owned();
813                let path = safe_entry_name(&name)?;
814                let kind = file.header().entry_type();
815                if !kind.is_file() && !kind.is_dir() {
816                    return Err("archive links and special files are not allowed".into());
817                }
818                expanded = expanded
819                    .checked_add(file.size())
820                    .ok_or("archive size overflow")?;
821                if expanded > total {
822                    return Err("expanded archive exceeds size limit".into());
823                }
824                let kind = if kind.is_dir() {
825                    EntryKind::Directory
826                } else {
827                    EntryKind::File
828                };
829                visit(&path, kind, &mut file)?;
830            }
831        }
832        _ => return Err("unsupported prebuilt archive format".into()),
833    }
834    Ok(())
835}
836
837/// Read only the declared library. Legacy callers, such as the CLI's own release
838/// archives, never carry sidecars, so every other entry is ignored.
839pub(crate) fn extract_library(
840    archive: &[u8],
841    format: &str,
842    library: &str,
843) -> Result<Vec<u8>, String> {
844    let mut found = None;
845    walk_archive(archive, format, MAX_ARCHIVE, |path, kind, reader| {
846        if kind == EntryKind::File && path == Path::new(library) {
847            if found.is_some() {
848                return Err("duplicate declared library in archive".into());
849            }
850            found = Some(read_library(reader)?);
851        }
852        Ok(())
853    })?;
854    found.ok_or_else(|| format!("archive does not contain the exact declared library {library}"))
855}
856
857/// Extract a prebuilt package: its library and, when the archive has a
858/// `runtime-assets.json` index, every declared sidecar, all verified.
859pub(crate) fn extract_contents(
860    archive: &[u8],
861    format: &str,
862    library: &str,
863) -> Result<PrebuiltContents, String> {
864    extract_contents_with_limits(archive, format, library, ArchiveLimits::PREBUILT)
865}
866
867/// Two passes over the archive. The first reads the library and the index, so
868/// the index can be validated before any sidecar byte is read. The second
869/// reads each declared sidecar and rejects anything the index does not name.
870/// Without an index the archive is the legacy single-library layout.
871fn extract_contents_with_limits(
872    archive: &[u8],
873    format: &str,
874    library: &str,
875    limits: ArchiveLimits,
876) -> Result<PrebuiltContents, String> {
877    let library_path = Path::new(library);
878    let index_path = Path::new(RUNTIME_ASSETS_FILE);
879    let mut produced = 0u64;
880    let mut library_bytes = None;
881    let mut index_bytes = None;
882    walk_archive(archive, format, limits.total, |path, kind, reader| {
883        if kind == EntryKind::Directory {
884            return Ok(());
885        }
886        if path == library_path {
887            if library_bytes.is_some() {
888                return Err("duplicate declared library in archive".into());
889            }
890            library_bytes = Some(read_budgeted(
891                reader,
892                &mut produced,
893                limits,
894                limits.per_file,
895                "extracted library exceeds size limit",
896            )?);
897        } else if path == index_path {
898            if index_bytes.is_some() {
899                return Err(format!("duplicate {RUNTIME_ASSETS_FILE} in archive"));
900            }
901            index_bytes = Some(read_budgeted(
902                reader,
903                &mut produced,
904                limits,
905                MAX_ASSET_INDEX,
906                "runtime-assets.json exceeds size limit",
907            )?);
908        }
909        Ok(())
910    })?;
911    let library_bytes = library_bytes
912        .ok_or_else(|| format!("archive does not contain the exact declared library {library}"))?;
913    let Some(index_bytes) = index_bytes else {
914        return Ok(PrebuiltContents {
915            library: library_bytes,
916            assets: Vec::new(),
917        });
918    };
919    let declared = declared_assets(&index_bytes, library, limits)?;
920    let mut found: Vec<Option<Vec<u8>>> = vec![None; declared.len()];
921    walk_archive(archive, format, limits.total, |path, kind, reader| {
922        if kind == EntryKind::Directory {
923            if has_node_modules(path) {
924                return Err(format!("archive contains node_modules: {}", path.display()));
925            }
926            return Ok(());
927        }
928        // Already read and checked by the first pass.
929        if path == library_path || path == index_path {
930            return Ok(());
931        }
932        let Some(position) = declared
933            .iter()
934            .position(|asset| Path::new(&asset.path) == path)
935        else {
936            return Err(format!("undeclared file in archive: {}", path.display()));
937        };
938        let asset = &declared[position];
939        if found[position].is_some() {
940            return Err(format!(
941                "duplicate declared asset in archive: {}",
942                asset.path
943            ));
944        }
945        let bytes = read_budgeted(
946            reader,
947            &mut produced,
948            limits,
949            limits.per_file,
950            "extracted asset exceeds size limit",
951        )?;
952        if bytes.len() as u64 != asset.size {
953            return Err(format!(
954                "asset {} size does not match runtime-assets.json",
955                asset.path
956            ));
957        }
958        check_hash(&bytes, &asset.sha256).map_err(|e| format!("asset {}: {e}", asset.path))?;
959        found[position] = Some(bytes);
960        Ok(())
961    })?;
962    let mut assets = Vec::with_capacity(declared.len());
963    for (asset, bytes) in declared.into_iter().zip(found) {
964        let bytes = bytes
965            .ok_or_else(|| format!("archive does not contain declared asset {}", asset.path))?;
966        assets.push(VerifiedAsset {
967            path: asset.path,
968            sha256: asset.sha256,
969            bytes,
970        });
971    }
972    Ok(PrebuiltContents {
973        library: library_bytes,
974        assets,
975    })
976}
977
978/// Parse and validate `runtime-assets.json`. Paths, sizes, digests and collisions
979/// are all checked before any sidecar is read.
980fn declared_assets(
981    bytes: &[u8],
982    library: &str,
983    limits: ArchiveLimits,
984) -> Result<Vec<RuntimeAsset>, String> {
985    let index: RuntimeAssetIndex =
986        serde_json::from_slice(bytes).map_err(|e| format!("invalid {RUNTIME_ASSETS_FILE}: {e}"))?;
987    if index.schema_version != 1 {
988        return Err(format!(
989            "unsupported runtime asset index schema {}",
990            index.schema_version
991        ));
992    }
993    // The library and the index are two of the archive's entries.
994    if index.assets.len() + 2 > MAX_ENTRIES {
995        return Err("too many runtime assets".into());
996    }
997    let reserved = [
998        library.to_ascii_lowercase(),
999        RUNTIME_ASSETS_FILE.to_ascii_lowercase(),
1000    ];
1001    let mut declared: Vec<RuntimeAsset> = Vec::with_capacity(index.assets.len());
1002    for asset in index.assets {
1003        validate_asset_path(&asset.path)?;
1004        if reserved
1005            .iter()
1006            .any(|name| asset_paths_conflict(name, &asset.path))
1007        {
1008            return Err(format!(
1009                "asset path `{}` collides with the library or manifest",
1010                asset.path
1011            ));
1012        }
1013        if declared
1014            .iter()
1015            .any(|other| asset_paths_conflict(&other.path, &asset.path))
1016        {
1017            return Err(format!(
1018                "duplicate or overlapping asset path `{}`",
1019                asset.path
1020            ));
1021        }
1022        if asset.size > limits.per_file {
1023            return Err(format!("runtime asset {} exceeds size limit", asset.path));
1024        }
1025        if !is_sha256_hex(&asset.sha256) {
1026            return Err(format!("invalid SHA-256 for runtime asset {}", asset.path));
1027        }
1028        declared.push(asset);
1029    }
1030    Ok(declared)
1031}
1032
1033/// Read one archive entry under its per-file cap and the archive's remaining
1034/// expansion budget. Budgets count bytes actually produced, so a header that
1035/// understates its size cannot bypass them.
1036fn read_budgeted(
1037    reader: &mut dyn Read,
1038    produced: &mut u64,
1039    limits: ArchiveLimits,
1040    per_file: u64,
1041    file_error: &str,
1042) -> Result<Vec<u8>, String> {
1043    let remaining = limits.total.saturating_sub(*produced);
1044    let limit = per_file.min(remaining);
1045    let mut bytes = Vec::new();
1046    reader
1047        .take(limit.saturating_add(1))
1048        .read_to_end(&mut bytes)
1049        .map_err(|e| e.to_string())?;
1050    if bytes.len() as u64 > limit {
1051        return Err(if limit == remaining {
1052            "expanded archive exceeds size limit".into()
1053        } else {
1054            file_error.into()
1055        });
1056    }
1057    *produced += bytes.len() as u64;
1058    Ok(bytes)
1059}
1060
1061/// Sidecar paths are relative, forward-slash and plain ASCII. Components cannot be
1062/// empty, `.`, `..` or hidden, cannot be a Windows device name or end in a dot,
1063/// cannot be `node_modules`, and cannot carry a native library extension, because
1064/// the loader scans the extension store for libraries.
1065pub(crate) fn validate_asset_path(value: &str) -> Result<(), String> {
1066    let invalid = || format!("invalid asset path `{value}`");
1067    if value.is_empty() || value.len() > MAX_ASSET_PATH {
1068        return Err(invalid());
1069    }
1070    for component in value.split('/') {
1071        // Windows maps these stems to devices even with an extension, and drops trailing dots.
1072        let stem = component
1073            .split('.')
1074            .next()
1075            .unwrap_or_default()
1076            .to_ascii_uppercase();
1077        let device = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")
1078            || (stem.len() == 4
1079                && (stem.starts_with("COM") || stem.starts_with("LPT"))
1080                && stem.as_bytes()[3].is_ascii_digit());
1081        if component.is_empty()
1082            || component.starts_with('.')
1083            || component.ends_with('.')
1084            || device
1085            || !component
1086                .bytes()
1087                .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
1088        {
1089            return Err(invalid());
1090        }
1091        if component.eq_ignore_ascii_case("node_modules") {
1092            return Err(format!(
1093                "asset `{value}` vendors node_modules; dependencies must be installed at runtime"
1094            ));
1095        }
1096        if crate::install::is_dynamic_library(Path::new(component)) {
1097            return Err(format!(
1098                "asset `{value}` has a native library extension and cannot be installed as an asset"
1099            ));
1100        }
1101    }
1102    Ok(())
1103}
1104
1105/// Whether two store paths name one file, compared case-insensitively, or nest one under the other.
1106pub(crate) fn asset_paths_conflict(left: &str, right: &str) -> bool {
1107    let (left, right) = (left.to_ascii_lowercase(), right.to_ascii_lowercase());
1108    left == right
1109        || left.starts_with(&format!("{right}/"))
1110        || right.starts_with(&format!("{left}/"))
1111}
1112
1113fn has_node_modules(path: &Path) -> bool {
1114    path.components()
1115        .any(|part| part.as_os_str().eq_ignore_ascii_case("node_modules"))
1116}
1117
1118fn is_sha256_hex(value: &str) -> bool {
1119    value.len() == 64
1120        && value
1121            .bytes()
1122            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
1123}
1124
1125/// Verify the native object format/architecture without executing downloaded code.
1126fn validate_library_target(bytes: &[u8], target: &str) -> Result<(), String> {
1127    validate_native_target(bytes, target, true)
1128}
1129
1130pub(crate) fn validate_executable_target(bytes: &[u8], target: &str) -> Result<(), String> {
1131    validate_native_target(bytes, target, false)
1132}
1133
1134fn validate_native_target(bytes: &[u8], target: &str, library: bool) -> Result<(), String> {
1135    let u16_at = |n: usize| {
1136        bytes
1137            .get(n..n.checked_add(2)?)
1138            .map(|b| u16::from_le_bytes([b[0], b[1]]))
1139    };
1140    let u32_at = |n: usize| {
1141        bytes
1142            .get(n..n.checked_add(4)?)
1143            .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
1144    };
1145    let valid = match target {
1146        "x86_64-pc-windows-msvc" => {
1147            let offset = u32_at(0x3c).unwrap_or(u32::MAX) as usize;
1148            bytes.starts_with(b"MZ")
1149                && bytes.get(offset..offset.saturating_add(4)) == Some(b"PE\0\0".as_slice())
1150                && u16_at(offset.saturating_add(4)) == Some(0x8664)
1151                && u16_at(offset.saturating_add(22)).is_some_and(|flags| {
1152                    if library {
1153                        flags & 0x2000 != 0
1154                    } else {
1155                        flags & 0x2000 == 0 && flags & 2 != 0
1156                    }
1157                })
1158        }
1159        "x86_64-unknown-linux-gnu" | "x86_64-unknown-linux-musl" | "aarch64-unknown-linux-gnu" => {
1160            bytes.starts_with(b"\x7fELF\x02\x01")
1161                && u16_at(16).is_some_and(|kind| kind == 3 || (!library && kind == 2))
1162                && u16_at(18)
1163                    == Some(if target.starts_with("aarch64") {
1164                        183
1165                    } else {
1166                        62
1167                    })
1168        }
1169        "x86_64-apple-darwin" | "aarch64-apple-darwin" => {
1170            u32_at(0) == Some(0xfeedfacf)
1171                && u32_at(12) == Some(if library { 6 } else { 2 })
1172                && u32_at(4)
1173                    == Some(if target.starts_with("aarch64") {
1174                        0x0100000c
1175                    } else {
1176                        0x01000007
1177                    })
1178        }
1179        _ => false,
1180    };
1181    if !valid {
1182        return Err(format!(
1183            "declared artifact is not a compatible native {} for {target}",
1184            if library {
1185                "shared library"
1186            } else {
1187                "executable"
1188            }
1189        ));
1190    }
1191    Ok(())
1192}
1193
1194#[cfg(test)]
1195mod tests {
1196    use super::*;
1197    use std::io::Write;
1198
1199    const TARGETS: [&str; 6] = [
1200        "x86_64-pc-windows-msvc",
1201        "x86_64-unknown-linux-gnu",
1202        "x86_64-unknown-linux-musl",
1203        "aarch64-unknown-linux-gnu",
1204        "x86_64-apple-darwin",
1205        "aarch64-apple-darwin",
1206    ];
1207
1208    fn object(target: &str) -> Vec<u8> {
1209        let mut bytes = vec![0u8; 128];
1210        if target.contains("windows") {
1211            bytes[..2].copy_from_slice(b"MZ");
1212            bytes[0x3c..0x40].copy_from_slice(&64u32.to_le_bytes());
1213            bytes[64..68].copy_from_slice(b"PE\0\0");
1214            bytes[68..70].copy_from_slice(&0x8664u16.to_le_bytes());
1215            bytes[86..88].copy_from_slice(&0x2000u16.to_le_bytes());
1216        } else if target.contains("linux") {
1217            bytes[..6].copy_from_slice(b"\x7fELF\x02\x01");
1218            bytes[16..18].copy_from_slice(&3u16.to_le_bytes());
1219            bytes[18..20].copy_from_slice(
1220                &(if target.starts_with("aarch64") {
1221                    183u16
1222                } else {
1223                    62u16
1224                })
1225                .to_le_bytes(),
1226            );
1227        } else {
1228            bytes[..4].copy_from_slice(&0xfeedfacfu32.to_le_bytes());
1229            bytes[4..8].copy_from_slice(
1230                &(if target.starts_with("aarch64") {
1231                    0x0100000cu32
1232                } else {
1233                    0x01000007u32
1234                })
1235                .to_le_bytes(),
1236            );
1237            bytes[12..16].copy_from_slice(&6u32.to_le_bytes());
1238        }
1239        bytes
1240    }
1241
1242    fn zip(files: &[(&str, &[u8])]) -> Vec<u8> {
1243        let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
1244        for (name, bytes) in files {
1245            zip.start_file(*name, zip::write::SimpleFileOptions::default())
1246                .unwrap();
1247            zip.write_all(bytes).unwrap();
1248        }
1249        zip.finish().unwrap().into_inner()
1250    }
1251
1252    fn tgz(files: &[(&str, &[u8])]) -> Vec<u8> {
1253        let mut tar = tar::Builder::new(flate2::write::GzEncoder::new(
1254            Vec::new(),
1255            flate2::Compression::default(),
1256        ));
1257        for (name, bytes) in files {
1258            let mut header = tar::Header::new_gnu();
1259            header.set_size(bytes.len() as u64);
1260            header.set_mode(0o644);
1261            header.set_cksum();
1262            tar.append_data(&mut header, name, *bytes).unwrap();
1263        }
1264        tar.into_inner().unwrap().finish().unwrap()
1265    }
1266
1267    fn fixture(target: &str) -> (ResolvedPackage, serde_json::Value, Vec<u8>) {
1268        fixture_with_entries(target, &[])
1269    }
1270
1271    /// The fixture release for `target`, with `extra` files archived beside the library.
1272    fn fixture_with_entries(
1273        target: &str,
1274        extra: &[(&str, &[u8])],
1275    ) -> (ResolvedPackage, serde_json::Value, Vec<u8>) {
1276        let package = ResolvedPackage {
1277            name: "independent-plugin".into(),
1278            version: "1.2.3".into(),
1279            repository: "https://github.com/publisher/monorepo".into(),
1280            custom_repository: false,
1281        };
1282        // The library target deliberately differs from the crate name.
1283        let (format, library, file) = if target.contains("windows") {
1284            ("zip", "custom_runtime.dll", "package.zip")
1285        } else if target.contains("apple") {
1286            ("tar.gz", "libcustom_runtime.dylib", "package.tar.gz")
1287        } else {
1288            ("tar.gz", "libcustom_runtime.so", "package.tar.gz")
1289        };
1290        let bytes = object(target);
1291        let mut entries = vec![(library, bytes.as_slice())];
1292        entries.extend_from_slice(extra);
1293        let archive = if format == "zip" {
1294            zip(&entries)
1295        } else {
1296            tgz(&entries)
1297        };
1298        let manifest = serde_json::json!({
1299            "schema_version":1, "name":package.name, "version":package.version,
1300            "repository":package.repository, "tag":"independent-plugin-v1.2.3", "source_commit":"a".repeat(40),
1301            "sdk":{"version":"0.3.23", "plugin_abi":rpi_plugin_sdk::RPI_PLUGIN_ABI_VERSION_UNIFIED},
1302            "targets":{target:{"url":release_url(&package.repository,&package.name,&package.version,file).unwrap(),
1303                "format":format,"size":archive.len(),"sha256":hash(&archive),"library":{"path":library,"sha256":hash(&bytes)}}}
1304        });
1305        (package, manifest, archive)
1306    }
1307
1308    #[test]
1309    fn declared_runtime_assets_install_beside_the_library() {
1310        let target = TARGETS[0];
1311        let worker = b"export const ready = true;\n";
1312        let index = serde_json::to_vec(&serde_json::json!({
1313            "schema_version": 1,
1314            "assets": [{"path": "runtime/main.mjs", "size": worker.len(), "sha256": hash(worker)}]
1315        }))
1316        .unwrap();
1317        let (package, value, archive) = fixture_with_entries(
1318            target,
1319            &[
1320                ("runtime-assets.json", &index[..]),
1321                ("runtime/main.mjs", &worker[..]),
1322            ],
1323        );
1324        let manifest: Manifest = serde_json::from_value(value.clone()).unwrap();
1325        let agent = tempfile::tempdir().unwrap();
1326        let paths = install_archive_at(
1327            &package,
1328            &manifest,
1329            &serde_json::to_vec(&value).unwrap(),
1330            &archive,
1331            target,
1332            agent.path(),
1333            false,
1334        )
1335        .unwrap();
1336        let extensions = agent.path().join("extensions");
1337        assert_eq!(
1338            std::fs::read(extensions.join("runtime/main.mjs")).unwrap(),
1339            worker
1340        );
1341        assert!(paths.contains(&extensions.join("runtime/main.mjs")));
1342        assert!(!extensions.join("runtime-assets.json").exists());
1343    }
1344
1345    #[test]
1346    fn runtime_asset_index_rejects_unsafe_or_inconsistent_declarations() {
1347        let library = object(TARGETS[0]);
1348        let worker: &[u8] = b"export const ready = true;\n";
1349        let entry = |path: &str, bytes: &[u8]| serde_json::json!({"path": path, "size": bytes.len(), "sha256": hash(bytes)});
1350        let index = |assets: Vec<serde_json::Value>| {
1351            serde_json::to_vec(&serde_json::json!({"schema_version": 1, "assets": assets})).unwrap()
1352        };
1353        let many: Vec<serde_json::Value> = (0..127)
1354            .map(|i| entry(&format!("assets/f{i}.mjs"), worker))
1355            .collect();
1356        let cases: Vec<(&str, Vec<u8>, Vec<(&str, Vec<u8>)>, &str)> = vec![
1357            (
1358                "absolute path",
1359                index(vec![entry("/etc/main.mjs", worker)]),
1360                vec![],
1361                "invalid asset path",
1362            ),
1363            (
1364                "parent traversal",
1365                index(vec![entry("../main.mjs", worker)]),
1366                vec![],
1367                "invalid asset path",
1368            ),
1369            (
1370                "dot component",
1371                index(vec![entry("./main.mjs", worker)]),
1372                vec![],
1373                "invalid asset path",
1374            ),
1375            (
1376                "backslash",
1377                index(vec![entry("runtime\\main.mjs", worker)]),
1378                vec![],
1379                "invalid asset path",
1380            ),
1381            (
1382                "drive prefix",
1383                index(vec![entry("C:main.mjs", worker)]),
1384                vec![],
1385                "invalid asset path",
1386            ),
1387            (
1388                "hidden component",
1389                index(vec![entry(".env", worker)]),
1390                vec![],
1391                "invalid asset path",
1392            ),
1393            (
1394                "trailing slash",
1395                index(vec![entry("runtime/", worker)]),
1396                vec![],
1397                "invalid asset path",
1398            ),
1399            (
1400                "overlong path",
1401                index(vec![entry(&format!("{}.mjs", "a".repeat(510)), worker)]),
1402                vec![],
1403                "invalid asset path",
1404            ),
1405            (
1406                "node_modules",
1407                index(vec![entry("runtime/node_modules/dep.mjs", worker)]),
1408                vec![],
1409                "vendors node_modules",
1410            ),
1411            (
1412                "native library",
1413                index(vec![entry("native/helper.so", worker)]),
1414                vec![],
1415                "native library extension",
1416            ),
1417            (
1418                "index name",
1419                index(vec![entry("runtime-assets.json", worker)]),
1420                vec![],
1421                "collides with the library or manifest",
1422            ),
1423            (
1424                "case-folded duplicate",
1425                index(vec![
1426                    entry("runtime/main.mjs", worker),
1427                    entry("Runtime/Main.mjs", worker),
1428                ]),
1429                vec![],
1430                "duplicate or overlapping",
1431            ),
1432            (
1433                "nested path",
1434                index(vec![
1435                    entry("runtime", worker),
1436                    entry("runtime/main.mjs", worker),
1437                ]),
1438                vec![],
1439                "duplicate or overlapping",
1440            ),
1441            (
1442                "malformed digest",
1443                index(vec![
1444                    serde_json::json!({"path": "main.mjs", "size": worker.len(), "sha256": "ABC"}),
1445                ]),
1446                vec![],
1447                "invalid SHA-256",
1448            ),
1449            (
1450                "windows device name",
1451                index(vec![entry("runtime/CON.mjs", worker)]),
1452                vec![],
1453                "invalid asset path",
1454            ),
1455            (
1456                "windows bare device name",
1457                index(vec![entry("runtime/nul", worker)]),
1458                vec![],
1459                "invalid asset path",
1460            ),
1461            (
1462                "windows trailing dot",
1463                index(vec![entry("runtime/main.mjs.", worker)]),
1464                vec![],
1465                "invalid asset path",
1466            ),
1467            (
1468                "empty component",
1469                index(vec![entry("runtime//main.mjs", worker)]),
1470                vec![],
1471                "invalid asset path",
1472            ),
1473            (
1474                "unc prefix",
1475                index(vec![entry("\\\\server\\share\\main.mjs", worker)]),
1476                vec![],
1477                "invalid asset path",
1478            ),
1479            (
1480                "missing digest",
1481                index(vec![
1482                    serde_json::json!({"path": "main.mjs", "size": worker.len()}),
1483                ]),
1484                vec![("main.mjs", worker.to_vec())],
1485                "invalid runtime-assets.json",
1486            ),
1487            (
1488                "uppercase digest",
1489                index(vec![
1490                    serde_json::json!({"path": "main.mjs", "size": worker.len(), "sha256": hash(worker).to_uppercase()}),
1491                ]),
1492                vec![("main.mjs", worker.to_vec())],
1493                "invalid SHA-256",
1494            ),
1495            (
1496                "traversing archive entry",
1497                index(vec![]),
1498                vec![("../escape.mjs", worker.to_vec())],
1499                "unsafe archive entry path",
1500            ),
1501            (
1502                "absolute archive entry",
1503                index(vec![]),
1504                vec![("/escape.mjs", worker.to_vec())],
1505                "unsafe archive entry path",
1506            ),
1507            (
1508                "backslash archive entry",
1509                index(vec![entry("runtime/main.mjs", worker)]),
1510                vec![("runtime\\main.mjs", worker.to_vec())],
1511                "unsafe archive entry path",
1512            ),
1513            (
1514                "case-folded archive entry",
1515                index(vec![entry("runtime/main.mjs", worker)]),
1516                vec![("Runtime/Main.mjs", worker.to_vec())],
1517                "undeclared file in archive",
1518            ),
1519            (
1520                "unknown schema",
1521                serde_json::to_vec(&serde_json::json!({"schema_version": 2, "assets": []}))
1522                    .unwrap(),
1523                vec![],
1524                "unsupported runtime asset index schema",
1525            ),
1526            (
1527                "malformed index",
1528                b"{".to_vec(),
1529                vec![],
1530                "invalid runtime-assets.json",
1531            ),
1532            (
1533                "too many assets",
1534                index(many),
1535                vec![],
1536                "too many runtime assets",
1537            ),
1538            (
1539                "undeclared file",
1540                index(vec![]),
1541                vec![("runtime/main.mjs", worker.to_vec())],
1542                "undeclared file in archive",
1543            ),
1544            (
1545                "missing declared file",
1546                index(vec![entry("runtime/main.mjs", worker)]),
1547                vec![],
1548                "does not contain declared asset",
1549            ),
1550            (
1551                "size mismatch",
1552                index(vec![
1553                    serde_json::json!({"path": "main.mjs", "size": worker.len() + 1, "sha256": hash(worker)}),
1554                ]),
1555                vec![("main.mjs", worker.to_vec())],
1556                "size does not match",
1557            ),
1558            (
1559                "digest mismatch",
1560                index(vec![
1561                    serde_json::json!({"path": "main.mjs", "size": worker.len(), "sha256": hash(b"other")}),
1562                ]),
1563                vec![("main.mjs", worker.to_vec())],
1564                "SHA-256 mismatch",
1565            ),
1566        ];
1567        for (label, index, extra, expected) in cases {
1568            let mut entries: Vec<(&str, &[u8])> = vec![
1569                ("custom_runtime.dll", library.as_slice()),
1570                ("runtime-assets.json", index.as_slice()),
1571            ];
1572            entries.extend(extra.iter().map(|(name, bytes)| (*name, bytes.as_slice())));
1573            let Err(error) = extract_contents(&zip(&entries), "zip", "custom_runtime.dll") else {
1574                panic!("{label} was accepted");
1575            };
1576            assert!(error.contains(expected), "{label}: {error}");
1577        }
1578    }
1579
1580    #[test]
1581    fn runtime_asset_limits_bound_each_file_and_the_whole_archive() {
1582        let library = object(TARGETS[0]);
1583        let worker = vec![b'x'; 200];
1584        let index = |size: u64| {
1585            serde_json::to_vec(&serde_json::json!({
1586                "schema_version": 1,
1587                "assets": [{"path": "runtime/main.mjs", "size": size, "sha256": hash(&worker)}]
1588            }))
1589            .unwrap()
1590        };
1591        let declared = index(worker.len() as u64);
1592        let archive = |index: &[u8], worker: &[u8]| {
1593            zip(&[
1594                ("custom_runtime.dll", library.as_slice()),
1595                ("runtime-assets.json", index),
1596                ("runtime/main.mjs", worker),
1597            ])
1598        };
1599        let limits = |per_file, total| ArchiveLimits { per_file, total };
1600
1601        // A sidecar larger than the per-file cap is refused by its declaration.
1602        let error = extract_contents_with_limits(
1603            &archive(&declared, &worker),
1604            "zip",
1605            "custom_runtime.dll",
1606            limits(128, u64::MAX),
1607        )
1608        .err()
1609        .unwrap();
1610        assert!(
1611            error.contains("runtime asset runtime/main.mjs exceeds size limit"),
1612            "{error}"
1613        );
1614
1615        // A declaration that understates the bytes is stopped by the read cap.
1616        let understated = index(4);
1617        let error = extract_contents_with_limits(
1618            &archive(&understated, &worker),
1619            "zip",
1620            "custom_runtime.dll",
1621            limits(128, u64::MAX),
1622        )
1623        .err()
1624        .unwrap();
1625        assert!(
1626            error.contains("extracted asset exceeds size limit"),
1627            "{error}"
1628        );
1629
1630        // The expanded total counts every entry, including the library and index.
1631        let exact = library.len() as u64 + declared.len() as u64 + worker.len() as u64;
1632        let contents = extract_contents_with_limits(
1633            &archive(&declared, &worker),
1634            "zip",
1635            "custom_runtime.dll",
1636            limits(u64::MAX, exact),
1637        )
1638        .unwrap();
1639        assert_eq!(contents.assets[0].bytes, worker);
1640        let error = extract_contents_with_limits(
1641            &archive(&declared, &worker),
1642            "zip",
1643            "custom_runtime.dll",
1644            limits(u64::MAX, exact - 1),
1645        )
1646        .err()
1647        .unwrap();
1648        assert!(
1649            error.contains("expanded archive exceeds size limit"),
1650            "{error}"
1651        );
1652    }
1653
1654    #[test]
1655    fn archive_walk_bounds_expanded_size_for_every_archive() {
1656        // Undeclared entries are never read, so the header-declared total is the
1657        // only bound on a legacy archive's expansion.
1658        let archive = zip(&[("a.bin", &[0u8; 12][..]), ("b.bin", &[0u8; 12][..])]);
1659        let error = walk_archive(&archive, "zip", 20, |_, _, _| Ok(())).unwrap_err();
1660        assert!(
1661            error.contains("expanded archive exceeds size limit"),
1662            "{error}"
1663        );
1664        walk_archive(&archive, "zip", 24, |_, _, _| Ok(())).unwrap();
1665
1666        // The tar.gz stream is capped as well, so its framing counts toward the total.
1667        let tar = tgz(&[("a.bin", &[0u8; 12][..]), ("b.bin", &[0u8; 12][..])]);
1668        assert!(walk_archive(&tar, "tar.gz", 20, |_, _, _| Ok(())).is_err());
1669        walk_archive(&tar, "tar.gz", 64 * 1024, |_, _, _| Ok(())).unwrap();
1670    }
1671
1672    #[test]
1673    fn runtime_asset_index_size_is_capped() {
1674        let mut index = br#"{"schema_version":1,"assets":[]}"#.to_vec();
1675        index.resize(MAX_ASSET_INDEX as usize + 1, b' ');
1676        let library = object(TARGETS[0]);
1677        let archive = zip(&[
1678            ("custom_runtime.dll", library.as_slice()),
1679            ("runtime-assets.json", index.as_slice()),
1680        ]);
1681        let Err(error) = extract_contents(&archive, "zip", "custom_runtime.dll") else {
1682            panic!("an oversized index was accepted");
1683        };
1684        assert!(
1685            error.contains("runtime-assets.json exceeds size limit"),
1686            "{error}"
1687        );
1688    }
1689
1690    #[test]
1691    fn runtime_asset_entry_count_is_exact() {
1692        let library = object(TARGETS[0]);
1693        let worker: &[u8] = b"export const ready = true;\n";
1694        let names: Vec<String> = (0..126).map(|i| format!("assets/f{i}.mjs")).collect();
1695        let assets: Vec<serde_json::Value> = names
1696            .iter()
1697            .map(|name| serde_json::json!({"path": name, "size": worker.len(), "sha256": hash(worker)}))
1698            .collect();
1699        let index = serde_json::to_vec(&serde_json::json!({"schema_version": 1, "assets": assets}))
1700            .unwrap();
1701        let mut entries: Vec<(&str, &[u8])> = vec![
1702            ("custom_runtime.dll", library.as_slice()),
1703            ("runtime-assets.json", index.as_slice()),
1704        ];
1705        entries.extend(names.iter().map(|name| (name.as_str(), worker)));
1706        // 126 sidecars plus the library and the index make the 128-entry ceiling.
1707        let contents = extract_contents(&zip(&entries), "zip", "custom_runtime.dll").unwrap();
1708        assert_eq!(contents.assets.len(), 126);
1709
1710        // A legacy archive is bounded by the same entry ceiling.
1711        let legacy: Vec<String> = (0..129).map(|i| format!("docs/{i}.md")).collect();
1712        let legacy: Vec<(&str, &[u8])> = legacy
1713            .iter()
1714            .map(|name| (name.as_str(), &b"x"[..]))
1715            .collect();
1716        let error = extract_library(&zip(&legacy), "zip", "custom_runtime.dll").unwrap_err();
1717        assert!(error.contains("too many archive entries"), "{error}");
1718    }
1719
1720    /// Rewrite the uncompressed size that the local and central headers of `name`
1721    /// claim. The stored bytes do not change, so the entry still holds its real length.
1722    fn understate_entry(archive: &mut [u8], name: &str, claimed: u32) {
1723        let name = name.as_bytes();
1724        let local: Vec<usize> = (0..archive.len())
1725            .filter(|&at| {
1726                archive[at..].starts_with(b"PK\x03\x04")
1727                    && archive
1728                        .get(at + 30..)
1729                        .is_some_and(|rest| rest.starts_with(name))
1730            })
1731            .collect();
1732        let central: Vec<usize> = (0..archive.len())
1733            .filter(|&at| {
1734                archive[at..].starts_with(b"PK\x01\x02")
1735                    && archive
1736                        .get(at + 46..)
1737                        .is_some_and(|rest| rest.starts_with(name))
1738            })
1739            .collect();
1740        assert!(!local.is_empty() && !central.is_empty());
1741        for at in local {
1742            archive[at + 22..at + 26].copy_from_slice(&claimed.to_le_bytes());
1743        }
1744        for at in central {
1745            archive[at + 24..at + 28].copy_from_slice(&claimed.to_le_bytes());
1746        }
1747    }
1748
1749    #[test]
1750    fn runtime_asset_budget_holds_when_zip_headers_understate_sizes() {
1751        let library = object(TARGETS[0]);
1752        let worker = vec![b'x'; 200];
1753        let index = serde_json::to_vec(&serde_json::json!({
1754            "schema_version": 1,
1755            "assets": [{"path": "runtime/main.mjs", "size": worker.len(), "sha256": hash(&worker)}]
1756        }))
1757        .unwrap();
1758        let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new()));
1759        let stored = zip::write::SimpleFileOptions::default()
1760            .compression_method(zip::CompressionMethod::Stored);
1761        for (name, bytes) in [
1762            ("custom_runtime.dll", library.as_slice()),
1763            ("runtime-assets.json", index.as_slice()),
1764            ("runtime/main.mjs", worker.as_slice()),
1765        ] {
1766            writer.start_file(name, stored).unwrap();
1767            writer.write_all(bytes).unwrap();
1768        }
1769        let mut archive = writer.finish().unwrap().into_inner();
1770        // The headers now claim one byte for the sidecar that really holds 200.
1771        understate_entry(&mut archive, "runtime/main.mjs", 1);
1772
1773        // The walker sees a small entry, so only the read budget can stop the bytes.
1774        let exact = (library.len() + index.len() + worker.len()) as u64;
1775        let limits = ArchiveLimits {
1776            per_file: u64::MAX,
1777            total: exact - 1,
1778        };
1779        let error = extract_contents_with_limits(&archive, "zip", "custom_runtime.dll", limits)
1780            .err()
1781            .unwrap();
1782        assert!(
1783            error.contains("expanded archive exceeds size limit"),
1784            "{error}"
1785        );
1786
1787        let limits = ArchiveLimits {
1788            per_file: u64::MAX,
1789            total: exact,
1790        };
1791        let contents =
1792            extract_contents_with_limits(&archive, "zip", "custom_runtime.dll", limits).unwrap();
1793        assert_eq!(contents.assets[0].bytes, worker);
1794    }
1795
1796    #[test]
1797    fn runtime_asset_archives_reject_symlinked_files_and_node_modules_directories() {
1798        let library = object(TARGETS[0]);
1799        let worker = b"export {};\n";
1800        let index = serde_json::to_vec(&serde_json::json!({
1801            "schema_version": 1,
1802            "assets": [{"path": "runtime/main.mjs", "size": worker.len(), "sha256": hash(worker)}]
1803        }))
1804        .unwrap();
1805        let mut linked = zip::ZipWriter::new(Cursor::new(Vec::new()));
1806        linked
1807            .start_file(
1808                "custom_runtime.dll",
1809                zip::write::SimpleFileOptions::default(),
1810            )
1811            .unwrap();
1812        linked.write_all(&library).unwrap();
1813        linked
1814            .start_file(
1815                "runtime-assets.json",
1816                zip::write::SimpleFileOptions::default(),
1817            )
1818            .unwrap();
1819        linked.write_all(&index).unwrap();
1820        linked
1821            .add_symlink(
1822                "runtime/main.mjs",
1823                "/etc/passwd",
1824                zip::write::SimpleFileOptions::default(),
1825            )
1826            .unwrap();
1827        let archive = linked.finish().unwrap().into_inner();
1828        let Err(error) = extract_contents(&archive, "zip", "custom_runtime.dll") else {
1829            panic!("a symlinked sidecar was accepted");
1830        };
1831        assert!(error.contains("symlinks are not allowed"), "{error}");
1832
1833        let empty =
1834            serde_json::to_vec(&serde_json::json!({"schema_version": 1, "assets": []})).unwrap();
1835        let mut vendored = zip::ZipWriter::new(Cursor::new(Vec::new()));
1836        vendored
1837            .start_file(
1838                "custom_runtime.dll",
1839                zip::write::SimpleFileOptions::default(),
1840            )
1841            .unwrap();
1842        vendored.write_all(&library).unwrap();
1843        vendored
1844            .start_file(
1845                "runtime-assets.json",
1846                zip::write::SimpleFileOptions::default(),
1847            )
1848            .unwrap();
1849        vendored.write_all(&empty).unwrap();
1850        vendored
1851            .add_directory("node_modules/", zip::write::SimpleFileOptions::default())
1852            .unwrap();
1853        let archive = vendored.finish().unwrap().into_inner();
1854        let Err(error) = extract_contents(&archive, "zip", "custom_runtime.dll") else {
1855            panic!("a node_modules directory was accepted");
1856        };
1857        assert!(error.contains("node_modules"), "{error}");
1858    }
1859
1860    #[test]
1861    fn runtime_asset_digest_mismatch_keeps_the_installed_sidecars() {
1862        let target = TARGETS[1];
1863        let worker = b"export {};\n";
1864        let index = serde_json::to_vec(&serde_json::json!({
1865            "schema_version": 1,
1866            "assets": [{"path": "runtime/main.mjs", "size": worker.len(), "sha256": hash(worker)}]
1867        }))
1868        .unwrap();
1869        let (package, value, archive) = fixture_with_entries(
1870            target,
1871            &[
1872                ("runtime-assets.json", &index[..]),
1873                ("runtime/main.mjs", &worker[..]),
1874            ],
1875        );
1876        let manifest: Manifest = serde_json::from_value(value.clone()).unwrap();
1877        let agent = tempfile::tempdir().unwrap();
1878        install_archive_at(
1879            &package,
1880            &manifest,
1881            &serde_json::to_vec(&value).unwrap(),
1882            &archive,
1883            target,
1884            agent.path(),
1885            false,
1886        )
1887        .unwrap();
1888        let metadata = std::fs::read(agent.path().join("native-packages.json")).unwrap();
1889
1890        // The manifest and archive hashes are consistent. The sidecar keeps its size and changes its bytes.
1891        let tampered: &[u8] = b"export [];\n";
1892        assert_eq!(tampered.len(), worker.len());
1893        let (package, value, archive) = fixture_with_entries(
1894            target,
1895            &[
1896                ("runtime-assets.json", &index[..]),
1897                ("runtime/main.mjs", tampered),
1898            ],
1899        );
1900        let manifest: Manifest = serde_json::from_value(value.clone()).unwrap();
1901        let error = install_archive_at(
1902            &package,
1903            &manifest,
1904            &serde_json::to_vec(&value).unwrap(),
1905            &archive,
1906            target,
1907            agent.path(),
1908            true,
1909        )
1910        .unwrap_err();
1911        assert!(
1912            error.contains("asset runtime/main.mjs: SHA-256 mismatch"),
1913            "{error}"
1914        );
1915        let extensions = agent.path().join("extensions");
1916        assert_eq!(
1917            std::fs::read(extensions.join("runtime/main.mjs")).unwrap(),
1918            worker
1919        );
1920        assert_eq!(
1921            std::fs::read(agent.path().join("native-packages.json")).unwrap(),
1922            metadata
1923        );
1924    }
1925
1926    #[test]
1927    fn runtime_asset_tar_archives_reject_duplicate_index_and_declared_entries() {
1928        let library = object(TARGETS[1]);
1929        let worker = b"export {};\n";
1930        let index = serde_json::to_vec(&serde_json::json!({
1931            "schema_version": 1,
1932            "assets": [{"path": "runtime/main.mjs", "size": worker.len(), "sha256": hash(worker)}]
1933        }))
1934        .unwrap();
1935        let archive = tgz(&[
1936            ("libcustom_runtime.so", &library),
1937            ("runtime-assets.json", &index),
1938            ("runtime/main.mjs", worker),
1939            ("runtime/main.mjs", worker),
1940        ]);
1941        let Err(error) = extract_contents(&archive, "tar.gz", "libcustom_runtime.so") else {
1942            panic!("a duplicated sidecar was accepted");
1943        };
1944        assert!(error.contains("duplicate declared asset"), "{error}");
1945
1946        let archive = tgz(&[
1947            ("libcustom_runtime.so", &library),
1948            ("runtime-assets.json", &index),
1949            ("runtime-assets.json", &index),
1950        ]);
1951        let Err(error) = extract_contents(&archive, "tar.gz", "libcustom_runtime.so") else {
1952            panic!("a duplicated index was accepted");
1953        };
1954        assert!(error.contains("duplicate runtime-assets.json"), "{error}");
1955    }
1956
1957    #[test]
1958    fn legacy_archives_install_only_the_library_and_keep_their_records_unchanged() {
1959        for target in TARGETS {
1960            let (package, value, archive) =
1961                fixture_with_entries(target, &[("README.md", b"not a sidecar")]);
1962            let manifest: Manifest = serde_json::from_value(value.clone()).unwrap();
1963            let agent = tempfile::tempdir().unwrap();
1964            let paths = install_archive_at(
1965                &package,
1966                &manifest,
1967                &serde_json::to_vec(&value).unwrap(),
1968                &archive,
1969                target,
1970                agent.path(),
1971                false,
1972            )
1973            .unwrap();
1974            assert_eq!(paths.len(), 1);
1975            assert!(!agent.path().join("extensions/README.md").exists());
1976            let records: serde_json::Value = serde_json::from_slice(
1977                &std::fs::read(agent.path().join("native-packages.json")).unwrap(),
1978            )
1979            .unwrap();
1980            assert!(records[0]["prebuilt"].get("assets").is_none());
1981        }
1982    }
1983
1984    #[test]
1985    fn all_six_distributions_install_and_record_exact_provenance() {
1986        for target in TARGETS {
1987            let (package, value, archive) = fixture(target);
1988            let manifest: Manifest = serde_json::from_value(value.clone()).unwrap();
1989            let raw = serde_json::to_vec(&value).unwrap();
1990            let agent = tempfile::tempdir().unwrap();
1991            let paths = install_archive_at(
1992                &package,
1993                &manifest,
1994                &raw,
1995                &archive,
1996                target,
1997                agent.path(),
1998                false,
1999            )
2000            .unwrap();
2001            assert_eq!(paths.len(), 1);
2002            assert_eq!(std::fs::read(&paths[0]).unwrap(), object(target));
2003            let records: Vec<crate::install::InstalledNativePackage> = serde_json::from_slice(
2004                &std::fs::read(agent.path().join("native-packages.json")).unwrap(),
2005            )
2006            .unwrap();
2007            assert_eq!(records[0].name, "independent-plugin");
2008            assert_eq!(records[0].version, "1.2.3");
2009            assert_eq!(
2010                records[0].artifacts,
2011                [manifest.targets[target].library.path.clone()]
2012            );
2013            let origin = records[0].prebuilt.as_ref().unwrap();
2014            assert_eq!(origin.target, target);
2015            assert_eq!(origin.manifest_sha256, hash(&raw));
2016            assert_eq!(origin.repository, package.repository);
2017            assert_eq!(origin.archive_sha256, hash(&archive));
2018            assert_eq!(origin.library_sha256, hash(&object(target)));
2019        }
2020    }
2021
2022    #[test]
2023    fn prebuilt_packages_upgrade_without_force_and_same_version_is_unchanged() {
2024        for target in TARGETS {
2025            let (mut package, mut value, archive) = fixture(target);
2026            let manifest: Manifest = serde_json::from_value(value.clone()).unwrap();
2027            let agent = tempfile::tempdir().unwrap();
2028            install_archive_at(
2029                &package,
2030                &manifest,
2031                &serde_json::to_vec(&value).unwrap(),
2032                &archive,
2033                target,
2034                agent.path(),
2035                false,
2036            )
2037            .unwrap();
2038            package.version = "1.2.4".into();
2039            value["version"] = serde_json::json!(package.version);
2040            value["tag"] = serde_json::json!("independent-plugin-v1.2.4");
2041            let distribution = value.pointer_mut(&format!("/targets/{target}")).unwrap();
2042            let format = distribution["format"].as_str().unwrap();
2043            let file = if format == "zip" {
2044                "package.zip"
2045            } else {
2046                "package.tar.gz"
2047            };
2048            distribution["url"] = serde_json::json!(release_url(
2049                &package.repository,
2050                &package.name,
2051                &package.version,
2052                file,
2053            )
2054            .unwrap());
2055            let manifest = serde_json::from_value(value.clone()).unwrap();
2056            let raw = serde_json::to_vec(&value).unwrap();
2057            assert_eq!(
2058                install_archive_at(
2059                    &package,
2060                    &manifest,
2061                    &raw,
2062                    &archive,
2063                    target,
2064                    agent.path(),
2065                    false,
2066                )
2067                .unwrap()
2068                .len(),
2069                1
2070            );
2071            let metadata = agent.path().join("native-packages.json");
2072            let registry = std::fs::read(&metadata).unwrap();
2073            let records: Vec<crate::install::InstalledNativePackage> =
2074                serde_json::from_slice(&registry).unwrap();
2075            assert_eq!(records[0].version, "1.2.4");
2076            assert!(install_archive_at(
2077                &package,
2078                &manifest,
2079                &raw,
2080                &archive,
2081                target,
2082                agent.path(),
2083                false,
2084            )
2085            .unwrap()
2086            .is_empty());
2087            assert_eq!(std::fs::read(&metadata).unwrap(), registry);
2088        }
2089    }
2090
2091    #[test]
2092    fn bad_release_identity_hash_abi_and_target_leave_installed_version_intact() {
2093        let target = TARGETS[0];
2094        let (package, good, archive) = fixture(target);
2095        let manifest: Manifest = serde_json::from_value(good.clone()).unwrap();
2096        let agent = tempfile::tempdir().unwrap();
2097        let path = install_archive_at(
2098            &package,
2099            &manifest,
2100            &serde_json::to_vec(&good).unwrap(),
2101            &archive,
2102            target,
2103            agent.path(),
2104            false,
2105        )
2106        .unwrap()
2107        .remove(0);
2108        let original_record = std::fs::read(agent.path().join("native-packages.json")).unwrap();
2109        let mutations = [
2110            ("/schema_version",serde_json::json!(99)), ("/name",serde_json::json!("other-plugin")),
2111            ("/version",serde_json::json!("9.9.9")), ("/tag",serde_json::json!("v1.2.3")),
2112            ("/repository",serde_json::json!("https://github.com/other/repo")),
2113            ("/sdk/plugin_abi",serde_json::json!(99)),
2114            ("/targets/x86_64-pc-windows-msvc/sha256",serde_json::json!("0".repeat(64))),
2115            ("/targets/x86_64-pc-windows-msvc/library/sha256",serde_json::json!("0".repeat(64))),
2116            ("/targets/x86_64-pc-windows-msvc/library/path",serde_json::json!("../custom_runtime.dll")),
2117            ("/targets/x86_64-pc-windows-msvc/url",serde_json::json!("https://github.com/other/repo/releases/download/independent-plugin-v1.2.3/package.zip")),
2118            ("/targets/x86_64-pc-windows-msvc/size",serde_json::json!(archive.len()+1)),
2119        ];
2120        for (pointer, value) in mutations {
2121            let mut bad = good.clone();
2122            *bad.pointer_mut(pointer).unwrap() = value;
2123            let bad_manifest = serde_json::from_value(bad.clone()).unwrap();
2124            assert!(
2125                install_archive_at(
2126                    &package,
2127                    &bad_manifest,
2128                    &serde_json::to_vec(&bad).unwrap(),
2129                    &archive,
2130                    target,
2131                    agent.path(),
2132                    true
2133                )
2134                .is_err(),
2135                "{pointer}"
2136            );
2137            assert_eq!(std::fs::read(&path).unwrap(), object(target));
2138            assert_eq!(
2139                std::fs::read(agent.path().join("native-packages.json")).unwrap(),
2140                original_record
2141            );
2142        }
2143        assert!(install_archive_at(
2144            &package,
2145            &manifest,
2146            &[],
2147            &archive,
2148            TARGETS[1],
2149            agent.path(),
2150            true
2151        )
2152        .is_err());
2153    }
2154
2155    #[test]
2156    fn same_abi_but_wrong_binary_architecture_is_rejected_before_activation() {
2157        let (package, mut value, _) = fixture(TARGETS[0]);
2158        let wrong = object(TARGETS[2]);
2159        let archive = zip(&[("custom_runtime.dll", &wrong)]);
2160        let distribution = value
2161            .pointer_mut("/targets/x86_64-pc-windows-msvc")
2162            .unwrap();
2163        distribution["size"] = serde_json::json!(archive.len());
2164        distribution["sha256"] = serde_json::json!(hash(&archive));
2165        distribution["library"]["sha256"] = serde_json::json!(hash(&wrong));
2166        let manifest = serde_json::from_value(value).unwrap();
2167        let agent = tempfile::tempdir().unwrap();
2168        assert!(install_archive_at(
2169            &package,
2170            &manifest,
2171            &[],
2172            &archive,
2173            TARGETS[0],
2174            agent.path(),
2175            false
2176        )
2177        .unwrap_err()
2178        .contains("shared library"));
2179        assert!(!agent.path().join("native-packages.json").exists());
2180        assert!(!agent.path().join("extensions").exists());
2181    }
2182
2183    #[test]
2184    fn archives_cannot_traverse_retain_links_or_substitute_another_library() {
2185        let library = object(TARGETS[0]);
2186        assert!(
2187            extract_library(&zip(&[("../escape.dll", &library)]), "zip", "escape.dll").is_err()
2188        );
2189        assert!(
2190            extract_library(&zip(&[("C:\\escape.dll", &library)]), "zip", "escape.dll").is_err()
2191        );
2192        assert!(extract_library(&zip(&[("other.dll", &library)]), "zip", "declared.dll").is_err());
2193        let mut linked = zip::ZipWriter::new(Cursor::new(Vec::new()));
2194        linked
2195            .add_symlink(
2196                "declared.dll",
2197                "outside.dll",
2198                zip::write::SimpleFileOptions::default(),
2199            )
2200            .unwrap();
2201        assert!(extract_library(
2202            &linked.finish().unwrap().into_inner(),
2203            "zip",
2204            "declared.dll"
2205        )
2206        .is_err());
2207        let mut tar = tar::Builder::new(flate2::write::GzEncoder::new(
2208            Vec::new(),
2209            flate2::Compression::default(),
2210        ));
2211        let mut header = tar::Header::new_gnu();
2212        header.set_entry_type(tar::EntryType::Link);
2213        header.set_size(0);
2214        header.set_mode(0o644);
2215        header.set_cksum();
2216        tar.append_link(&mut header, "declared.so", "outside.so")
2217            .unwrap();
2218        assert!(extract_library(
2219            &tar.into_inner().unwrap().finish().unwrap(),
2220            "tar.gz",
2221            "declared.so"
2222        )
2223        .is_err());
2224    }
2225
2226    #[test]
2227    fn object_headers_cannot_cross_platform_or_architecture() {
2228        for target in TARGETS {
2229            assert!(validate_library_target(&object(target), target).is_ok());
2230            for other in TARGETS {
2231                if other != target {
2232                    // ELF headers do not encode the libc choice, so GNU and
2233                    // musl x86_64 objects are intentionally indistinguishable
2234                    // to this architecture check. Exact target manifests still
2235                    // keep those distributions separate.
2236                    if target.starts_with("x86_64-unknown-linux-")
2237                        && other.starts_with("x86_64-unknown-linux-")
2238                    {
2239                        continue;
2240                    }
2241                    assert!(validate_library_target(&object(other), target).is_err());
2242                }
2243            }
2244        }
2245        assert!(validate_library_target(&[0u8; 8], TARGETS[0]).is_err());
2246        let mut damaged = object(TARGETS[0]);
2247        damaged[0x3c..0x40].copy_from_slice(&u32::MAX.to_le_bytes());
2248        assert!(validate_library_target(&damaged, TARGETS[0]).is_err());
2249    }
2250
2251    #[test]
2252    fn exact_versions_ignore_yanked_and_prerelease_latest() {
2253        let versions = [
2254            RegistryVersion {
2255                num: "1.0.0".into(),
2256                yanked: false,
2257            },
2258            RegistryVersion {
2259                num: "9.0.0".into(),
2260                yanked: true,
2261            },
2262            RegistryVersion {
2263                num: "2.0.0-beta.1".into(),
2264                yanked: false,
2265            },
2266        ];
2267        assert_eq!(select_version(&versions, None).unwrap(), "1.0.0");
2268        assert_eq!(
2269            select_version(&versions, Some("2.0.0-beta.1")).unwrap(),
2270            "2.0.0-beta.1"
2271        );
2272        assert!(select_version(&versions, Some("9.0.0")).is_err());
2273        assert!(select_version(&versions, Some("^1")).is_err());
2274    }
2275
2276    #[test]
2277    fn github_case_and_encoded_semver_build_metadata_preserve_release_identity() {
2278        let (mut package, mut value, _) = fixture(TARGETS[0]);
2279        package.version = "1.2.3+build.1".into();
2280        value["version"] = serde_json::json!(package.version);
2281        value["tag"] = serde_json::json!("independent-plugin-v1.2.3+build.1");
2282        value["repository"] = serde_json::json!("https://github.com/Publisher/MonoRepo");
2283        value["targets"][TARGETS[0]]["url"] = serde_json::json!("https://github.com/Publisher/MonoRepo/releases/download/independent-plugin-v1.2.3%2Bbuild.1/package.zip");
2284        let manifest = serde_json::from_value(value).unwrap();
2285        assert!(validate_manifest(&manifest, &package, TARGETS[0]).is_ok());
2286        assert_eq!(
2287            canonical_repository("Publisher/MonoRepo").unwrap(),
2288            package.repository
2289        );
2290    }
2291
2292    #[test]
2293    fn repository_urls_are_explicit_and_release_tags_use_package_versions() {
2294        assert_eq!(
2295            canonical_repository("git+https://github.com/publisher/monorepo.git").unwrap(),
2296            "https://github.com/publisher/monorepo"
2297        );
2298        assert_eq!(
2299            canonical_repository("https://github.com/publisher/monorepo/tree/main/packages/plugin")
2300                .unwrap(),
2301            "https://github.com/publisher/monorepo"
2302        );
2303        for invalid in [
2304            "https://gitlab.com/x/y",
2305            "https://user@github.com/x/y",
2306            "https://github.com/x",
2307            "https://github.com/x/y/releases/latest",
2308            "https://github.com:8443/x/y",
2309        ] {
2310            assert!(canonical_repository(invalid).is_err());
2311        }
2312        assert_eq!(release_url("https://github.com/publisher/monorepo","plugin-one","1.2.3","rpi-extension.json").unwrap(),"https://github.com/publisher/monorepo/releases/download/plugin-one-v1.2.3/rpi-extension.json");
2313        assert!(release_url(
2314            "https://github.com/publisher/monorepo",
2315            "plugin-two",
2316            "4.5.6",
2317            "rpi-extension.json"
2318        )
2319        .unwrap()
2320        .contains("plugin-two-v4.5.6"));
2321    }
2322
2323    fn one_response(body: Vec<u8>) -> (String, std::thread::JoinHandle<String>) {
2324        response_with_status("200 OK", body)
2325    }
2326
2327    fn response_with_status(
2328        status: &'static str,
2329        body: Vec<u8>,
2330    ) -> (String, std::thread::JoinHandle<String>) {
2331        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2332        let url = format!("http://{}", listener.local_addr().unwrap());
2333        let thread = std::thread::spawn(move || {
2334            let (mut socket, _) = listener.accept().unwrap();
2335            socket
2336                .set_read_timeout(Some(std::time::Duration::from_secs(5)))
2337                .unwrap();
2338            let mut request = Vec::new();
2339            let mut byte = [0];
2340            while !request.ends_with(b"\r\n\r\n") {
2341                socket.read_exact(&mut byte).unwrap();
2342                request.push(byte[0]);
2343            }
2344            write!(
2345                socket,
2346                "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
2347                body.len()
2348            )
2349            .unwrap();
2350            socket.write_all(&body).unwrap();
2351            String::from_utf8(request).unwrap()
2352        });
2353        (url, thread)
2354    }
2355
2356    #[tokio::test]
2357    async fn downloaded_manifest_and_archive_install_into_an_isolated_profile() {
2358        let target = host_target().unwrap();
2359        let (package, value, archive) = fixture(target);
2360        let raw = serde_json::to_vec(&value).unwrap();
2361        let client = reqwest::Client::builder().no_proxy().build().unwrap();
2362        let (url, server) = one_response(raw.clone());
2363        let response = client.get(url).send().await.unwrap();
2364        let (manifest, received) = read_manifest_response(response, &package).await.unwrap();
2365        server.join().unwrap();
2366        assert_eq!(received, raw);
2367        let distribution = validate_manifest(&manifest, &package, target).unwrap();
2368        let (url, server) = one_response(archive);
2369        let response = client.get(url).send().await.unwrap();
2370        let downloaded = body_limited(response, distribution.size).await.unwrap();
2371        server.join().unwrap();
2372        let profile = tempfile::tempdir().unwrap();
2373        let paths = install_archive_at(
2374            &package,
2375            &manifest,
2376            &received,
2377            &downloaded,
2378            target,
2379            profile.path(),
2380            false,
2381        )
2382        .unwrap();
2383        assert_eq!(std::fs::read(&paths[0]).unwrap(), object(target));
2384        assert!(profile.path().join("native-packages.json").is_file());
2385    }
2386
2387    #[tokio::test]
2388    async fn missing_invalid_and_oversized_manifests_fail_before_installation() {
2389        let (package, _, _) = fixture(TARGETS[0]);
2390        let client = reqwest::Client::builder().no_proxy().build().unwrap();
2391        for (status, body, expected) in [
2392            (
2393                "404 Not Found",
2394                b"missing".to_vec(),
2395                "rpi-extension.json is missing",
2396            ),
2397            ("403 Forbidden", b"denied".to_vec(), "403 Forbidden"),
2398            ("200 OK", b"not json".to_vec(), "invalid rpi-extension.json"),
2399            (
2400                "200 OK",
2401                vec![b' '; MAX_MANIFEST as usize + 1],
2402                "size limit",
2403            ),
2404        ] {
2405            let (url, server) = response_with_status(status, body);
2406            let response = client.get(url).send().await.unwrap();
2407            let error = read_manifest_response(response, &package)
2408                .await
2409                .err()
2410                .unwrap();
2411            assert!(error.contains(expected), "{error}");
2412            server.join().unwrap();
2413        }
2414    }
2415
2416    #[tokio::test]
2417    async fn explicit_repository_and_version_do_not_require_a_registry_record() {
2418        let client = reqwest::Client::new();
2419        let resolved = resolve_package(
2420            &client,
2421            "http://127.0.0.1:1",
2422            "private-extension",
2423            Some("2.3.4"),
2424            Some("https://github.com/custom-owner/custom-repo.git"),
2425        )
2426        .await
2427        .unwrap();
2428        assert_eq!(
2429            resolved.repository,
2430            "https://github.com/custom-owner/custom-repo"
2431        );
2432        assert_eq!(resolved.name, "private-extension");
2433        assert_eq!(resolved.version, "2.3.4");
2434        assert!(release_url(
2435            &resolved.repository,
2436            &resolved.name,
2437            &resolved.version,
2438            "rpi-extension.json"
2439        )
2440        .unwrap()
2441        .contains("custom-repo/releases/download/private-extension-v2.3.4/"));
2442    }
2443
2444    #[tokio::test]
2445    async fn custom_repository_versions_are_scoped_to_the_package() {
2446        let refs = serde_json::to_vec(&serde_json::json!([
2447            {"ref":"refs/tags/independent-plugin-v1.2.3"},
2448            {"ref":"refs/tags/independent-plugin-v1.4.0"},
2449            {"ref":"refs/tags/other-plugin-v99.0.0"},
2450            {"ref":"refs/tags/independent-plugin-v2.0.0-beta.1"}
2451        ]))
2452        .unwrap();
2453        let (api, server) = one_response(refs);
2454        let client = reqwest::Client::builder().no_proxy().build().unwrap();
2455        assert_eq!(
2456            repository_version(
2457                &client,
2458                &api,
2459                "independent-plugin",
2460                "https://github.com/publisher/monorepo"
2461            )
2462            .await
2463            .unwrap(),
2464            "1.4.0"
2465        );
2466        assert!(server.join().unwrap().starts_with(
2467            "GET /repos/publisher/monorepo/git/matching-refs/tags/independent-plugin-v "
2468        ));
2469    }
2470
2471    #[tokio::test]
2472    async fn registry_discovery_uses_repository_metadata_and_downloads_are_bounded() {
2473        let payload = serde_json::to_vec(&serde_json::json!({"crate":{"id":"independent-plugin","repository":"https://github.com/publisher/monorepo.git"},"versions":[{"num":"1.2.3","yanked":false},{"num":"3.0.0-beta.1","yanked":false},{"num":"9.0.0","yanked":true}]})).unwrap();
2474        let (url, server) = one_response(payload);
2475        let client = reqwest::Client::builder().no_proxy().build().unwrap();
2476        let package = resolve_package(&client, &url, "independent-plugin", None, None)
2477            .await
2478            .unwrap();
2479        assert_eq!(package.repository, "https://github.com/publisher/monorepo");
2480        assert_eq!(package.version, "1.2.3");
2481        assert!(server
2482            .join()
2483            .unwrap()
2484            .starts_with("GET /independent-plugin "));
2485        let (url, server) = one_response(vec![0u8; 32]);
2486        let response = client.get(url).send().await.unwrap();
2487        assert!(body_limited(response, 8).await.is_err());
2488        server.join().unwrap();
2489    }
2490}