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