Skip to content

Commit 3425e80

Browse files
aqeelatzkochan
andauthored
feat(config): support an _auth setting for registry authentication (#12559)
Add an `_auth` setting that carries registry authentication as one structured, URL-keyed value instead of many `//host/:_authToken=…` keys. GitHub Actions silently drops env vars whose names contain `/`, `:`, or `.` (and bash/zsh reject them outright), which broke the `pnpm_config_//host/:_authToken=…` form on CI (#12314). The `pnpm_config__auth` env var — the env projection of the `_auth` setting — sidesteps the runner-level filter while preserving host scoping. The same value can be set in the global pnpm config.yaml as a native YAML map. Design: - `_auth` is honored only from the env var and the global config.yaml — never a project pnpm-workspace.yaml / .npmrc — so repo-controlled config can never supply registry auth. The env var wins over the global config on a conflicting key. - The value is host-keyed: `{ "https://registry.example": { "@": {...}, "@org": {...} } }`. The host and credential arrive in one trusted value, so the same entry is a safe source of registry routing — repo config cannot redirect an env token to a different host. Routes inferred from `_auth` are applied after workspace yaml (env/global wins over repo config) and before PNPM_CONFIG_* so an explicit registry override still wins — matching pnpm's "CLI > _auth > yaml" precedence. - Reuses npm's deprecated `_auth` key name on purpose: pnpm reads the structured form only from its own yaml (and the env projection), so it never collides with npm's legacy `.npmrc` `_auth` scalar, and it is already covered by the existing protected-settings redaction (prints as `(protected)`). - Only `authToken` is accepted (maps byte-for-byte to the existing `//host/:_authToken` .npmrc key), so the parser is a thin adapter onto the existing auth pipeline. The deprecated `basicAuth` / `username` + `password` forms and `tokenHelper` are excluded — dropped with a warning. - Malformed values, non-object shapes, non-URL keys, non-http(s) schemes, URLs carrying credentials/query/fragment, invalid scopes, and unsupported auth fields each push a distinct warning and are skipped without aborting the load. Warnings never leak raw URL credentials. Parity: implemented on both sides (TS CLI + pacquet). Both support the single credential field `authToken`. Closes #12314. --------- Co-authored-by: Zoltan Kochan <[email protected]>
1 parent 40441c3 commit 3425e80

13 files changed

Lines changed: 1900 additions & 22 deletions

File tree

‎.changeset/json-env-auth.md‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
---
2+
"@pnpm/config.reader": minor
3+
"pnpm": minor
4+
---
5+
6+
Added an `_auth` setting for configuring registry authentication as a single structured (URL-keyed) value. It can be set in the **global** pnpm config (`config.yaml`) or, for CI, via the `pnpm_config__auth` environment variable. The env form sidesteps the GitHub Actions / bash / zsh limitation that broke the existing `pnpm_config_//host/:_authToken=…` form (env var names containing `/`, `:`, or `.` are silently dropped). Closes pnpm/pnpm#12314.
7+
8+
The value is keyed by registry URL so each secret is explicitly bound to the host that may receive it. Registry URL keys must use `http` or `https` and must not include credentials, query strings, or fragments:
9+
10+
```sh
11+
export pnpm_config__auth='{"https://registry.npmjs.org":{"@":{"authToken":"npm-token"},"@org":{"authToken":"org-token"}}}'
12+
```
13+
14+
The equivalent in the global `config.yaml`:
15+
16+
```yaml
17+
_auth:
18+
https://registry.npmjs.org:
19+
'@':
20+
authToken: npm-token
21+
'@org':
22+
authToken: org-token
23+
```
24+
25+
Within each registry URL, `@` means registry-wide/default credentials and package scopes like `@org` bind credentials to that scope on the same host. The only supported credential field is `authToken` (maps to `_authToken` / bearer auth); the deprecated `basicAuth` / `username` + `password` forms are intentionally not accepted here.
26+
27+
Each entry also infers a trusted registry route: `@` routes the default registry (and `pnpm add <pkg>` resolves there), and `@org` routes that scope. Because the credential and destination host arrive in one trusted value, repo-controlled `pnpm-workspace.yaml` or project `.npmrc` cannot redirect the token to a different host. `_auth` is honored **only** from the env var and the global config — it is ignored in a project `pnpm-workspace.yaml` / `.npmrc`, so repo-controlled config can never supply registry auth. Precedence: CLI flags (`--registry`, `--@scope:registry`) > `pnpm_config__auth` > global `config.yaml` `_auth` > `pnpm-workspace.yaml`.
28+
29+
Both `pnpm_config__auth` (lowercase, documented form) and `PNPM_CONFIG__AUTH` (all-caps, the shell convention some CI runners apply) are honored. If both are set, lowercase wins unless it is empty, in which case uppercase is used. The env var wins over the global `config.yaml` `_auth` on a conflicting key. `tokenHelper` is not supported in `_auth`. Parsing is strict: a malformed value (bad JSON, wrong shape, invalid registry URL or scope, an unsupported credential field) fails fast with an error rather than being silently dropped.
30+
31+
**Pacquet parity note:** the pacquet (Rust) port supports the same single credential field as the TS CLI: `authToken`.

‎Cargo.lock‎

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎pacquet/crates/cli/src/config_overrides.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,9 +60,16 @@ impl ConfigOverrides {
6060
pub fn apply(&self, config: &mut Config) {
6161
if let Some(registry) = &self.registry {
6262
config.registry.clone_from(registry);
63+
config.registries.insert("default".to_string(), registry.clone());
64+
config.package_manager_bootstrap.registry.clone_from(registry);
65+
config
66+
.package_manager_bootstrap
67+
.registries
68+
.insert("default".to_string(), registry.clone());
6369
}
6470
for (scope, registry) in &self.registries {
6571
config.registries.insert(scope.clone(), registry.clone());
72+
config.package_manager_bootstrap.registries.insert(scope.clone(), registry.clone());
6673
}
6774
}
6875
}

‎pacquet/crates/cli/src/config_overrides/tests.rs‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,12 @@ fn extract_separates_config_tokens_from_argv() {
1919
let mut config = Config::default();
2020
overrides.apply(&mut config);
2121
assert_eq!(config.registry, "https://example.test/");
22+
assert_eq!(config.package_manager_bootstrap.registry, "https://example.test/");
23+
assert_eq!(config.registries.get("default").map(String::as_str), Some("https://example.test/"));
24+
assert_eq!(
25+
config.package_manager_bootstrap.registries.get("default").map(String::as_str),
26+
Some("https://example.test/"),
27+
);
2228
}
2329

2430
#[test]
@@ -35,6 +41,10 @@ fn extract_applies_scoped_registry_overrides() {
3541
config.registries.get("@private").map(String::as_str),
3642
Some("https://private.example/npm/"),
3743
);
44+
assert_eq!(
45+
config.package_manager_bootstrap.registries.get("@private").map(String::as_str),
46+
Some("https://private.example/npm/"),
47+
);
3848
}
3949

4050
#[test]
@@ -43,11 +53,19 @@ fn scoped_registry_override_wins_over_existing_config() {
4353
ConfigOverrides::extract(argv(["--config.@private:registry=https://cli.example/npm/"]));
4454
let mut config = Config::default();
4555
config.registries.insert("@private".to_string(), "https://workspace.example/npm/".to_string());
56+
config
57+
.package_manager_bootstrap
58+
.registries
59+
.insert("@private".to_string(), "https://json-env.example/npm/".to_string());
4660
overrides.apply(&mut config);
4761
assert_eq!(
4862
config.registries.get("@private").map(String::as_str),
4963
Some("https://cli.example/npm/"),
5064
);
65+
assert_eq!(
66+
config.package_manager_bootstrap.registries.get("@private").map(String::as_str),
67+
Some("https://cli.example/npm/"),
68+
);
5169
}
5270

5371
#[test]
@@ -77,6 +95,7 @@ fn last_value_wins_for_repeated_keys() {
7795
let mut config = Config::default();
7896
overrides.apply(&mut config);
7997
assert_eq!(config.registry, "https://second.test/");
98+
assert_eq!(config.package_manager_bootstrap.registry, "https://second.test/");
8099
}
81100

82101
#[test]

‎pacquet/crates/config/Cargo.toml‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,15 +32,17 @@ serde-saphyr = { workspace = true }
3232
serde_json = { workspace = true }
3333
smart-default = { workspace = true }
3434
tracing = { workspace = true }
35+
url = { workspace = true }
3536

3637
[target.'cfg(all(unix, not(target_os = "cygwin")))'.dependencies]
3738
libc = { workspace = true }
3839

3940
[dev-dependencies]
4041
pacquet-testing-utils = { workspace = true }
4142

42-
pretty_assertions = { workspace = true }
43-
tempfile = { workspace = true }
43+
pretty_assertions = { workspace = true }
44+
tempfile = { workspace = true }
45+
tracing-subscriber = { workspace = true }
4446

4547
[lints]
4648
workspace = true

‎pacquet/crates/config/src/lib.rs‎

Lines changed: 42 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ mod workspace_yaml;
99

1010
pub use crate::api::{EnvVar, EnvVarOs, GetCurrentDir, GetHomeDir, Host, LinkProbe};
1111

12+
use crate::npmrc_auth::NpmrcAuth;
1213
use indexmap::IndexMap;
1314
use pacquet_patching::{
1415
CalcPatchHashError, PatchGroupRecord, ResolvePatchedDependenciesError, calc_patch_hashes,
@@ -1866,15 +1867,14 @@ impl Config {
18661867
// project `.npmrc` > `auth.ini` > user-level `.npmrc`. Each is
18671868
// parsed and rescoped independently before being folded together.
18681869
let parse_trusted_source = |text: String, dir: PathBuf, label: &str| {
1869-
let mut auth = crate::npmrc_auth::NpmrcAuth::from_ini::<Sys>(&text, &dir);
1870+
let mut auth = NpmrcAuth::from_ini::<Sys>(&text, &dir);
18701871
auth.rescope_unscoped(label);
18711872
auth
18721873
};
18731874
let project_npmrc_dir =
18741875
workspace_yaml.as_ref().map_or(start_dir, |(base_dir, _)| base_dir.as_path());
18751876
let project_source = read_npmrc(project_npmrc_dir).map(|text| {
1876-
let mut auth =
1877-
crate::npmrc_auth::NpmrcAuth::from_project_ini::<Sys>(&text, project_npmrc_dir);
1877+
let mut auth = NpmrcAuth::from_project_ini::<Sys>(&text, project_npmrc_dir);
18781878
auth.rescope_unscoped("<project>/.npmrc");
18791879
auth
18801880
});
@@ -1903,20 +1903,42 @@ impl Config {
19031903
// `.npmrc` — mirroring the env-over-workspace ordering in pnpm's
19041904
// [`loadNpmrcFiles.ts`](https://github.com/pnpm/pnpm/blob/main/config/reader/src/loadNpmrcFiles.ts).
19051905
let env_scoped_source = {
1906-
let auth = crate::npmrc_auth::NpmrcAuth::from_url_scoped_env::<Sys>();
1906+
let auth = NpmrcAuth::from_url_scoped_env::<Sys>();
19071907
(!auth.creds_by_scope_by_uri.is_empty()).then_some(auth)
19081908
};
19091909

1910+
// Structured `_auth` registry auth from its two trusted sources:
1911+
// the `pnpm_config__auth` env var and the global `config.yaml`'s
1912+
// `_auth` key (env wins on conflict). See `from_json_sources`.
1913+
let json_auth = global_settings
1914+
.as_ref()
1915+
.and_then(|settings| settings.auth.as_ref())
1916+
.pipe(NpmrcAuth::from_json_sources::<Sys>)
1917+
.map_err(|source| LoadWorkspaceYamlError::InvalidJsonAuth { source })?;
1918+
let json_auth_has_content = !json_auth.creds_by_scope_by_uri.is_empty()
1919+
|| !json_auth.json_env_registries.is_empty();
1920+
let env_json_source = json_auth_has_content.then_some(json_auth);
1921+
19101922
// Capture the trusted sources (everything but `project_source`) for
19111923
// [`PackageManagerBootstrap`] before the fold below consumes them.
1912-
let trusted_sources =
1913-
[env_scoped_source.clone(), auth_ini_source.clone(), user_source.clone()];
1924+
let trusted_sources = [
1925+
env_json_source.clone(),
1926+
env_scoped_source.clone(),
1927+
auth_ini_source.clone(),
1928+
user_source.clone(),
1929+
];
19141930

19151931
// Fold high-priority-first: the first present source is the
19161932
// base, each lower source fills the gaps it left
1917-
// ([`NpmrcAuth::merge_under`]).
1933+
// ([`NpmrcAuth::merge_under`]). `env_json_source` is listed before
1934+
// `env_scoped_source` so the JSON env var wins on the rare occasion
1935+
// both define the same `//host/:_authToken` key — matches pnpm's
1936+
// TS merge, where JSON auth is spread after `envScopedConfig` so
1937+
// later wins.
19181938
let mut sources =
1919-
[env_scoped_source, project_source, auth_ini_source, user_source].into_iter().flatten();
1939+
[env_json_source, env_scoped_source, project_source, auth_ini_source, user_source]
1940+
.into_iter()
1941+
.flatten();
19201942
let mut npmrc_auth = sources.next().unwrap_or_default();
19211943
for lower in sources {
19221944
npmrc_auth.merge_under(lower);
@@ -2038,6 +2060,12 @@ impl Config {
20382060
}
20392061
}
20402062

2063+
// Apply `_auth` routes after workspace yaml (so they win over
2064+
// repo-controlled registries) but before `PNPM_CONFIG_*` (so an
2065+
// explicit `pnpm_config_registry` / `--registry` still wins) —
2066+
// pnpm's "CLI > _auth > yaml" precedence.
2067+
npmrc_auth.apply_json_env_registries(&mut self);
2068+
20412069
// Apply `PNPM_CONFIG_*` env vars *after* `pnpm-workspace.yaml`,
20422070
// mirroring pnpm v11's loop at
20432071
// [`config/reader/src/index.ts:471-488`](https://github.com/pnpm/pnpm/blob/2a9bd897bf/config/reader/src/index.ts#L471-L488):
@@ -2065,8 +2093,11 @@ impl Config {
20652093
env_settings.apply_to(&mut self, start_dir);
20662094
self.workspace_dir = saved_workspace_dir;
20672095
if let Some(registry) = env_registry_override {
2068-
self.package_manager_bootstrap.registry =
2096+
let normalized =
20692097
if registry.ends_with('/') { registry } else { format!("{registry}/") };
2098+
self.registries.insert("default".to_string(), normalized.clone());
2099+
self.package_manager_bootstrap.registry.clone_from(&normalized);
2100+
self.package_manager_bootstrap.registries.insert("default".to_string(), normalized);
20702101
}
20712102

20722103
// Build the per-URI auth-header lookup. Credentials were already
@@ -2132,13 +2163,14 @@ impl Config {
21322163
/// full config uses so the bootstrap cascade matches the project cascade
21332164
/// minus the repository-controlled sources.
21342165
fn build_package_manager_bootstrap<Sys: EnvVar>(
2135-
mut trusted_auth: crate::npmrc_auth::NpmrcAuth,
2166+
mut trusted_auth: NpmrcAuth,
21362167
) -> PackageManagerBootstrap {
21372168
// The full-config fold already surfaced these sources' `${VAR}` warnings;
21382169
// drop the duplicates this second pass would log.
21392170
trusted_auth.warnings.clear();
21402171
let mut config = Config::default();
21412172
trusted_auth.apply_registry_and_warn(&mut config);
2173+
trusted_auth.apply_json_env_registries(&mut config);
21422174
trusted_auth.apply_proxy_cascade::<Sys>(&mut config);
21432175
trusted_auth.apply_tls_and_local_address(&mut config);
21442176
trusted_auth.build_auth_headers(&mut config);

0 commit comments

Comments
 (0)