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