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