Skip to content

feat(pacquet): honor NODE_EXTRA_CA_CERTS for custom CA trust - #12508

Merged
zkochan merged 4 commits into
pnpm:mainfrom
jdalton:feat/node-extra-ca-certs
Jun 18, 2026
Merged

zkochan merged 4 commits into
pnpm:mainfrom
jdalton:feat/node-extra-ca-certs

Conversation

@jdalton

@jdalton jdalton commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

What

Make pacquet's registry HTTP client honor the NODE_EXTRA_CA_CERTS environment variable.

Why

pacquet's reqwest client trusts only its bundled webpki roots plus the .npmrc ca/cafile material — it consults no environment for CA trust. pnpm running on Node, however, does trust NODE_EXTRA_CA_CERTS — implicitly, via Node's TLS runtime. So users behind a corporate MITM proxy or a self-signed registry who set NODE_EXTRA_CA_CERTS (the standard Node convention) have working TLS under pnpm-on-Node today and would silently lose it under the native path. Reading the variable explicitly restores real-world parity rather than diverging from it.

This is the class of breakage tracked in #5400 (native fetch path not seeing the JS-config CA), approached from the env-var side.

How

apply_node_extra_ca_certs reads NODE_EXTRA_CA_CERTS; when set and non-empty, every certificate in the named PEM bundle is added as an additional trust root.

  • It lives in default_client_builder — the single chokepoint every client (default + per-registry) routes through — so the .npmrc-derived TlsConfig stays env-free and the existing "TLS config is .npmrc-only, no env vars" parity policy is preserved. The tls.rs module doc is updated to record this as the one deliberate, documented exception (it's a process-global Node convention, not a pnpm setting).
  • Additive, lowest-priority. Layered under the .npmrc ca/cafile roots apply_tls adds afterward and under the built-in webpki roots; the rustls root store is a union so ordering is immaterial.
  • Silently tolerant. A missing, unreadable, or malformed file is ignored rather than failing the client build — matching pnpm's silent treatment of a missing cafile.

Test

Adds node_extra_ca_certs_env_adds_root_and_tolerates_bad_path (serialized env mutation + restore), pointing the var at the existing tests/fixtures/test-ca.pem and then at a missing file, asserting for_installs builds in both cases.

cargo fmt, cargo clippy -p pacquet-network --tests, and cargo test -p pacquet-network all clean. No changeset added — the change is confined to the pacquet-* Rust crates; happy to add one if the workflow expects it.

Note: this intentionally adds CA-trust behavior the TS dispatcher doesn't have in code. The argument is parity-by-effect (Node already grants it to pnpm), but flagging it explicitly since tls.rs documents a deliberate no-env-vars stance — happy to adjust framing or gate it if you'd prefer.

Related: Socket Firewall (sfw)

This is also helpful with Socket Firewall (sfw, repo SocketDev/sfw-free) — a free tool that wraps your package manager behind a local MITM CA proxy to block known-malicious packages at install time. pnpm-on-Node works with it today because Node trusts the proxy CA via NODE_EXTRA_CA_CERTS; honoring that variable in the native client lets sfw pnpm … keep working as pnpm moves onto the pacquet path — no per-.npmrc cafile wiring required.

Summary by CodeRabbit

  • New Features
    • Added support for NODE_EXTRA_CA_CERTS to trust additional certificate authorities for secure connections.
  • Bug Fixes
    • Failures to load the PEM bundle (missing/empty value, unreadable file, invalid PEM, nonexistent path) are non-fatal and safely add no extra roots.
  • Documentation
    • Updated TLS documentation to clearly describe NODE_EXTRA_CA_CERTS handling.
  • Tests
    • Added coverage that verifies NODE_EXTRA_CA_CERTS parsing and non-fatal behavior across valid, empty, and invalid inputs.
  • Chores
    • Updated dev dependencies and formatting.

pacquet's reqwest client trusts only its bundled webpki roots plus the
.npmrc ca/cafile material — it ignores NODE_EXTRA_CA_CERTS. pnpm running
on Node picks that variable up transitively via Node's TLS runtime, so a
native port has to read it explicitly to keep real-world parity for
users behind a corporate MITM proxy or a self-signed registry.

Load the named PEM bundle as additional trust roots in
default_client_builder (the single chokepoint every client routes
through), keeping the .npmrc-derived TlsConfig env-free. Additive and
lowest-priority; a missing, unreadable, or malformed file is silently
ignored, matching pnpm's silent treatment of a missing cafile. Documented
as the one deliberate exception to the TlsConfig no-env-vars parity note.
@jdalton
jdalton requested a review from zkochan as a code owner June 18, 2026 20:39
Copilot AI review requested due to automatic review settings June 18, 2026 20:39
@coderabbitai

coderabbitai Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: a4e6ecb3-fc0e-4ff7-97ec-b5c2e58f2b55

📥 Commits

Reviewing files that changed from the base of the PR and between dc5aa5c and fc96cc1.

📒 Files selected for processing (1)
  • pacquet/crates/network/src/lib.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • pacquet/crates/network/src/lib.rs

📝 Walkthrough

Walkthrough

ThrottledClient::for_installs in pacquet/crates/network is extended with a new load_node_extra_ca_certs helper that reads the NODE_EXTRA_CA_CERTS environment variable once per call, parses the referenced file as a PEM bundle, and adds each certificate as an additional trusted root to each per-registry client before applying the configured TlsConfig. Missing, unreadable, or unparseable input is silently ignored. A doc update and a serialized test are included.

Changes

NODE_EXTRA_CA_CERTS TLS trust root injection

Layer / File(s) Summary
load_node_extra_ca_certs helper and TLS documentation
pacquet/crates/network/src/lib.rs, pacquet/crates/network/src/tls.rs
A new load_node_extra_ca_certs() helper resolves NODE_EXTRA_CA_CERTS from the environment, reads and parses the referenced file as a PEM bundle into Certificate objects, and returns an empty list on missing/empty/unreadable/unparseable input. tls.rs documentation records NODE_EXTRA_CA_CERTS as an explicit exception to the .npmrc-only TLS config policy, applied at the client-builder layer.
Integration into ThrottledClient::for_installs
pacquet/crates/network/src/lib.rs
ThrottledClient::for_installs reads NODE_EXTRA_CA_CERTS once at startup, storing the certificate list for reuse. When constructing each per-registry Client, the code iterates over preloaded extra certificates and adds each one as an additional root to the ClientBuilder before applying the configured TlsConfig.
Test coverage and dev dependencies
pacquet/crates/network/Cargo.toml, pacquet/crates/network/src/tests.rs
Adds node_extra_ca_certs_is_loaded_and_failures_are_non_fatal test using EnvGuard to serialize env mutation, verifying that ThrottledClient::for_installs succeeds with a valid PEM fixture and succeeds with invalid or missing paths (non-fatal). Updates Cargo.toml dev-dependencies to include pacquet-testing-utils for the EnvGuard utility.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • pnpm/pnpm#12047: Modifies the same ThrottledClient::for_installs and client construction wiring in pacquet/crates/network/src/lib.rs to incorporate configurable network settings.

Suggested reviewers

  • zkochan
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

Honor NODE_EXTRA_CA_CERTS for pacquet registry TLS trust
✨ Enhancement 🧪 Tests 📝 Documentation 🕐 20-40 Minutes

Grey Divider

Description

• Add NODE_EXTRA_CA_CERTS PEM bundle as an additional rustls trust root.
• Keep .npmrc-derived TLS config env-free by applying at client-builder chokepoint.
• Add regression test for valid bundle loading and missing-file tolerance.
Diagram

graph TD
A["ThrottledClient::for_installs"] --> B["default_client_builder"] --> C["apply_node_extra_ca_certs"] --> D["apply_tls (.npmrc)"] --> E["Reqwest Client"]
F["NODE_EXTRA_CA_CERTS"] --> G[("PEM bundle")] --> C
H["TlsConfig"] --> D
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Fold NODE_EXTRA_CA_CERTS into TlsConfig during config resolution
  • ➕ All TLS inputs live in a single struct; simpler mental model at call sites
  • ➕ Easier to expose/override in higher-level tooling
  • ➖ Violates the documented “.npmrc-only” stance of TlsConfig and mixes env with config
  • ➖ Harder to reason about parity boundaries (process-global vs per-project config)
2. Adopt system trust store (e.g., rustls-native-certs) instead of Node-specific env
  • ➕ Better aligns with native-binary expectations on many platforms
  • ➕ Potentially avoids bespoke Node-compat logic
  • ➖ Not equivalent to pnpm-on-Node behavior; risks new trust differences
  • ➖ Adds dependency/behavioral surface area beyond the parity goal
3. Warn or error when NODE_EXTRA_CA_CERTS is unreadable/malformed
  • ➕ More diagnosable when users misconfigure CA bundles
  • ➖ Diverges from pnpm’s silent handling of missing cafile and the PR’s parity goal
  • ➖ Could become a new hard-failure mode in corporate proxy environments

Recommendation: Keep the PR’s current approach: applying NODE_EXTRA_CA_CERTS in default_client_builder preserves .npmrc-only semantics for TlsConfig while restoring real-world parity with pnpm-on-Node. The best-effort, non-fatal handling is consistent with upstream behavior and reduces the risk of introducing new install-time failures.

Files changed (3) +92 / -2

Enhancement (1) +40 / -2
lib.rsApply NODE_EXTRA_CA_CERTS trust roots during client builder setup +40/-2

Apply NODE_EXTRA_CA_CERTS trust roots during client builder setup

• Refactors 'default_client_builder' to pass the builder through a new 'apply_node_extra_ca_certs' helper. The helper reads 'NODE_EXTRA_CA_CERTS', loads a PEM bundle, and adds each certificate as an additional reqwest/rustls root certificate, silently ignoring missing/unreadable/malformed inputs.

pacquet/crates/network/src/lib.rs

Tests (1) +44 / -0
tests.rsTest NODE_EXTRA_CA_CERTS integration and missing-file tolerance +44/-0

Test NODE_EXTRA_CA_CERTS integration and missing-file tolerance

• Adds a serialized env-mutation test that points 'NODE_EXTRA_CA_CERTS' at an existing PEM fixture and then at a nonexistent path. Verifies 'ThrottledClient::for_installs' still builds in both cases and restores the prior env var value.

pacquet/crates/network/src/tests.rs

Documentation (1) +8 / -0
tls.rsDocument NODE_EXTRA_CA_CERTS as the sole env-var TLS exception +8/-0

Document NODE_EXTRA_CA_CERTS as the sole env-var TLS exception

• Updates the module-level TLS parity documentation to explicitly call out that NODE_EXTRA_CA_CERTS is honored outside 'TlsConfig', at the client-builder layer, to preserve parity with pnpm-on-Node.

pacquet/crates/network/src/tls.rs

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jun 18, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (2) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Unbounded CA bundle read 🐞 Bug ☼ Reliability
Description
load_node_extra_ca_certs uses std::fs::read on the NODE_EXTRA_CA_CERTS path, which can hang on
special files (e.g. /dev/zero) or OOM on very large inputs during ThrottledClient::for_installs
startup. This turns a single environment variable into a process-startup DoS vector.
Code

pacquet/crates/network/src/lib.rs[R451-458]

+    let Some(path) = std::env::var_os("NODE_EXTRA_CA_CERTS").filter(|value| !value.is_empty())
+    else {
+        return Vec::new();
+    };
+    let Ok(bytes) = std::fs::read(&path) else {
+        return Vec::new();
+    };
+    Certificate::from_pem_bundle(&bytes).unwrap_or_default()
Evidence
The new helper reads arbitrary bytes from the env-provided path with an unbounded full-file read,
and it is invoked during install-client initialization, so a blocking/huge source directly impacts
startup.

pacquet/crates/network/src/lib.rs[274-306]
pacquet/crates/network/src/lib.rs[450-459]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`load_node_extra_ca_certs()` reads the file referenced by `NODE_EXTRA_CA_CERTS` with `std::fs::read`, which will read until EOF with no size/type checks. This can hang on special files (device files, FIFOs) or allocate unbounded memory on very large files, causing client initialization to stall or crash.
## Issue Context
This function is called during `ThrottledClient::for_installs()` client construction, so the impact is at startup / initialization time.
## Fix Focus Areas
- pacquet/crates/network/src/lib.rs[450-459]
## Suggested fix
- Before reading, call `std::fs::metadata(&path)` and return an empty list if:
- metadata lookup fails, or
- `file_type().is_file()` is false (skip device files/FIFOs), or
- `len()` exceeds a reasonable maximum (e.g. 1–5 MiB).
- Replace `std::fs::read(&path)` with a bounded read (e.g. `File::open` + `Read::take(MAX+1)`), and if the read exceeds the cap, return empty.
- Keep the existing “silent tolerance” behavior (do not error the client build); optionally add a `tracing::debug!` for diagnostics if the project’s policy allows.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Env restore not panic-safe ✓ Resolved 🐞 Bug ☼ Reliability
Description
The new test mutates NODE_EXTRA_CA_CERTS but only restores it at the end of the function, so any
panic between set_var and the final restore leaks process-global env state into sibling tests (and
can make later tests flaky). The per-test static LOCK also doesn’t serialize with other
env-mutating tests unless they use the same lock.
Code

pacquet/crates/network/src/tests.rs[R427-468]

+#[test]
+fn node_extra_ca_certs_env_adds_root_and_tolerates_bad_path() {
+    // Serialize against any other env-mutating test in this binary and
+    // restore the prior value before returning. There is no shared
+    // `EnvGuard` helper in this crate, and one isn't needed for
+    // correctness: `apply_node_extra_ca_certs` is purely additive and
+    // silently ignores read/parse failures, so a value observed by a
+    // concurrent `for_installs` build can't change that build's
+    // outcome. The lock + restore only keep the test from leaking the
+    // var into a developer's shell or a sibling test's assertions.
+    static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
+    let _guard = LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
+    let prior = std::env::var_os("NODE_EXTRA_CA_CERTS");
+
+    let build = || {
+        ThrottledClient::for_installs(
+            &ProxyConfig::default(),
+            &TlsConfig::default(),
+            &PerRegistryTls::default(),
+            &NetworkSettings::default(),
+        )
+    };
+
+    // A valid PEM bundle is loaded and added as an extra trust root.
+    let fixture = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/test-ca.pem");
+    // SAFETY: serialized by `LOCK`; restored before the test returns.
+    unsafe { std::env::set_var("NODE_EXTRA_CA_CERTS", fixture) };
+    build().expect("NODE_EXTRA_CA_CERTS pointing at a valid PEM builds");
+
+    // A missing / unreadable file is silently ignored, never fatal —
+    // matching pnpm's silent treatment of a missing `cafile`.
+    // SAFETY: serialized by `LOCK`; restored before the test returns.
+    unsafe { std::env::set_var("NODE_EXTRA_CA_CERTS", "/pacquet/does-not-exist.pem") };
+    build().expect("NODE_EXTRA_CA_CERTS pointing at a missing file is ignored, not fatal");
+
+    // SAFETY: serialized by `LOCK`.
+    unsafe {
+        match prior {
+            Some(value) => std::env::set_var("NODE_EXTRA_CA_CERTS", value),
+            None => std::env::remove_var("NODE_EXTRA_CA_CERTS"),
+        }
+    }
Evidence
The test sets NODE_EXTRA_CA_CERTS twice and restores it only at the end, which is not panic-safe.
The repo’s EnvGuard provides a process-wide serialization mutex and a Drop restore path
specifically to avoid this class of leakage, and other tests already use it for env mutation safety.

pacquet/crates/network/src/tests.rs[427-468]
pacquet/crates/testing-utils/src/env_guard.rs[4-16]
pacquet/crates/testing-utils/src/env_guard.rs[55-107]
pacquet/crates/config/src/tests.rs[866-887]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`node_extra_ca_certs_env_adds_root_and_tolerates_bad_path` manually sets and restores `NODE_EXTRA_CA_CERTS`. If the test panics (e.g., a failing `expect`) before reaching the restore block, the env var remains mutated for the rest of the test process.
## Issue Context
The repo already has an `EnvGuard` helper that (1) uses a process-wide mutex and (2) restores env vars on `Drop`, making it panic-safe.
## Fix Focus Areas
- pacquet/crates/network/src/tests.rs[427-469]
- pacquet/crates/network/Cargo.toml[21-25]
- pacquet/crates/testing-utils/src/env_guard.rs[55-107]
## Suggested fix
- Add `pacquet-testing-utils` as a `dev-dependency` of `pacquet-network`.
- In the test, replace the custom `static LOCK` + manual restore with `let g = EnvGuard::snapshot(["NODE_EXTRA_CA_CERTS"]);` and `g.set("NODE_EXTRA_CA_CERTS", fixture)` / `g.set("NODE_EXTRA_CA_CERTS", "/pacquet/does-not-exist.pem")`.
- Remove the manual restore block; rely on `Drop` to restore even on panic.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Repeated CA bundle parsing ✓ Resolved 🐞 Bug ➹ Performance
Description
When NODE_EXTRA_CA_CERTS is set, apply_node_extra_ca_certs synchronously reads and parses the
PEM bundle on every default_client_builder call. ThrottledClient::for_installs calls
default_client_builder once per per-registry client, so the same CA bundle can be re-read and
re-parsed N times during startup.
Code

pacquet/crates/network/src/lib.rs[R436-448]

+fn apply_node_extra_ca_certs(mut builder: reqwest::ClientBuilder) -> reqwest::ClientBuilder {
+    let path = match std::env::var_os("NODE_EXTRA_CA_CERTS") {
+        Some(value) if !value.is_empty() => value,
+        _ => return builder,
+    };
+    let Ok(bytes) = std::fs::read(&path) else {
+        return builder;
+    };
+    if let Ok(certs) = Certificate::from_pem_bundle(&bytes) {
+        for cert in certs {
+            builder = builder.add_root_certificate(cert);
+        }
+    }
Evidence
default_client_builder now always calls apply_node_extra_ca_certs, which reads/parses the
env-specified file. for_installs calls default_client_builder for the default client and again
inside a loop for each per-registry override, multiplying that cost by the number of per-registry
clients built.

pacquet/crates/network/src/lib.rs[287-311]
pacquet/crates/network/src/lib.rs[393-449]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`apply_node_extra_ca_certs` performs file I/O (`std::fs::read`) and PEM parsing (`Certificate::from_pem_bundle`) each time a client builder is created. In `for_installs`, client builders are created once for the default client and again for each per-registry override, potentially repeating this work multiple times.
## Issue Context
This only happens when `NODE_EXTRA_CA_CERTS` is set, which is common in corporate environments and the CA bundle can be non-trivial in size. The repeated work is avoidable because the env var and file contents are effectively process-static.
## Fix Focus Areas
- pacquet/crates/network/src/lib.rs[274-312]
- pacquet/crates/network/src/lib.rs[393-449]
## Suggested fix
- Introduce a cached loader, e.g. `static EXTRA_CA_CERTS: OnceLock<Option<Vec<Certificate>>>`, that:
- reads `NODE_EXTRA_CA_CERTS` once,
- reads the file once,
- parses into `Vec<Certificate>` once,
- caches `None` for the missing/unreadable/malformed cases too.
- Change `apply_node_extra_ca_certs` to only iterate the cached `Vec<Certificate>` and call `add_root_certificate` without repeating I/O/parsing.
- Keep the current “silently ignore failures” behavior by caching `None` on any error.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

4. Brittle missing-path test 🐞 Bug ☼ Reliability
Description
The new NODE_EXTRA_CA_CERTS test hard-codes an absolute Unix-style path as the “missing file” case,
which relies on an external assumption (that this path does not exist) rather than guaranteeing it.
This makes the test less robust/portable given the repo’s multi-OS CI matrix.
Code

pacquet/crates/network/src/tests.rs[R452-457]

+    // A missing / unreadable file yields no roots and is silently
+    // ignored, never fatal — matching pnpm's treatment of a missing
+    // `cafile`.
+    env.set("NODE_EXTRA_CA_CERTS", "/pacquet/does-not-exist.pem");
+    assert!(super::load_node_extra_ca_certs().is_empty());
+    build().expect("NODE_EXTRA_CA_CERTS pointing at a missing file is ignored, not fatal");
Evidence
The test sets NODE_EXTRA_CA_CERTS to a hard-coded absolute path to simulate a missing file, while
the project’s CI explicitly runs Rust tests on Windows as well as Unix platforms; this makes it
preferable to generate a guaranteed-missing temp path instead of assuming a specific absolute path
is absent.

pacquet/crates/network/src/tests.rs[446-458]
.github/workflows/pacquet-ci.yml[66-80]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The test `node_extra_ca_certs_env_adds_root_and_tolerates_bad_path` uses a hard-coded absolute path (`/pacquet/does-not-exist.pem`) to represent a missing/unreadable file. That relies on an assumption about the filesystem rather than ensuring the path is absent.
### Issue Context
CI runs this test suite on Windows/macOS/Linux, so it’s better for tests to construct OS-native paths and guarantee non-existence deterministically.
### Fix Focus Areas
- pacquet/crates/network/src/tests.rs[446-458]
### Suggested change
- Replace the hard-coded missing path with a path under a freshly created temp directory (e.g., `std::env::temp_dir().join(format!("pacquet-missing-{}-{}.pem", std::process::id(), unique_counter))`) and **do not create the file**.
- Optionally, build the fixture path using `PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(...)` instead of string concatenation for cleaner cross-platform path handling.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

Comment thread pacquet/crates/network/src/tests.rs Resolved
Comment thread pacquet/crates/network/src/lib.rs Resolved
@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Jun 18, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds NODE_EXTRA_CA_CERTS support to pacquet’s registry HTTP client so native TLS trust matches pnpm’s behavior when run under Node (where Node implicitly honors this env var).

Changes:

  • Apply NODE_EXTRA_CA_CERTS (PEM bundle) as additional trust roots in the shared reqwest ClientBuilder path.
  • Document the env-var exception to the “.npmrc-only TLS config” policy in TlsConfig module docs.
  • Add a unit test that mutates NODE_EXTRA_CA_CERTS and asserts client construction is tolerant of missing paths.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 3 comments.

File Description
pacquet/crates/network/src/lib.rs Adds apply_node_extra_ca_certs() and wires it into default_client_builder().
pacquet/crates/network/src/tls.rs Updates TLS module docs to record the NODE_EXTRA_CA_CERTS exception.
pacquet/crates/network/src/tests.rs Adds an env-var mutation test for NODE_EXTRA_CA_CERTS behavior/tolerance.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread pacquet/crates/network/src/tests.rs Resolved
Comment thread pacquet/crates/network/src/tests.rs Resolved
Comment thread pacquet/crates/network/src/lib.rs Resolved
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 493ac9b

Addresses review on the NODE_EXTRA_CA_CERTS change:

- Read and parse the bundle once in for_installs via
  load_node_extra_ca_certs(), then clone the parsed certs into the
  default client and each per-registry client. Previously
  default_client_builder re-read and re-parsed the file on every call,
  i.e. once per per-registry override.
- Use the existing EnvGuard test helper (process-wide lock + restore on
  drop, panic-safe) instead of a hand-rolled lock with manual restore.
  The test now also asserts a valid bundle parses to one root and a
  missing file yields none.
@jdalton

jdalton commented Jun 18, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Addressed in 01560b8:

  • Repeated CA bundle parsing — load_node_extra_ca_certs() now reads + parses the bundle once in for_installs and the parsed Vec<Certificate> is cloned into the default client and each per-registry client, so the file is no longer re-read/re-parsed per per-registry override. Kept it out of TlsConfig so the .npmrc-only parity policy stands.
  • Env restore not panic-safe — switched the test to the existing EnvGuard helper (process-wide lock + restore on Drop, panic-safe) instead of the hand-rolled lock + manual restore. Added pacquet-testing-utils as a dev-dependency. The test also now asserts a valid bundle parses to one root and a missing file yields none.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
pacquet/crates/network/src/lib.rs (1)

435-436: 💤 Low value

Doc comment references Self::for_installs but this is a free function.

The doc comment uses Self::for_installs and Self::for_installs (line 435, 439), but load_node_extra_ca_certs is a module-level free function, not an inherent method. Self has no meaning here. Reference the function directly or use the full path.

📝 Suggested fix
-/// The certs are added in [`Self::for_installs`]
+/// The certs are added in [`ThrottledClient::for_installs`]
 ...
-/// Read and parsed once per [`Self::for_installs`] call — `for_installs`
+/// Read and parsed once per [`ThrottledClient::for_installs`] call — `for_installs`
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pacquet/crates/network/src/lib.rs` around lines 435 - 436, The doc comment
for the free function `load_node_extra_ca_certs` incorrectly references
`Self::for_installs` in multiple places, but `Self` is not valid in a free
function context. Replace all instances of `Self::for_installs` with a direct
reference to the function, either using just the function name `for_installs` or
the full module path depending on where it is located relative to
`load_node_extra_ca_certs`.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@pacquet/crates/network/src/lib.rs`:
- Around line 435-436: The doc comment for the free function
`load_node_extra_ca_certs` incorrectly references `Self::for_installs` in
multiple places, but `Self` is not valid in a free function context. Replace all
instances of `Self::for_installs` with a direct reference to the function,
either using just the function name `for_installs` or the full module path
depending on where it is located relative to `load_node_extra_ca_certs`.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 8eed889f-0d40-45b7-8be3-592d4543b505

📥 Commits

Reviewing files that changed from the base of the PR and between 493ac9b and 01560b8.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock, !Cargo.lock
📒 Files selected for processing (4)
  • pacquet/crates/network/Cargo.toml
  • pacquet/crates/network/src/lib.rs
  • pacquet/crates/network/src/tests.rs
  • pacquet/crates/network/src/tls.rs
✅ Files skipped from review due to trivial changes (1)
  • pacquet/crates/network/src/tls.rs

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 01560b8

Make the pacquet and aube tests mirror each other in form and coverage:
exercise the same four cases in the same order — empty value, valid
bundle (asserting one parsed root plus a successful client build), a
readable non-PEM file, and a missing file — each asserting
load_node_extra_ca_certs() yields the expected roots. Also align the
env-var read in load_node_extra_ca_certs to the same let-else + filter
form aube uses (no behavior change).
Copilot AI review requested due to automatic review settings June 18, 2026 21:04
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit dc5aa5c

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
pacquet/crates/network/src/tests.rs (1)

457-463: ⚡ Quick win

Use tempfile for the invalid-PEM fixture instead of a predictable temp path.

Building a filename from temp_dir + pid is collision-prone and less robust in parallel/CI runs. Prefer tempfile::NamedTempFile (or TempDir) so creation/cleanup is atomic and isolated.

Suggested update
-    let bad =
-        std::env::temp_dir().join(format!("pacquet-node-extra-ca-{}.pem", std::process::id()));
-    std::fs::write(&bad, b"not a certificate").expect("write temp ca bundle");
-    env.set("NODE_EXTRA_CA_CERTS", &bad);
+    let bad = tempfile::NamedTempFile::new().expect("create temp ca bundle");
+    std::fs::write(bad.path(), b"not a certificate").expect("write temp ca bundle");
+    env.set("NODE_EXTRA_CA_CERTS", bad.path());
     assert!(super::load_node_extra_ca_certs().is_empty());
-    let _ = std::fs::remove_file(&bad);

As per coding guidelines, “Prefer real fixtures using tempfile::TempDir ... for testing” in pacquet/**/*.rs.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pacquet/crates/network/src/tests.rs` around lines 457 - 463, The test fixture
is creating a temporary file using a predictable path combining
std::env::temp_dir() and std::process::id(), which is collision-prone and not
suitable for parallel or CI environments. Replace this manual temp file creation
with tempfile::NamedTempFile to ensure atomic creation and automatic cleanup.
Create the NamedTempFile, write the invalid PEM content to it, obtain its path
to set in the NODE_EXTRA_CA_CERTS environment variable via env.set(), and then
invoke super::load_node_extra_ca_certs() for the assertion. Remove the explicit
std::fs::remove_file call since NamedTempFile handles cleanup automatically when
dropped.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@pacquet/crates/network/src/tests.rs`:
- Around line 457-463: The test fixture is creating a temporary file using a
predictable path combining std::env::temp_dir() and std::process::id(), which is
collision-prone and not suitable for parallel or CI environments. Replace this
manual temp file creation with tempfile::NamedTempFile to ensure atomic creation
and automatic cleanup. Create the NamedTempFile, write the invalid PEM content
to it, obtain its path to set in the NODE_EXTRA_CA_CERTS environment variable
via env.set(), and then invoke super::load_node_extra_ca_certs() for the
assertion. Remove the explicit std::fs::remove_file call since NamedTempFile
handles cleanup automatically when dropped.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: f3402ced-1db1-4b51-bc98-c1b8f012e897

📥 Commits

Reviewing files that changed from the base of the PR and between 01560b8 and dc5aa5c.

📒 Files selected for processing (2)
  • pacquet/crates/network/src/lib.rs
  • pacquet/crates/network/src/tests.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • pacquet/crates/network/src/lib.rs

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 4 out of 5 changed files in this pull request and generated 1 comment.

Comment thread pacquet/crates/network/src/lib.rs Resolved
@codecov-commenter

codecov-commenter commented Jun 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.19%. Comparing base (0474a9c) to head (fc96cc1).
⚠️ Report is 6 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #12508   +/-   ##
=======================================
  Coverage   88.18%   88.19%           
=======================================
  Files         313      313           
  Lines       43074    43085   +11     
=======================================
+ Hits        37983    37997   +14     
+ Misses       5091     5088    -3     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

The free function's doc used [`Self::for_installs`], but `Self` only
resolves in impl/trait contexts, so rustdoc flagged it as an unresolved
intra-doc link and the Rust CI Doc job (RUSTDOCFLAGS=-D warnings) failed.
Reference [`ThrottledClient::for_installs`] instead.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit fc96cc1

@zkochan
zkochan enabled auto-merge (squash) June 18, 2026 21:31
@zkochan
zkochan merged commit 2dd79e3 into pnpm:main Jun 18, 2026
29 checks passed
@welcome

welcome Bot commented Jun 18, 2026

Copy link
Copy Markdown

Congrats on merging your first pull request! 🎉🎉🎉

@jdalton

jdalton commented Jun 18, 2026

Copy link
Copy Markdown
Contributor Author

👯 🕺 👯

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

product: pacquet reviewed: coderabbit CodeRabbit submitted an approving review state: automerge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants