1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
use base64::Engine;
use base64::prelude::BASE64_STANDARD;
use starbase_sandbox::{Sandbox, create_empty_sandbox, locate_fixture};
use starbase_utils::fs;
use std::path::PathBuf;
use std::time::Duration;
use warpgate::{
DataLocator, FileLocator, GitHubLocator, Id, PluginLoader, PluginLocator, RegistryConfig,
RegistryLocator, UrlLocator, hash_sha256,
};
// A pinned, stable .wasm release to use across URL-based tests.
const SYSTEM_TOOLCHAIN_URL: &str = "https://github.com/moonrepo/plugins/releases/download/system_toolchain-v1.0.0/system_toolchain.wasm";
fn create_loader() -> (Sandbox, PluginLoader) {
let sandbox = create_empty_sandbox();
let loader = PluginLoader::new(sandbox.path().join("plugins"), sandbox.path().join("temp"));
(sandbox, loader)
}
fn create_loader_with_registries(registries: Vec<RegistryConfig>) -> (Sandbox, PluginLoader) {
let (sandbox, mut loader) = create_loader();
loader.add_registries(registries);
(sandbox, loader)
}
// Returns the expected cache path for a URL download with id="test".
fn url_cache_path(loader: &PluginLoader, url: &str) -> PathBuf {
loader.create_cache_path(&Id::raw("test"), &hash_sha256(url), "wasm", false)
}
mod loader {
use super::*;
// -------------------------------------------------------------------------
// Data / blob locator
// -------------------------------------------------------------------------
mod data {
use super::*;
fn make_locator(wasm: &[u8]) -> PluginLocator {
PluginLocator::Data(Box::new(DataLocator {
data: format!("data://{}", BASE64_STANDARD.encode(wasm)),
bytes: None,
}))
}
#[tokio::test]
async fn decodes_bytes() {
let (sandbox, loader) = create_loader();
let fixture = locate_fixture("loader");
let wasm = fs::read_file_bytes(fixture.join("test.wasm")).unwrap();
let path = loader
.load_plugin(Id::raw("test"), make_locator(&wasm))
.await
.unwrap();
assert_eq!(
path,
sandbox.path().join(
"plugins/test-fb04dcb6970e4c3d1873de51fd5a50d7bb46b3383113602665c350ec40b5f990.wasm"
)
);
}
// Second call with identical blob data must return the same path from
// cache without re-writing the file (modification time stays the same).
#[tokio::test]
async fn uses_cache_on_second_call() {
let (_sandbox, loader) = create_loader();
let fixture = locate_fixture("loader");
let wasm = fs::read_file_bytes(fixture.join("test.wasm")).unwrap();
let path1 = loader
.load_plugin(Id::raw("test"), make_locator(&wasm))
.await
.unwrap();
assert!(path1.exists());
let mtime1 = path1.metadata().unwrap().modified().unwrap();
let path2 = loader
.load_plugin(Id::raw("test"), make_locator(&wasm))
.await
.unwrap();
assert_eq!(path1, path2);
let mtime2 = path2.metadata().unwrap().modified().unwrap();
assert_eq!(mtime1, mtime2);
}
// Concurrent calls with the same blob data must all resolve to the same
// path without errors, and the in-process lock must prevent duplicate writes.
#[tokio::test]
async fn concurrent_calls_return_same_path() {
let (_sandbox, loader) = create_loader();
let fixture = locate_fixture("loader");
let wasm = fs::read_file_bytes(fixture.join("test.wasm")).unwrap();
let (r1, r2, r3) = tokio::join!(
loader.load_plugin(Id::raw("test"), make_locator(&wasm)),
loader.load_plugin(Id::raw("test"), make_locator(&wasm)),
loader.load_plugin(Id::raw("test"), make_locator(&wasm)),
);
let path1 = r1.unwrap();
let path2 = r2.unwrap();
let path3 = r3.unwrap();
assert!(path1.exists());
assert_eq!(path1, path2);
assert_eq!(path1, path3);
}
}
// -------------------------------------------------------------------------
// File locator
// -------------------------------------------------------------------------
mod source_file {
use super::*;
#[tokio::test]
#[should_panic(expected = "MissingSourceFile")]
async fn errors_missing_file() {
let (_sandbox, loader) = create_loader();
loader
.load_plugin(
Id::raw("test"),
PluginLocator::File(Box::new(FileLocator {
file: "".into(),
path: Some(PathBuf::from("fake-file")),
})),
)
.await
.unwrap();
}
#[tokio::test]
async fn returns_path_asis() {
let (_sandbox, loader) = create_loader();
let fixture = locate_fixture("loader");
let path = loader
.load_plugin(
Id::raw("test"),
PluginLocator::File(Box::new(FileLocator {
file: "".into(),
path: Some(fixture.join("test.wasm")),
})),
)
.await
.unwrap();
assert_eq!(path, fixture.join("test.wasm"));
}
}
// -------------------------------------------------------------------------
// URL locator
// -------------------------------------------------------------------------
mod source_url {
use super::*;
fn make_locator(url: &str) -> PluginLocator {
PluginLocator::Url(Box::new(UrlLocator { url: url.into() }))
}
// -- Error cases ------------------------------------------------------
#[tokio::test]
#[should_panic(expected = "NotFound")]
async fn errors_broken_url() {
let (_sandbox, loader) = create_loader();
loader
.load_plugin(
Id::raw("test"),
make_locator("https://github.com/moonrepo/deno-plugin/releases/download/v0.0.2/deno_plugin_invalid_name.wasm"),
)
.await
.unwrap();
}
// When offline and the plugin is not yet cached, load_plugin must fail
// with a RequiredInternetConnection error rather than hanging or panicking.
#[tokio::test]
#[should_panic(expected = "RequiredInternetConnection")]
async fn offline_errors_when_no_cache() {
let (_sandbox, mut loader) = create_loader();
loader.set_offline_checker(|| true);
loader
.load_plugin(Id::raw("test"), make_locator(SYSTEM_TOOLCHAIN_URL))
.await
.unwrap();
}
// -- Download basics --------------------------------------------------
#[tokio::test]
async fn downloads_to_plugins() {
let (sandbox, loader) = create_loader();
let path = loader
.load_plugin(
Id::raw("test"),
make_locator("https://github.com/moonrepo/deno-plugin/releases/download/v0.0.2/deno_plugin.wasm"),
)
.await
.unwrap();
assert_eq!(
path,
sandbox.path().join(
"plugins/test-bf1e7cdc7ca22a4b75e10560bfce659bd51125f2e64bad2143633d20e30e9e01.wasm"
)
);
}
#[tokio::test]
async fn supports_latest() {
let (sandbox, loader) = create_loader();
let path = loader
.load_plugin(
Id::raw("test"),
make_locator("https://github.com/moonrepo/deno-plugin/releases/latest/download/deno_plugin.wasm"),
)
.await
.unwrap();
assert_eq!(
path,
sandbox.path().join(
"plugins/test-latest-07bced931a4b253ba3da8836c0510275512ce09436c63ed44b77b3683effae91.wasm"
)
);
}
// Downloaded file must be a valid, non-empty .wasm binary.
#[tokio::test]
async fn downloads_valid_wasm() {
let (_sandbox, loader) = create_loader();
let path = loader
.load_plugin(Id::raw("test"), make_locator(SYSTEM_TOOLCHAIN_URL))
.await
.unwrap();
assert!(path.exists());
assert!(path.extension().is_some_and(|e| e == "wasm"));
let bytes = fs::read_file_bytes(&path).unwrap();
// All WASM binaries begin with the 4-byte magic header `\0asm`.
assert!(bytes.starts_with(b"\0asm"));
}
// -- Cache behaviour --------------------------------------------------
// The second call with the same URL must return the same path from the
// local cache without triggering a network request (modification time
// must be unchanged).
#[tokio::test]
async fn uses_cache_on_second_call() {
let (_sandbox, loader) = create_loader();
let path1 = loader
.load_plugin(Id::raw("test"), make_locator(SYSTEM_TOOLCHAIN_URL))
.await
.unwrap();
assert!(path1.exists());
let mtime1 = path1.metadata().unwrap().modified().unwrap();
let path2 = loader
.load_plugin(Id::raw("test"), make_locator(SYSTEM_TOOLCHAIN_URL))
.await
.unwrap();
assert_eq!(path1, path2);
let mtime2 = path2.metadata().unwrap().modified().unwrap();
assert_eq!(mtime1, mtime2);
}
// With zero cache duration the loader treats any cached file as stale
// and calls download_plugin. However, when offline the stale file must
// still be returned rather than failing.
#[tokio::test]
async fn offline_uses_stale_cache() {
let (sandbox, mut loader) = create_loader();
// Pre-create the cache file to simulate a previous download.
let cache_path = url_cache_path(&loader, SYSTEM_TOOLCHAIN_URL);
fs::create_dir_all(sandbox.path().join("plugins")).unwrap();
fs::write_file(&cache_path, b"\0asm fake cached wasm").unwrap();
// Zero duration means the file is always "stale" when online,
// but the offline override should rescue it.
loader.set_cache_duration(Duration::ZERO);
loader.set_offline_checker(|| true);
let path = loader
.load_plugin(Id::raw("test"), make_locator(SYSTEM_TOOLCHAIN_URL))
.await
.unwrap();
assert_eq!(path, cache_path);
}
// -- In-process locking behaviour -------------------------------------
// When multiple async tasks concurrently request the same URL, they
// must all receive the same valid path, and only one actual download
// should be triggered (the rest skip via the in-process Mutex).
#[tokio::test]
async fn concurrent_calls_return_same_path() {
let (_sandbox, loader) = create_loader();
let (r1, r2, r3) = tokio::join!(
loader.load_plugin(Id::raw("test"), make_locator(SYSTEM_TOOLCHAIN_URL)),
loader.load_plugin(Id::raw("test"), make_locator(SYSTEM_TOOLCHAIN_URL)),
loader.load_plugin(Id::raw("test"), make_locator(SYSTEM_TOOLCHAIN_URL)),
);
let path1 = r1.unwrap();
let path2 = r2.unwrap();
let path3 = r3.unwrap();
assert!(path1.exists());
assert_eq!(path1, path2);
assert_eq!(path1, path3);
}
// If a competing process (or prior call) already wrote the destination
// file between the outer is_cached check and the inner lock acquisition,
// download_plugin must exit early without overwriting or re-downloading.
// We simulate this by pre-populating dest_file and forcing a zero cache
// duration so that is_cached → false and download_plugin is entered.
#[tokio::test]
async fn skips_download_when_dest_exists_after_acquiring_lock() {
let (sandbox, mut loader) = create_loader();
let cache_path = url_cache_path(&loader, SYSTEM_TOOLCHAIN_URL);
fs::create_dir_all(sandbox.path().join("plugins")).unwrap();
// Write a sentinel payload — a real download would overwrite this
// with the actual WASM binary.
let sentinel = b"sentinel - should not be overwritten";
fs::write_file(&cache_path, sentinel).unwrap();
// Zero duration bypasses is_cached so download_plugin is invoked,
// but it must see dest_file.exists() == true and return early.
loader.set_cache_duration(Duration::ZERO);
let path = loader
.load_plugin(Id::raw("test"), make_locator(SYSTEM_TOOLCHAIN_URL))
.await
.unwrap();
assert_eq!(path, cache_path);
let written = fs::read_file_bytes(&cache_path).unwrap();
assert_eq!(written, sentinel);
}
// After a successful download the per-URL temp file must be removed.
// The temp subdirectory (keyed by the URL hash) may remain but must
// contain no leftover files.
#[tokio::test]
async fn cleans_temp_file_after_download() {
let (sandbox, loader) = create_loader();
loader
.load_plugin(Id::raw("test"), make_locator(SYSTEM_TOOLCHAIN_URL))
.await
.unwrap();
let temp_url_dir = sandbox
.path()
.join("temp")
.join(hash_sha256(SYSTEM_TOOLCHAIN_URL));
if temp_url_dir.exists() {
let leftover: Vec<_> = temp_url_dir
.read_dir()
.unwrap()
.filter_map(|e| e.ok())
.collect();
assert!(
leftover.is_empty(),
"temp files were not cleaned up after download: {:?}",
leftover.iter().map(|e| e.path()).collect::<Vec<_>>()
);
}
}
}
// -------------------------------------------------------------------------
// GitHub locator
// -------------------------------------------------------------------------
mod github {
use super::*;
#[tokio::test]
#[should_panic(expected = "MissingGitHubAsset")]
async fn errors_invalid_slug() {
let (_sandbox, loader) = create_loader();
loader
.load_plugin(
Id::raw("test"),
PluginLocator::GitHub(Box::new(GitHubLocator {
repo_slug: "moonrepo/invalid-repo".into(),
tag: None,
project_name: None,
})),
)
.await
.unwrap();
}
#[tokio::test]
async fn downloads_to_plugins() {
let (sandbox, loader) = create_loader();
let path = loader
.load_plugin(
Id::raw("test"),
PluginLocator::GitHub(Box::new(GitHubLocator {
repo_slug: "moonrepo/bun-plugin".into(),
tag: Some("v0.0.3".into()),
project_name: None,
})),
)
.await
.unwrap();
assert_eq!(
path,
sandbox.path().join(
"plugins/test-d38b431dfda1d53f9d1bc97ea409a97dcaa03efa11a508d73f1f9497b9bcaa3a.wasm"
)
);
}
#[tokio::test]
async fn supports_latest() {
let (sandbox, loader) = create_loader();
let path = loader
.load_plugin(
Id::raw("test"),
PluginLocator::GitHub(Box::new(GitHubLocator {
repo_slug: "moonrepo/bun-plugin".into(),
tag: None,
project_name: None,
})),
)
.await
.unwrap();
assert_eq!(
path,
sandbox.path().join(
"plugins/test-latest-171d1fba97b9fe0489125b9253b8fdb8a85d37837f966aaacd06df662292f507.wasm"
)
);
}
}
// -------------------------------------------------------------------------
// Registry (OCI) locator
// -------------------------------------------------------------------------
mod registry {
use super::*;
// A pinned, anonymous-pullable image on GHCR. This is one of the
// built-in plugins shipped in `crates/core/src/config.rs`, so it must
// remain available for the project to function.
const FIXTURE_IMAGE: &str = "node_tool";
const FIXTURE_TAG: &str = "0.17.9";
const FIXTURE_HOST: &str = "ghcr.io";
const FIXTURE_NAMESPACE: &str = "moonrepo";
fn make_locator(
registry: Option<&str>,
namespace: Option<&str>,
image: &str,
tag: Option<&str>,
) -> PluginLocator {
PluginLocator::Registry(Box::new(RegistryLocator {
registry: registry.map(Into::into),
namespace: namespace.map(Into::into),
image: image.into(),
tag: tag.map(Into::into),
}))
}
fn assert_wasm(path: &std::path::Path) {
assert!(path.exists(), "expected plugin path to exist: {path:?}");
let bytes = fs::read_file_bytes(path).unwrap();
// All WASM binaries begin with the 4-byte magic header `\0asm`.
assert!(
bytes.starts_with(b"\0asm"),
"expected WASM magic header at {path:?}",
);
}
// -- Step 1: locator host matches a configured registry --------------
// When the locator's host AND namespace match a configured registry,
// pull_image is called with that config (fallthrough = true) and the
// blob is returned successfully.
#[tokio::test]
async fn matches_configured_registry() {
let (_sandbox, loader) = create_loader_with_registries(vec![RegistryConfig {
auth: false,
default: false,
registry: FIXTURE_HOST.into(),
namespace: Some(FIXTURE_NAMESPACE.into()),
}]);
let path = loader
.load_plugin(
Id::raw("test"),
make_locator(
Some(FIXTURE_HOST),
Some(FIXTURE_NAMESPACE),
FIXTURE_IMAGE,
Some(FIXTURE_TAG),
),
)
.await
.unwrap();
assert_wasm(&path);
}
// -- Step 2: locator host without a matching config ------------------
// When the locator has a host but no registry config matches, the
// loader synthesizes an explicit `RegistryConfig` (auth = true) and
// tries it. With an anonymous-pullable image, this still resolves.
#[tokio::test]
async fn explicit_host_no_matching_config_uses_explicit_fallback() {
let (_sandbox, loader) = create_loader_with_registries(vec![]);
let path = loader
.load_plugin(
Id::raw("test"),
make_locator(
Some(FIXTURE_HOST),
Some(FIXTURE_NAMESPACE),
FIXTURE_IMAGE,
Some(FIXTURE_TAG),
),
)
.await
.unwrap();
assert_wasm(&path);
}
// -- Step 3: locator without a host, iterate configured registries --
// With no host on the locator, Steps 1 & 2 are skipped and the final
// for-loop tries each configured registry.
#[tokio::test]
async fn no_host_iterates_configured_registries() {
let (_sandbox, loader) = create_loader_with_registries(vec![RegistryConfig {
auth: false,
default: false,
registry: FIXTURE_HOST.into(),
namespace: Some(FIXTURE_NAMESPACE.into()),
}]);
let path = loader
.load_plugin(
Id::raw("test"),
make_locator(None, None, FIXTURE_IMAGE, Some(FIXTURE_TAG)),
)
.await
.unwrap();
assert_wasm(&path);
}
// -- Step 4: error path (no host, no registries) ---------------------
// When the locator has no host and no registries are configured,
// both early branches are skipped and the final for-loop is empty,
// so the loader returns OCIReferenceError without making any network
// requests.
#[tokio::test]
#[should_panic(expected = "No valid registry or layer found for node_tool.")]
async fn no_registries_no_host_returns_oci_reference_error() {
let (_sandbox, loader) = create_loader_with_registries(vec![]);
loader
.load_plugin(
Id::raw("test"),
make_locator(None, None, FIXTURE_IMAGE, Some(FIXTURE_TAG)),
)
.await
.unwrap();
}
// -- Tag / cache behaviour -------------------------------------------
// A locator with no tag is treated as the `latest` tag, which is
// reflected in the cache path by the `-latest-` segment.
#[tokio::test]
async fn uses_latest_when_tag_is_none() {
let (sandbox, loader) = create_loader_with_registries(vec![]);
let path = loader
.load_plugin(
Id::raw("test"),
make_locator(
Some(FIXTURE_HOST),
Some(FIXTURE_NAMESPACE),
FIXTURE_IMAGE,
None,
),
)
.await
.unwrap();
assert!(path.exists());
let file_name = path.file_name().unwrap().to_string_lossy().to_string();
assert!(
file_name.contains("-latest-"),
"expected cache filename to include `-latest-`, got {file_name}"
);
assert!(path.starts_with(sandbox.path().join("plugins")));
}
// After a successful pull, a second call with the same locator must
// return the same path from cache without re-downloading (mtime is
// unchanged).
#[tokio::test]
async fn uses_cache_on_second_call() {
let (_sandbox, loader) = create_loader_with_registries(vec![RegistryConfig {
auth: false,
default: false,
registry: FIXTURE_HOST.into(),
namespace: Some(FIXTURE_NAMESPACE.into()),
}]);
let locator = make_locator(
Some(FIXTURE_HOST),
Some(FIXTURE_NAMESPACE),
FIXTURE_IMAGE,
Some(FIXTURE_TAG),
);
let path1 = loader
.load_plugin(Id::raw("test"), locator.clone())
.await
.unwrap();
assert!(path1.exists());
let mtime1 = path1.metadata().unwrap().modified().unwrap();
let path2 = loader.load_plugin(Id::raw("test"), locator).await.unwrap();
assert_eq!(path1, path2);
let mtime2 = path2.metadata().unwrap().modified().unwrap();
assert_eq!(mtime1, mtime2);
}
}
}