Skip to content

Commit cb35d5a

Browse files
committed
Respect scoped registries when resolving vlt lock nodes
1 parent 1bc4388 commit cb35d5a

4 files changed

Lines changed: 150 additions & 30 deletions

File tree

‎crates/socket-patch-core/src/patch/redirect/upstream/vlt.rs‎

Lines changed: 52 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ fn tarball_url(base: &str, name: &str, version: &str) -> String {
5252
fn records_url(
5353
era: DepIdEra,
5454
segment: &str,
55+
name: &str,
5556
siblings: &[(DepIdEra, bool)],
5657
options: Option<&Map<String, Value>>,
5758
) -> bool {
@@ -69,22 +70,26 @@ fn records_url(
6970
.and_then(|o| o.get("registries"))
7071
.is_some_and(Value::is_object)
7172
&& (segment.is_empty() || default_registry_alias(options) == Some(segment))
72-
&& !under_configured_registry(segment, options)
73+
&& !under_configured_registry(segment, name, options)
7374
}
7475

7576
/// Would a default-registry node on `segment` resolve under the lock's
7677
/// recorded `options.registry`? vlt omits slot [3] for such a node
7778
/// (`lockfile/save.ts`: `customRegistry = resolved && (!registry ||
7879
/// !resolved.startsWith(registry))`).
79-
fn under_configured_registry(segment: &str, options: Option<&Map<String, Value>>) -> bool {
80+
fn under_configured_registry(
81+
segment: &str,
82+
name: &str,
83+
options: Option<&Map<String, Value>>,
84+
) -> bool {
8085
let Some(registry) = options
8186
.and_then(|o| o.get("registry"))
8287
.and_then(Value::as_str)
8388
.filter(|r| !r.is_empty())
8489
else {
8590
return false;
8691
};
87-
registry_base(segment, options).is_some_and(|base| base.starts_with(registry))
92+
registry_base(segment, name, options).is_some_and(|base| base.starts_with(registry))
8893
}
8994

9095
pub(crate) async fn restore(
@@ -246,8 +251,8 @@ pub(crate) async fn restore(
246251
};
247252
let line = parse_node_line(lines[hit.line]).expect("the hit line parsed above");
248253
let json = |s: &str| serde_json::to_string(s).expect("a str serializes to JSON");
249-
let slot3 = if records_url(hit.era, &hit.segment, &siblings, options) {
250-
let Some(base) = registry_base(&hit.segment, options) else {
254+
let slot3 = if records_url(hit.era, &hit.segment, &hit.name, &siblings, options) {
255+
let Some(base) = registry_base(&hit.segment, &hit.name, options) else {
251256
result.refuse(
252257
&hit.uuid,
253258
format!("{rel} maps no registry for the `{}` segment", hit.segment),
@@ -323,49 +328,54 @@ mod tests {
323328
assert!(!records_url(
324329
DepIdEra::Tilde,
325330
"npm",
331+
"left-pad",
326332
&[(DepIdEra::Tilde, false)],
327333
Some(&with_registries)
328334
));
329335
assert!(records_url(
330336
DepIdEra::Tilde,
331337
"npm",
338+
"left-pad",
332339
&[(DepIdEra::Tilde, true)],
333340
None
334341
));
335342
// Another era's siblings do not.
336343
assert!(!records_url(
337344
DepIdEra::Legacy,
338345
"npm",
346+
"left-pad",
339347
&[(DepIdEra::Tilde, true)],
340348
Some(&with_registries)
341349
));
342350
// No siblings: the rc.33+ writer records `registries`.
343351
assert!(records_url(
344352
DepIdEra::Tilde,
345353
"npm",
354+
"left-pad",
346355
&[],
347356
Some(&with_registries)
348357
));
349-
assert!(!records_url(DepIdEra::Tilde, "npm", &[], None));
358+
assert!(!records_url(DepIdEra::Tilde, "npm", "left-pad", &[], None));
350359
assert!(!records_url(
351360
DepIdEra::Tilde,
352361
"https://registry.example.com/",
362+
"left-pad",
353363
&[],
354364
Some(&with_registries)
355365
));
356366
let alias = opts(r#"{"default-registry-alias":"corp","registries":{"corp":"https://c/"}}"#);
357-
assert!(records_url(DepIdEra::Tilde, "corp", &[], Some(&alias)));
367+
assert!(records_url(DepIdEra::Tilde, "corp", "left-pad", &[], Some(&alias)));
358368
// A recorded `registry` the node resolves under: vlt (rc.33 … 1.2.0
359369
// with `config.registry`) writes no slot [3].
360370
let configured = opts(
361371
r#"{"registry":"http://127.0.0.1:4873/","registries":{"npm":"http://127.0.0.1:4873/"}}"#,
362372
);
363-
assert!(!records_url(DepIdEra::Tilde, "npm", &[], Some(&configured)));
373+
assert!(!records_url(DepIdEra::Tilde, "npm", "left-pad", &[], Some(&configured)));
364374
// ...but a node on another registry than the configured one does.
365375
let elsewhere = opts(
366376
r#"{"registry":"https://registry.npmjs.org/","registries":{"npm":"http://127.0.0.1:4873/"}}"#,
367377
);
368-
assert!(records_url(DepIdEra::Tilde, "npm", &[], Some(&elsewhere)));
378+
assert!(records_url(DepIdEra::Tilde, "npm", "left-pad", &[], Some(&elsewhere)));
369379
}
370380

371381
use super::super::{restore_upstream, RestoreOptions, RestoreOutcome};
@@ -412,7 +422,7 @@ mod tests {
412422
dist["integrity"] = (*i).into();
413423
}
414424
Mock::given(method("GET"))
415-
.and(path(format!("/{name}/{version}")))
425+
.and(path(format!("/{}/{version}", name.replace('/', "%2f"))))
416426
.respond_with(
417427
ResponseTemplate::new(200).set_body_json(serde_json::json!({ "dist": dist })),
418428
)
@@ -530,6 +540,38 @@ mod tests {
530540
std::env::remove_var("SOCKET_NPM_REGISTRY");
531541
}
532542

543+
#[tokio::test]
544+
#[serial_test::serial]
545+
async fn restore_honors_scope_for_slot3_and_configured_registry_omission() {
546+
use crate::vendor::vlt_lock_text::SCOPED_REGISTRY_OPTIONS;
547+
let server = registry(&[("@s/a", "1.0.0", Some(LP_UPSTREAM))]).await;
548+
std::env::set_var("SOCKET_NPM_REGISTRY", server.uri());
549+
let url = hosted(LP_UUID, "a-1.0.0.tgz");
550+
for records_url in [false, true] {
551+
let sibling = if records_url {
552+
",\n \"~npm~ms@2.1.3\": [0,\"ms\",\"sha512-M==\",\"https://b.example/ms/-/ms-2.1.3.tgz\"]"
553+
} else {
554+
""
555+
};
556+
let text = format!(
557+
"{{\n \"lockfileVersion\": 1,\n \"options\": {SCOPED_REGISTRY_OPTIONS},\n \"nodes\": {{\n \"~npm~@s+a@1.0.0\": [0,\"@s/a\",\"sha512-AA==\",\"{url}\"]{sibling}\n }},\n \"edges\": {{}}\n}}\n"
558+
);
559+
let (outcome, after) =
560+
run(&text, &[pin("pkg:npm/@s/a@1.0.0", LP_UUID)], false).await;
561+
assert!(refused(&outcome).is_empty(), "{:?}", refused(&outcome));
562+
let after: Value = serde_json::from_str(&after).unwrap();
563+
let expected = if records_url {
564+
serde_json::json!([0, "@s/a", LP_UPSTREAM, "https://a.example/@s/a/-/a-1.0.0.tgz"])
565+
} else {
566+
// The scoped URL is under options.registry, even though
567+
// registries.npm names a different base: vlt omits slot 3.
568+
serde_json::json!([0, "@s/a", LP_UPSTREAM])
569+
};
570+
assert_eq!(after["nodes"]["~npm~@s+a@1.0.0"], expected);
571+
}
572+
std::env::remove_var("SOCKET_NPM_REGISTRY");
573+
}
574+
533575
#[tokio::test]
534576
#[serial_test::serial]
535577
async fn missing_registry_integrity_refuses() {

‎crates/socket-patch-core/src/vendor/lock_inventory/tests.rs‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2725,6 +2725,33 @@ async fn vlt_inventory_resolves_registries_through_the_shared_registry_base() {
27252725
}
27262726
}
27272727

2728+
#[tokio::test]
2729+
async fn vlt_inventory_honors_scope_for_named_and_url_registry_segments() {
2730+
use crate::vendor::vlt_lock_text::{
2731+
encode_segment, DepIdEra, SCOPED_REGISTRY_OPTIONS,
2732+
};
2733+
for segment in ["npm", "corp", "https://explicit.example/npm"] {
2734+
let tmp = tempfile::tempdir().unwrap();
2735+
let node = format!(
2736+
r#""~{}~@s+a@1.0.0": [0,"@s/a","sha512-a=="]"#,
2737+
encode_segment(segment, DepIdEra::Tilde)
2738+
);
2739+
write(
2740+
tmp.path(),
2741+
"vlt-lock.json",
2742+
&vlt_lock(SCOPED_REGISTRY_OPTIONS, &[&node]),
2743+
)
2744+
.await;
2745+
let entries = inventory_vlt(tmp.path()).await.unwrap();
2746+
assert_eq!(entries.len(), 1, "{segment}");
2747+
assert_eq!(
2748+
entries[0].resolved.as_deref(),
2749+
Some("https://a.example/@s/a/-/a-1.0.0.tgz"),
2750+
"{segment}"
2751+
);
2752+
}
2753+
}
2754+
27282755
#[tokio::test]
27292756
async fn unreadable_vlt_locks_inventory_to_nothing() {
27302757
let good = vlt_lock("{}", &[r#""~npm~a@1.0.0": [0,"a","sha512-a=="]"#]);

‎crates/socket-patch-core/src/vendor/lock_inventory/vlt.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ pub(crate) fn vlt_registry_entries(lock: &VltLock) -> Vec<LockfileEntry> {
106106
return None;
107107
}
108108
let resolved = node.location.as_deref().and_then(http_url).or_else(|| {
109-
registry_base(&node.dep_id.first, options)
109+
registry_base(&node.dep_id.first, name, options)
110110
.map(|base| npm_tarball_url(base.trim_end_matches('/'), name, version))
111111
});
112112
let integrity = node

‎crates/socket-patch-core/src/vendor/vlt_lock_text.rs‎

Lines changed: 70 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -442,16 +442,24 @@ pub(crate) fn default_registry_alias(options: Option<&Map<String, Value>>) -> Op
442442
}
443443

444444
/// The registry base URL (with a trailing `/`) a decoded DepID registry
445-
/// segment names, given the lock's `options`, as vlt hydrates the DepID
445+
/// segment names for `name`, given the lock's `options`, as vlt hydrates the DepID
446446
/// (`@vltpkg/dep-id` `hydrateTuple`, `@vltpkg/spec`):
447+
/// First resolve the segment's base:
447448
/// - an http(s) URL segment is its own base;
448449
/// - a named segment is its `options.registries` URL when the lock maps it;
449450
/// - the empty segment, and an unmapped segment that still names the
450451
/// default registry ([`is_default_registry`]), is `options.registry`,
451452
/// else the default alias's `options.registries` URL, else the public
452453
/// npm registry (`registry ?? registries[default-registry-alias]`);
453454
/// - any other segment is `None`: the lock names an alias it never maps.
454-
pub(crate) fn registry_base(segment: &str, options: Option<&Map<String, Value>>) -> Option<String> {
455+
/// Once the segment resolves, a configured scope registry takes precedence,
456+
/// including in a named/URL registry spec's final subspec. Unknown aliases
457+
/// still fail before scope lookup, as `hydrateTuple` does.
458+
pub(crate) fn registry_base(
459+
segment: &str,
460+
name: &str,
461+
options: Option<&Map<String, Value>>,
462+
) -> Option<String> {
455463
let string = |value: Option<&Value>| {
456464
value
457465
.and_then(Value::as_str)
@@ -465,21 +473,32 @@ pub(crate) fn registry_base(segment: &str, options: Option<&Map<String, Value>>)
465473
.and_then(|r| r.get(alias)),
466474
)
467475
};
468-
if reqwest::Url::parse(segment).is_ok_and(|url| matches!(url.scheme(), "http" | "https")) {
469-
return Some(with_trailing_slash(segment));
470-
}
471-
if let Some(base) = Some(segment).filter(|s| !s.is_empty()).and_then(alias_url) {
472-
return Some(base);
473-
}
474-
if !is_default_registry(segment, options) {
476+
let base = if reqwest::Url::parse(segment)
477+
.is_ok_and(|url| matches!(url.scheme(), "http" | "https"))
478+
{
479+
with_trailing_slash(segment)
480+
} else if let Some(base) = Some(segment).filter(|s| !s.is_empty()).and_then(alias_url) {
481+
base
482+
} else if is_default_registry(segment, options) {
483+
string(options.and_then(|o| o.get("registry")))
484+
.or_else(|| default_registry_alias(options).and_then(alias_url))
485+
.unwrap_or_else(|| {
486+
with_trailing_slash(crate::vendor::registry_fetch::DEFAULT_NPM_REGISTRY)
487+
})
488+
} else {
475489
return None;
476-
}
477-
let base = string(options.and_then(|o| o.get("registry")))
478-
.or_else(|| default_registry_alias(options).and_then(alias_url))
479-
.unwrap_or_else(|| {
480-
with_trailing_slash(crate::vendor::registry_fetch::DEFAULT_NPM_REGISTRY)
481-
});
482-
Some(base)
490+
};
491+
name.split_once('/')
492+
.map(|(scope, _)| scope)
493+
.filter(|scope| scope.starts_with('@'))
494+
.and_then(|scope| {
495+
string(
496+
options
497+
.and_then(|o| o.get("scoped-registries"))
498+
.and_then(|registries| registries.get(scope)),
499+
)
500+
})
501+
.or(Some(base))
483502
}
484503

485504
/// Is `segment` an http(s) URL naming `options.registry` (a trailing `/`
@@ -542,6 +561,12 @@ pub(crate) const REGISTRY_BASE_CASES: &[(&str, &str, Option<&str>)] = &[
542561
("https://u.example", "{}", Some("https://u.example/")),
543562
];
544563

564+
/// @vltpkg/spec + dep-id 1.3.5 produce `~npm~@s+a@1.0.0` for
565+
/// `@s/a@npm:@s/a@1.0.0` under these options. Its final registry is `a`,
566+
/// while an unscoped `npm:` package uses `b`.
567+
#[cfg(test)]
568+
pub(crate) const SCOPED_REGISTRY_OPTIONS: &str = r#"{"registry":"https://a.example/","registries":{"npm":"https://b.example/","corp":"https://corp.example/"},"scoped-registries":{"@s":"https://a.example/"}}"#;
569+
545570
// ── lock-level sniff ─────────────────────────────────────────────────────
546571

547572
/// A `vlt-lock.json` that parsed as a JSON object with a known version.
@@ -1773,16 +1798,42 @@ mod tests {
17731798
for (segment, opts, want) in REGISTRY_BASE_CASES {
17741799
let opts = options(opts);
17751800
assert_eq!(
1776-
registry_base(segment, Some(&opts)).as_deref(),
1801+
registry_base(segment, "left-pad", Some(&opts)).as_deref(),
17771802
*want,
17781803
"{segment:?} with {opts:?}"
17791804
);
17801805
}
17811806
assert_eq!(
1782-
registry_base("npm", None).as_deref(),
1807+
registry_base("npm", "left-pad", None).as_deref(),
17831808
Some("https://registry.npmjs.org/")
17841809
);
1785-
assert_eq!(registry_base("corp", None), None);
1810+
assert_eq!(registry_base("corp", "left-pad", None), None);
1811+
}
1812+
1813+
#[test]
1814+
fn registry_base_applies_scope_after_resolving_the_segment() {
1815+
let opts = options(SCOPED_REGISTRY_OPTIONS);
1816+
for (segment, unscoped) in [
1817+
("", "https://a.example/"),
1818+
("npm", "https://b.example/"),
1819+
("corp", "https://corp.example/"),
1820+
("https://explicit.example/npm", "https://explicit.example/npm/"),
1821+
] {
1822+
assert_eq!(
1823+
registry_base(segment, "@s/a", Some(&opts)).as_deref(),
1824+
Some("https://a.example/"),
1825+
"{segment}"
1826+
);
1827+
for name in ["a", "@other/a"] {
1828+
assert_eq!(
1829+
registry_base(segment, name, Some(&opts)).as_deref(),
1830+
Some(unscoped),
1831+
"{segment}: {name}"
1832+
);
1833+
}
1834+
}
1835+
// A scope mapping must not make an unknown registry alias valid.
1836+
assert_eq!(registry_base("unmapped", "@s/a", Some(&opts)), None);
17861837
}
17871838

17881839
fn readable(text: &str) -> ParsedLock {

0 commit comments

Comments
 (0)