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)]
153pub(crate) struct GitReference {
154    #[serde(rename = "ref")]
155    reference: String,
156}
157
158pub(crate) fn best_tag_version(refs: &[GitReference], name: &str) -> Option<semver::Version> {
159    let prefix = format!("refs/tags/{name}-v");
160    refs.iter()
161        .filter_map(|reference| reference.reference.strip_prefix(&prefix))
162        .filter_map(|version| semver::Version::parse(version).ok())
163        .filter(|version| version.pre.is_empty())
164        .max()
165}
166
167pub(crate) fn tag_published(refs: &[GitReference], name: &str, version: &str) -> bool {
168    let expected = format!("refs/tags/{name}-v{version}");
169    refs.iter().any(|reference| reference.reference == expected)
170}
171
172pub(crate) async fn repository_tags(
173    client: &reqwest::Client,
174    api: &str,
175    name: &str,
176    repository: &str,
177) -> Result<Vec<GitReference>, String> {
178    let repo = repository
179        .strip_prefix("https://github.com/")
180        .ok_or("invalid GitHub repository")?;
181    let url = format!("{api}/repos/{repo}/git/matching-refs/tags/{name}-v");
182    let response = crate::install_http::send(|| {
183        client
184            .get(&url)
185            .header(reqwest::header::ACCEPT, "application/vnd.github+json")
186    })
187    .await
188    .map_err(|error| format!("GitHub tag lookup for {repo}/{name}: {error}"))?;
189    if !response.status().is_success() {
190        return Err(format!("GitHub tag lookup returned {}", response.status()));
191    }
192    serde_json::from_slice(&body_limited(response, MAX_METADATA).await?)
193        .map_err(|e| format!("invalid GitHub tag metadata: {e}"))
194}
195
196/// Highest stable release across the requested repository and, after a
197/// repository move, its current home. The winning repository is returned with
198/// the version because its release assets are the ones that must be verified
199/// and recorded; this is what migrates an installed extension to the new
200/// location instead of freezing it on the old, no-longer-published tags.
201async fn repository_version(
202    client: &reqwest::Client,
203    api: &str,
204    name: &str,
205    repository: &str,
206) -> Result<(String, String), String> {
207    let requested = canonical_repository(repository)?;
208    let current = moved_repository(&requested).to_string();
209    let mut candidates = vec![requested.clone()];
210    if current != requested {
211        candidates.push(current);
212    }
213    let mut best: Option<(semver::Version, String)> = None;
214    let mut failure = None;
215    for candidate in candidates {
216        match repository_tags(client, api, name, &candidate).await {
217            Ok(refs) => {
218                let Some(version) = best_tag_version(&refs, name) else {
219                    continue;
220                };
221                // Ties prefer the later candidate, which is the current home
222                // of a moved repository: a release that both locations still
223                // publish records the new location instead of pinning the
224                // install to the previous one.
225                if best.as_ref().is_none_or(|(best, _)| version >= *best) {
226                    best = Some((version, candidate));
227                }
228            }
229            Err(error) => failure = failure.or(Some(error)),
230        }
231    }
232    match best {
233        Some((version, repository)) => Ok((version.to_string(), repository)),
234        None => Err(match failure {
235            Some(error) => format!("{}: {error}", short_repository(&requested)),
236            None => format!(
237                "no stable {name}-v<version> tag exists in this repository; specify --version explicitly"
238            ),
239        }),
240    }
241}
242
243/// Supported triples are deliberately exact: GNU/musl and MSVC/GNU are
244/// different native-library distributions.
245pub fn host_target() -> Result<&'static str, String> {
246    match (std::env::consts::OS, std::env::consts::ARCH) {
247        ("windows", "x86_64") if cfg!(target_env = "msvc") => Ok("x86_64-pc-windows-msvc"),
248        ("linux", "x86_64") if cfg!(target_env = "gnu") => Ok("x86_64-unknown-linux-gnu"),
249        ("linux", "x86_64") if cfg!(target_env = "musl") => Ok("x86_64-unknown-linux-musl"),
250        ("linux", "aarch64") if cfg!(target_env = "gnu") => Ok("aarch64-unknown-linux-gnu"),
251        ("macos", "x86_64") => Ok("x86_64-apple-darwin"),
252        ("macos", "aarch64") => Ok("aarch64-apple-darwin"),
253        _ => Err(
254            "no supported prebuilt target for this host; use --build to compile explicitly".into(),
255        ),
256    }
257}
258
259fn valid_segment(value: &str) -> bool {
260    !value.is_empty()
261        && !matches!(value, "." | "..")
262        && value
263            .bytes()
264            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
265}
266
267/// Accept an explicit owner/repo override or repository metadata URLs,
268/// including Cargo's common .git / git+https forms and GitHub tree subpaths.
269pub(crate) fn canonical_repository(value: &str) -> Result<String, String> {
270    let value = value.trim().strip_prefix("git+").unwrap_or(value.trim());
271    let value = if value.contains("://") {
272        value.to_string()
273    } else {
274        format!("https://github.com/{value}")
275    };
276    let url = reqwest::Url::parse(&value).map_err(|_| "invalid GitHub repository".to_string())?;
277    if url.scheme() != "https"
278        || url.host_str() != Some("github.com")
279        || !url.username().is_empty()
280        || url.password().is_some()
281        || url.port().is_some()
282    {
283        return Err("prebuilt repository must be an HTTPS GitHub repository; use --build for other repositories".into());
284    }
285    let segments: Vec<_> = url
286        .path_segments()
287        .ok_or("invalid GitHub repository path")?
288        .collect();
289    if segments.len() < 2 || !valid_segment(segments[0]) {
290        return Err("repository must identify a GitHub owner and repository".into());
291    }
292    let repo = segments[1].strip_suffix(".git").unwrap_or(segments[1]);
293    if !valid_segment(repo) {
294        return Err("invalid GitHub repository name".into());
295    }
296    if segments.len() > 2
297        && !segments[2..].iter().all(|s| s.is_empty())
298        && !matches!(segments[2], "tree" | "blob")
299    {
300        return Err("unsupported GitHub repository URL path".into());
301    }
302    Ok(format!(
303        "https://github.com/{}/{}",
304        segments[0].to_ascii_lowercase(),
305        repo.to_ascii_lowercase()
306    ))
307}
308
309/// Repositories that moved to a new home, as `(previous, current)` canonical
310/// URLs. The previous location keeps serving the releases and CDN objects it
311/// already published, so pinned versions and already-installed extensions keep
312/// working; version discovery, upgrade detection and new releases follow the
313/// move.
314const MOVED_REPOSITORIES: &[(&str, &str)] = &[(
315    "https://github.com/pi-rust/rpi-package",
316    "https://github.com/pi-rust/rpi-extension",
317)];
318
319/// The current home of a moved repository, else `repository` unchanged.
320///
321/// Callers pass canonical URLs (see [`canonical_repository`]).
322fn moved_repository(repository: &str) -> &str {
323    MOVED_REPOSITORIES
324        .iter()
325        .find(|(previous, _)| *previous == repository)
326        .map(|(_, current)| *current)
327        .unwrap_or(repository)
328}
329
330/// Whether two canonical repository URLs identify the same extension project,
331/// including the previous and current spelling of a moved repository.
332///
333/// Provenance records written before a move must not be treated as a different
334/// publisher: that would both hide updates and refuse to install them.
335pub(crate) fn same_repository_project(one: &str, other: &str) -> bool {
336    moved_repository(one) == moved_repository(other)
337}
338
339pub(crate) fn short_repository(repository: &str) -> &str {
340    repository
341        .strip_prefix("https://github.com/")
342        .unwrap_or(repository)
343}
344
345fn release_url(repository: &str, name: &str, version: &str, file: &str) -> Result<String, String> {
346    let mut url = reqwest::Url::parse(repository).map_err(|e| e.to_string())?;
347    url.path_segments_mut()
348        .map_err(|_| "invalid release repository")?
349        .push("releases")
350        .push("download")
351        .push(&format!("{name}-v{version}"))
352        .push(file);
353    Ok(url.into())
354}
355
356fn select_version(versions: &[RegistryVersion], requested: Option<&str>) -> Result<String, String> {
357    let requested = requested
358        .map(semver::Version::parse)
359        .transpose()
360        .map_err(|_| "--version requires an exact semantic version")?;
361    available_version(versions, requested.as_ref()).ok_or_else(|| match requested {
362        Some(version) => format!("version {version} is absent or yanked on crates.io"),
363        None => "no non-yanked stable version is available".into(),
364    })
365}
366
367fn available_version(
368    versions: &[RegistryVersion],
369    requested: Option<&semver::Version>,
370) -> Option<String> {
371    if let Some(requested) = requested {
372        let requested = requested.to_string();
373        return versions
374            .iter()
375            .any(|version| !version.yanked && version.num == requested)
376            .then_some(requested);
377    }
378    versions
379        .iter()
380        .filter(|version| !version.yanked)
381        .filter_map(|version| semver::Version::parse(&version.num).ok())
382        .filter(|version| version.pre.is_empty())
383        .max()
384        .map(|version| version.to_string())
385}
386
387pub(crate) async fn body_limited(
388    response: reqwest::Response,
389    limit: u64,
390) -> Result<Vec<u8>, String> {
391    crate::install_http::read_limited_body(response, limit)
392        .await
393        .map_err(|error| error.to_string())
394}
395
396async fn resolve_package(
397    client: &reqwest::Client,
398    api: &str,
399    name: &str,
400    version: Option<&str>,
401    repository: Option<&str>,
402) -> Result<ResolvedPackage, String> {
403    // An explicit repository + version also supports unpublished third-party extensions.
404    if let Some(repository) = repository {
405        let repository = canonical_repository(repository)?;
406        let (version, repository) = match version {
407            Some(version) => {
408                let version = semver::Version::parse(version)
409                    .map_err(|_| "--version requires an exact semantic version".to_string())?
410                    .to_string();
411                // A pinned version also follows a repository move when the
412                // current home publishes it; otherwise the previous location,
413                // which still hosts that release, keeps serving it.
414                let repository = follow_repository_move(
415                    client,
416                    "https://api.github.com",
417                    repository,
418                    name,
419                    &version,
420                )
421                .await;
422                (version, repository)
423            }
424            None => repository_version(client, "https://api.github.com", name, &repository).await?,
425        };
426        return Ok(ResolvedPackage {
427            name: name.into(),
428            version,
429            repository,
430            custom_repository: true,
431        });
432    }
433    let data = registry_package(client, api, name)
434        .await?
435        .ok_or_else(|| format!("crates.io lookup for {name} returned 404 Not Found"))?;
436    let version = select_version(&data.versions, version)?;
437    let mut package = registry_release(data, version)?;
438    package.repository = follow_repository_move(
439        client,
440        "https://api.github.com",
441        package.repository,
442        &package.name,
443        &package.version,
444    )
445    .await;
446    Ok(package)
447}
448
449async fn registry_package(
450    client: &reqwest::Client,
451    api: &str,
452    name: &str,
453) -> Result<Option<RegistryPackage>, String> {
454    let url = format!("{api}/{name}");
455    let response = crate::install_http::send(|| client.get(&url))
456        .await
457        .map_err(|error| format!("crates.io lookup for {name}: {error}"))?;
458    if response.status() == reqwest::StatusCode::NOT_FOUND {
459        return Ok(None);
460    }
461    if !response.status().is_success() {
462        return Err(format!(
463            "crates.io lookup for {name} returned {}",
464            response.status()
465        ));
466    }
467    let data: RegistryPackage =
468        serde_json::from_slice(&body_limited(response, MAX_METADATA).await?)
469            .map_err(|e| format!("invalid crates.io metadata: {e}"))?;
470    if !data
471        .metadata
472        .id
473        .replace('-', "_")
474        .eq_ignore_ascii_case(&name.replace('-', "_"))
475    {
476        return Err("crates.io metadata identifies a different package".into());
477    }
478    Ok(Some(data))
479}
480
481fn registry_release(data: RegistryPackage, version: String) -> Result<ResolvedPackage, String> {
482    let repository = data
483        .metadata
484        .repository
485        .as_deref()
486        .ok_or("crate has no repository metadata; use --github owner/repo or --build")?;
487    Ok(ResolvedPackage {
488        name: data.metadata.id,
489        version,
490        repository: canonical_repository(repository)?,
491        custom_repository: false,
492    })
493}
494
495/// Prefer a moved repository's current home for a version it actually
496/// publishes. Published or pinned versions that only exist in the previous
497/// location keep resolving there, so a stale crates.io `repository` field never
498/// makes an install fail and never loses an existing release.
499async fn follow_repository_move(
500    client: &reqwest::Client,
501    api: &str,
502    repository: String,
503    name: &str,
504    version: &str,
505) -> String {
506    let current = moved_repository(&repository).to_string();
507    if current == repository {
508        return repository;
509    }
510    let Ok(url) = release_url(&current, name, version, "rpi-extension.json") else {
511        return repository;
512    };
513    match client.head(url).send().await {
514        Ok(response) if response.status().is_success() => current,
515        Ok(_) => repository,
516        // The release host can be unreachable while the GitHub API still
517        // answers (proxies and restricted networks), so fall back to the tag
518        // list instead of assuming the previous location still publishes.
519        Err(_) => match repository_tags(client, api, name, &current).await {
520            Ok(refs) if tag_published(&refs, name, version) => current,
521            _ => repository,
522        },
523    }
524}
525
526pub(crate) fn hash(bytes: &[u8]) -> String {
527    format!("{:x}", Sha256::digest(bytes))
528}
529
530pub(crate) fn check_hash(bytes: &[u8], expected: &str) -> Result<(), String> {
531    if expected.len() != 64
532        || !expected
533            .bytes()
534            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
535    {
536        return Err("manifest SHA-256 must be 64 lowercase hexadecimal characters".into());
537    }
538    if hash(bytes) != expected {
539        return Err("SHA-256 mismatch".into());
540    }
541    Ok(())
542}
543
544fn validate_manifest<'a>(
545    manifest: &'a Manifest,
546    package: &ResolvedPackage,
547    target: &str,
548) -> Result<&'a Distribution, String> {
549    if manifest.schema_version != 1 {
550        return Err(format!(
551            "unsupported prebuilt manifest schema {}",
552            manifest.schema_version
553        ));
554    }
555    if manifest.name != package.name
556        || manifest.version != package.version
557        || manifest.tag != format!("{}-v{}", package.name, package.version)
558        || !same_repository_project(
559            &canonical_repository(&manifest.repository)?,
560            &package.repository,
561        )
562    {
563        return Err("prebuilt manifest package, version, repository or tag does not match the requested package".into());
564    }
565    if manifest.source_commit.len() != 40
566        || !manifest
567            .source_commit
568            .bytes()
569            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
570    {
571        return Err("manifest source_commit must be a full Git commit SHA".into());
572    }
573    semver::Version::parse(&manifest.sdk.version).map_err(|_| "invalid SDK version in manifest")?;
574    if manifest.sdk.plugin_abi != rpi_plugin_sdk::RPI_PLUGIN_ABI_VERSION_UNIFIED {
575        return Err(format!(
576            "extension SDK ABI {} is incompatible with host ABI {}",
577            manifest.sdk.plugin_abi,
578            rpi_plugin_sdk::RPI_PLUGIN_ABI_VERSION_UNIFIED
579        ));
580    }
581    let distribution = manifest.targets.get(target).ok_or_else(|| {
582        format!(
583            "no prebuilt extension for exact target {target}; use --build to compile explicitly"
584        )
585    })?;
586    if distribution.size == 0
587        || distribution.size > MAX_ARCHIVE
588        || !matches!(distribution.format.as_str(), "zip" | "tar.gz")
589    {
590        return Err("unsupported archive format or size in manifest".into());
591    }
592    let name = &distribution.library.path;
593    let extension = if target.contains("windows") {
594        ".dll"
595    } else if target.contains("apple") {
596        ".dylib"
597    } else {
598        ".so"
599    };
600    if name.is_empty()
601        || !name.ends_with(extension)
602        || name.contains(['/', '\\', ':'])
603        || !name
604            .bytes()
605            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
606        || matches!(name.as_str(), "." | "..")
607    {
608        return Err(
609            "manifest library.path must be a flat library filename for the selected target".into(),
610        );
611    }
612    for expected in [&distribution.sha256, &distribution.library.sha256] {
613        if expected.len() != 64
614            || !expected
615                .bytes()
616                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
617        {
618            return Err("invalid SHA-256 in manifest".into());
619        }
620    }
621    validate_release_asset_url(&distribution.url, &package.repository, &manifest.tag)?;
622    Ok(distribution)
623}
624
625pub(crate) fn validate_release_asset_url(
626    value: &str,
627    repository: &str,
628    tag: &str,
629) -> Result<(), String> {
630    let url = reqwest::Url::parse(value).map_err(|_| "invalid archive URL")?;
631    let segments: Vec<String> = url
632        .path_segments()
633        .ok_or("archive URL has no path")?
634        .map(|s| {
635            percent_encoding::percent_decode_str(s)
636                .decode_utf8()
637                .map(|s| s.into_owned())
638                .map_err(|_| "invalid encoded archive URL")
639        })
640        .collect::<Result<_, _>>()?;
641    if url.scheme() != "https"
642        || url.host_str() != Some("github.com")
643        || url.port().is_some()
644        || !url.username().is_empty()
645        || url.password().is_some()
646        || url.query().is_some()
647        || url.fragment().is_some()
648        || segments.len() != 6
649        || segments[2] != "releases"
650        || segments[3] != "download"
651        || segments[4] != tag
652        || !same_repository_project(
653            &canonical_repository(&format!(
654                "https://github.com/{}/{}",
655                segments[0], segments[1]
656            ))?,
657            repository,
658        )
659        || segments[5].is_empty()
660        || matches!(segments[5].as_str(), "." | "..")
661        || !segments[5]
662            .bytes()
663            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'+'))
664    {
665        return Err(
666            "archive URL must belong to the same GitHub repository and package Release".into(),
667        );
668    }
669    Ok(())
670}
671
672async fn fetch_manifest(
673    client: &reqwest::Client,
674    package: &ResolvedPackage,
675) -> Result<(Manifest, Vec<u8>), String> {
676    read_manifest_response(request_manifest(client, package).await?, package).await
677}
678
679async fn request_manifest(
680    client: &reqwest::Client,
681    package: &ResolvedPackage,
682) -> Result<reqwest::Response, String> {
683    let url = release_url(
684        &package.repository,
685        &package.name,
686        &package.version,
687        "rpi-extension.json",
688    )?;
689    crate::install_http::send(|| client.get(&url))
690        .await
691        .map_err(|error| {
692            format!(
693                "prebuilt manifest at {url}: {error}; retry later or use --build to build with Cargo"
694            )
695        })
696}
697
698async fn read_manifest_response(
699    response: reqwest::Response,
700    package: &ResolvedPackage,
701) -> Result<(Manifest, Vec<u8>), String> {
702    if response.status() == reqwest::StatusCode::NOT_FOUND {
703        return Err(format!("prebuilt release for {} {} is not ready (rpi-extension.json is missing); retry later or use --build explicitly", package.name, package.version));
704    }
705    if !response.status().is_success() {
706        return Err(format!(
707            "prebuilt manifest for {} {} in {} returned {}; use --build to build with Cargo",
708            package.name,
709            package.version,
710            package.repository,
711            response.status()
712        ));
713    }
714    let bytes = body_limited(response, MAX_MANIFEST).await?;
715    let manifest =
716        serde_json::from_slice(&bytes).map_err(|e| format!("invalid rpi-extension.json: {e}"))?;
717    Ok((manifest, bytes))
718}
719
720/// Only advertise an update when its exact platform manifest is available and compatible.
721pub async fn latest_compatible_version(
722    client: &reqwest::Client,
723    package: &crate::install::InstalledNativePackage,
724) -> Result<Option<String>, String> {
725    let Some(record) = &package.prebuilt else {
726        return Ok(None);
727    };
728    let repository = record
729        .custom_repository
730        .then_some(record.repository.as_str());
731    let resolved = resolve_package(client, CRATES_API, &package.name, None, repository).await?;
732    if !same_repository_project(&resolved.repository, &record.repository) {
733        return Err(
734            "extension repository changed; reinstall explicitly to select a new publisher".into(),
735        );
736    }
737    if !crate::updates::is_newer(&package.version, &resolved.version) {
738        return Ok(Some(resolved.version));
739    }
740    let (manifest, _) = fetch_manifest(client, &resolved).await?;
741    validate_manifest(&manifest, &resolved, host_target()?)?;
742    Ok(Some(resolved.version))
743}
744
745pub(crate) struct PublishedExtension {
746    package: ResolvedPackage,
747    manifest: Manifest,
748    bytes: Vec<u8>,
749}
750
751pub(crate) async fn probe_install(
752    name: &str,
753    version: Option<&semver::Version>,
754) -> Result<Option<PublishedExtension>, String> {
755    let client = install_client()?;
756    let records = crate::install::installed_native_packages_strict()?;
757    if let Some(repository) = custom_repository(&records, name) {
758        let version = version.map(ToString::to_string);
759        let package = resolve_package(
760            &client,
761            CRATES_API,
762            name,
763            version.as_deref(),
764            Some(repository),
765        )
766        .await?;
767        let (manifest, bytes) = fetch_manifest(&client, &package).await?;
768        validate_manifest(&manifest, &package, host_target()?)?;
769        return Ok(Some(PublishedExtension {
770            package,
771            manifest,
772            bytes,
773        }));
774    }
775    probe_registry_install(&client, CRATES_API, name, version).await
776}
777
778async fn probe_registry_install(
779    client: &reqwest::Client,
780    api: &str,
781    name: &str,
782    version: Option<&semver::Version>,
783) -> Result<Option<PublishedExtension>, String> {
784    let Some(data) = registry_package(client, api, name).await? else {
785        return Ok(None);
786    };
787    let Some(version) = available_version(&data.versions, version) else {
788        return Ok(None);
789    };
790    // Crates.io also indexes ordinary crates. Without a supported repository
791    // there is no prebuilt release to look up for automatic installation.
792    let Ok(mut package) = registry_release(data, version) else {
793        return Ok(None);
794    };
795    let previous = package.repository.clone();
796    package.repository = moved_repository(&previous).into();
797    let mut response = request_manifest(client, &package).await?;
798    if response.status() == reqwest::StatusCode::NOT_FOUND && package.repository != previous {
799        let current = std::mem::replace(&mut package.repository, previous.clone());
800        response = request_manifest(client, &package).await?;
801        if response.status() == reqwest::StatusCode::NOT_FOUND
802            && has_release_tag(client, &package, &current).await?
803        {
804            return Err(format!(
805                "rpi-extension.json is missing for {} {} in {current}",
806                package.name, package.version
807            ));
808        }
809    }
810    if response.status() == reqwest::StatusCode::NOT_FOUND
811        && !has_release_tag(client, &package, &previous).await?
812    {
813        return Ok(None);
814    }
815    let (manifest, bytes) = read_manifest_response(response, &package).await?;
816    validate_manifest(&manifest, &package, host_target()?)?;
817    Ok(Some(PublishedExtension {
818        package,
819        manifest,
820        bytes,
821    }))
822}
823
824async fn has_release_tag(
825    client: &reqwest::Client,
826    package: &ResolvedPackage,
827    repository: &str,
828) -> Result<bool, String> {
829    let refs = repository_tags(client, "https://api.github.com", &package.name, repository).await?;
830    Ok(tag_published(&refs, &package.name, &package.version))
831}
832
833fn install_client() -> Result<reqwest::Client, String> {
834    reqwest::Client::builder()
835        // 60s client-level cap: metadata (crates.io / GitHub API / manifests)
836        // is small but GitHub TLS handshakes intermittently take >15s on lossy
837        // links ("error sending request" clusters). Archives override with a
838        // 300s per-request timeout in cdn::download_one; the size limits +
839        // sha256 verification remain the actual integrity guards.
840        .timeout(std::time::Duration::from_secs(60))
841        .user_agent(format!("rpi/{}", crate::VERSION))
842        .build()
843        .map_err(|e| e.to_string())
844}
845
846fn custom_repository<'a>(
847    records: &'a [crate::install::InstalledNativePackage],
848    name: &str,
849) -> Option<&'a str> {
850    records
851        .iter()
852        .find(|p| p.name == name)?
853        .prebuilt
854        .as_ref()
855        .filter(|record| record.custom_repository)
856        .map(|record| record.repository.as_str())
857}
858
859pub async fn install(
860    name: &str,
861    version: Option<&str>,
862    repository: Option<&str>,
863    force: bool,
864    cdn_base: Option<&reqwest::Url>,
865) -> Result<(), String> {
866    install_prebuilt(name, version, repository, force, cdn_base, None).await
867}
868
869pub(crate) async fn install_published(
870    name: &str,
871    release: PublishedExtension,
872    cdn_base: Option<&reqwest::Url>,
873) -> Result<(), String> {
874    eprintln!(
875        "install: detected Rust extension `{}` {}",
876        release.package.name, release.package.version
877    );
878    install_prebuilt(name, None, None, false, cdn_base, Some(release)).await
879}
880
881async fn install_prebuilt(
882    name: &str,
883    version: Option<&str>,
884    repository: Option<&str>,
885    force: bool,
886    cdn_base: Option<&reqwest::Url>,
887    published: Option<PublishedExtension>,
888) -> Result<(), String> {
889    let records = crate::install::installed_native_packages_strict()?;
890    let existing = records.iter().find(|p| p.name == name);
891    let target = host_target()?;
892    let client = install_client()?;
893    let repository = repository.or_else(|| custom_repository(&records, name));
894    let detected = published.is_some();
895    let (package, manifest) = match published {
896        Some(published) => (
897            published.package,
898            Some((published.manifest, published.bytes)),
899        ),
900        None => (
901            resolve_package(&client, CRATES_API, name, version, repository).await?,
902            None,
903        ),
904    };
905    if let Some(record) = existing.and_then(|p| p.prebuilt.as_ref()) {
906        if !same_repository_project(&record.repository, &package.repository)
907            && (detected || repository.is_none())
908        {
909            return Err(
910                "extension repository changed; select the new repository explicitly with --github"
911                    .into(),
912            );
913        }
914        if record.repository != package.repository
915            && same_repository_project(&record.repository, &package.repository)
916        {
917            println!(
918                "publisher moved from {} to {}; recording the new location",
919                short_repository(&record.repository),
920                short_repository(&package.repository)
921            );
922        }
923    }
924    if !crate::install::should_install_version(
925        name,
926        existing.map(|p| p.version.as_str()),
927        &package.version,
928        force,
929    )? {
930        crate::install::print_already_installed(name, &package.version);
931        return Ok(());
932    }
933    println!(
934        "downloading prebuilt {} {} for {target}",
935        package.name, package.version
936    );
937    let (manifest, manifest_bytes) = match manifest {
938        Some(manifest) => manifest,
939        None => fetch_manifest(&client, &package).await?,
940    };
941    let distribution = validate_manifest(&manifest, &package, target)?;
942    let cdn_urls = cdn_base
943        .map(|base| {
944            crate::cdn::archive_urls(base, &package.repository, &manifest.tag, &distribution.url)
945        })
946        .transpose()?
947        .unwrap_or_default();
948    let archive = crate::cdn::download_with_fallback(
949        &client,
950        &cdn_urls,
951        &distribution.url,
952        distribution.size,
953        &distribution.sha256,
954        "archive",
955    )
956    .await?;
957    let agent_dir = crate::config::agent_dir().map_err(|e| e.to_string())?;
958    let agent_dir_for_gc = agent_dir.clone();
959    let target = target.to_string();
960    let installed = tokio::task::spawn_blocking(move || {
961        install_archive_at(
962            &package,
963            &manifest,
964            &manifest_bytes,
965            &archive,
966            &target,
967            &agent_dir,
968            force,
969        )
970    })
971    .await
972    .map_err(|e| format!("prebuilt installation failed: {e}"))??;
973    for path in installed {
974        println!("installed {}", path.display());
975    }
976    if matches!(
977        crate::install::gc_retired_native_artifacts(&agent_dir_for_gc),
978        crate::install::RetiredGcOutcome::Deferred
979    ) {
980        eprintln!(
981            "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"
982        );
983    }
984    println!("rpi will validate the plugin entrypoint/SDK API size and load this extension on the next start.");
985    Ok(())
986}
987
988fn install_archive_at(
989    package: &ResolvedPackage,
990    manifest: &Manifest,
991    manifest_bytes: &[u8],
992    archive: &[u8],
993    target: &str,
994    agent_dir: &Path,
995    force: bool,
996) -> Result<Vec<PathBuf>, String> {
997    let distribution = validate_manifest(manifest, package, target)?;
998    if archive.len() as u64 != distribution.size {
999        return Err("archive byte length does not match manifest".into());
1000    }
1001    check_hash(archive, &distribution.sha256)?;
1002    // Everything is verified in memory before the extension store is touched.
1003    let contents = extract_contents(archive, &distribution.format, &distribution.library.path)?;
1004    check_hash(&contents.library, &distribution.library.sha256)?;
1005    validate_library_target(&contents.library, target)?;
1006    let provenance = PrebuiltRecord {
1007        repository: package.repository.clone(),
1008        target: target.into(),
1009        manifest_sha256: hash(manifest_bytes),
1010        source_commit: manifest.source_commit.clone(),
1011        sdk_version: manifest.sdk.version.clone(),
1012        plugin_abi: manifest.sdk.plugin_abi,
1013        archive_sha256: distribution.sha256.clone(),
1014        library_sha256: distribution.library.sha256.clone(),
1015        custom_repository: package.custom_repository,
1016        assets: contents
1017            .assets
1018            .iter()
1019            .map(|asset| PrebuiltAsset {
1020                path: asset.path.clone(),
1021                sha256: asset.sha256.clone(),
1022            })
1023            .collect(),
1024    };
1025    let temporary = tempfile::tempdir().map_err(|e| e.to_string())?;
1026    let artifact = temporary.path().join(&distribution.library.path);
1027    std::fs::write(&artifact, &contents.library).map_err(|e| e.to_string())?;
1028    let assets: Vec<crate::install::NativeAssetFile> = contents
1029        .assets
1030        .into_iter()
1031        .map(|asset| crate::install::NativeAssetFile {
1032            path: asset.path,
1033            bytes: asset.bytes,
1034        })
1035        .collect();
1036    let record = crate::install::InstalledNativePackage {
1037        name: package.name.clone(),
1038        version: package.version.clone(),
1039        // Older hosts regard this as a non-registry source and will not rebuild it.
1040        source: Some(format!("prebuilt:{}", package.repository)),
1041        prebuilt: Some(provenance),
1042        artifacts: Vec::new(),
1043    };
1044    crate::install::install_native_package_with_assets_at(
1045        &agent_dir.join("extensions"),
1046        &agent_dir.join("native-packages.json"),
1047        record,
1048        &[artifact],
1049        &assets,
1050        force,
1051    )
1052}
1053
1054fn safe_entry_name(name: &str) -> Result<PathBuf, String> {
1055    if name.contains(['\\', ':'])
1056        || Path::new(name).components().any(|p| {
1057            matches!(
1058                p,
1059                Component::ParentDir | Component::RootDir | Component::Prefix(_)
1060            )
1061        })
1062    {
1063        return Err("unsafe archive entry path".into());
1064    }
1065    Ok(Path::new(name)
1066        .components()
1067        .filter(|c| !matches!(c, Component::CurDir))
1068        .collect())
1069}
1070
1071fn read_library(reader: impl Read) -> Result<Vec<u8>, String> {
1072    let mut bytes = Vec::new();
1073    reader
1074        .take(MAX_LIBRARY + 1)
1075        .read_to_end(&mut bytes)
1076        .map_err(|e| e.to_string())?;
1077    if bytes.len() as u64 > MAX_LIBRARY {
1078        return Err("extracted library exceeds size limit".into());
1079    }
1080    Ok(bytes)
1081}
1082
1083#[derive(Clone, Copy, PartialEq, Eq)]
1084enum EntryKind {
1085    Directory,
1086    File,
1087}
1088
1089/// Visit every entry of a prebuilt archive in archive order. Unsafe names, links,
1090/// more than `MAX_ENTRIES` entries and more than `total` expanded bytes are rejected
1091/// here, for every archive. Visitors decide what to read.
1092fn walk_archive(
1093    archive: &[u8],
1094    format: &str,
1095    total: u64,
1096    mut visit: impl FnMut(&Path, EntryKind, &mut dyn Read) -> Result<(), String>,
1097) -> Result<(), String> {
1098    let mut expanded = 0u64;
1099    match format {
1100        "zip" => {
1101            let mut zip = zip::ZipArchive::new(Cursor::new(archive)).map_err(|e| e.to_string())?;
1102            if zip.len() > MAX_ENTRIES {
1103                return Err("too many archive entries".into());
1104            }
1105            for i in 0..zip.len() {
1106                let mut file = zip.by_index(i).map_err(|e| e.to_string())?;
1107                let path = safe_entry_name(file.name())?;
1108                if file
1109                    .unix_mode()
1110                    .is_some_and(|mode| mode & 0o170000 == 0o120000)
1111                {
1112                    return Err("archive symlinks are not allowed".into());
1113                }
1114                expanded = expanded
1115                    .checked_add(file.size())
1116                    .ok_or("archive size overflow")?;
1117                if expanded > total {
1118                    return Err("expanded archive exceeds size limit".into());
1119                }
1120                let kind = if file.is_dir() {
1121                    EntryKind::Directory
1122                } else {
1123                    EntryKind::File
1124                };
1125                visit(&path, kind, &mut file)?;
1126            }
1127        }
1128        "tar.gz" => {
1129            let decoder = flate2::read::GzDecoder::new(Cursor::new(archive)).take(total + 1);
1130            let mut tar = tar::Archive::new(decoder);
1131            for (i, entry) in tar.entries().map_err(|e| e.to_string())?.enumerate() {
1132                if i >= MAX_ENTRIES {
1133                    return Err("too many archive entries".into());
1134                }
1135                let mut file = entry.map_err(|e| e.to_string())?;
1136                let name = file
1137                    .path()
1138                    .map_err(|e| e.to_string())?
1139                    .to_string_lossy()
1140                    .into_owned();
1141                let path = safe_entry_name(&name)?;
1142                let kind = file.header().entry_type();
1143                if !kind.is_file() && !kind.is_dir() {
1144                    return Err("archive links and special files are not allowed".into());
1145                }
1146                expanded = expanded
1147                    .checked_add(file.size())
1148                    .ok_or("archive size overflow")?;
1149                if expanded > total {
1150                    return Err("expanded archive exceeds size limit".into());
1151                }
1152                let kind = if kind.is_dir() {
1153                    EntryKind::Directory
1154                } else {
1155                    EntryKind::File
1156                };
1157                visit(&path, kind, &mut file)?;
1158            }
1159        }
1160        _ => return Err("unsupported prebuilt archive format".into()),
1161    }
1162    Ok(())
1163}
1164
1165/// Read only the declared library. Legacy callers, such as the CLI's own release
1166/// archives, never carry sidecars, so every other entry is ignored.
1167pub(crate) fn extract_library(
1168    archive: &[u8],
1169    format: &str,
1170    library: &str,
1171) -> Result<Vec<u8>, String> {
1172    let mut found = None;
1173    walk_archive(archive, format, MAX_ARCHIVE, |path, kind, reader| {
1174        if kind == EntryKind::File && path == Path::new(library) {
1175            if found.is_some() {
1176                return Err("duplicate declared library in archive".into());
1177            }
1178            found = Some(read_library(reader)?);
1179        }
1180        Ok(())
1181    })?;
1182    found.ok_or_else(|| format!("archive does not contain the exact declared library {library}"))
1183}
1184
1185/// Extract a prebuilt package: its library and, when the archive has a
1186/// `runtime-assets.json` index, every declared sidecar, all verified.
1187pub(crate) fn extract_contents(
1188    archive: &[u8],
1189    format: &str,
1190    library: &str,
1191) -> Result<PrebuiltContents, String> {
1192    extract_contents_with_limits(archive, format, library, ArchiveLimits::PREBUILT)
1193}
1194
1195/// Two passes over the archive. The first reads the library and the index, so
1196/// the index can be validated before any sidecar byte is read. The second
1197/// reads each declared sidecar and rejects anything the index does not name.
1198/// Without an index the archive is the legacy single-library layout.
1199fn extract_contents_with_limits(
1200    archive: &[u8],
1201    format: &str,
1202    library: &str,
1203    limits: ArchiveLimits,
1204) -> Result<PrebuiltContents, String> {
1205    let library_path = Path::new(library);
1206    let index_path = Path::new(RUNTIME_ASSETS_FILE);
1207    let mut produced = 0u64;
1208    let mut library_bytes = None;
1209    let mut index_bytes = None;
1210    walk_archive(archive, format, limits.total, |path, kind, reader| {
1211        if kind == EntryKind::Directory {
1212            return Ok(());
1213        }
1214        if path == library_path {
1215            if library_bytes.is_some() {
1216                return Err("duplicate declared library in archive".into());
1217            }
1218            library_bytes = Some(read_budgeted(
1219                reader,
1220                &mut produced,
1221                limits,
1222                limits.per_file,
1223                "extracted library exceeds size limit",
1224            )?);
1225        } else if path == index_path {
1226            if index_bytes.is_some() {
1227                return Err(format!("duplicate {RUNTIME_ASSETS_FILE} in archive"));
1228            }
1229            index_bytes = Some(read_budgeted(
1230                reader,
1231                &mut produced,
1232                limits,
1233                MAX_ASSET_INDEX,
1234                "runtime-assets.json exceeds size limit",
1235            )?);
1236        }
1237        Ok(())
1238    })?;
1239    let library_bytes = library_bytes
1240        .ok_or_else(|| format!("archive does not contain the exact declared library {library}"))?;
1241    let Some(index_bytes) = index_bytes else {
1242        return Ok(PrebuiltContents {
1243            library: library_bytes,
1244            assets: Vec::new(),
1245        });
1246    };
1247    let declared = declared_assets(&index_bytes, library, limits)?;
1248    let mut found: Vec<Option<Vec<u8>>> = vec![None; declared.len()];
1249    walk_archive(archive, format, limits.total, |path, kind, reader| {
1250        if kind == EntryKind::Directory {
1251            if has_node_modules(path) {
1252                return Err(format!("archive contains node_modules: {}", path.display()));
1253            }
1254            return Ok(());
1255        }
1256        // Already read and checked by the first pass.
1257        if path == library_path || path == index_path {
1258            return Ok(());
1259        }
1260        let Some(position) = declared
1261            .iter()
1262            .position(|asset| Path::new(&asset.path) == path)
1263        else {
1264            return Err(format!("undeclared file in archive: {}", path.display()));
1265        };
1266        let asset = &declared[position];
1267        if found[position].is_some() {
1268            return Err(format!(
1269                "duplicate declared asset in archive: {}",
1270                asset.path
1271            ));
1272        }
1273        let bytes = read_budgeted(
1274            reader,
1275            &mut produced,
1276            limits,
1277            limits.per_file,
1278            "extracted asset exceeds size limit",
1279        )?;
1280        if bytes.len() as u64 != asset.size {
1281            return Err(format!(
1282                "asset {} size does not match runtime-assets.json",
1283                asset.path
1284            ));
1285        }
1286        check_hash(&bytes, &asset.sha256).map_err(|e| format!("asset {}: {e}", asset.path))?;
1287        found[position] = Some(bytes);
1288        Ok(())
1289    })?;
1290    let mut assets = Vec::with_capacity(declared.len());
1291    for (asset, bytes) in declared.into_iter().zip(found) {
1292        let bytes = bytes
1293            .ok_or_else(|| format!("archive does not contain declared asset {}", asset.path))?;
1294        assets.push(VerifiedAsset {
1295            path: asset.path,
1296            sha256: asset.sha256,
1297            bytes,
1298        });
1299    }
1300    Ok(PrebuiltContents {
1301        library: library_bytes,
1302        assets,
1303    })
1304}
1305
1306/// Parse and validate `runtime-assets.json`. Paths, sizes, digests and collisions
1307/// are all checked before any sidecar is read.
1308fn declared_assets(
1309    bytes: &[u8],
1310    library: &str,
1311    limits: ArchiveLimits,
1312) -> Result<Vec<RuntimeAsset>, String> {
1313    let index: RuntimeAssetIndex =
1314        serde_json::from_slice(bytes).map_err(|e| format!("invalid {RUNTIME_ASSETS_FILE}: {e}"))?;
1315    if index.schema_version != 1 {
1316        return Err(format!(
1317            "unsupported runtime asset index schema {}",
1318            index.schema_version
1319        ));
1320    }
1321    // The library and the index are two of the archive's entries.
1322    if index.assets.len() + 2 > MAX_ENTRIES {
1323        return Err("too many runtime assets".into());
1324    }
1325    let reserved = [
1326        library.to_ascii_lowercase(),
1327        RUNTIME_ASSETS_FILE.to_ascii_lowercase(),
1328    ];
1329    let mut declared: Vec<RuntimeAsset> = Vec::with_capacity(index.assets.len());
1330    for asset in index.assets {
1331        validate_asset_path(&asset.path)?;
1332        if reserved
1333            .iter()
1334            .any(|name| asset_paths_conflict(name, &asset.path))
1335        {
1336            return Err(format!(
1337                "asset path `{}` collides with the library or manifest",
1338                asset.path
1339            ));
1340        }
1341        if declared
1342            .iter()
1343            .any(|other| asset_paths_conflict(&other.path, &asset.path))
1344        {
1345            return Err(format!(
1346                "duplicate or overlapping asset path `{}`",
1347                asset.path
1348            ));
1349        }
1350        if asset.size > limits.per_file {
1351            return Err(format!("runtime asset {} exceeds size limit", asset.path));
1352        }
1353        if !is_sha256_hex(&asset.sha256) {
1354            return Err(format!("invalid SHA-256 for runtime asset {}", asset.path));
1355        }
1356        declared.push(asset);
1357    }
1358    Ok(declared)
1359}
1360
1361/// Read one archive entry under its per-file cap and the archive's remaining
1362/// expansion budget. Budgets count bytes actually produced, so a header that
1363/// understates its size cannot bypass them.
1364fn read_budgeted(
1365    reader: &mut dyn Read,
1366    produced: &mut u64,
1367    limits: ArchiveLimits,
1368    per_file: u64,
1369    file_error: &str,
1370) -> Result<Vec<u8>, String> {
1371    let remaining = limits.total.saturating_sub(*produced);
1372    let limit = per_file.min(remaining);
1373    let mut bytes = Vec::new();
1374    reader
1375        .take(limit.saturating_add(1))
1376        .read_to_end(&mut bytes)
1377        .map_err(|e| e.to_string())?;
1378    if bytes.len() as u64 > limit {
1379        return Err(if limit == remaining {
1380            "expanded archive exceeds size limit".into()
1381        } else {
1382            file_error.into()
1383        });
1384    }
1385    *produced += bytes.len() as u64;
1386    Ok(bytes)
1387}
1388
1389/// Sidecar paths are relative, forward-slash and plain ASCII. Components cannot be
1390/// empty, `.`, `..` or hidden, cannot be a Windows device name or end in a dot,
1391/// cannot be `node_modules`, and cannot carry a native library extension, because
1392/// the loader scans the extension store for libraries.
1393pub(crate) fn validate_asset_path(value: &str) -> Result<(), String> {
1394    let invalid = || format!("invalid asset path `{value}`");
1395    if value.is_empty() || value.len() > MAX_ASSET_PATH {
1396        return Err(invalid());
1397    }
1398    for component in value.split('/') {
1399        // Windows maps these stems to devices even with an extension, and drops trailing dots.
1400        let stem = component
1401            .split('.')
1402            .next()
1403            .unwrap_or_default()
1404            .to_ascii_uppercase();
1405        let device = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")
1406            || (stem.len() == 4
1407                && (stem.starts_with("COM") || stem.starts_with("LPT"))
1408                && stem.as_bytes()[3].is_ascii_digit());
1409        if component.is_empty()
1410            || component.starts_with('.')
1411            || component.ends_with('.')
1412            || device
1413            || !component
1414                .bytes()
1415                .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
1416        {
1417            return Err(invalid());
1418        }
1419        if component.eq_ignore_ascii_case("node_modules") {
1420            return Err(format!(
1421                "asset `{value}` vendors node_modules; dependencies must be installed at runtime"
1422            ));
1423        }
1424        if crate::install::is_dynamic_library(Path::new(component)) {
1425            return Err(format!(
1426                "asset `{value}` has a native library extension and cannot be installed as an asset"
1427            ));
1428        }
1429    }
1430    Ok(())
1431}
1432
1433/// Whether two store paths name one file, compared case-insensitively, or nest one under the other.
1434pub(crate) fn asset_paths_conflict(left: &str, right: &str) -> bool {
1435    let (left, right) = (left.to_ascii_lowercase(), right.to_ascii_lowercase());
1436    left == right
1437        || left.starts_with(&format!("{right}/"))
1438        || right.starts_with(&format!("{left}/"))
1439}
1440
1441fn has_node_modules(path: &Path) -> bool {
1442    path.components()
1443        .any(|part| part.as_os_str().eq_ignore_ascii_case("node_modules"))
1444}
1445
1446fn is_sha256_hex(value: &str) -> bool {
1447    value.len() == 64
1448        && value
1449            .bytes()
1450            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
1451}
1452
1453/// Verify the native object format/architecture without executing downloaded code.
1454fn validate_library_target(bytes: &[u8], target: &str) -> Result<(), String> {
1455    validate_native_target(bytes, target, true)
1456}
1457
1458pub(crate) fn validate_executable_target(bytes: &[u8], target: &str) -> Result<(), String> {
1459    validate_native_target(bytes, target, false)
1460}
1461
1462fn validate_native_target(bytes: &[u8], target: &str, library: bool) -> Result<(), String> {
1463    let u16_at = |n: usize| {
1464        bytes
1465            .get(n..n.checked_add(2)?)
1466            .map(|b| u16::from_le_bytes([b[0], b[1]]))
1467    };
1468    let u32_at = |n: usize| {
1469        bytes
1470            .get(n..n.checked_add(4)?)
1471            .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
1472    };
1473    let valid = match target {
1474        "x86_64-pc-windows-msvc" => {
1475            let offset = u32_at(0x3c).unwrap_or(u32::MAX) as usize;
1476            bytes.starts_with(b"MZ")
1477                && bytes.get(offset..offset.saturating_add(4)) == Some(b"PE\0\0".as_slice())
1478                && u16_at(offset.saturating_add(4)) == Some(0x8664)
1479                && u16_at(offset.saturating_add(22)).is_some_and(|flags| {
1480                    if library {
1481                        flags & 0x2000 != 0
1482                    } else {
1483                        flags & 0x2000 == 0 && flags & 2 != 0
1484                    }
1485                })
1486        }
1487        "x86_64-unknown-linux-gnu" | "x86_64-unknown-linux-musl" | "aarch64-unknown-linux-gnu" => {
1488            bytes.starts_with(b"\x7fELF\x02\x01")
1489                && u16_at(16).is_some_and(|kind| kind == 3 || (!library && kind == 2))
1490                && u16_at(18)
1491                    == Some(if target.starts_with("aarch64") {
1492                        183
1493                    } else {
1494                        62
1495                    })
1496        }
1497        "x86_64-apple-darwin" | "aarch64-apple-darwin" => {
1498            u32_at(0) == Some(0xfeedfacf)
1499                && u32_at(12) == Some(if library { 6 } else { 2 })
1500                && u32_at(4)
1501                    == Some(if target.starts_with("aarch64") {
1502                        0x0100000c
1503                    } else {
1504                        0x01000007
1505                    })
1506        }
1507        _ => false,
1508    };
1509    if !valid {
1510        return Err(format!(
1511            "declared artifact is not a compatible native {} for {target}",
1512            if library {
1513                "shared library"
1514            } else {
1515                "executable"
1516            }
1517        ));
1518    }
1519    Ok(())
1520}
1521
1522#[cfg(test)]
1523mod tests {
1524    use super::*;
1525    use std::io::Write;
1526
1527    const TARGETS: [&str; 6] = [
1528        "x86_64-pc-windows-msvc",
1529        "x86_64-unknown-linux-gnu",
1530        "x86_64-unknown-linux-musl",
1531        "aarch64-unknown-linux-gnu",
1532        "x86_64-apple-darwin",
1533        "aarch64-apple-darwin",
1534    ];
1535
1536    fn object(target: &str) -> Vec<u8> {
1537        // Header-only objects suffice for format validation on other platforms,
1538        // but Darwin installation actually re-signs the DLL. Use a real linked,
1539        // deterministically signed fixture there, never bypass the signer.
1540        #[cfg(target_os = "macos")]
1541        if target.ends_with("-apple-darwin") {
1542            return signed_mach_o_fixture(target);
1543        }
1544        let mut bytes = vec![0u8; 128];
1545        if target.contains("windows") {
1546            bytes[..2].copy_from_slice(b"MZ");
1547            bytes[0x3c..0x40].copy_from_slice(&64u32.to_le_bytes());
1548            bytes[64..68].copy_from_slice(b"PE\0\0");
1549            bytes[68..70].copy_from_slice(&0x8664u16.to_le_bytes());
1550            bytes[86..88].copy_from_slice(&0x2000u16.to_le_bytes());
1551        } else if target.contains("linux") {
1552            bytes[..6].copy_from_slice(b"\x7fELF\x02\x01");
1553            bytes[16..18].copy_from_slice(&3u16.to_le_bytes());
1554            bytes[18..20].copy_from_slice(
1555                &(if target.starts_with("aarch64") {
1556                    183u16
1557                } else {
1558                    62u16
1559                })
1560                .to_le_bytes(),
1561            );
1562        } else {
1563            bytes[..4].copy_from_slice(&0xfeedfacfu32.to_le_bytes());
1564            bytes[4..8].copy_from_slice(
1565                &(if target.starts_with("aarch64") {
1566                    0x0100000cu32
1567                } else {
1568                    0x01000007u32
1569                })
1570                .to_le_bytes(),
1571            );
1572            bytes[12..16].copy_from_slice(&6u32.to_le_bytes());
1573        }
1574        bytes
1575    }
1576
1577    #[cfg(target_os = "macos")]
1578    fn signed_mach_o_fixture(target: &str) -> Vec<u8> {
1579        use std::sync::OnceLock;
1580        static ARM: OnceLock<Vec<u8>> = OnceLock::new();
1581        static X86: OnceLock<Vec<u8>> = OnceLock::new();
1582        let (cache, arch) = if target.starts_with("aarch64") {
1583            (&ARM, "arm64")
1584        } else {
1585            (&X86, "x86_64")
1586        };
1587        cache
1588            .get_or_init(|| {
1589                let root = tempfile::tempdir().unwrap();
1590                let path = root.path().join("libcustom_runtime.dylib");
1591                let mut child = std::process::Command::new("/usr/bin/clang")
1592                    .args([
1593                        "-dynamiclib",
1594                        "-arch",
1595                        arch,
1596                        "-mmacosx-version-min=11.0",
1597                        "-Wl,-no_uuid",
1598                        "-Wl,-install_name,@rpath/libcustom_runtime.dylib",
1599                        "-x",
1600                        "c",
1601                        "-",
1602                        "-o",
1603                    ])
1604                    .arg(&path)
1605                    .stdin(std::process::Stdio::piped())
1606                    .stdout(std::process::Stdio::piped())
1607                    .stderr(std::process::Stdio::piped())
1608                    .spawn()
1609                    .expect("Darwin signing tests require the system C toolchain");
1610                child
1611                    .stdin
1612                    .take()
1613                    .unwrap()
1614                    .write_all(b"int rpi_prebuilt_fixture(void) { return 42; }\n")
1615                    .unwrap();
1616                let output = child.wait_with_output().unwrap();
1617                assert!(
1618                    output.status.success(),
1619                    "could not link {arch} Mach-O fixture: {}",
1620                    String::from_utf8_lossy(&output.stderr)
1621                );
1622                // Match the production identifier before archiving: re-signing
1623                // under a randomized staging filename must preserve exact bytes
1624                // and all existing provenance/content assertions.
1625                crate::install::resign_staged_native(&path).unwrap();
1626                std::fs::read(path).unwrap()
1627            })
1628            .clone()
1629    }
1630
1631    #[cfg(target_os = "macos")]
1632    #[test]
1633    fn real_mach_o_fixtures_verify_and_remain_identical_after_resigning() {
1634        for target in &TARGETS[4..] {
1635            let bytes = object(target);
1636            assert!(bytes.len() > 128);
1637            let root = tempfile::tempdir().unwrap();
1638            let path = root.path().join("different-staging-name.dylib");
1639            std::fs::write(&path, &bytes).unwrap();
1640            crate::install::resign_staged_native(&path).unwrap();
1641            let verified = std::process::Command::new("/usr/bin/codesign")
1642                .args(["--verify", "--strict"])
1643                .arg(&path)
1644                .output()
1645                .unwrap();
1646            assert!(
1647                verified.status.success(),
1648                "{target}: {}",
1649                String::from_utf8_lossy(&verified.stderr)
1650            );
1651            assert_eq!(std::fs::read(path).unwrap(), bytes);
1652        }
1653    }
1654
1655    fn zip(files: &[(&str, &[u8])]) -> Vec<u8> {
1656        let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
1657        for (name, bytes) in files {
1658            zip.start_file(*name, zip::write::SimpleFileOptions::default())
1659                .unwrap();
1660            zip.write_all(bytes).unwrap();
1661        }
1662        zip.finish().unwrap().into_inner()
1663    }
1664
1665    fn tgz(files: &[(&str, &[u8])]) -> Vec<u8> {
1666        let mut tar = tar::Builder::new(flate2::write::GzEncoder::new(
1667            Vec::new(),
1668            flate2::Compression::default(),
1669        ));
1670        for (name, bytes) in files {
1671            let mut header = tar::Header::new_gnu();
1672            header.set_size(bytes.len() as u64);
1673            header.set_mode(0o644);
1674            header.set_cksum();
1675            tar.append_data(&mut header, name, *bytes).unwrap();
1676        }
1677        tar.into_inner().unwrap().finish().unwrap()
1678    }
1679
1680    fn fixture(target: &str) -> (ResolvedPackage, serde_json::Value, Vec<u8>) {
1681        fixture_with_entries(target, &[])
1682    }
1683
1684    /// The fixture release for `target`, with `extra` files archived beside the library.
1685    fn fixture_with_entries(
1686        target: &str,
1687        extra: &[(&str, &[u8])],
1688    ) -> (ResolvedPackage, serde_json::Value, Vec<u8>) {
1689        let package = ResolvedPackage {
1690            name: "independent-plugin".into(),
1691            version: "1.2.3".into(),
1692            repository: "https://github.com/publisher/monorepo".into(),
1693            custom_repository: false,
1694        };
1695        // The library target deliberately differs from the crate name.
1696        let (format, library, file) = if target.contains("windows") {
1697            ("zip", "custom_runtime.dll", "package.zip")
1698        } else if target.contains("apple") {
1699            ("tar.gz", "libcustom_runtime.dylib", "package.tar.gz")
1700        } else {
1701            ("tar.gz", "libcustom_runtime.so", "package.tar.gz")
1702        };
1703        let bytes = object(target);
1704        let mut entries = vec![(library, bytes.as_slice())];
1705        entries.extend_from_slice(extra);
1706        let archive = if format == "zip" {
1707            zip(&entries)
1708        } else {
1709            tgz(&entries)
1710        };
1711        let manifest = serde_json::json!({
1712            "schema_version":1, "name":package.name, "version":package.version,
1713            "repository":package.repository, "tag":"independent-plugin-v1.2.3", "source_commit":"a".repeat(40),
1714            "sdk":{"version":"0.3.23", "plugin_abi":rpi_plugin_sdk::RPI_PLUGIN_ABI_VERSION_UNIFIED},
1715            "targets":{target:{"url":release_url(&package.repository,&package.name,&package.version,file).unwrap(),
1716                "format":format,"size":archive.len(),"sha256":hash(&archive),"library":{"path":library,"sha256":hash(&bytes)}}}
1717        });
1718        (package, manifest, archive)
1719    }
1720
1721    #[test]
1722    fn declared_runtime_assets_install_beside_the_library() {
1723        let target = TARGETS[0];
1724        let worker = b"export const ready = true;\n";
1725        let index = serde_json::to_vec(&serde_json::json!({
1726            "schema_version": 1,
1727            "assets": [{"path": "runtime/main.mjs", "size": worker.len(), "sha256": hash(worker)}]
1728        }))
1729        .unwrap();
1730        let (package, value, archive) = fixture_with_entries(
1731            target,
1732            &[
1733                ("runtime-assets.json", &index[..]),
1734                ("runtime/main.mjs", &worker[..]),
1735            ],
1736        );
1737        let manifest: Manifest = serde_json::from_value(value.clone()).unwrap();
1738        let agent = tempfile::tempdir().unwrap();
1739        let paths = install_archive_at(
1740            &package,
1741            &manifest,
1742            &serde_json::to_vec(&value).unwrap(),
1743            &archive,
1744            target,
1745            agent.path(),
1746            false,
1747        )
1748        .unwrap();
1749        let extensions = agent.path().join("extensions");
1750        assert_eq!(
1751            std::fs::read(extensions.join("runtime/main.mjs")).unwrap(),
1752            worker
1753        );
1754        assert!(paths.contains(&extensions.join("runtime/main.mjs")));
1755        assert!(!extensions.join("runtime-assets.json").exists());
1756    }
1757
1758    #[test]
1759    fn runtime_asset_index_rejects_unsafe_or_inconsistent_declarations() {
1760        let library = object(TARGETS[0]);
1761        let worker: &[u8] = b"export const ready = true;\n";
1762        let entry = |path: &str, bytes: &[u8]| serde_json::json!({"path": path, "size": bytes.len(), "sha256": hash(bytes)});
1763        let index = |assets: Vec<serde_json::Value>| {
1764            serde_json::to_vec(&serde_json::json!({"schema_version": 1, "assets": assets})).unwrap()
1765        };
1766        let many: Vec<serde_json::Value> = (0..127)
1767            .map(|i| entry(&format!("assets/f{i}.mjs"), worker))
1768            .collect();
1769        let cases: Vec<(&str, Vec<u8>, Vec<(&str, Vec<u8>)>, &str)> = vec![
1770            (
1771                "absolute path",
1772                index(vec![entry("/etc/main.mjs", worker)]),
1773                vec![],
1774                "invalid asset path",
1775            ),
1776            (
1777                "parent traversal",
1778                index(vec![entry("../main.mjs", worker)]),
1779                vec![],
1780                "invalid asset path",
1781            ),
1782            (
1783                "dot component",
1784                index(vec![entry("./main.mjs", worker)]),
1785                vec![],
1786                "invalid asset path",
1787            ),
1788            (
1789                "backslash",
1790                index(vec![entry("runtime\\main.mjs", worker)]),
1791                vec![],
1792                "invalid asset path",
1793            ),
1794            (
1795                "drive prefix",
1796                index(vec![entry("C:main.mjs", worker)]),
1797                vec![],
1798                "invalid asset path",
1799            ),
1800            (
1801                "hidden component",
1802                index(vec![entry(".env", worker)]),
1803                vec![],
1804                "invalid asset path",
1805            ),
1806            (
1807                "trailing slash",
1808                index(vec![entry("runtime/", worker)]),
1809                vec![],
1810                "invalid asset path",
1811            ),
1812            (
1813                "overlong path",
1814                index(vec![entry(&format!("{}.mjs", "a".repeat(510)), worker)]),
1815                vec![],
1816                "invalid asset path",
1817            ),
1818            (
1819                "node_modules",
1820                index(vec![entry("runtime/node_modules/dep.mjs", worker)]),
1821                vec![],
1822                "vendors node_modules",
1823            ),
1824            (
1825                "native library",
1826                index(vec![entry("native/helper.so", worker)]),
1827                vec![],
1828                "native library extension",
1829            ),
1830            (
1831                "index name",
1832                index(vec![entry("runtime-assets.json", worker)]),
1833                vec![],
1834                "collides with the library or manifest",
1835            ),
1836            (
1837                "case-folded duplicate",
1838                index(vec![
1839                    entry("runtime/main.mjs", worker),
1840                    entry("Runtime/Main.mjs", worker),
1841                ]),
1842                vec![],
1843                "duplicate or overlapping",
1844            ),
1845            (
1846                "nested path",
1847                index(vec![
1848                    entry("runtime", worker),
1849                    entry("runtime/main.mjs", worker),
1850                ]),
1851                vec![],
1852                "duplicate or overlapping",
1853            ),
1854            (
1855                "malformed digest",
1856                index(vec![
1857                    serde_json::json!({"path": "main.mjs", "size": worker.len(), "sha256": "ABC"}),
1858                ]),
1859                vec![],
1860                "invalid SHA-256",
1861            ),
1862            (
1863                "windows device name",
1864                index(vec![entry("runtime/CON.mjs", worker)]),
1865                vec![],
1866                "invalid asset path",
1867            ),
1868            (
1869                "windows bare device name",
1870                index(vec![entry("runtime/nul", worker)]),
1871                vec![],
1872                "invalid asset path",
1873            ),
1874            (
1875                "windows trailing dot",
1876                index(vec![entry("runtime/main.mjs.", worker)]),
1877                vec![],
1878                "invalid asset path",
1879            ),
1880            (
1881                "empty component",
1882                index(vec![entry("runtime//main.mjs", worker)]),
1883                vec![],
1884                "invalid asset path",
1885            ),
1886            (
1887                "unc prefix",
1888                index(vec![entry("\\\\server\\share\\main.mjs", worker)]),
1889                vec![],
1890                "invalid asset path",
1891            ),
1892            (
1893                "missing digest",
1894                index(vec![
1895                    serde_json::json!({"path": "main.mjs", "size": worker.len()}),
1896                ]),
1897                vec![("main.mjs", worker.to_vec())],
1898                "invalid runtime-assets.json",
1899            ),
1900            (
1901                "uppercase digest",
1902                index(vec![
1903                    serde_json::json!({"path": "main.mjs", "size": worker.len(), "sha256": hash(worker).to_uppercase()}),
1904                ]),
1905                vec![("main.mjs", worker.to_vec())],
1906                "invalid SHA-256",
1907            ),
1908            (
1909                "traversing archive entry",
1910                index(vec![]),
1911                vec![("../escape.mjs", worker.to_vec())],
1912                "unsafe archive entry path",
1913            ),
1914            (
1915                "absolute archive entry",
1916                index(vec![]),
1917                vec![("/escape.mjs", worker.to_vec())],
1918                "unsafe archive entry path",
1919            ),
1920            (
1921                "backslash archive entry",
1922                index(vec![entry("runtime/main.mjs", worker)]),
1923                vec![("runtime\\main.mjs", worker.to_vec())],
1924                "unsafe archive entry path",
1925            ),
1926            (
1927                "case-folded archive entry",
1928                index(vec![entry("runtime/main.mjs", worker)]),
1929                vec![("Runtime/Main.mjs", worker.to_vec())],
1930                "undeclared file in archive",
1931            ),
1932            (
1933                "unknown schema",
1934                serde_json::to_vec(&serde_json::json!({"schema_version": 2, "assets": []}))
1935                    .unwrap(),
1936                vec![],
1937                "unsupported runtime asset index schema",
1938            ),
1939            (
1940                "malformed index",
1941                b"{".to_vec(),
1942                vec![],
1943                "invalid runtime-assets.json",
1944            ),
1945            (
1946                "too many assets",
1947                index(many),
1948                vec![],
1949                "too many runtime assets",
1950            ),
1951            (
1952                "undeclared file",
1953                index(vec![]),
1954                vec![("runtime/main.mjs", worker.to_vec())],
1955                "undeclared file in archive",
1956            ),
1957            (
1958                "missing declared file",
1959                index(vec![entry("runtime/main.mjs", worker)]),
1960                vec![],
1961                "does not contain declared asset",
1962            ),
1963            (
1964                "size mismatch",
1965                index(vec![
1966                    serde_json::json!({"path": "main.mjs", "size": worker.len() + 1, "sha256": hash(worker)}),
1967                ]),
1968                vec![("main.mjs", worker.to_vec())],
1969                "size does not match",
1970            ),
1971            (
1972                "digest mismatch",
1973                index(vec![
1974                    serde_json::json!({"path": "main.mjs", "size": worker.len(), "sha256": hash(b"other")}),
1975                ]),
1976                vec![("main.mjs", worker.to_vec())],
1977                "SHA-256 mismatch",
1978            ),
1979        ];
1980        for (label, index, extra, expected) in cases {
1981            let mut entries: Vec<(&str, &[u8])> = vec![
1982                ("custom_runtime.dll", library.as_slice()),
1983                ("runtime-assets.json", index.as_slice()),
1984            ];
1985            entries.extend(extra.iter().map(|(name, bytes)| (*name, bytes.as_slice())));
1986            let Err(error) = extract_contents(&zip(&entries), "zip", "custom_runtime.dll") else {
1987                panic!("{label} was accepted");
1988            };
1989            assert!(error.contains(expected), "{label}: {error}");
1990        }
1991    }
1992
1993    #[test]
1994    fn runtime_asset_limits_bound_each_file_and_the_whole_archive() {
1995        let library = object(TARGETS[0]);
1996        let worker = vec![b'x'; 200];
1997        let index = |size: u64| {
1998            serde_json::to_vec(&serde_json::json!({
1999                "schema_version": 1,
2000                "assets": [{"path": "runtime/main.mjs", "size": size, "sha256": hash(&worker)}]
2001            }))
2002            .unwrap()
2003        };
2004        let declared = index(worker.len() as u64);
2005        let archive = |index: &[u8], worker: &[u8]| {
2006            zip(&[
2007                ("custom_runtime.dll", library.as_slice()),
2008                ("runtime-assets.json", index),
2009                ("runtime/main.mjs", worker),
2010            ])
2011        };
2012        let limits = |per_file, total| ArchiveLimits { per_file, total };
2013
2014        // A sidecar larger than the per-file cap is refused by its declaration.
2015        let error = extract_contents_with_limits(
2016            &archive(&declared, &worker),
2017            "zip",
2018            "custom_runtime.dll",
2019            limits(128, u64::MAX),
2020        )
2021        .err()
2022        .unwrap();
2023        assert!(
2024            error.contains("runtime asset runtime/main.mjs exceeds size limit"),
2025            "{error}"
2026        );
2027
2028        // A declaration that understates the bytes is stopped by the read cap.
2029        let understated = index(4);
2030        let error = extract_contents_with_limits(
2031            &archive(&understated, &worker),
2032            "zip",
2033            "custom_runtime.dll",
2034            limits(128, u64::MAX),
2035        )
2036        .err()
2037        .unwrap();
2038        assert!(
2039            error.contains("extracted asset exceeds size limit"),
2040            "{error}"
2041        );
2042
2043        // The expanded total counts every entry, including the library and index.
2044        let exact = library.len() as u64 + declared.len() as u64 + worker.len() as u64;
2045        let contents = extract_contents_with_limits(
2046            &archive(&declared, &worker),
2047            "zip",
2048            "custom_runtime.dll",
2049            limits(u64::MAX, exact),
2050        )
2051        .unwrap();
2052        assert_eq!(contents.assets[0].bytes, worker);
2053        let error = extract_contents_with_limits(
2054            &archive(&declared, &worker),
2055            "zip",
2056            "custom_runtime.dll",
2057            limits(u64::MAX, exact - 1),
2058        )
2059        .err()
2060        .unwrap();
2061        assert!(
2062            error.contains("expanded archive exceeds size limit"),
2063            "{error}"
2064        );
2065    }
2066
2067    #[test]
2068    fn archive_walk_bounds_expanded_size_for_every_archive() {
2069        // Undeclared entries are never read, so the header-declared total is the
2070        // only bound on a legacy archive's expansion.
2071        let archive = zip(&[("a.bin", &[0u8; 12][..]), ("b.bin", &[0u8; 12][..])]);
2072        let error = walk_archive(&archive, "zip", 20, |_, _, _| Ok(())).unwrap_err();
2073        assert!(
2074            error.contains("expanded archive exceeds size limit"),
2075            "{error}"
2076        );
2077        walk_archive(&archive, "zip", 24, |_, _, _| Ok(())).unwrap();
2078
2079        // The tar.gz stream is capped as well, so its framing counts toward the total.
2080        let tar = tgz(&[("a.bin", &[0u8; 12][..]), ("b.bin", &[0u8; 12][..])]);
2081        assert!(walk_archive(&tar, "tar.gz", 20, |_, _, _| Ok(())).is_err());
2082        walk_archive(&tar, "tar.gz", 64 * 1024, |_, _, _| Ok(())).unwrap();
2083    }
2084
2085    #[test]
2086    fn runtime_asset_index_size_is_capped() {
2087        let mut index = br#"{"schema_version":1,"assets":[]}"#.to_vec();
2088        index.resize(MAX_ASSET_INDEX as usize + 1, b' ');
2089        let library = object(TARGETS[0]);
2090        let archive = zip(&[
2091            ("custom_runtime.dll", library.as_slice()),
2092            ("runtime-assets.json", index.as_slice()),
2093        ]);
2094        let Err(error) = extract_contents(&archive, "zip", "custom_runtime.dll") else {
2095            panic!("an oversized index was accepted");
2096        };
2097        assert!(
2098            error.contains("runtime-assets.json exceeds size limit"),
2099            "{error}"
2100        );
2101    }
2102
2103    #[test]
2104    fn runtime_asset_entry_count_is_exact() {
2105        let library = object(TARGETS[0]);
2106        let worker: &[u8] = b"export const ready = true;\n";
2107        let names: Vec<String> = (0..126).map(|i| format!("assets/f{i}.mjs")).collect();
2108        let assets: Vec<serde_json::Value> = names
2109            .iter()
2110            .map(|name| serde_json::json!({"path": name, "size": worker.len(), "sha256": hash(worker)}))
2111            .collect();
2112        let index = serde_json::to_vec(&serde_json::json!({"schema_version": 1, "assets": assets}))
2113            .unwrap();
2114        let mut entries: Vec<(&str, &[u8])> = vec![
2115            ("custom_runtime.dll", library.as_slice()),
2116            ("runtime-assets.json", index.as_slice()),
2117        ];
2118        entries.extend(names.iter().map(|name| (name.as_str(), worker)));
2119        // 126 sidecars plus the library and the index make the 128-entry ceiling.
2120        let contents = extract_contents(&zip(&entries), "zip", "custom_runtime.dll").unwrap();
2121        assert_eq!(contents.assets.len(), 126);
2122
2123        // A legacy archive is bounded by the same entry ceiling.
2124        let legacy: Vec<String> = (0..129).map(|i| format!("docs/{i}.md")).collect();
2125        let legacy: Vec<(&str, &[u8])> = legacy
2126            .iter()
2127            .map(|name| (name.as_str(), &b"x"[..]))
2128            .collect();
2129        let error = extract_library(&zip(&legacy), "zip", "custom_runtime.dll").unwrap_err();
2130        assert!(error.contains("too many archive entries"), "{error}");
2131    }
2132
2133    /// Rewrite the uncompressed size that the local and central headers of `name`
2134    /// claim. The stored bytes do not change, so the entry still holds its real length.
2135    fn understate_entry(archive: &mut [u8], name: &str, claimed: u32) {
2136        let name = name.as_bytes();
2137        let local: Vec<usize> = (0..archive.len())
2138            .filter(|&at| {
2139                archive[at..].starts_with(b"PK\x03\x04")
2140                    && archive
2141                        .get(at + 30..)
2142                        .is_some_and(|rest| rest.starts_with(name))
2143            })
2144            .collect();
2145        let central: Vec<usize> = (0..archive.len())
2146            .filter(|&at| {
2147                archive[at..].starts_with(b"PK\x01\x02")
2148                    && archive
2149                        .get(at + 46..)
2150                        .is_some_and(|rest| rest.starts_with(name))
2151            })
2152            .collect();
2153        assert!(!local.is_empty() && !central.is_empty());
2154        for at in local {
2155            archive[at + 22..at + 26].copy_from_slice(&claimed.to_le_bytes());
2156        }
2157        for at in central {
2158            archive[at + 24..at + 28].copy_from_slice(&claimed.to_le_bytes());
2159        }
2160    }
2161
2162    #[test]
2163    fn runtime_asset_budget_holds_when_zip_headers_understate_sizes() {
2164        let library = object(TARGETS[0]);
2165        let worker = vec![b'x'; 200];
2166        let index = serde_json::to_vec(&serde_json::json!({
2167            "schema_version": 1,
2168            "assets": [{"path": "runtime/main.mjs", "size": worker.len(), "sha256": hash(&worker)}]
2169        }))
2170        .unwrap();
2171        let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new()));
2172        let stored = zip::write::SimpleFileOptions::default()
2173            .compression_method(zip::CompressionMethod::Stored);
2174        for (name, bytes) in [
2175            ("custom_runtime.dll", library.as_slice()),
2176            ("runtime-assets.json", index.as_slice()),
2177            ("runtime/main.mjs", worker.as_slice()),
2178        ] {
2179            writer.start_file(name, stored).unwrap();
2180            writer.write_all(bytes).unwrap();
2181        }
2182        let mut archive = writer.finish().unwrap().into_inner();
2183        // The headers now claim one byte for the sidecar that really holds 200.
2184        understate_entry(&mut archive, "runtime/main.mjs", 1);
2185
2186        // The walker sees a small entry, so only the read budget can stop the bytes.
2187        let exact = (library.len() + index.len() + worker.len()) as u64;
2188        let limits = ArchiveLimits {
2189            per_file: u64::MAX,
2190            total: exact - 1,
2191        };
2192        let error = extract_contents_with_limits(&archive, "zip", "custom_runtime.dll", limits)
2193            .err()
2194            .unwrap();
2195        assert!(
2196            error.contains("expanded archive exceeds size limit"),
2197            "{error}"
2198        );
2199
2200        let limits = ArchiveLimits {
2201            per_file: u64::MAX,
2202            total: exact,
2203        };
2204        let contents =
2205            extract_contents_with_limits(&archive, "zip", "custom_runtime.dll", limits).unwrap();
2206        assert_eq!(contents.assets[0].bytes, worker);
2207    }
2208
2209    #[test]
2210    fn runtime_asset_archives_reject_symlinked_files_and_node_modules_directories() {
2211        let library = object(TARGETS[0]);
2212        let worker = b"export {};\n";
2213        let index = serde_json::to_vec(&serde_json::json!({
2214            "schema_version": 1,
2215            "assets": [{"path": "runtime/main.mjs", "size": worker.len(), "sha256": hash(worker)}]
2216        }))
2217        .unwrap();
2218        let mut linked = zip::ZipWriter::new(Cursor::new(Vec::new()));
2219        linked
2220            .start_file(
2221                "custom_runtime.dll",
2222                zip::write::SimpleFileOptions::default(),
2223            )
2224            .unwrap();
2225        linked.write_all(&library).unwrap();
2226        linked
2227            .start_file(
2228                "runtime-assets.json",
2229                zip::write::SimpleFileOptions::default(),
2230            )
2231            .unwrap();
2232        linked.write_all(&index).unwrap();
2233        linked
2234            .add_symlink(
2235                "runtime/main.mjs",
2236                "/etc/passwd",
2237                zip::write::SimpleFileOptions::default(),
2238            )
2239            .unwrap();
2240        let archive = linked.finish().unwrap().into_inner();
2241        let Err(error) = extract_contents(&archive, "zip", "custom_runtime.dll") else {
2242            panic!("a symlinked sidecar was accepted");
2243        };
2244        assert!(error.contains("symlinks are not allowed"), "{error}");
2245
2246        let empty =
2247            serde_json::to_vec(&serde_json::json!({"schema_version": 1, "assets": []})).unwrap();
2248        let mut vendored = zip::ZipWriter::new(Cursor::new(Vec::new()));
2249        vendored
2250            .start_file(
2251                "custom_runtime.dll",
2252                zip::write::SimpleFileOptions::default(),
2253            )
2254            .unwrap();
2255        vendored.write_all(&library).unwrap();
2256        vendored
2257            .start_file(
2258                "runtime-assets.json",
2259                zip::write::SimpleFileOptions::default(),
2260            )
2261            .unwrap();
2262        vendored.write_all(&empty).unwrap();
2263        vendored
2264            .add_directory("node_modules/", zip::write::SimpleFileOptions::default())
2265            .unwrap();
2266        let archive = vendored.finish().unwrap().into_inner();
2267        let Err(error) = extract_contents(&archive, "zip", "custom_runtime.dll") else {
2268            panic!("a node_modules directory was accepted");
2269        };
2270        assert!(error.contains("node_modules"), "{error}");
2271    }
2272
2273    #[test]
2274    fn runtime_asset_digest_mismatch_keeps_the_installed_sidecars() {
2275        let target = TARGETS[1];
2276        let worker = b"export {};\n";
2277        let index = serde_json::to_vec(&serde_json::json!({
2278            "schema_version": 1,
2279            "assets": [{"path": "runtime/main.mjs", "size": worker.len(), "sha256": hash(worker)}]
2280        }))
2281        .unwrap();
2282        let (package, value, archive) = fixture_with_entries(
2283            target,
2284            &[
2285                ("runtime-assets.json", &index[..]),
2286                ("runtime/main.mjs", &worker[..]),
2287            ],
2288        );
2289        let manifest: Manifest = serde_json::from_value(value.clone()).unwrap();
2290        let agent = tempfile::tempdir().unwrap();
2291        install_archive_at(
2292            &package,
2293            &manifest,
2294            &serde_json::to_vec(&value).unwrap(),
2295            &archive,
2296            target,
2297            agent.path(),
2298            false,
2299        )
2300        .unwrap();
2301        let metadata = std::fs::read(agent.path().join("native-packages.json")).unwrap();
2302
2303        // The manifest and archive hashes are consistent. The sidecar keeps its size and changes its bytes.
2304        let tampered: &[u8] = b"export [];\n";
2305        assert_eq!(tampered.len(), worker.len());
2306        let (package, value, archive) = fixture_with_entries(
2307            target,
2308            &[
2309                ("runtime-assets.json", &index[..]),
2310                ("runtime/main.mjs", tampered),
2311            ],
2312        );
2313        let manifest: Manifest = serde_json::from_value(value.clone()).unwrap();
2314        let error = install_archive_at(
2315            &package,
2316            &manifest,
2317            &serde_json::to_vec(&value).unwrap(),
2318            &archive,
2319            target,
2320            agent.path(),
2321            true,
2322        )
2323        .unwrap_err();
2324        assert!(
2325            error.contains("asset runtime/main.mjs: SHA-256 mismatch"),
2326            "{error}"
2327        );
2328        let extensions = agent.path().join("extensions");
2329        assert_eq!(
2330            std::fs::read(extensions.join("runtime/main.mjs")).unwrap(),
2331            worker
2332        );
2333        assert_eq!(
2334            std::fs::read(agent.path().join("native-packages.json")).unwrap(),
2335            metadata
2336        );
2337    }
2338
2339    #[test]
2340    fn runtime_asset_tar_archives_reject_duplicate_index_and_declared_entries() {
2341        let library = object(TARGETS[1]);
2342        let worker = b"export {};\n";
2343        let index = serde_json::to_vec(&serde_json::json!({
2344            "schema_version": 1,
2345            "assets": [{"path": "runtime/main.mjs", "size": worker.len(), "sha256": hash(worker)}]
2346        }))
2347        .unwrap();
2348        let archive = tgz(&[
2349            ("libcustom_runtime.so", &library),
2350            ("runtime-assets.json", &index),
2351            ("runtime/main.mjs", worker),
2352            ("runtime/main.mjs", worker),
2353        ]);
2354        let Err(error) = extract_contents(&archive, "tar.gz", "libcustom_runtime.so") else {
2355            panic!("a duplicated sidecar was accepted");
2356        };
2357        assert!(error.contains("duplicate declared asset"), "{error}");
2358
2359        let archive = tgz(&[
2360            ("libcustom_runtime.so", &library),
2361            ("runtime-assets.json", &index),
2362            ("runtime-assets.json", &index),
2363        ]);
2364        let Err(error) = extract_contents(&archive, "tar.gz", "libcustom_runtime.so") else {
2365            panic!("a duplicated index was accepted");
2366        };
2367        assert!(error.contains("duplicate runtime-assets.json"), "{error}");
2368    }
2369
2370    #[test]
2371    fn legacy_archives_install_only_the_library_and_keep_their_records_unchanged() {
2372        for target in TARGETS {
2373            let (package, value, archive) =
2374                fixture_with_entries(target, &[("README.md", b"not a sidecar")]);
2375            let manifest: Manifest = serde_json::from_value(value.clone()).unwrap();
2376            let agent = tempfile::tempdir().unwrap();
2377            let paths = install_archive_at(
2378                &package,
2379                &manifest,
2380                &serde_json::to_vec(&value).unwrap(),
2381                &archive,
2382                target,
2383                agent.path(),
2384                false,
2385            )
2386            .unwrap();
2387            assert_eq!(paths.len(), 1);
2388            assert!(!agent.path().join("extensions/README.md").exists());
2389            let records: serde_json::Value = serde_json::from_slice(
2390                &std::fs::read(agent.path().join("native-packages.json")).unwrap(),
2391            )
2392            .unwrap();
2393            assert!(records[0]["prebuilt"].get("assets").is_none());
2394        }
2395    }
2396
2397    #[test]
2398    fn all_six_distributions_install_and_record_exact_provenance() {
2399        for target in TARGETS {
2400            let (package, value, archive) = fixture(target);
2401            let manifest: Manifest = serde_json::from_value(value.clone()).unwrap();
2402            let raw = serde_json::to_vec(&value).unwrap();
2403            let agent = tempfile::tempdir().unwrap();
2404            let paths = install_archive_at(
2405                &package,
2406                &manifest,
2407                &raw,
2408                &archive,
2409                target,
2410                agent.path(),
2411                false,
2412            )
2413            .unwrap();
2414            assert_eq!(paths.len(), 1);
2415            assert_eq!(std::fs::read(&paths[0]).unwrap(), object(target));
2416            let records: Vec<crate::install::InstalledNativePackage> = serde_json::from_slice(
2417                &std::fs::read(agent.path().join("native-packages.json")).unwrap(),
2418            )
2419            .unwrap();
2420            assert_eq!(records[0].name, "independent-plugin");
2421            assert_eq!(records[0].version, "1.2.3");
2422            assert_eq!(
2423                records[0].artifacts,
2424                [manifest.targets[target].library.path.clone()]
2425            );
2426            let origin = records[0].prebuilt.as_ref().unwrap();
2427            assert_eq!(origin.target, target);
2428            assert_eq!(origin.manifest_sha256, hash(&raw));
2429            assert_eq!(origin.repository, package.repository);
2430            assert_eq!(origin.archive_sha256, hash(&archive));
2431            assert_eq!(origin.library_sha256, hash(&object(target)));
2432        }
2433    }
2434
2435    #[test]
2436    fn prebuilt_packages_upgrade_without_force_and_same_version_is_unchanged() {
2437        for target in TARGETS {
2438            let (mut package, mut value, archive) = fixture(target);
2439            let manifest: Manifest = serde_json::from_value(value.clone()).unwrap();
2440            let agent = tempfile::tempdir().unwrap();
2441            install_archive_at(
2442                &package,
2443                &manifest,
2444                &serde_json::to_vec(&value).unwrap(),
2445                &archive,
2446                target,
2447                agent.path(),
2448                false,
2449            )
2450            .unwrap();
2451            package.version = "1.2.4".into();
2452            value["version"] = serde_json::json!(package.version);
2453            value["tag"] = serde_json::json!("independent-plugin-v1.2.4");
2454            let distribution = value.pointer_mut(&format!("/targets/{target}")).unwrap();
2455            let format = distribution["format"].as_str().unwrap();
2456            let file = if format == "zip" {
2457                "package.zip"
2458            } else {
2459                "package.tar.gz"
2460            };
2461            distribution["url"] = serde_json::json!(release_url(
2462                &package.repository,
2463                &package.name,
2464                &package.version,
2465                file,
2466            )
2467            .unwrap());
2468            let manifest = serde_json::from_value(value.clone()).unwrap();
2469            let raw = serde_json::to_vec(&value).unwrap();
2470            assert_eq!(
2471                install_archive_at(
2472                    &package,
2473                    &manifest,
2474                    &raw,
2475                    &archive,
2476                    target,
2477                    agent.path(),
2478                    false,
2479                )
2480                .unwrap()
2481                .len(),
2482                1
2483            );
2484            let metadata = agent.path().join("native-packages.json");
2485            let registry = std::fs::read(&metadata).unwrap();
2486            let records: Vec<crate::install::InstalledNativePackage> =
2487                serde_json::from_slice(&registry).unwrap();
2488            assert_eq!(records[0].version, "1.2.4");
2489            assert!(install_archive_at(
2490                &package,
2491                &manifest,
2492                &raw,
2493                &archive,
2494                target,
2495                agent.path(),
2496                false,
2497            )
2498            .unwrap()
2499            .is_empty());
2500            assert_eq!(std::fs::read(&metadata).unwrap(), registry);
2501        }
2502    }
2503
2504    #[test]
2505    fn bad_release_identity_hash_abi_and_target_leave_installed_version_intact() {
2506        let target = TARGETS[0];
2507        let (package, good, archive) = fixture(target);
2508        let manifest: Manifest = serde_json::from_value(good.clone()).unwrap();
2509        let agent = tempfile::tempdir().unwrap();
2510        let path = install_archive_at(
2511            &package,
2512            &manifest,
2513            &serde_json::to_vec(&good).unwrap(),
2514            &archive,
2515            target,
2516            agent.path(),
2517            false,
2518        )
2519        .unwrap()
2520        .remove(0);
2521        let original_record = std::fs::read(agent.path().join("native-packages.json")).unwrap();
2522        let mutations = [
2523            ("/schema_version",serde_json::json!(99)), ("/name",serde_json::json!("other-plugin")),
2524            ("/version",serde_json::json!("9.9.9")), ("/tag",serde_json::json!("v1.2.3")),
2525            ("/repository",serde_json::json!("https://github.com/other/repo")),
2526            ("/sdk/plugin_abi",serde_json::json!(99)),
2527            ("/targets/x86_64-pc-windows-msvc/sha256",serde_json::json!("0".repeat(64))),
2528            ("/targets/x86_64-pc-windows-msvc/library/sha256",serde_json::json!("0".repeat(64))),
2529            ("/targets/x86_64-pc-windows-msvc/library/path",serde_json::json!("../custom_runtime.dll")),
2530            ("/targets/x86_64-pc-windows-msvc/url",serde_json::json!("https://github.com/other/repo/releases/download/independent-plugin-v1.2.3/package.zip")),
2531            ("/targets/x86_64-pc-windows-msvc/size",serde_json::json!(archive.len()+1)),
2532        ];
2533        for (pointer, value) in mutations {
2534            let mut bad = good.clone();
2535            *bad.pointer_mut(pointer).unwrap() = value;
2536            let bad_manifest = serde_json::from_value(bad.clone()).unwrap();
2537            assert!(
2538                install_archive_at(
2539                    &package,
2540                    &bad_manifest,
2541                    &serde_json::to_vec(&bad).unwrap(),
2542                    &archive,
2543                    target,
2544                    agent.path(),
2545                    true
2546                )
2547                .is_err(),
2548                "{pointer}"
2549            );
2550            assert_eq!(std::fs::read(&path).unwrap(), object(target));
2551            assert_eq!(
2552                std::fs::read(agent.path().join("native-packages.json")).unwrap(),
2553                original_record
2554            );
2555        }
2556        assert!(install_archive_at(
2557            &package,
2558            &manifest,
2559            &[],
2560            &archive,
2561            TARGETS[1],
2562            agent.path(),
2563            true
2564        )
2565        .is_err());
2566    }
2567
2568    #[test]
2569    fn same_abi_but_wrong_binary_architecture_is_rejected_before_activation() {
2570        let (package, mut value, _) = fixture(TARGETS[0]);
2571        let wrong = object(TARGETS[2]);
2572        let archive = zip(&[("custom_runtime.dll", &wrong)]);
2573        let distribution = value
2574            .pointer_mut("/targets/x86_64-pc-windows-msvc")
2575            .unwrap();
2576        distribution["size"] = serde_json::json!(archive.len());
2577        distribution["sha256"] = serde_json::json!(hash(&archive));
2578        distribution["library"]["sha256"] = serde_json::json!(hash(&wrong));
2579        let manifest = serde_json::from_value(value).unwrap();
2580        let agent = tempfile::tempdir().unwrap();
2581        assert!(install_archive_at(
2582            &package,
2583            &manifest,
2584            &[],
2585            &archive,
2586            TARGETS[0],
2587            agent.path(),
2588            false
2589        )
2590        .unwrap_err()
2591        .contains("shared library"));
2592        assert!(!agent.path().join("native-packages.json").exists());
2593        assert!(!agent.path().join("extensions").exists());
2594    }
2595
2596    #[test]
2597    fn archives_cannot_traverse_retain_links_or_substitute_another_library() {
2598        let library = object(TARGETS[0]);
2599        assert!(
2600            extract_library(&zip(&[("../escape.dll", &library)]), "zip", "escape.dll").is_err()
2601        );
2602        assert!(
2603            extract_library(&zip(&[("C:\\escape.dll", &library)]), "zip", "escape.dll").is_err()
2604        );
2605        assert!(extract_library(&zip(&[("other.dll", &library)]), "zip", "declared.dll").is_err());
2606        let mut linked = zip::ZipWriter::new(Cursor::new(Vec::new()));
2607        linked
2608            .add_symlink(
2609                "declared.dll",
2610                "outside.dll",
2611                zip::write::SimpleFileOptions::default(),
2612            )
2613            .unwrap();
2614        assert!(extract_library(
2615            &linked.finish().unwrap().into_inner(),
2616            "zip",
2617            "declared.dll"
2618        )
2619        .is_err());
2620        let mut tar = tar::Builder::new(flate2::write::GzEncoder::new(
2621            Vec::new(),
2622            flate2::Compression::default(),
2623        ));
2624        let mut header = tar::Header::new_gnu();
2625        header.set_entry_type(tar::EntryType::Link);
2626        header.set_size(0);
2627        header.set_mode(0o644);
2628        header.set_cksum();
2629        tar.append_link(&mut header, "declared.so", "outside.so")
2630            .unwrap();
2631        assert!(extract_library(
2632            &tar.into_inner().unwrap().finish().unwrap(),
2633            "tar.gz",
2634            "declared.so"
2635        )
2636        .is_err());
2637    }
2638
2639    #[test]
2640    fn object_headers_cannot_cross_platform_or_architecture() {
2641        for target in TARGETS {
2642            assert!(validate_library_target(&object(target), target).is_ok());
2643            for other in TARGETS {
2644                if other != target {
2645                    // ELF headers do not encode the libc choice, so GNU and
2646                    // musl x86_64 objects are intentionally indistinguishable
2647                    // to this architecture check. Exact target manifests still
2648                    // keep those distributions separate.
2649                    if target.starts_with("x86_64-unknown-linux-")
2650                        && other.starts_with("x86_64-unknown-linux-")
2651                    {
2652                        continue;
2653                    }
2654                    assert!(validate_library_target(&object(other), target).is_err());
2655                }
2656            }
2657        }
2658        assert!(validate_library_target(&[0u8; 8], TARGETS[0]).is_err());
2659        let mut damaged = object(TARGETS[0]);
2660        damaged[0x3c..0x40].copy_from_slice(&u32::MAX.to_le_bytes());
2661        assert!(validate_library_target(&damaged, TARGETS[0]).is_err());
2662    }
2663
2664    #[test]
2665    fn exact_versions_ignore_yanked_and_prerelease_latest() {
2666        let versions = [
2667            RegistryVersion {
2668                num: "1.0.0".into(),
2669                yanked: false,
2670            },
2671            RegistryVersion {
2672                num: "9.0.0".into(),
2673                yanked: true,
2674            },
2675            RegistryVersion {
2676                num: "2.0.0-beta.1".into(),
2677                yanked: false,
2678            },
2679        ];
2680        assert_eq!(select_version(&versions, None).unwrap(), "1.0.0");
2681        assert_eq!(
2682            select_version(&versions, Some("2.0.0-beta.1")).unwrap(),
2683            "2.0.0-beta.1"
2684        );
2685        assert!(select_version(&versions, Some("9.0.0")).is_err());
2686        assert!(select_version(&versions, Some("^1")).is_err());
2687    }
2688
2689    #[test]
2690    fn github_case_and_encoded_semver_build_metadata_preserve_release_identity() {
2691        let (mut package, mut value, _) = fixture(TARGETS[0]);
2692        package.version = "1.2.3+build.1".into();
2693        value["version"] = serde_json::json!(package.version);
2694        value["tag"] = serde_json::json!("independent-plugin-v1.2.3+build.1");
2695        value["repository"] = serde_json::json!("https://github.com/Publisher/MonoRepo");
2696        value["targets"][TARGETS[0]]["url"] = serde_json::json!("https://github.com/Publisher/MonoRepo/releases/download/independent-plugin-v1.2.3%2Bbuild.1/package.zip");
2697        let manifest = serde_json::from_value(value).unwrap();
2698        assert!(validate_manifest(&manifest, &package, TARGETS[0]).is_ok());
2699        assert_eq!(
2700            canonical_repository("Publisher/MonoRepo").unwrap(),
2701            package.repository
2702        );
2703    }
2704
2705    #[test]
2706    fn repository_urls_are_explicit_and_release_tags_use_package_versions() {
2707        assert_eq!(
2708            canonical_repository("git+https://github.com/publisher/monorepo.git").unwrap(),
2709            "https://github.com/publisher/monorepo"
2710        );
2711        assert_eq!(
2712            canonical_repository("https://github.com/publisher/monorepo/tree/main/packages/plugin")
2713                .unwrap(),
2714            "https://github.com/publisher/monorepo"
2715        );
2716        for invalid in [
2717            "https://gitlab.com/x/y",
2718            "https://user@github.com/x/y",
2719            "https://github.com/x",
2720            "https://github.com/x/y/releases/latest",
2721            "https://github.com:8443/x/y",
2722        ] {
2723            assert!(canonical_repository(invalid).is_err());
2724        }
2725        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");
2726        assert!(release_url(
2727            "https://github.com/publisher/monorepo",
2728            "plugin-two",
2729            "4.5.6",
2730            "rpi-extension.json"
2731        )
2732        .unwrap()
2733        .contains("plugin-two-v4.5.6"));
2734    }
2735
2736    fn one_response(body: Vec<u8>) -> (String, std::thread::JoinHandle<String>) {
2737        response_with_status("200 OK", body)
2738    }
2739
2740    fn response_with_status(
2741        status: &'static str,
2742        body: Vec<u8>,
2743    ) -> (String, std::thread::JoinHandle<String>) {
2744        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2745        let url = format!("http://{}", listener.local_addr().unwrap());
2746        let thread = std::thread::spawn(move || {
2747            let (mut socket, _) = listener.accept().unwrap();
2748            socket
2749                .set_read_timeout(Some(std::time::Duration::from_secs(5)))
2750                .unwrap();
2751            let mut request = Vec::new();
2752            let mut byte = [0];
2753            while !request.ends_with(b"\r\n\r\n") {
2754                socket.read_exact(&mut byte).unwrap();
2755                request.push(byte[0]);
2756            }
2757            write!(
2758                socket,
2759                "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
2760                body.len()
2761            )
2762            .unwrap();
2763            socket.write_all(&body).unwrap();
2764            String::from_utf8(request).unwrap()
2765        });
2766        (url, thread)
2767    }
2768
2769    #[tokio::test]
2770    async fn downloaded_manifest_and_archive_install_into_an_isolated_profile() {
2771        let target = host_target().unwrap();
2772        let (package, value, archive) = fixture(target);
2773        let raw = serde_json::to_vec(&value).unwrap();
2774        let client = reqwest::Client::builder().no_proxy().build().unwrap();
2775        let (url, server) = one_response(raw.clone());
2776        let response = client.get(url).send().await.unwrap();
2777        let (manifest, received) = read_manifest_response(response, &package).await.unwrap();
2778        server.join().unwrap();
2779        assert_eq!(received, raw);
2780        let distribution = validate_manifest(&manifest, &package, target).unwrap();
2781        let (url, server) = one_response(archive);
2782        let response = client.get(url).send().await.unwrap();
2783        let downloaded = body_limited(response, distribution.size).await.unwrap();
2784        server.join().unwrap();
2785        let profile = tempfile::tempdir().unwrap();
2786        let paths = install_archive_at(
2787            &package,
2788            &manifest,
2789            &received,
2790            &downloaded,
2791            target,
2792            profile.path(),
2793            false,
2794        )
2795        .unwrap();
2796        assert_eq!(std::fs::read(&paths[0]).unwrap(), object(target));
2797        assert!(profile.path().join("native-packages.json").is_file());
2798    }
2799
2800    #[tokio::test]
2801    async fn missing_invalid_and_oversized_manifests_fail_before_installation() {
2802        let (package, _, _) = fixture(TARGETS[0]);
2803        let client = reqwest::Client::builder().no_proxy().build().unwrap();
2804        for (status, body, expected) in [
2805            (
2806                "404 Not Found",
2807                b"missing".to_vec(),
2808                "rpi-extension.json is missing",
2809            ),
2810            ("403 Forbidden", b"denied".to_vec(), "403 Forbidden"),
2811            ("200 OK", b"not json".to_vec(), "invalid rpi-extension.json"),
2812            (
2813                "200 OK",
2814                vec![b' '; MAX_MANIFEST as usize + 1],
2815                "size limit",
2816            ),
2817        ] {
2818            let (url, server) = response_with_status(status, body);
2819            let response = client.get(url).send().await.unwrap();
2820            let error = read_manifest_response(response, &package)
2821                .await
2822                .err()
2823                .unwrap();
2824            assert!(error.contains(expected), "{error}");
2825            server.join().unwrap();
2826        }
2827    }
2828
2829    #[tokio::test]
2830    async fn explicit_repository_and_version_do_not_require_a_registry_record() {
2831        let client = reqwest::Client::new();
2832        let resolved = resolve_package(
2833            &client,
2834            "http://127.0.0.1:1",
2835            "private-extension",
2836            Some("2.3.4"),
2837            Some("https://github.com/custom-owner/custom-repo.git"),
2838        )
2839        .await
2840        .unwrap();
2841        assert_eq!(
2842            resolved.repository,
2843            "https://github.com/custom-owner/custom-repo"
2844        );
2845        assert_eq!(resolved.name, "private-extension");
2846        assert_eq!(resolved.version, "2.3.4");
2847        assert!(release_url(
2848            &resolved.repository,
2849            &resolved.name,
2850            &resolved.version,
2851            "rpi-extension.json"
2852        )
2853        .unwrap()
2854        .contains("custom-repo/releases/download/private-extension-v2.3.4/"));
2855    }
2856
2857    #[tokio::test]
2858    async fn custom_repository_versions_are_scoped_to_the_package() {
2859        let refs = serde_json::to_vec(&serde_json::json!([
2860            {"ref":"refs/tags/independent-plugin-v1.2.3"},
2861            {"ref":"refs/tags/independent-plugin-v1.4.0"},
2862            {"ref":"refs/tags/other-plugin-v99.0.0"},
2863            {"ref":"refs/tags/independent-plugin-v2.0.0-beta.1"}
2864        ]))
2865        .unwrap();
2866        let (api, server) = one_response(refs);
2867        let client = reqwest::Client::builder().no_proxy().build().unwrap();
2868        assert_eq!(
2869            repository_version(
2870                &client,
2871                &api,
2872                "independent-plugin",
2873                "https://github.com/publisher/monorepo"
2874            )
2875            .await
2876            .unwrap(),
2877            (
2878                "1.4.0".to_string(),
2879                "https://github.com/publisher/monorepo".to_string()
2880            )
2881        );
2882        assert!(server.join().unwrap().starts_with(
2883            "GET /repos/publisher/monorepo/git/matching-refs/tags/independent-plugin-v "
2884        ));
2885    }
2886
2887    /// Serve one response per request, in request order, and return the
2888    /// request heads so a test can assert which repositories were queried.
2889    fn sequenced_responses(
2890        responses: Vec<(&'static str, Vec<u8>)>,
2891    ) -> (String, std::thread::JoinHandle<Vec<String>>) {
2892        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2893        let url = format!("http://{}", listener.local_addr().unwrap());
2894        let thread = std::thread::spawn(move || {
2895            let mut requests = Vec::new();
2896            for (status, body) in responses {
2897                let (mut socket, _) = listener.accept().unwrap();
2898                socket
2899                    .set_read_timeout(Some(std::time::Duration::from_secs(5)))
2900                    .unwrap();
2901                let mut request = Vec::new();
2902                let mut byte = [0];
2903                while !request.ends_with(b"\r\n\r\n") {
2904                    socket.read_exact(&mut byte).unwrap();
2905                    request.push(byte[0]);
2906                }
2907                write!(
2908                    socket,
2909                    "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
2910                    body.len()
2911                )
2912                .unwrap();
2913                socket.write_all(&body).unwrap();
2914                requests.push(String::from_utf8(request).unwrap());
2915            }
2916            requests
2917        });
2918        (url, thread)
2919    }
2920
2921    #[test]
2922    fn moved_repository_spellings_identify_one_project() {
2923        assert!(same_repository_project(
2924            "https://github.com/pi-rust/rpi-package",
2925            "https://github.com/pi-rust/rpi-extension"
2926        ));
2927        assert!(same_repository_project(
2928            "https://github.com/publisher/monorepo",
2929            "https://github.com/publisher/monorepo"
2930        ));
2931        assert!(!same_repository_project(
2932            "https://github.com/pi-rust/rpi-extension",
2933            "https://github.com/publisher/monorepo"
2934        ));
2935    }
2936
2937    #[test]
2938    fn tag_published_matches_the_exact_package_tag() {
2939        let refs = vec![
2940            GitReference {
2941                reference: "refs/tags/rpi-todo-v0.3.4".into(),
2942            },
2943            GitReference {
2944                reference: "refs/tags/rpi-todo-v0.3.10".into(),
2945            },
2946            GitReference {
2947                reference: "refs/tags/other-v0.3.4".into(),
2948            },
2949        ];
2950        assert!(tag_published(&refs, "rpi-todo", "0.3.4"));
2951        assert!(tag_published(&refs, "rpi-todo", "0.3.10"));
2952        assert!(!tag_published(&refs, "rpi-todo", "0.3"));
2953        assert!(!tag_published(&refs, "other", "0.3.10"));
2954        assert!(!tag_published(&[], "rpi-todo", "0.3.4"));
2955    }
2956
2957    #[test]
2958    fn released_assets_are_accepted_across_a_repository_move() {
2959        validate_release_asset_url(
2960            "https://github.com/pi-rust/rpi-package/releases/download/rpi-todo-v1.2.3/rpi-todo.zip",
2961            "https://github.com/pi-rust/rpi-extension",
2962            "rpi-todo-v1.2.3",
2963        )
2964        .unwrap();
2965        // A different publisher is still rejected.
2966        assert!(validate_release_asset_url(
2967            "https://github.com/publisher/monorepo/releases/download/rpi-todo-v1.2.3/rpi-todo.zip",
2968            "https://github.com/pi-rust/rpi-extension",
2969            "rpi-todo-v1.2.3",
2970        )
2971        .is_err());
2972    }
2973
2974    async fn version_for(
2975        responses: Vec<(&'static str, Vec<u8>)>,
2976        legacy: bool,
2977    ) -> ((String, String), Vec<String>) {
2978        let (api, server) = sequenced_responses(responses);
2979        let client = reqwest::Client::builder().no_proxy().build().unwrap();
2980        let repository = if legacy {
2981            "https://github.com/pi-rust/rpi-package"
2982        } else {
2983            "https://github.com/pi-rust/rpi-extension"
2984        };
2985        let resolved = repository_version(&client, &api, "rpi-todo", repository)
2986            .await
2987            .map(|resolved| (resolved, server.join().unwrap()));
2988        match resolved {
2989            Ok(result) => result,
2990            Err(error) => panic!("{error}"),
2991        }
2992    }
2993
2994    #[tokio::test]
2995    async fn upgrade_detection_follows_a_moved_repository() {
2996        let previous =
2997            serde_json::to_vec(&serde_json::json!([{"ref":"refs/tags/rpi-todo-v0.1.0"}])).unwrap();
2998        let current =
2999            serde_json::to_vec(&serde_json::json!([{"ref":"refs/tags/rpi-todo-v0.2.0"}])).unwrap();
3000        let (resolved, requests) =
3001            version_for(vec![("200 OK", previous), ("200 OK", current)], true).await;
3002        assert_eq!(
3003            resolved,
3004            (
3005                "0.2.0".to_string(),
3006                "https://github.com/pi-rust/rpi-extension".to_string()
3007            )
3008        );
3009        assert!(requests[0]
3010            .starts_with("GET /repos/pi-rust/rpi-package/git/matching-refs/tags/rpi-todo-v "));
3011        assert!(requests[1]
3012            .starts_with("GET /repos/pi-rust/rpi-extension/git/matching-refs/tags/rpi-todo-v "));
3013    }
3014
3015    #[tokio::test]
3016    async fn releases_present_in_both_locations_record_the_current_home() {
3017        let previous =
3018            serde_json::to_vec(&serde_json::json!([{"ref":"refs/tags/rpi-todo-v0.3.4"}])).unwrap();
3019        let current =
3020            serde_json::to_vec(&serde_json::json!([{"ref":"refs/tags/rpi-todo-v0.3.4"}])).unwrap();
3021        let (resolved, _) =
3022            version_for(vec![("200 OK", previous), ("200 OK", current)], true).await;
3023        assert_eq!(
3024            resolved,
3025            (
3026                "0.3.4".to_string(),
3027                "https://github.com/pi-rust/rpi-extension".to_string()
3028            )
3029        );
3030    }
3031
3032    #[tokio::test]
3033    async fn versions_only_the_previous_location_published_stay_installable() {
3034        let previous =
3035            serde_json::to_vec(&serde_json::json!([{"ref":"refs/tags/rpi-todo-v0.3.0"}])).unwrap();
3036        let current =
3037            serde_json::to_vec(&serde_json::json!([{"ref":"refs/tags/rpi-todo-v0.2.0"}])).unwrap();
3038        let (resolved, _) =
3039            version_for(vec![("200 OK", previous), ("200 OK", current)], true).await;
3040        assert_eq!(
3041            resolved,
3042            (
3043                "0.3.0".to_string(),
3044                "https://github.com/pi-rust/rpi-package".to_string()
3045            )
3046        );
3047    }
3048
3049    #[tokio::test]
3050    async fn upgrade_detection_survives_a_retired_previous_location() {
3051        let current =
3052            serde_json::to_vec(&serde_json::json!([{"ref":"refs/tags/rpi-todo-v0.3.4"}])).unwrap();
3053        let (resolved, _) = version_for(
3054            vec![("404 Not Found", Vec::new()), ("200 OK", current)],
3055            true,
3056        )
3057        .await;
3058        assert_eq!(
3059            resolved,
3060            (
3061                "0.3.4".to_string(),
3062                "https://github.com/pi-rust/rpi-extension".to_string()
3063            )
3064        );
3065    }
3066
3067    #[tokio::test]
3068    async fn a_repository_without_a_move_is_queried_once() {
3069        let tags =
3070            serde_json::to_vec(&serde_json::json!([{"ref":"refs/tags/rpi-todo-v0.1.0"}])).unwrap();
3071        let (resolved, requests) = version_for(vec![("200 OK", tags)], false).await;
3072        assert_eq!(
3073            resolved,
3074            (
3075                "0.1.0".to_string(),
3076                "https://github.com/pi-rust/rpi-extension".to_string()
3077            )
3078        );
3079        assert_eq!(requests.len(), 1);
3080    }
3081
3082    #[tokio::test]
3083    async fn auto_install_distinguishes_an_absent_crate_from_registry_failure() {
3084        let client = reqwest::Client::builder().no_proxy().build().unwrap();
3085        for status in [
3086            "404 Not Found",
3087            "403 Forbidden",
3088            "429 Too Many Requests",
3089            "503 Service Unavailable",
3090        ] {
3091            let attempts = if status.starts_with("429") || status.starts_with("503") {
3092                3
3093            } else {
3094                1
3095            };
3096            let (url, server) = sequenced_responses(vec![(status, Vec::new()); attempts]);
3097            let result = probe_registry_install(&client, &url, "demo", None).await;
3098            server.join().unwrap();
3099            if status.starts_with("404") {
3100                assert!(result.unwrap().is_none());
3101            } else {
3102                assert!(result.err().unwrap().contains(&status[..3]));
3103            }
3104        }
3105    }
3106
3107    #[tokio::test]
3108    async fn auto_install_ignores_crates_without_a_supported_release_repository() {
3109        let client = reqwest::Client::builder().no_proxy().build().unwrap();
3110        for (repository, explicit_error) in [
3111            (None, "crate has no repository metadata"),
3112            (
3113                Some("https://gitlab.example.test/team/demo"),
3114                "prebuilt repository must be an HTTPS GitHub repository",
3115            ),
3116        ] {
3117            let metadata = serde_json::to_vec(&serde_json::json!({
3118                "crate": {"id": "demo", "repository": repository},
3119                "versions": [{"num": "1.0.0", "yanked": false}]
3120            }))
3121            .unwrap();
3122            let (url, server) = one_response(metadata.clone());
3123            let result = probe_registry_install(&client, &url, "demo", None).await;
3124            server.join().unwrap();
3125            assert!(result.unwrap().is_none(), "{repository:?}");
3126
3127            let (url, server) = one_response(metadata);
3128            let explicit = resolve_package(&client, &url, "demo", None, None).await;
3129            server.join().unwrap();
3130            assert!(explicit.err().unwrap().contains(explicit_error));
3131        }
3132    }
3133
3134    #[tokio::test]
3135    async fn registry_discovery_uses_repository_metadata_and_downloads_are_bounded() {
3136        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();
3137        let (url, server) = one_response(payload);
3138        let client = reqwest::Client::builder().no_proxy().build().unwrap();
3139        let package = resolve_package(&client, &url, "independent-plugin", None, None)
3140            .await
3141            .unwrap();
3142        assert_eq!(package.repository, "https://github.com/publisher/monorepo");
3143        assert_eq!(package.version, "1.2.3");
3144        assert!(server
3145            .join()
3146            .unwrap()
3147            .starts_with("GET /independent-plugin "));
3148        let (url, server) = one_response(vec![0u8; 32]);
3149        let response = client.get(url).send().await.unwrap();
3150        assert!(body_limited(response, 8).await.is_err());
3151        server.join().unwrap();
3152    }
3153}