Skip to main content

rpi_cli/
prebuilt_extensions.rs

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