Skip to content

Commit 1dd12bd

Browse files
authored
feat(pnpr): make resolver cache authorization-aware (#12700)
Make the pnpr resolver cache authorization-aware and route private dependencies through per-uplink registry endpoints. Add route classification at the single fetch/auth-selection point: pnpr selects its own server-owned upstream credentials instead of forwarding client upstream auth, records a per-resolve footprint, and rejects inline URL credentials. A uplinks: entry that declares an access: policy becomes the private-route credential (folding in the former upstreamAliases block), matched by registry origin and exposed as a read-only registry endpoint at /~<uplink>/. access reuses bearer-token-backed pnpr identities, package access policy, and static groups; a SHA-256 digest of the uplink's credential participates in the footprint, so rotating the upstream credential automatically moves new resolves to a fresh namespace. The credential is attached only over a matching scheme (no token over plain http). Gate every server-side fetch behind a default-deny allowlist (built-in npm host, public routes, configured uplinks and their /~<uplink>/ endpoints, and pnpr itself). A registry/namedRegistries matching none is rejected at the request boundary, closing the resolver's SSRF surface at the source and superseding the link-local denylist. The boundary also covers direct-URL (http(s)/git, incl. scp-style) dependency specs, overrides, and lockfile tarballs; a `..` path segment is rejected; and the same allowlist re-validates every redirect hop. The official npm registry is a built-in host-level public route (scoped names included), so the npmjsPublic toggle is gone. With no off-allowlist route to resolve, every route is public or carries a private descriptor: RouteClass::Unknown, the non-shareable footprint tier, and the MetadataCacheScope::Bypass tier are removed. Transitive deps fetched during the tree walk are a connect-time-guard follow-up (#12705). Route resolver tarball URLs through those endpoints. A proxied route emits its /~<uplink>/ endpoint URL; public routes keep their upstream URL (fetched directly from the registry/CDN); pnpr-hosted packages use pnpr-hosted URLs. An endpoint URL is canonical for a client whose scope points there, so the lockfile entry stays integrity-only and the host comes from the client's registry config rather than the lockfile — a project resolves to the same lockfile through /resolve or a direct/proxied install. verification_lockfile reverses endpoint URLs to upstream for input-lockfile verification, and classification recognizes pnpr's own /~<uplink>/ URLs. The opaque per-tarball gateway scheme and its in-memory key->URL map are removed. Serve each access-bearing uplink as a /~<uplink>/ registry endpoint (packument + tarball, gated by the uplink access policy) with a private cache namespaced by an HMAC of (uplink, credential), so a private install caches like a public one, a rotation re-keys automatically, and a private uplink's content never lands in the shared mirror. Store bounded candidate lists under an auth-excluded base key instead of a single lockfile. Public candidates match every caller; private candidates carry the footprint and descriptor HMAC and are reused only when the caller still satisfies the stored uplink-or-hosted gates. Compute the base key for both no-lockfile and lockfile-seeded requests, using hash_lockfile() for input lockfiles, and evict expired/LRU private candidates before public ones. Record metadata fast-path routes into the footprint. The hook only fires at the auth-selection point, which the npm resolver's metadata fast paths (in-memory hit, offline disk read, version-spec exact match, publishedBy mtime shortcut) bypass. AuthHeaders::record_route drives the hook without a request, called up front in pick_package so every layer contributes to the footprint. Scope the npm metadata mirror by private access descriptor. A MetadataCacheScope (Public / Private) classified per (registry, package) fetch threads through pick_package, fetch_full_metadata_cached, the mirror path, in-memory/fetch-lock keys, and the verifier's local-mirror read. A private route stores its packument under v11/metadata-private/<descriptor-id>/. Fail closed on 401/403/private-404. The CLI installs no hook, so every fetch stays Public and the global mirror is unchanged. Related to #12699 and pnpm/rfcs#11.
1 parent c00400d commit 1dd12bd

38 files changed

Lines changed: 5321 additions & 344 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
"@pnpm/installing.deps-installer": minor
3+
"@pnpm/pnpr.client": minor
4+
"pnpm": minor
5+
---
6+
7+
When resolving through a pnpr install-accelerator server, pnpm no longer forwards its own upstream registry credentials in the resolve request. Only the `Authorization` header identifying the caller to pnpr is sent. The pnpr server now selects upstream credentials from its own route policy (operator-configured upstream credential aliases), so private dependencies resolve through a pnpr-managed alias the caller is authorized to use, rather than by sending the client's registry tokens to the server.

‎pacquet/crates/cli/src/cli_args/install.rs‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -676,10 +676,9 @@ pub(crate) async fn install_via_pnpr<Reporter: self::Reporter + 'static>(
676676
optional_dependencies,
677677
registry: resolve_registry,
678678
named_registries: state.config.named_registries.clone(),
679-
// Forward the whole credential map: the registries a graph
680-
// touches aren't known up front (scope-routed or tarball-URL
681-
// sub-deps), so the server attaches the right token per URL.
682-
auth_headers: state.config.auth_headers.to_by_scope(),
679+
// Only the caller's identity to pnpr is sent. Upstream registry
680+
// credentials are never forwarded: pnpr selects them from its own
681+
// route policy, so they stay out of the request body.
683682
authorization: state.config.auth_headers.for_url(pnpr_server),
684683
overrides,
685684
lockfile: state

‎pacquet/crates/cli/tests/pnpr_install.rs‎

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,11 @@
22
//!
33
//! Runs the real `pacquet` binary against a mocked fixtures registry,
44
//! with an in-process `pnpr` hosting the fast-path endpoints. The pnpr
5-
//! server's own uplink is left at the default — the client sends the
6-
//! registry it wants resolved from (the mock), so a passing test proves
7-
//! resolution used the client-supplied registry. The client then links
8-
//! `node_modules` from the server-produced lockfile.
5+
//! server's own uplink is left at the default; the client sends the
6+
//! registry it wants resolved from (the mock, which the server allowlists
7+
//! as a public route), so a passing test proves resolution used the
8+
//! client-supplied registry. The client then links `node_modules` from the
9+
//! server-produced lockfile.
910
1011
use assert_cmd::prelude::*;
1112
use command_extra::CommandExtra;
@@ -24,8 +25,11 @@ use std::{
2425
};
2526

2627
/// Start an in-process pnpr with the fast-path endpoints on a detached
27-
/// thread; returns its base URL and a pre-seeded bearer token.
28-
fn start_pnpr() -> (String, String) {
28+
/// thread, allowlisting `registry_url` as a public route so the client may
29+
/// resolve against it (off-allowlist registries are rejected at the request
30+
/// boundary); returns its base URL and a pre-seeded bearer token.
31+
fn start_pnpr(registry_url: &str) -> (String, String) {
32+
let registry_url = registry_url.to_string();
2933
// Persisted (not cleaned) because the detached server thread outlives
3034
// this function.
3135
let storage = tempfile::tempdir().expect("pnpr storage").keep();
@@ -54,6 +58,10 @@ fn start_pnpr() -> (String, String) {
5458
let mut config = pnpr::Config::proxy(addr, storage);
5559
config.public_url = format!("http://{addr}");
5660
config.auth.tokens.file = Some(tokens_path);
61+
config
62+
.route_policy
63+
.public
64+
.push(pnpr::PublicRoute { registry: Some(registry_url), package: None });
5765
let listener = tokio::net::TcpListener::from_std(listener).expect("tokio listener");
5866
let _ = pnpr::serve_listener(config, listener).await;
5967
});
@@ -93,7 +101,7 @@ fn install_via_pnpr_links_node_modules() {
93101
CommandTempCwd::init().add_mocked_registry();
94102
let AddMockedRegistry { npmrc_path, store_dir, mock_instance, .. } = npmrc_info;
95103

96-
let (pnpr_url, token) = start_pnpr();
104+
let (pnpr_url, token) = start_pnpr(&mock_instance.url());
97105
configure_pnpr_auth(&npmrc_path, &pnpr_url, &token);
98106

99107
let manifest_path = workspace.join("package.json");
@@ -128,7 +136,7 @@ fn frozen_install_via_pnpr_verifies_the_local_lockfile_without_resolving_or_redo
128136
CommandTempCwd::init().add_mocked_registry();
129137
let AddMockedRegistry { npmrc_path, mock_instance, .. } = npmrc_info;
130138

131-
let (pnpr_url, token) = start_pnpr();
139+
let (pnpr_url, token) = start_pnpr(&mock_instance.url());
132140
configure_pnpr_auth(&npmrc_path, &pnpr_url, &token);
133141

134142
let manifest_path = workspace.join("package.json");
@@ -198,7 +206,7 @@ fn install_via_pnpr_lockfile_only_writes_lockfile_without_linking() {
198206
CommandTempCwd::init().add_mocked_registry();
199207
let AddMockedRegistry { npmrc_path, store_dir, mock_instance, .. } = npmrc_info;
200208

201-
let (pnpr_url, token) = start_pnpr();
209+
let (pnpr_url, token) = start_pnpr(&mock_instance.url());
202210
configure_pnpr_auth(&npmrc_path, &pnpr_url, &token);
203211

204212
let manifest_path = workspace.join("package.json");
@@ -232,7 +240,7 @@ fn import_via_pnpr_server_writes_lockfile_without_linking() {
232240
CommandTempCwd::init().add_mocked_registry();
233241
let AddMockedRegistry { npmrc_path, store_dir, mock_instance, .. } = npmrc_info;
234242

235-
let (pnpr_url, token) = start_pnpr();
243+
let (pnpr_url, token) = start_pnpr(&mock_instance.url());
236244
configure_pnpr_auth(&npmrc_path, &pnpr_url, &token);
237245

238246
let manifest_path = workspace.join("package.json");

‎pacquet/crates/network/src/auth.rs‎

Lines changed: 136 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,20 +17,81 @@
1717
//! key at that host or prefix in `.npmrc`; if it redirects across
1818
//! hosts, no header is attached, matching upstream.
1919
20-
use std::collections::{BTreeMap, HashMap};
20+
use std::{
21+
collections::{BTreeMap, HashMap},
22+
fmt,
23+
sync::Arc,
24+
};
2125

2226
pub const DEFAULT_REGISTRY_SCOPE: &str = "@";
2327

2428
pub type AuthHeadersByScope = BTreeMap<String, BTreeMap<String, String>>;
2529

30+
/// Server-side override for upstream auth selection.
31+
///
32+
/// A plain [`AuthHeaders`] answers "what `Authorization` header does the
33+
/// client's `.npmrc` attach to this URL?" — the right question for the
34+
/// pnpm CLI, which fetches as the user. A server (pnpr) that resolves on
35+
/// behalf of many callers must instead answer "what credential does *this
36+
/// deployment's route policy* attach to this fetch, for this caller?" and
37+
/// record which private route was touched so the result can be cached
38+
/// without leaking one caller's private resolution to another.
39+
///
40+
/// When a hook is attached via [`AuthHeaders::with_route_hook`], every
41+
/// [`AuthHeaders::for_url`] / [`AuthHeaders::for_url_with_package`] lookup
42+
/// is delegated to it: the client-forwarded credentials carried by the
43+
/// [`AuthHeaders`] are ignored, and the hook alone decides the header
44+
/// (returning `None` for an anonymous/public fetch) and records the
45+
/// route. A `None` hook (the CLI case) leaves lookup behavior unchanged.
46+
pub trait UpstreamRouteHook: Send + Sync {
47+
/// Decide the `Authorization` header value for a fetch to `url` for
48+
/// package `package` (`None` for non-package fetches), and record the
49+
/// route the decision selected. `None` means fetch anonymously.
50+
fn authorize(&self, url: &str, package: Option<&str>) -> Option<String>;
51+
52+
/// Classify the metadata cache scope for a fetch to `url` for package
53+
/// `package` (`None` for non-package fetches). Unlike [`Self::authorize`]
54+
/// this is a read-only query — it must **not** record into the resolve's
55+
/// footprint — so the resolver can pick the on-disk mirror namespace and
56+
/// in-memory/fetch-lock keys without double-counting a route.
57+
///
58+
/// Defaults to [`MetadataCacheScope::Public`] for hooks that don't
59+
/// partition metadata by route.
60+
fn metadata_scope(&self, _url: &str, _package: Option<&str>) -> MetadataCacheScope {
61+
MetadataCacheScope::Public
62+
}
63+
}
64+
65+
/// The cache namespace a metadata fetch for one `(registry, package)` route
66+
/// belongs to, decided once per fetch from the route policy. A server (pnpr)
67+
/// that resolves on behalf of many callers must keep one caller's private
68+
/// metadata out of the global mirror every other caller reads; this enum is
69+
/// how the route decision reaches the npm resolver's mirror path, in-memory
70+
/// cache key, and fetch-lock key.
71+
///
72+
/// The pnpm CLI has no route hook, so every fetch is [`Self::Public`] and the
73+
/// global mirror behaves exactly as before.
74+
#[derive(Debug, Clone, PartialEq, Eq)]
75+
pub enum MetadataCacheScope {
76+
/// Public route: the shared, global metadata mirror — current behavior,
77+
/// shared by every caller.
78+
Public,
79+
/// Private route keyed by a private access descriptor. `descriptor_id`
80+
/// is a filesystem-safe, server-secret-keyed digest that namespaces the
81+
/// on-disk mirror, in-memory cache, and fetch lock, so one caller's
82+
/// private metadata never satisfies a fetch for a caller who does not
83+
/// reproduce the same descriptor.
84+
Private { descriptor_id: String },
85+
}
86+
2687
/// Bag of `Authorization` header values keyed by the nerf-darted form
2788
/// of each registry URL. Pacquet builds one of these from the parsed
2889
/// `.npmrc` and shares it across every HTTP call made during install.
2990
///
3091
/// Construct via [`AuthHeaders::from_parts`], [`AuthHeaders::from_creds_map`],
3192
/// [`AuthHeaders::from_map`], or [`AuthHeaders::default`] (empty). Look up via
3293
/// [`AuthHeaders::for_url`].
33-
#[derive(Debug, Default, Clone)]
94+
#[derive(Default, Clone)]
3495
pub struct AuthHeaders {
3596
/// Keys are the nerf-darted form (`//host[:port]/path/`). Values
3697
/// are ready-to-send header values like `Bearer abc123` or
@@ -47,6 +108,23 @@ pub struct AuthHeaders {
47108
/// The longest registry key per package scope, measured the same
48109
/// way as `max_parts`.
49110
max_scoped_parts_by_scope: HashMap<String, usize>,
111+
/// Server-side route hook. When set, it owns every auth lookup and
112+
/// the client-forwarded credentials above are ignored. See
113+
/// [`UpstreamRouteHook`].
114+
route_hook: Option<Arc<dyn UpstreamRouteHook>>,
115+
}
116+
117+
impl fmt::Debug for AuthHeaders {
118+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119+
// Header values carry credentials, so the maps' *contents* must
120+
// never reach a log line; show only key counts plus whether a
121+
// server route hook is overriding lookup.
122+
f.debug_struct("AuthHeaders")
123+
.field("by_uri", &self.by_uri.len())
124+
.field("scoped_by_scope", &self.scoped_by_scope.len())
125+
.field("route_hook", &self.route_hook.is_some())
126+
.finish_non_exhaustive()
127+
}
50128
}
51129

52130
impl AuthHeaders {
@@ -132,7 +210,13 @@ impl AuthHeaders {
132210
}
133211
}
134212
let max_parts = by_uri.keys().map(|key| key.split('/').count()).max().unwrap_or(0);
135-
AuthHeaders { by_uri, scoped_by_scope, max_parts, max_scoped_parts_by_scope }
213+
AuthHeaders {
214+
by_uri,
215+
scoped_by_scope,
216+
max_parts,
217+
max_scoped_parts_by_scope,
218+
route_hook: None,
219+
}
136220
}
137221

138222
/// Build an [`AuthHeaders`] from the structured pnpr wire shape:
@@ -194,10 +278,59 @@ impl AuthHeaders {
194278
self.for_url_with_package(url, None)
195279
}
196280

281+
/// Attach a server-side [`UpstreamRouteHook`] that takes over auth
282+
/// selection. The returned [`AuthHeaders`] keeps its
283+
/// client-forwarded credentials (so [`Self::to_by_scope`] still
284+
/// reflects them) but no longer consults them on lookup — the hook
285+
/// decides. Used by pnpr to resolve as the deployment's route policy
286+
/// rather than as the calling client.
287+
#[must_use]
288+
pub fn with_route_hook(mut self, hook: Arc<dyn UpstreamRouteHook>) -> Self {
289+
self.route_hook = Some(hook);
290+
self
291+
}
292+
293+
/// Record the route for a metadata/tarball fetch that is about to be
294+
/// served from an in-memory or on-disk cache *without* an HTTP
295+
/// request, so a server [`UpstreamRouteHook`]'s footprint still
296+
/// reflects every private route the resolve depended on. The route is
297+
/// classified exactly as the real fetch would have (same `url`, same
298+
/// `pkg_name`); the credential the hook selects is discarded because
299+
/// no request is sent.
300+
///
301+
/// No-op when no route hook is installed (the CLI case): a fetch that
302+
/// never happens needs no `Authorization` header, and the CLI keeps no
303+
/// footprint. Idempotent for the hook — recording the same route more
304+
/// than once collapses to one footprint entry.
305+
pub fn record_route(&self, url: &str, pkg_name: Option<&str>) {
306+
if let Some(hook) = &self.route_hook {
307+
hook.authorize(url, pkg_name);
308+
}
309+
}
310+
311+
/// The metadata cache scope a fetch to `url` for `pkg_name` belongs to.
312+
/// A server route hook owns the decision; without one (the CLI case)
313+
/// every fetch is [`MetadataCacheScope::Public`], leaving the global
314+
/// mirror unchanged. Read-only — never records into a footprint.
315+
#[must_use]
316+
pub fn metadata_scope(&self, url: &str, pkg_name: Option<&str>) -> MetadataCacheScope {
317+
match &self.route_hook {
318+
Some(hook) => hook.metadata_scope(url, pkg_name),
319+
None => MetadataCacheScope::Public,
320+
}
321+
}
322+
197323
/// Resolve an `Authorization` header for `url`, preferring
198324
/// package-scope credentials when `pkg_name` is scoped.
199325
#[must_use]
200326
pub fn for_url_with_package(&self, url: &str, pkg_name: Option<&str>) -> Option<String> {
327+
// A server route hook owns the decision: ignore the
328+
// client-forwarded credentials entirely (including any inline
329+
// `user:pass@` in `url`) and let the deployment's policy pick the
330+
// credential and record the route.
331+
if let Some(hook) = &self.route_hook {
332+
return hook.authorize(url, pkg_name);
333+
}
201334
// Append a trailing `/` first, matching pnpm's lookup which
202335
// does the same before parsing. Without this, a URL like
203336
// `https://npm.pkg.github.com/pnpm` (registry without

‎pacquet/crates/network/src/auth/tests.rs‎

Lines changed: 72 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,78 @@
11
use super::{
2-
AuthHeaders, DEFAULT_REGISTRY_SCOPE, base64_encode, nerf_dart, redact_and_sanitize,
3-
redact_url_credentials,
2+
AuthHeaders, DEFAULT_REGISTRY_SCOPE, UpstreamRouteHook, base64_encode, nerf_dart,
3+
redact_and_sanitize, redact_url_credentials,
44
};
55
use pretty_assertions::assert_eq;
6+
use std::sync::{
7+
Arc,
8+
atomic::{AtomicUsize, Ordering},
9+
};
10+
11+
/// Records every `(url, package)` it is asked about and answers with a
12+
/// fixed header, so a test can assert the hook — not the client
13+
/// credentials — drove the lookup.
14+
#[derive(Default)]
15+
struct RecordingHook {
16+
calls: AtomicUsize,
17+
answer: Option<String>,
18+
}
19+
20+
impl UpstreamRouteHook for RecordingHook {
21+
fn authorize(&self, _url: &str, _package: Option<&str>) -> Option<String> {
22+
self.calls.fetch_add(1, Ordering::Relaxed);
23+
self.answer.clone()
24+
}
25+
}
26+
27+
#[test]
28+
fn route_hook_overrides_client_credentials() {
29+
let client_creds = AuthHeaders::from_map(
30+
std::iter::once(("//reg.com/".to_string(), "Bearer client-token".to_string())).collect(),
31+
);
32+
// Without a hook the client-forwarded token is returned.
33+
assert_eq!(
34+
client_creds.for_url("https://reg.com/pkg"),
35+
Some("Bearer client-token".to_string()),
36+
);
37+
38+
let hook =
39+
Arc::new(RecordingHook { answer: Some("Bearer alias".to_string()), ..Default::default() });
40+
let hooked = client_creds.with_route_hook(Arc::clone(&hook) as Arc<dyn UpstreamRouteHook>);
41+
// With a hook the client token is ignored and the hook decides.
42+
assert_eq!(hooked.for_url("https://reg.com/pkg"), Some("Bearer alias".to_string()));
43+
assert_eq!(hook.calls.load(Ordering::Relaxed), 1);
44+
}
45+
46+
#[test]
47+
fn record_route_drives_the_hook_without_a_fetch() {
48+
let hook =
49+
Arc::new(RecordingHook { answer: Some("Bearer alias".to_string()), ..Default::default() });
50+
let hooked =
51+
AuthHeaders::default().with_route_hook(Arc::clone(&hook) as Arc<dyn UpstreamRouteHook>);
52+
// A cache-served metadata pick records its route through the hook so a
53+
// server footprint stays complete, discarding the selected credential
54+
// because no request is sent.
55+
hooked.record_route("https://reg.com/@scope/pkg", Some("@scope/pkg"));
56+
assert_eq!(hook.calls.load(Ordering::Relaxed), 1);
57+
}
58+
59+
#[test]
60+
fn record_route_is_a_noop_without_a_hook() {
61+
// The CLI never installs a hook: a fetch that doesn't happen needs no
62+
// header and there is no footprint to record into. This must not panic
63+
// or otherwise touch the client-forwarded credentials.
64+
AuthHeaders::default().record_route("https://reg.com/pkg", None);
65+
}
66+
67+
#[test]
68+
fn route_hook_suppresses_inline_url_basic_auth() {
69+
// A bare `AuthHeaders` would synthesize a `Basic` header from inline
70+
// `user:pass@`; with a hook attached the inline credential must not
71+
// leak through — the hook (returning None here) owns the decision.
72+
let hook = Arc::new(RecordingHook::default());
73+
let hooked = AuthHeaders::default().with_route_hook(hook as Arc<dyn UpstreamRouteHook>);
74+
assert_eq!(hooked.for_url("https://user:[email protected]/pkg"), None);
75+
}
676

777
#[test]
878
fn redact_url_credentials_strips_embedded_basic_auth() {

0 commit comments

Comments
 (0)