Skip to content

fix(pnpr): reject dist.integrity tampering in the partial-unpublish PUT - #12647

Merged
zkochan merged 11 commits into
pnpm:mainfrom
YESHYUNGSEOK:fix/pnpr-packument-integrity-guard
Jun 25, 2026
Merged

zkochan merged 11 commits into
pnpm:mainfrom
YESHYUNGSEOK:fix/pnpr-packument-integrity-guard

Conversation

@YESHYUNGSEOK

@YESHYUNGSEOK YESHYUNGSEOK commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

update_packument (PUT /:pkg/-rev/:rev, the partial-unpublish flow) stripped only
_attachments / _rev / _revisions and wrote the client body verbatim. A publisher with both
publish and unpublish rights could therefore set versions[v].dist.integrity to a bogus SRI while
the real tarball on disk stayed valid — a permanent client-side EINTEGRITY DoS for that version,
with no upload required. The body name was also never checked against the URL.

This adds three guards:

  1. Name match — reject a body whose name doesn't match the URL package (400).
  2. Integrity immutability — reject any change to an already-published version's
    dist.integrity. The hosted packument is read under the package lock so a concurrent publish
    can't race the check (400).
  3. SRI validity — reject a malformed dist.integrity on a newly added version entry (400).

The legitimate partial-unpublish flow (remove a version, leave the rest byte-for-byte unchanged)
is unaffected.

Squash Commit Body

update_packument (PUT /:pkg/-rev/:rev) stripped only _attachments/_rev/_revisions and wrote the
body verbatim, so a publisher with publish+unpublish rights could set versions[v].dist.integrity
to a bogus SRI while the real tarball stayed valid — a permanent client-side EINTEGRITY DoS for
that version, with no upload. The body name was also unchecked.

Add three guards: reject a body whose name does not match the URL package; reject any change to
an already-published version's dist.integrity (read under the package lock so a concurrent publish
cannot race it); and reject a malformed SRI on a newly added version entry. All map to 400. The
partial-unpublish flow is unaffected.

Checklist

  • Added or updated tests — update_packument_rejects_tampering_with_a_published_version_integrity
    publishes a version, PUTs back a packument with a poisoned dist.integrity, asserts 400, and
    confirms the stored integrity is unchanged.
  • Updated the documentation if needed — n/a.

(No changeset: pnpr is not a published npm package. No pnpm-side port: pnpr-only endpoint.)


Written by an agent (Claude Code, claude-opus-4-8).

Summary by CodeRabbit

  • Bug Fixes
    • PUT partial-unpublish now returns 400 BadRequest when the optional request-body package name doesn’t match the URL package name.
    • Prevents tampering with already-published versions[*].dist.integrity during partial-unpublish: differing integrity is rejected with 400 BadRequest; if omitted, the hosted integrity is restored.
    • Rejects invalid dist.integrity values (including non-string or null) with 400 BadRequest.
  • Tests
    • Added integration tests covering rejection of integrity tampering and invalid dist.integrity, plus assertions that previously stored integrity remains unchanged.

@YESHYUNGSEOK
YESHYUNGSEOK requested a review from zkochan as a code owner June 25, 2026 05:06
@coderabbitai

coderabbitai Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The partial-unpublish packument update now rejects mismatched package names, validates dist.integrity before persisting, and blocks changes to already-published integrity data. Integration tests cover tampered, null, and retained integrity cases.

Changes

Partial-unpublish packument validation

Layer / File(s) Summary
Name matching
pnpr/crates/pnpr/src/server.rs
update_packument rejects packuments whose embedded name does not match the request package name.
Integrity screening
pnpr/crates/pnpr/src/server.rs
update_packument now validates hosted integrity data under the package lock, restores omitted integrity for published versions, and rejects tampered or malformed dist.integrity values before writing.
Integrity tampering test
pnpr/crates/pnpr/tests/auth_publish.rs
The integration tests reject tampered and non-string dist.integrity values, and confirm retained versions keep a string integrity after partial-unpublish.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant update_packument
  participant HostedPackument
  participant parse_integrity

  Client->>update_packument: PUT /:pkg/-rev/:rev packument JSON
  update_packument->>HostedPackument: read current hosted packument
  update_packument->>parse_integrity: validate incoming dist.integrity values
  update_packument-->>Client: persist packument or return BadRequest
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • pnpm/pnpm#12579: Also changes update_packument in the same handler path, with adjacent logic around unpublish handling and request authorization.

Suggested labels

product: pnpr

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.

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

Copy link
Copy Markdown

PR Summary by Qodo

Reject dist.integrity tampering in partial-unpublish packument PUT
🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

Description

• Validate packument body name matches URL package before persisting updates.
• Prevent rewriting versions[*].dist.integrity for already-published versions under package lock.
• Reject malformed SRI on newly-added version entries and add regression test coverage.
Diagram

graph TD
  C{{"Publisher"}} --> H["update_packument PUT"] --> L["Package lock"] --> S["Storage API"] --> F[("Hosted packument")] --> K{"Validate name & integrity"} --> S --> R["Respond 201/400"]
  K --> P["SRI parse"]
  subgraph Legend
    direction LR
    _ext{{"External"}} ~~~ _svc["Handler/service"] ~~~ _db[("Storage")] ~~~ _dec{"Decision"}
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Server-side partial-unpublish operation (don’t accept full packument)
  • ➕ Eliminates broad trust in client-supplied packument rewrites
  • ➕ Allows narrowly-scoped authorization and validation (remove version/tag only)
  • ➕ Reduces future attack surface from other mutable fields
  • ➖ May diverge from pnpm/verdaccio behavior and require client changes
  • ➖ More implementation work (version/tag mutation logic, conflict handling)
2. Stricter packument immutability checks (diff-and-allowlist)
  • ➕ Blocks tampering of additional fields beyond dist.integrity
  • ➕ Makes partial-unpublish semantics explicit (only allow version/tag removals)
  • ➖ Risk of rejecting legitimate client rewrites due to packument shape differences
  • ➖ Higher maintenance cost as packument schema evolves

Recommendation: The PR’s targeted guards are the best near-term fix: they close the concrete DoS vector (integrity poisoning) while preserving the existing pnpm-compatible partial-unpublish flow. Consider a future server-side unpublish endpoint or broader allowlist validation if additional tampering vectors are discovered.

Files changed (2) +111 / -0

Bug fix (1) +71 / -0
server.rsAdd name match + dist.integrity immutability/SRI validation to update_packument +71/-0

Add name match + dist.integrity immutability/SRI validation to update_packument

• Adds a 400 guard when the incoming packument 'name' does not match the URL package. Under the per-package lock, reads the hosted packument and rejects any attempt to change 'dist.integrity' for already-published versions, and validates SRI syntax for newly introduced version entries before writing the packument.

pnpr/crates/pnpr/src/server.rs

Tests (1) +40 / -0
auth_publish.rsRegression test for rejecting published-version integrity tampering via PUT +40/-0

Regression test for rejecting published-version integrity tampering via PUT

• Introduces a tokio test that publishes a version, fetches its packument, mutates 'versions[1.0.0].dist.integrity', and asserts the partial-unpublish PUT returns 400 and does not change stored integrity.

pnpr/crates/pnpr/tests/auth_publish.rs

@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.

Actionable comments posted: 1

🤖 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.

Inline comments:
In `@pnpr/crates/pnpr/src/server.rs`:
- Around line 1904-1908: The hosted-packument handling in
server::read_hosted_packument logic is swallowing JSON parse failures by
converting serde_json::from_slice(&bytes) into None, which bypasses the
immutability check. Update the hosted packument load path so a malformed
packument is treated like an Err from storage: propagate the parse failure
instead of falling back to the None branch, and ensure the hosted_versions
comparison path only runs when the packument was successfully parsed.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: c23cfb12-5251-4e59-a951-bae75861bde9

📥 Commits

Reviewing files that changed from the base of the PR and between 54c5c0e and 668b163.

📒 Files selected for processing (2)
  • pnpr/crates/pnpr/src/server.rs
  • pnpr/crates/pnpr/tests/auth_publish.rs

Comment thread pnpr/crates/pnpr/src/server.rs Resolved
@qodo-free-for-open-source-projects

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Unpublish PUT seeds versions 🐞 Bug ⛨ Security
Description
When no hosted packument exists, enforce_published_version_immutability accepts the body and
update_packument writes it as authoritative hosted state, allowing callers to create version
entries without uploading tarballs. Since publish_package rejects publishing any version already
present in the hosted packument, this can permanently block later legitimate publishing of those
versions (durable DoS).
Code

pnpr/crates/pnpr/src/server.rs[R1950-2001]

+    let hosted: Option<Value> = match state.inner.storage.read_hosted_packument(name).await {
+        // Fail closed: a corrupt hosted packument must not silently disable the
+        // immutability gate (which would let tampered dist fields through).
+        Ok(Some(bytes)) => match serde_json::from_slice(&bytes) {
+            Ok(value) => Some(value),
+            Err(err) => return Some(RegistryError::Json(err)),
+        },
+        Ok(None) => None,
+        Err(err) => return Some(err),
+    };
+    let hosted_versions =
+        hosted.as_ref().and_then(|value| value.get("versions")).and_then(Value::as_object);
+    // (version, dist key, hosted value) triples re-inserted after the scan, for
+    // published versions whose body omitted an immutable dist field (a borrow of
+    // `incoming` is live until then).
+    let mut restore: Vec<(String, &'static str, Value)> = Vec::new();
+    for (version, manifest) in incoming_versions {
+        // A present dist.integrity must be a string — a valid SRI is the only
+        // acceptable shape. A present-but-non-string value (null, number,
+        // object) would slip past the string-only checks below and still break
+        // tarball serving, so reject it outright.
+        let incoming_integrity = match manifest.get("dist").and_then(|dist| dist.get("integrity")) {
+            None => None,
+            Some(Value::String(value)) => Some(value.as_str()),
+            Some(_) => {
+                return Some(RegistryError::BadRequest {
+                    reason: format!("dist.integrity for version {version:?} must be a string"),
+                });
+            }
+        };
+        let Some(existing) = hosted_versions.and_then(|versions| versions.get(version)) else {
+            // Partial-unpublish only removes versions from an existing package;
+            // it must not add one. A new entry could declare a dist.tarball
+            // basename colliding with a published version, which makes
+            // expected_tarball_dist fail closed (502) for that filename. Only
+            // when there is no hosted packument is there nothing to unpublish
+            // from, so a fresh body is accepted once its SRI is validated.
+            if hosted_versions.is_some() {
+                return Some(RegistryError::BadRequest {
+                    reason: format!(
+                        "version {version:?} is not in the published package; this endpoint removes versions, it does not add them",
+                    ),
+                });
+            }
+            if let Some(sri) = incoming_integrity
+                && let Err(err) = crate::streaming::parse_integrity(sri)
+            {
+                return Some(RegistryError::BadRequest {
+                    reason: format!("malformed dist.integrity for version {version:?}: {err}"),
+                });
+            }
+            continue;
Evidence
enforce_published_version_immutability explicitly treats read_hosted_packument returning
Ok(None) as a valid state and then allows versions to pass through (only optionally validating
integrity syntax). update_packument then writes the result to the hosted store. Separately, the
publish path checks hosted packument versions and rejects publishing over any version already
present, so pre-seeding versions via this PUT can block future legitimate publishes of those
versions.

pnpr/crates/pnpr/src/server.rs[1859-1909]
pnpr/crates/pnpr/src/server.rs[1949-2002]
pnpr/crates/pnpr/src/server.rs[1569-1590]

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

## Issue description
`PUT /:pkg/-rev/:rev` (partial-unpublish) can currently *bootstrap* a hosted packument when none exists. This bypasses the publish flow’s attachment/tarball verification and can create “hosted versions” that have no hosted tarballs, while also blocking future legitimate publishes of those version numbers (publish rejects versions already present in the hosted packument).
### Issue Context
- `update_packument` always writes the incoming (mutated) JSON to the hosted packument after calling `enforce_published_version_immutability`.
- In `enforce_published_version_immutability`, `Ok(None)` from `read_hosted_packument` is treated as “no hosted packument”, and incoming versions are allowed through (with only optional SRI syntax validation).
- `stage_publish` rejects publishing a version if it already exists in the hosted packument’s `versions` map.
### Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[1859-1909]
- pnpr/crates/pnpr/src/server.rs[1949-2002]
- pnpr/crates/pnpr/src/server.rs[1569-1590]
### Expected fix
Fail closed for partial-unpublish when there is no existing hosted packument (e.g. return 404/400), or otherwise require publish-equivalent invariants (and likely hosted tarball presence) before allowing the write.

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


2. Tarball basename bypass 🐞 Bug ⛨ Security
Description
enforce_published_version_immutability only enforces dist.tarball immutability when the hosted
packument’s stored dist.tarball has a parseable basename; if the stored URL has no basename (e.g.
trailing /), the check is skipped and a partial-unpublish PUT can change the tarball basename.
This can redirect clients (via rewrite_tarball_urls) to a missing/foreign tarball route and break
installs for that version (404/verification failures), despite the new integrity immutability guard.
Code

pnpr/crates/pnpr/src/server.rs[R2009-2013]

+        let existing_tarball = existing_dist.and_then(|dist| dist.get("tarball"));
+        if let Some(stored_basename) =
+            existing_tarball.and_then(Value::as_str).and_then(tarball_basename)
+        {
+            let incoming_basename = manifest
Evidence
The new guard only enters the tarball-immutability branch when the hosted packument’s stored tarball
yields a basename; otherwise it performs no tarball check. Since publish merges incoming manifests
verbatim, a publisher can store a trailing-slash tarball URL, and rewrite_tarball_urls explicitly
supports such “no basename” URLs via a version-derived fallback, making this bypass reachable.

pnpr/crates/pnpr/src/server.rs[2009-2035]
pnpr/crates/pnpr/src/publish.rs[226-249]
pnpr/crates/pnpr/src/upstream.rs[390-415]

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 tarball immutability check is currently gated on `tarball_basename(stored_tarball)` returning `Some(_)`. If a published version’s *stored* `dist.tarball` has no basename (e.g., ends with `/`), tarball immutability is not enforced at all for that version, allowing a partial-unpublish PUT to change the effective basename and DoS installs.
### Issue Context
- Hosted packuments can persist arbitrary `dist.tarball` strings because publish merge copies incoming JSON verbatim.
- The server’s `rewrite_tarball_urls` already treats “no basename” tarball URLs as valid input and falls back to a version-derived canonical filename.
- The immutability check should therefore mirror that same fallback so it still protects published versions whose stored tarball URL lacks a basename.
### Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[2009-2035]

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


3. Tarball basename collision DoS 🐞 Bug ⛨ Security
Description
enforce_published_version_immutability allows newly added versions["..."] entries during the
partial-unpublish PUT without validating dist.tarball, so an attacker can add a version whose
dist.tarball basename duplicates an existing published version’s tarball. Later tarball GETs for
that filename will hit expected_tarball_dist’s duplicate-basename check and return
TarballIntegrity (HTTP 502), breaking installs for the affected tarball until the packument is
repaired.
Code

pnpr/crates/pnpr/src/server.rs[R1973-1984]

+        let Some(existing) = hosted_versions.and_then(|versions| versions.get(version)) else {
+            // Newly added version: not an immutability concern, but its SRI must
+            // be syntactically valid so it can't poison tarball serving later.
+            if let Some(sri) = incoming_integrity
+                && let Err(err) = crate::streaming::parse_integrity(sri)
+            {
+                return Some(RegistryError::BadRequest {
+                    reason: format!("malformed dist.integrity for version {version:?}: {err}"),
+                });
+            }
+            continue;
+        };
Evidence
The new-version branch in enforce_published_version_immutability only checks (optionally) for
malformed SRI and then continues, so it does not prevent new entries from claiming an existing
tarball basename. Tarball serving resolves a tarball request by scanning versions[*].dist.tarball
basenames and explicitly errors when multiple versions match the same basename; that error maps to
HTTP 502, turning a crafted packument into an availability failure.

pnpr/crates/pnpr/src/server.rs[1850-1907]
pnpr/crates/pnpr/src/server.rs[1959-1984]
pnpr/crates/pnpr/src/server.rs[987-1017]
pnpr/crates/pnpr/src/error.rs[278-320]

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

## Issue description
`PUT /:pkg/-rev/:rev` (partial-unpublish) can introduce *new* version entries whose `dist.tarball` basenames collide with already-hosted versions. Tarball serving resolves by basename and fails closed when multiple versions claim the same basename, so this allows an authenticated publisher+unpublisher to persist a packument state that causes persistent 502s for tarball requests.
### Issue Context
- The new immutability guard explicitly allows “newly added version” entries and only validates `dist.integrity` (and only if present).
- Tarball serving uses `expected_tarball_dist()` which errors if a basename maps to more than one version, and `TarballIntegrity` maps to HTTP 502.
### Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[1973-1984]
### Suggested fix
Implement one of the following (prefer the simplest that matches intended semantics):
1. **Disallow additions in update_packument**: if `hosted_versions` exists, reject the PUT when it contains any version key not present in the hosted packument. (Partial-unpublish should only remove versions, not add.)
2. **Or validate basenames for newly added versions**:
- Require new versions to have `dist.tarball` as a string.
- Extract `tarball_basename` and reject if it collides with any hosted version’s basename or duplicates any other incoming version’s basename.
- Return `BadRequest` with a clear reason when a collision is found.
Add/extend an integration test that:
- Publishes `[email protected]`.
- PUTs a packument that adds `9.9.9` with `dist.tarball` ending in `mypkg-1.0.0.tgz`.
- Asserts the PUT is rejected (400) and the stored packument remains unchanged.

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


View more (5)
4. Tarball rewrite still allowed 🐞 Bug ⛨ Security
Description
enforce_published_version_integrity only checks dist.integrity, so a partial-unpublish PUT can
still modify a published version’s dist.tarball basename and make clients fetch a different hosted
tarball than the version’s immutable integrity (client-side EINTEGRITY/failed installs for that
version). This works because served packuments rewrite dist.tarball using the stored basename and
hosted tarballs are served by filename without server-side integrity verification.
Code

pnpr/crates/pnpr/src/server.rs[R1952-1997]

+    for (version, manifest) in incoming_versions {
+        // A present dist.integrity must be a string — a valid SRI is the only
+        // acceptable shape. A present-but-non-string value (null, number,
+        // object) would slip past the string-only checks below and still break
+        // tarball serving, so reject it outright.
+        let incoming_integrity = match manifest.get("dist").and_then(|dist| dist.get("integrity")) {
+            None => None,
+            Some(Value::String(value)) => Some(value.as_str()),
+            Some(_) => {
+                return Some(RegistryError::BadRequest {
+                    reason: format!("dist.integrity for version {version:?} must be a string"),
+                });
+            }
+        };
+        match hosted_versions.and_then(|versions| versions.get(version)) {
+            Some(existing) => {
+                let existing_integrity = existing
+                    .get("dist")
+                    .and_then(|dist| dist.get("integrity"))
+                    .and_then(Value::as_str);
+                match (existing_integrity, incoming_integrity) {
+                    (Some(stored), Some(submitted)) if stored != submitted => {
+                        return Some(RegistryError::BadRequest {
+                            reason: format!(
+                                "dist.integrity for the published version {version:?} is immutable",
+                            ),
+                        });
+                    }
+                    // Integrity omitted: restore the stored value. Restoring
+                    // requires an object `dist` to write into, so a published
+                    // version sent with a non-object (or absent) `dist` is
+                    // rejected — otherwise the restore would silently no-op and
+                    // persist the version without its integrity, the very
+                    // stripping this guards against.
+                    (Some(stored), None) => {
+                        if !manifest.get("dist").is_some_and(Value::is_object) {
+                            return Some(RegistryError::BadRequest {
+                                reason: format!(
+                                    "dist for the published version {version:?} must be an object carrying its integrity",
+                                ),
+                            });
+                        }
+                        restore.push((version.clone(), stored.to_string()));
+                    }
+                    _ => {}
+                }
Evidence
The new guard only compares/restores dist.integrity, leaving dist.tarball mutable for published
versions. Served packuments derive their tarball URL from the stored basename, and hosted tarball
serving returns the on-disk tarball for the requested filename directly, so changing the basename
can redirect clients to different bytes while the integrity remains unchanged.

pnpr/crates/pnpr/src/server.rs[1952-1997]
pnpr/crates/pnpr/src/upstream.rs[360-415]
pnpr/crates/pnpr/src/server.rs[828-865]

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

## Issue description
`PUT /:pkg/-rev/:rev` now enforces immutability of `versions[v].dist.integrity` but still allows mutation of `versions[v].dist.tarball` for already-hosted versions. Because packument responses rewrite `dist.tarball` based on the stored basename, changing a published version’s basename can redirect clients to fetch a different on-disk tarball than the version’s immutable integrity, causing client-side `EINTEGRITY` (install DoS) without changing `dist.integrity`.
### Issue Context
- The new guard only inspects `dist.integrity`.
- The server rewrites tarball URLs on GET using the stored basename.
- Hosted tarballs are served directly from disk by the requested filename.
### Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[1931-2021]
### Suggested fix
Extend `enforce_published_version_integrity` (or add a sibling guard) to also enforce immutability for published versions’ `dist.tarball` *basename*:
- For versions present in the hosted packument:
- Extract hosted `dist.tarball` basename and incoming `dist.tarball` basename (require string shape).
- If incoming basename differs: reject with 400 **or** restore the hosted value (similar to the integrity restore path).
- If incoming omits `dist.tarball`: restore it from hosted.
- Keep the “newly added version” behavior consistent with the intended contract (if new versions are allowed at all, require a valid tarball shape too).

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


5. Integrity restore bypass 🐞 Bug ⛨ Security
Description
enforce_published_version_integrity queues restoration when a published version omits
dist.integrity, but the restore loop only runs when versions[v].dist is a JSON object. A caller
can set versions[v].dist to a non-object (e.g. null) to skip restoration and persist a hosted
packument missing dist.integrity for a published version, reintroducing client-side
integrity/metadata DoS.
Code

pnpr/crates/pnpr/src/server.rs[R1995-2003]

+    for (version, integrity) in restore {
+        if let Some(dist) = incoming
+            .get_mut("versions")
+            .and_then(|versions| versions.get_mut(&version))
+            .and_then(|manifest| manifest.get_mut("dist"))
+            .and_then(Value::as_object_mut)
+        {
+            dist.insert("integrity".to_string(), Value::String(integrity));
+        }
Evidence
The code explicitly queues restoration when a published version omits dist.integrity, but the
subsequent restore loop only inserts into dist if it is already an object; if dist is
null/non-object, insertion is skipped and the request proceeds. Downstream, pnpr treats missing
dist.integrity as an error condition in integrity-bound paths (and publish requires it), so
persisting a published version without it can break integrity guarantees and client behavior.

pnpr/crates/pnpr/src/server.rs[1966-1982]
pnpr/crates/pnpr/src/server.rs[1995-2004]
pnpr/crates/pnpr/src/server.rs[1018-1032]
pnpr/crates/pnpr/src/publish.rs[91-120]

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

## Issue description
`enforce_published_version_integrity` attempts to *repair* omitted `dist.integrity` for already-published versions, but the repair is currently conditional on `incoming["versions"][v]["dist"]` being an object. If the incoming manifest sets `dist` to a non-object (e.g. `null`) or makes the version manifest non-object, the code still queues a restore but then silently skips insertion, allowing the request to persist a published version without `dist.integrity`.
This undermines the security goal of the PR: a publisher with publish+unpublish rights can still create a persistent client-side failure mode by stripping integrity via a shape change.
### Issue Context
- The restore queue is populated when a hosted version exists and the incoming integrity is omitted.
- The restore application is gated by `Value::as_object_mut()` on `dist`, so non-object `dist` values prevent restoration.
### Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[1952-2004]
### Recommended fix
Implement one of these fail-closed options for *published* versions:
1. **Reject malformed shape**: if a hosted version exists and its `dist.integrity` is `Some(_)`, require that the incoming version manifest is an object and that `dist` is either absent or an object. If `dist` is present but non-object (including `null`), return `400 BadRequest`.
OR
2. **Repair shape before insert**: when restoring, ensure `dist` is an object by creating/replacing it (or better: copy the hosted version’s `dist` object) and then insert `integrity`.
Either approach prevents bypassing the integrity-restore guarantee by changing `dist`’s JSON type.

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


6. Integrity can be stripped 🐞 Bug ⛨ Security
Description
reject_packument_integrity_tampering only rejects a *changed* dist.integrity when both stored
and submitted values are present, so a PUT can omit versions[v].dist.integrity for an
already-published version and update_packument will persist a packument with the integrity
removed. This violates the publish invariant that hosted versions carry verified dist.integrity
and can weaken or disable downstream integrity guarantees for clients consuming the hosted
packument.
Code

pnpr/crates/pnpr/src/server.rs[R1937-1950]

+                // Reject only a *change* to an integrity that is already
+                // present. A partial-unpublish legitimately re-PUTs the
+                // remaining versions with dist.integrity omitted, so an absent
+                // incoming integrity is allowed — it doesn't substitute a bogus
+                // value, which is the tampering this guards against.
+                if let (Some(stored), Some(submitted)) = (existing_integrity, incoming_integrity)
+                    && stored != submitted
+                {
+                    return Some(RegistryError::BadRequest {
+                        reason: format!(
+                            "dist.integrity for the published version {version:?} is immutable",
+                        ),
+                    });
+                }
Evidence
The server explicitly allows omitted incoming_integrity for existing versions (only rejecting when
both stored and submitted are present and differ), then persists the incoming packument bytes to the
hosted store without re-injecting integrity fields. The publish flow documents dist.integrity as
required, and an existing test constructs a partial-unpublish PUT body whose retained version omits
dist.integrity, demonstrating this deletion can occur in practice.

pnpr/crates/pnpr/src/server.rs[1820-1883]
pnpr/crates/pnpr/src/server.rs[1937-1951]
pnpr/crates/pnpr/src/publish.rs[91-120]
pnpr/crates/pnpr/src/server.rs[2630-2652]
pnpr/crates/pnpr/tests/auth_publish.rs[1085-1114]

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

## Issue description
`PUT /:pkg/-rev/:rev` persists the client body (after stripping a few fields). The new guard blocks *changing* an already-published version’s `dist.integrity`, but it explicitly allows the incoming packument to omit it; that omission is then written to storage, effectively deleting the integrity hash for a published version.
### Issue Context
- Publish path treats `dist.integrity` as required and verified.
- `update_packument` writes `packument` back verbatim after checks.
- Current tampering check only compares when both stored+submitted integrity are `Some`.
### Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[1820-1891]
- pnpr/crates/pnpr/src/server.rs[1893-1964]
- pnpr/crates/pnpr/src/publish.rs[91-120]
### Suggested fix
While holding the package lock, read the hosted packument and enforce **immutability against deletion** as well:
1. Build a map of `hosted_versions[version].dist.integrity`.
2. For each incoming version that exists in hosted:
- If hosted has `dist.integrity = Some(string)` and incoming omits it, **re-insert the hosted integrity string into the incoming JSON** before writing (preferred, keeps partial-unpublish compatibility).
- If incoming supplies an integrity string and it differs, keep rejecting (current behavior).
- If incoming supplies a non-string, keep rejecting (current behavior).
3. Serialize/write the *possibly amended* incoming packument so the stored metadata cannot lose integrity hashes for already-published versions.

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


7. Integrity type bypass ✓ Resolved 🐞 Bug ⛨ Security
Description
reject_packument_integrity_tampering only compares dist.integrity when both stored and incoming
values are strings, so a caller can bypass immutability by setting a published version’s
dist.integrity to null/object/number. That malformed packument can later break tarball serving
because tarball resolution requires dist.integrity to be a string, resulting in
502s/EINTEGRITY-class failures for clients.
Code

pnpr/crates/pnpr/src/server.rs[R1917-1932]

+        let incoming_integrity =
+            manifest.get("dist").and_then(|dist| dist.get("integrity")).and_then(Value::as_str);
+        match hosted_versions.and_then(|versions| versions.get(version)) {
+            Some(existing) => {
+                let existing_integrity = existing
+                    .get("dist")
+                    .and_then(|dist| dist.get("integrity"))
+                    .and_then(Value::as_str);
+                // Reject only a *change* to an integrity that is already
+                // present. A partial-unpublish legitimately re-PUTs the
+                // remaining versions with dist.integrity omitted, so an absent
+                // incoming integrity is allowed — it doesn't substitute a bogus
+                // value, which is the tampering this guards against.
+                if let (Some(stored), Some(submitted)) = (existing_integrity, incoming_integrity)
+                    && stored != submitted
+                {
Evidence
The new guard reads dist.integrity using Value::as_str(), so non-string values are treated as
missing and skip the stored-vs-submitted comparison; this allows persisting a tampered packument.
Downstream, tarball resolution fails closed if dist.integrity is not a string, returning a
TarballIntegrity error (mapped to 502), producing an availability DoS for that version.

pnpr/crates/pnpr/src/server.rs[1916-1947]
pnpr/crates/pnpr/src/server.rs[987-1032]
pnpr/crates/pnpr/src/error.rs[34-41]
pnpr/crates/pnpr/src/error.rs[265-278]

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

## Issue description
`reject_packument_integrity_tampering` derives `incoming_integrity` via `Value::as_str()`, so if a client submits a non-string `versions[v].dist.integrity` (e.g. `null`, `{}`, `123`) it becomes `None`. For already-published versions, the immutability check only triggers when *both* stored and incoming integrities are `Some(&str)`, so this non-string mutation bypasses the guard and can be persisted.
This undermines the security goal of preventing integrity tampering/DoS: later tarball-serving logic requires `dist.integrity` to be a string, so the attacker can still create a persistent client-side failure mode.
## Issue Context
- For existing versions, keep allowing *omission* of `dist.integrity` (to preserve the partial-unpublish flow), but treat a present-yet-non-string `dist.integrity` as a bad request.
- For newly added version entries, also reject non-string `dist.integrity` (and still validate string SRIs).
## Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[1916-1949]
- pnpr/crates/pnpr/src/server.rs[987-1032]

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


8. Partial-unpublish body now invalid ✓ Resolved 🐞 Bug ≡ Correctness
Description
The new immutability check rejects PUT bodies that omit versions[v].dist.integrity for an
already-published version (incoming None vs stored Some), but the existing
unpublish_partial_writes_modified_packument test constructs exactly such a body for the retained
version. This likely breaks that test (and any similar client behavior) by turning what was
previously accepted into a 400 Bad Request.
Code

pnpr/crates/pnpr/src/server.rs[R1921-1931]

+                let existing_integrity = existing
+                    .get("dist")
+                    .and_then(|dist| dist.get("integrity"))
+                    .and_then(Value::as_str);
+                if incoming_integrity != existing_integrity {
+                    return Some(RegistryError::BadRequest {
+                        reason: format!(
+                            "dist.integrity for the published version {version:?} is immutable",
+                        ),
+                    });
+                }
Evidence
The server’s new guard rejects any mismatch between incoming and existing dist.integrity for a
published version, including omission. The existing partial-unpublish test publishes two versions
(publish bodies include dist.integrity) and then PUTs back a packument where the remaining
version’s dist omits integrity, while asserting a 201 response—this now conflicts with the new
guard logic.

pnpr/crates/pnpr/src/server.rs[1898-1941]
pnpr/crates/pnpr/tests/auth_publish.rs[1048-1093]
pnpr/crates/pnpr/tests/auth_publish.rs[1406-1423]

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

## Issue description
A test for the partial-unpublish flow PUTs back a modified packument where the remaining version’s `dist` includes only `tarball` (no `integrity`). The new guard treats this as an integrity change (removal) and returns 400, so the test (and any client sending similarly-trimmed bodies) will fail.
### Issue Context
Real pnpm partial-unpublish behavior is described as: GET packument → remove version from `versions`/`dist-tags` → PUT the result back. That round-trip body should retain `dist.integrity` for the remaining versions.
### Fix Focus Areas
- pnpr/crates/pnpr/tests/auth_publish.rs[1048-1093]
- pnpr/crates/pnpr/src/server.rs[1916-1931]
### What to change
- Adjust `unpublish_partial_writes_modified_packument` to build its PUT body from a real GET’d packument (or from the on-disk packument) and only delete the removed version/tag keys, preserving `dist.integrity` for the retained version.
- Alternatively (if you intentionally want to accept sparse PUT bodies), you’d need to define/implement a safe merge strategy for missing `dist.integrity`—but that risks weakening the immutability guarantee and should be carefully threat-modeled.

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



Remediation recommended

9. Lock held across I/O 🐞 Bug ➹ Performance
Description
update_packument takes the per-package stripe lock and then performs hosted packument read + JSON
parse (and pretty-serialization) before writing, extending the lock’s critical section. On S3-backed
storage this read can be a network call, so a caller can stall concurrent writers for the same
package and also any other package that hashes to the same stripe.
Code

pnpr/crates/pnpr/src/server.rs[R1896-1906]

   // Serialize the write against this instance's other same-package
   // packument writers (publish / dist-tag), so the client-supplied
   // rewrite can't interleave with a concurrent merge.
   let _packument_guard = state.inner.package_locks.lock(name.as_str()).await;
+    if let Some(err) = enforce_published_version_immutability(state, &name, &mut packument).await {
+        return error_response(&err);
+    }
+    let bytes = match serde_json::to_vec_pretty(&packument) {
+        Ok(b) => b,
+        Err(err) => return error_response(&RegistryError::Json(err)),
+    };
Evidence
The diff shows update_packument acquiring the stripe lock before calling the new immutability
enforcement and before serializing the packument for writing. The enforcement function performs
read_hosted_packument(...).await and serde_json::from_slice(...) under that lock. Storage can
be backed by S3, making the read potentially network I/O. PackageLocks explicitly uses a fixed
stripe set, so unrelated packages can serialize on the same stripe.

pnpr/crates/pnpr/src/server.rs[1896-1906]
pnpr/crates/pnpr/src/server.rs[1942-1947]
pnpr/crates/pnpr/src/storage.rs[294-317]
pnpr/crates/pnpr/src/server.rs[96-107]

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

## Issue description
`update_packument` currently holds `package_locks.lock()` while awaiting `read_hosted_packument()` (which can be remote I/O on S3) and while doing CPU-heavy JSON work (`serde_json::from_slice` and `to_vec_pretty`). This increases writer contention for the same lock stripe.
### Issue Context
This endpoint is a write path and uses `PackageLocks` stripe mutexes; unrelated packages can contend due to stripe collisions.
### Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[1896-1906]
- pnpr/crates/pnpr/src/server.rs[1942-1947]
- pnpr/crates/pnpr/src/server.rs[96-155]
- pnpr/crates/pnpr/src/storage.rs[294-317]
### Suggested fix
- Keep correctness (the check must remain serialized w.r.t. other same-package writers), but reduce lock hold cost:
- Avoid `serde_json::to_vec_pretty` on this path (use `to_vec`) to cut CPU/time under the lock.
- Consider offloading the JSON parse/serialization done inside the locked section to `tokio::task::spawn_blocking` to avoid blocking the async executor while the stripe lock is held.
- If S3 latency is a real concern, consider increasing `PackageLocks::STRIPES` to reduce cross-package stripe collisions (low memory cost) or introducing a per-package lock for high-contention write paths.

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


10. Corrupt packument returns 502 🐞 Bug ☼ Reliability
Description
If the hosted packument JSON is corrupt, enforce_published_version_immutability returns
RegistryError::Json, which is mapped to HTTP 502 Bad Gateway. This misclassifies an internal
storage/data corruption as a gateway error, making client behavior/monitoring misleading and
potentially increasing retry load during an incident.
Code

pnpr/crates/pnpr/src/server.rs[R1950-1956]

+    let hosted: Value = match state.inner.storage.read_hosted_packument(name).await {
+        // Fail closed: a corrupt hosted packument must not silently disable the
+        // immutability gate (which would let tampered dist fields through).
+        Ok(Some(bytes)) => match serde_json::from_slice(&bytes) {
+            Ok(value) => value,
+            Err(err) => return Some(RegistryError::Json(err)),
+        },
Evidence
The new immutability gate returns RegistryError::Json when the hosted packument cannot be parsed;
RegistryError::Json is mapped to StatusCode::BAD_GATEWAY (502), so hosted packument corruption
will surface to clients as 502 rather than an internal 500-class error.

pnpr/crates/pnpr/src/server.rs[1950-1956]
pnpr/crates/pnpr/src/error.rs[271-320]

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

## Issue description
`enforce_published_version_immutability` parses the *hosted* packument; if it fails, it returns `RegistryError::Json`, which is mapped to `502 Bad Gateway`. A corrupt hosted packument is an internal server/storage integrity problem and should surface as `500 Internal Server Error` (or a dedicated internal error kind), not a gateway error.
### Issue Context
- The new immutability gate intentionally “fails closed” on hosted corruption, but the current error variant implies an upstream/gateway fault.
- `RegistryError::Internal` already maps to HTTP 500.
### Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[1950-1956]
### Suggested change
- Replace `return Some(RegistryError::Json(err))` with something like:
- `return Some(RegistryError::Internal { reason: format!("hosted packument is corrupt: {err}") })`
- (or introduce a dedicated error variant for hosted-data corruption that maps to 500).
- Keep the log message detailed, but ensure the public response remains a generic 500 (already handled by `public_message()` for 5xx).

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


11. Name check type bypass 🐞 Bug ≡ Correctness
Description
update_packument only enforces the URL/body name match when body.name is a JSON string, so a
request with "name": null (or any non-string) bypasses the guard and persists an
inconsistent/malformed packument under the URL package. This can corrupt authoritative metadata and
break downstream consumers that assume name is a string matching the package route.
Code

pnpr/crates/pnpr/src/server.rs[R1881-1889]

+    if let Some(body_name) = packument.get("name").and_then(Value::as_str)
+        && body_name != name.as_str()
+    {
+        return error_response(&RegistryError::BadRequest {
+            reason: format!(
+                "packument name {body_name:?} does not match the URL package {:?}",
+                name.as_str(),
+            ),
+        });
Evidence
The new guard in update_packument only runs when packument["name"] is a string
(and_then(Value::as_str)), so non-string values skip the mismatch rejection and proceed to
write_hosted_packument. In contrast, other identity-matching flows (e.g. add_user) do not allow
a non-string name to bypass URL/body matching semantics.

pnpr/crates/pnpr/src/server.rs[1878-1907]
pnpr/crates/pnpr/src/server.rs[1093-1105]

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

## Issue description
`update_packument` currently checks `packument["name"]` only via `Value::as_str()`. If the field is present but not a string (e.g. `null`, number, object), the check is skipped entirely and the server writes an invalid/inconsistent packument to the hosted store under the URL package name.
### Issue Context
This PR explicitly adds a "name match" guard to prevent persisting inconsistent manifests, but the current implementation is bypassable by using a non-string `name` value.
### Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[1878-1890]
### Suggested fix
Treat a present-but-non-string `name` as a `400 BadRequest` (similar to how other endpoints treat required string identity fields). Concretely:
- If `packument.get("name")` is `None`: allow (keeps current behavior).
- If it is `Some(Value::String(s))`: enforce `s == name.as_str()`.
- If it is `Some(_)`: return `RegistryError::BadRequest { reason: "packument name must be a string" }` (or equivalent).

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


View more (2)
12. Unbounded error echo 🐞 Bug ⛨ Security
Description
update_packument includes attacker-controlled strings (e.g. request-body name) inside
BadRequest.reason, and error_response logs and returns that string verbatim for 4xx responses. A
large name value can therefore cause significant extra allocation, response-size amplification,
and log flooding on every rejected PUT.
Code

pnpr/crates/pnpr/src/server.rs[R1878-1889]

+    // The write destination is the URL package name; a mismatched body name
+    // would otherwise land under the URL package and persist an inconsistent
+    // manifest.
+    if let Some(body_name) = packument.get("name").and_then(Value::as_str)
+        && body_name != name.as_str()
+    {
+        return error_response(&RegistryError::BadRequest {
+            reason: format!(
+                "packument name {body_name:?} does not match the URL package {:?}",
+                name.as_str(),
+            ),
+        });
Evidence
The name-mismatch branch formats an error string containing body_name. For 4xx errors,
error_response logs the full error and returns err.public_message(), and public_message()
returns self.to_string() (which includes the formatted reason), so the attacker-controlled
body_name is echoed into both logs and the HTTP response body.

pnpr/crates/pnpr/src/server.rs[1878-1889]
pnpr/crates/pnpr/src/server.rs[2919-2931]
pnpr/crates/pnpr/src/error.rs[255-261]

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

## Issue description
`update_packument` formats `BadRequest.reason` using attacker-controlled strings (notably the request body’s `name`), and the server returns/logs that message verbatim for 4xx errors. This enables response-size and log-volume amplification (availability impact).
### Issue Context
- `error_response()` logs `%err` and returns `err.public_message()`; for 4xx, `public_message()` returns `self.to_string()`, which includes the `reason` string.
- The new name-mismatch guard embeds `body_name` directly into `reason`.
### Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[1878-1889]
- pnpr/crates/pnpr/src/server.rs[2919-2931]
- pnpr/crates/pnpr/src/error.rs[255-261]
### Suggested fix
- Avoid including raw user-controlled values in `BadRequest.reason` (or truncate to a small max, e.g. 200 bytes, and include only length/summary).
- Optionally add a generic cap for `public_message()` or for logged error strings on 4xx to prevent log flooding.

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


13. Mutable version breaks tarballs 🐞 Bug ≡ Correctness
Description
For manifests whose stored dist.tarball has no basename, the served tarball basename falls back to
manifest.version, but enforce_published_version_immutability does not enforce immutability (or
key-match) of versions[ver].version. A partial-unpublish PUT can therefore change
manifest.version while keeping dist.tarball basename-less, shifting the served tarball route and
breaking installs/fetches for that published version.
Code

pnpr/crates/pnpr/src/server.rs[R2073-2084]

+/// The tarball basename a version is actually served under, mirroring
+/// [`rewrite_tarball_urls`]: the `dist.tarball` URL's own basename when it has
+/// one, otherwise the version-derived canonical name the rewrite falls back to.
+/// Returns `None` when the manifest carries no string `dist.tarball` to serve.
+fn served_tarball_basename(manifest: &Value, pkg: &PackageName) -> Option<String> {
+    let url = manifest.get("dist").and_then(|dist| dist.get("tarball")).and_then(Value::as_str)?;
+    if let Some(basename) = tarball_basename(url) {
+        return Some(basename.to_owned());
+    }
+    let version = manifest.get("version").and_then(Value::as_str)?;
+    Some(pkg.tarball_name_for_version(version))
+}
Evidence
served_tarball_basename explicitly falls back to manifest["version"] when dist.tarball has no
basename, and rewrite_dist_tarball uses the same fallback when rewriting dist.tarball for
clients. The immutability enforcement scans only dist.integrity and dist.tarball and does not
validate/restore manifest.version, so a PUT can change the fallback value and thereby change the
tarball route clients will request for that version.

pnpr/crates/pnpr/src/server.rs[1966-2058]
pnpr/crates/pnpr/src/server.rs[2073-2084]
pnpr/crates/pnpr/src/upstream.rs[390-415]

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

## Issue description
When `dist.tarball` has no basename (URL ends in `/`), tarball serving/rewriting uses a fallback basename derived from `manifest["version"]`. The new immutability gate locks `dist.integrity` and the tarball basename, but it does not lock down `manifest["version"]`, allowing a PUT to change the fallback basename indirectly.
### Issue Context
- `served_tarball_basename()` derives the served basename from `manifest.version` when `dist.tarball` lacks a basename.
- `rewrite_dist_tarball()` in `upstream.rs` uses the same `version` fallback when rewriting.
- `enforce_published_version_immutability()` currently does not compare/restore `manifest["version"]` for published versions.
### Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[1966-2058]
- pnpr/crates/pnpr/src/server.rs[2073-2084]
- pnpr/crates/pnpr/src/upstream.rs[390-415]
### Suggested fix
- For hosted/published versions, require `manifest["version"]` to be a string equal to the version key (and optionally equal to the hosted manifest’s `version`).
- If you want to preserve client round-tripping, restore `manifest["version"]` from hosted data (similar to the `restore` mechanism) when it’s missing/changed.
- At minimum, apply this check when the hosted `dist.tarball` is basename-less, since that’s when `manifest.version` becomes part of the tarball-routing trust decision.

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


Grey Divider

Qodo Logo

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 668b163

@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Jun 25, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

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

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

Copy link
Copy Markdown

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

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 0d01227

1 similar comment
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 0d01227

@codecov-commenter

codecov-commenter commented Jun 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.48649% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.72%. Comparing base (a06591e) to head (3fc5203).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
pnpr/crates/pnpr/src/server.rs 86.48% 15 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   pnpm/pnpm#12647      +/-   ##
==========================================
+ Coverage   88.70%   88.72%   +0.02%     
==========================================
  Files         341      342       +1     
  Lines       50150    50449     +299     
==========================================
+ Hits        44484    44760     +276     
- Misses       5666     5689      +23     

☔ 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.

@YESHYUNGSEOK

Copy link
Copy Markdown
Contributor Author

Addressed the non-string dist.integrity bypass in 6ec3879. update_packument now distinguishes an absent integrity (allowed — the partial-unpublish flow re-PUTs remaining versions without it) from a present-but-non-string one (null, number, object), which is rejected with 400 for both already-published and newly added version entries; present strings keep the immutability/SRI checks. Added update_packument_rejects_a_non_string_dist_integrity; the full auth_publish suite passes (39/39).


Written by an agent (Claude Code, claude-opus-4-8).

@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)
pnpr/crates/pnpr/tests/auth_publish.rs (1)

283-295: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert storage immutability after the rejected non-string integrity update.

Line 294 checks 400, but this regression test should also verify the stored packument is unchanged after the rejected PUT (re-GET and compare versions["1.0.0"].dist.integrity to the pre-mutation value), so write-before-reject regressions are caught.

As per path instructions, REVIEW_GUIDE.md requires regression tests to assert both the rejection and that “stored packument remains unchanged.”

🤖 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 `@pnpr/crates/pnpr/tests/auth_publish.rs` around lines 283 - 295, The
regression test in auth_publish should verify not only that the invalid PUT is
rejected, but also that the stored packument remains unchanged after rejection.
In the existing test around app.oneshot and Request::put("/mypkg/-rev/1-0"),
capture the original integrity from the initial GET, perform the rejected
update, then issue a second GET for /mypkg and assert
versions["1.0.0"].dist.integrity still matches the pre-mutation value to catch
any write-before-reject behavior.

Source: Path instructions

🤖 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 `@pnpr/crates/pnpr/tests/auth_publish.rs`:
- Around line 283-295: The regression test in auth_publish should verify not
only that the invalid PUT is rejected, but also that the stored packument
remains unchanged after rejection. In the existing test around app.oneshot and
Request::put("/mypkg/-rev/1-0"), capture the original integrity from the initial
GET, perform the rejected update, then issue a second GET for /mypkg and assert
versions["1.0.0"].dist.integrity still matches the pre-mutation value to catch
any write-before-reject behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 40d8f5f9-c2de-434e-9d4b-73f5b1277b16

📥 Commits

Reviewing files that changed from the base of the PR and between 0d01227 and 6ec3879.

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

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 6ec3879

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 6ec3879

@YESHYUNGSEOK

Copy link
Copy Markdown
Contributor Author

Thanks @qodo — dispositions:

  • Integrity type bypass, Partial-unpublish body now invalid, Guard fails open on JSON ✅ Resolved across ba1a97b / 0d01227 / 6ec3879 (propagate the parse error / allow an absent integrity for partial-unpublish / reject a present non-string integrity).
  • New versions allow no integrity: by design — this is the partial-unpublish endpoint, and the legit flow re-PUTs remaining versions sometimes without integrity. Versions are added through the publish flow (which mandates integrity), not here; requiring it on this endpoint would break partial-unpublish.
  • Non-string name bypass: low impact — the stored location is derived entirely from the URL package name, so a non-string body name only skips a cosmetic equality check (no routing/security effect). Can tighten to reject for cleanliness.
  • Cross-replica race bypass: architectural — per-instance lock, same multi-replica class as pnpr: make remaining local state pluggable for stateless / serverless deployment tasks#21.
  • Serialize before validation: minor — the body is serialized before the integrity check; reordering to validate first is a small follow-up.

Written by an agent (Claude Code, claude-opus-4-8).

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

Copy link
Copy Markdown

Thanks @qodo — dispositions:

  • Integrity type bypass, Partial-unpublish body now invalid, Guard fails open on JSON ✅ Resolved across ba1a97b / 0d01227 / 6ec3879 (propagate the parse error / allow an absent integrity for partial-unpublish / reject a present non-string integrity).
  • New versions allow no integrity: by design — this is the partial-unpublish endpoint, and the legit flow re-PUTs remaining versions sometimes without integrity. Versions are added through the publish flow (which mandates integrity), not here; requiring it on this endpoint would break partial-unpublish.
  • Non-string name bypass: low impact — the stored location is derived entirely from the URL package name, so a non-string body name only skips a cosmetic equality check (no routing/security effect). Can tighten to reject for cleanliness.
  • Cross-replica race bypass: architectural — per-instance lock, same multi-replica class as pnpr: make remaining local state pluggable for stateless / serverless deployment tasks#21.
  • Serialize before validation: minor — the body is serialized before the integrity check; reordering to validate first is a small follow-up.

Written by an agent (Claude Code, claude-opus-4-8).

Thanks — that all lines up with the changes.

  • The integrity-related issues are now covered.
  • Allowing missing dist.integrity on partial-unpublish looks correct by design.
  • The non-string name case is just a cleanup opportunity, not a routing concern.
  • The cross-replica race is indeed the same architectural class.
  • And yes, validating before serializing would be a reasonable follow-up hardening, but not required for correctness here.

If you want, I can also help turn the remaining cleanup items into a small follow-up patch list.

@github-actions

github-actions Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Integrated-Benchmark Report (Linux)

Commit: 3fc52032bf5e

Each scenario reports direct installs and pnpr installs. Bencher consumes pacquet@HEAD and pnpr@HEAD.

Scenario: Isolated linker: fresh restore, cold cache + cold store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.347 ± 0.097 4.244 4.479 1.58 ± 0.09
pacquet@main 4.401 ± 0.153 4.179 4.647 1.60 ± 0.10
pnpr@HEAD 2.793 ± 0.151 2.602 3.031 1.01 ± 0.08
pnpr@main 2.756 ± 0.145 2.585 2.965 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.346565579960001,
      "stddev": 0.09661077543463302,
      "median": 4.32805666386,
      "user": 4.11870144,
      "system": 2.1158453200000005,
      "min": 4.243967849360001,
      "max": 4.4794410543600005,
      "times": [
        4.46168471936,
        4.47856471536,
        4.37281445536,
        4.33276310036,
        4.4794410543600005,
        4.2588451453600005,
        4.25341946436,
        4.243967849360001,
        4.260805068360001,
        4.323350227360001
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.40114448666,
      "stddev": 0.15271860641104498,
      "median": 4.367485522360001,
      "user": 4.09361764,
      "system": 2.13758712,
      "min": 4.17949740636,
      "max": 4.64694675636,
      "times": [
        4.3800022513600005,
        4.36304464136,
        4.64694675636,
        4.30678818536,
        4.17949740636,
        4.26333025936,
        4.33849852536,
        4.55517308636,
        4.371926403360001,
        4.60623735136
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 2.79271070246,
      "stddev": 0.15115704186920115,
      "median": 2.77334808586,
      "user": 2.98225254,
      "system": 1.8494488199999999,
      "min": 2.6024116563599997,
      "max": 3.03074873636,
      "times": [
        2.6024116563599997,
        2.77573892036,
        3.03074873636,
        2.6764598133599997,
        2.77095725136,
        2.94195495036,
        2.62751266236,
        2.78835152036,
        2.7137150483599997,
        2.99925646536
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 2.75630314916,
      "stddev": 0.1445776114119976,
      "median": 2.7231142678599998,
      "user": 2.9839712400000002,
      "system": 1.8424291199999998,
      "min": 2.5845338223599996,
      "max": 2.9645127093599997,
      "times": [
        2.9645127093599997,
        2.73175523736,
        2.95377566636,
        2.71447329836,
        2.6043922623599998,
        2.84147260136,
        2.5845338223599996,
        2.63809990136,
        2.64362799836,
        2.88638799436
      ]
    }
  ]
}

Scenario: Isolated linker: fresh restore, hot cache + hot store

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 473.4 ± 10.8 460.6 490.3 1.01 ± 0.03
pacquet@main 466.7 ± 10.5 450.5 480.4 1.00
pnpr@HEAD 563.8 ± 102.6 483.9 729.8 1.21 ± 0.22
pnpr@main 508.1 ± 20.5 490.9 551.7 1.09 ± 0.05
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.4733996421200001,
      "stddev": 0.010765172255606406,
      "median": 0.46739619982,
      "user": 0.38627424,
      "system": 0.7817538399999999,
      "min": 0.46064116732000004,
      "max": 0.49025967932000003,
      "times": [
        0.48828009732000005,
        0.48084712332000007,
        0.46528071732000004,
        0.48184614232000006,
        0.46675205632000005,
        0.49025967932000003,
        0.46064116732000004,
        0.46626025232000007,
        0.46804034332000005,
        0.46578884232000006
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.46671864842,
      "stddev": 0.010513629412235262,
      "median": 0.4663246173200001,
      "user": 0.38346014000000006,
      "system": 0.7721538399999999,
      "min": 0.45048696632000007,
      "max": 0.48035870332,
      "times": [
        0.48035870332,
        0.46721664332000007,
        0.45048696632000007,
        0.45495291732000004,
        0.46835091832000003,
        0.46242322432000005,
        0.4590385993200001,
        0.47931880732000004,
        0.46543259132000003,
        0.47960711332000006
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.5638347401200001,
      "stddev": 0.10261333492445367,
      "median": 0.5100924533200001,
      "user": 0.39812124000000004,
      "system": 0.80493814,
      "min": 0.4839283193200001,
      "max": 0.72976507032,
      "times": [
        0.49294860532000007,
        0.5119259043200001,
        0.51894180432,
        0.4839283193200001,
        0.49639173132000003,
        0.49503041132000003,
        0.7265008903200001,
        0.6746556623200001,
        0.72976507032,
        0.5082590023200001
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.5081169325200001,
      "stddev": 0.02053535712268694,
      "median": 0.49942209382,
      "user": 0.39203164,
      "system": 0.8005542399999998,
      "min": 0.49088431332000004,
      "max": 0.5516847033200001,
      "times": [
        0.50150838332,
        0.5296651733200001,
        0.5516847033200001,
        0.51759818132,
        0.49160018732000005,
        0.49169780432000004,
        0.4973358043200001,
        0.49196998132,
        0.51722479332,
        0.49088431332000004
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, cold cache + cold store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.541 ± 0.025 4.505 4.589 1.50 ± 0.11
pacquet@main 4.512 ± 0.061 4.446 4.660 1.49 ± 0.11
pnpr@HEAD 3.023 ± 0.219 2.815 3.485 1.00
pnpr@main 3.073 ± 0.100 2.922 3.213 1.02 ± 0.08
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.54132367608,
      "stddev": 0.02525244539820568,
      "median": 4.54116311758,
      "user": 4.1078357400000005,
      "system": 2.0851306199999997,
      "min": 4.50533661558,
      "max": 4.5893588445799995,
      "times": [
        4.50533661558,
        4.55733997458,
        4.5893588445799995,
        4.54480756158,
        4.50811483658,
        4.5536014075799995,
        4.531055998579999,
        4.52742091558,
        4.55868193258,
        4.53751867358
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.51165700288,
      "stddev": 0.061267898651578216,
      "median": 4.50181906758,
      "user": 4.09582764,
      "system": 2.08172082,
      "min": 4.44598838058,
      "max": 4.65954399458,
      "times": [
        4.65954399458,
        4.44598838058,
        4.50990104658,
        4.45523870058,
        4.498089709579999,
        4.510444715579999,
        4.50146045358,
        4.50217768158,
        4.56147877958,
        4.47224656658
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 3.0229441103800005,
      "stddev": 0.2188042403307649,
      "median": 2.9703919780800003,
      "user": 3.1049189399999997,
      "system": 1.92809442,
      "min": 2.8146707285800003,
      "max": 3.4852400995800004,
      "times": [
        3.0699628005800004,
        3.07882733558,
        2.8595797015800004,
        3.2859257415800003,
        3.4852400995800004,
        2.8146707285800003,
        2.8222073575800004,
        2.8722433825800002,
        3.0155135365800003,
        2.9252704195800003
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 3.07277976638,
      "stddev": 0.09974675533392058,
      "median": 3.06430803858,
      "user": 3.1089805399999997,
      "system": 1.9528474200000001,
      "min": 2.92205175658,
      "max": 3.2125284135800003,
      "times": [
        3.17574031458,
        3.04867931958,
        3.02887752158,
        3.16702674458,
        3.0612639945800004,
        3.0673520825800002,
        3.2125284135800003,
        3.12217229558,
        2.92205175658,
        2.92210522058
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, hot cache + hot store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 1.152 ± 0.013 1.132 1.180 1.00
pacquet@main 1.165 ± 0.031 1.128 1.236 1.01 ± 0.03
pnpr@HEAD 1.251 ± 0.063 1.210 1.427 1.09 ± 0.06
pnpr@main 1.251 ± 0.034 1.225 1.343 1.09 ± 0.03
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 1.1517544285399999,
      "stddev": 0.0134097456128189,
      "median": 1.15056081364,
      "user": 1.32704036,
      "system": 1.0154220000000003,
      "min": 1.13209355564,
      "max": 1.17982118064,
      "times": [
        1.14796945064,
        1.17982118064,
        1.15327427264,
        1.15158502864,
        1.14958265664,
        1.15153897064,
        1.16671205864,
        1.13209355564,
        1.13880643464,
        1.14616067664
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 1.16544499204,
      "stddev": 0.030517494872951172,
      "median": 1.1555142576400002,
      "user": 1.33537106,
      "system": 1.0066422,
      "min": 1.12821241564,
      "max": 1.23587448864,
      "times": [
        1.1857445606400001,
        1.14450901064,
        1.1527707736400001,
        1.14537913064,
        1.15825774164,
        1.15141428164,
        1.16765342064,
        1.12821241564,
        1.18463409664,
        1.23587448864
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.25144632134,
      "stddev": 0.06279890056923548,
      "median": 1.23748042364,
      "user": 0.5705080600000001,
      "system": 0.9358974999999999,
      "min": 1.20980299564,
      "max": 1.42676296664,
      "times": [
        1.2446833346400001,
        1.24651128464,
        1.21995998964,
        1.22643329964,
        1.20980299564,
        1.42676296664,
        1.22190843664,
        1.24344005864,
        1.23964977064,
        1.23531107664
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.25052449534,
      "stddev": 0.03393023493000444,
      "median": 1.24008396514,
      "user": 0.58055576,
      "system": 0.9229513,
      "min": 1.22479956864,
      "max": 1.34283399664,
      "times": [
        1.25540677364,
        1.23696251964,
        1.23134754464,
        1.23191834364,
        1.24660440264,
        1.25520387364,
        1.34283399664,
        1.23920348164,
        1.22479956864,
        1.24096444864
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, cold cache + hot store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 2.872 ± 0.024 2.837 2.911 2.28 ± 0.04
pacquet@main 2.853 ± 0.041 2.800 2.945 2.26 ± 0.05
pnpr@HEAD 1.276 ± 0.016 1.244 1.298 1.01 ± 0.02
pnpr@main 1.262 ± 0.022 1.236 1.300 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.8722081949000002,
      "stddev": 0.0242401066860428,
      "median": 2.8734493054000003,
      "user": 1.8374892199999997,
      "system": 1.20889812,
      "min": 2.8372889839,
      "max": 2.9108541849000003,
      "times": [
        2.8372889839,
        2.8431662189,
        2.8638912199,
        2.8494248069,
        2.8907130269,
        2.8897976619,
        2.8900472349,
        2.8826840139,
        2.8642145969,
        2.9108541849000003
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.8529611282000005,
      "stddev": 0.040977243340129595,
      "median": 2.8434443799,
      "user": 1.8163813199999996,
      "system": 1.2101761199999999,
      "min": 2.7997019299,
      "max": 2.9449900339,
      "times": [
        2.8206417519,
        2.8398721239,
        2.8768615559,
        2.8331333149,
        2.8801520349,
        2.8620186619,
        2.8470166359,
        2.8252232389,
        2.7997019299,
        2.9449900339
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.2760623726,
      "stddev": 0.016339849441541845,
      "median": 1.2746563099000001,
      "user": 0.5738972199999999,
      "system": 0.9596398199999999,
      "min": 1.2444477279,
      "max": 1.2975545579,
      "times": [
        1.2812153419,
        1.2975545579,
        1.2917194269,
        1.2637303429,
        1.2957424319,
        1.2755521779,
        1.2737604419,
        1.2444477279,
        1.2663293159,
        1.2705719609
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.2624021793,
      "stddev": 0.02167504173299687,
      "median": 1.2538569989,
      "user": 0.58109912,
      "system": 0.94451792,
      "min": 1.2362112639,
      "max": 1.3001363869,
      "times": [
        1.2539862779,
        1.2712157169,
        1.2526255779,
        1.2362112639,
        1.2488550139,
        1.2909658849,
        1.3001363869,
        1.2386104499,
        1.2776875009,
        1.2537277199
      ]
    }
  ]
}

@github-actions

github-actions Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/12647
Testbedpacquet
Click to view all benchmark results
BenchmarkLatencyBenchmark Result
milliseconds (ms)
(Result Δ%)
Upper Boundary
milliseconds (ms)
(Limit %)
isolated-linker.fresh-install.cold-cache.cold-store📈 view plot
🚷 view threshold
4,541.32 ms
(-5.42%)Baseline: 4,801.62 ms
5,761.94 ms
(78.82%)
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
🚷 view threshold
2,872.21 ms
(-5.76%)Baseline: 3,047.90 ms
3,657.48 ms
(78.53%)
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
🚷 view threshold
1,151.75 ms
(-15.31%)Baseline: 1,360.01 ms
1,632.01 ms
(70.57%)
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
🚷 view threshold
4,346.57 ms
(-8.07%)Baseline: 4,728.02 ms
5,673.62 ms
(76.61%)
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
🚷 view threshold
473.40 ms
(-25.97%)Baseline: 639.48 ms
767.38 ms
(61.69%)
🐰 View full continuous benchmarking report in Bencher

@zkochan
zkochan force-pushed the fix/pnpr-packument-integrity-guard branch from 6ec3879 to 6d4f1a3 Compare June 25, 2026 09:21

@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.

Actionable comments posted: 1

🤖 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.

Inline comments:
In `@pnpr/crates/pnpr/tests/auth_publish.rs`:
- Around line 1126-1128: Strengthen the restore test in the auth publish flow by
asserting the restored integrity value matches the original one, not just that
it is a string. Capture the `versions["2.0.0"]["dist"]["integrity"]` value
before the PUT in the existing auth publish test and compare it after the GET,
so the check in `auth_publish.rs` fails if the server restores the wrong hash.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 23d63646-65aa-4202-a59c-b790773a93e2

📥 Commits

Reviewing files that changed from the base of the PR and between 6ec3879 and 6d4f1a3.

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

Comment thread pnpr/crates/pnpr/tests/auth_publish.rs Resolved
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 6d4f1a3

YESHYUNGSEOK and others added 2 commits June 25, 2026 11:29
update_packument (PUT /:pkg/-rev/:rev) stripped only _attachments/_rev/_revisions and wrote the
body verbatim, so a publisher with publish+unpublish rights could set versions[v].dist.integrity
to a bogus SRI while the real tarball stayed valid — a permanent client-side EINTEGRITY DoS for
that version, with no upload. The body name was also unchecked.

Add three guards: reject a body whose name does not match the URL package; reject any change to
an already-published version's dist.integrity (read under the package lock so a concurrent publish
cannot race it); and reject a malformed SRI on a newly added version entry. All map to 400. The
partial-unpublish flow (removing a version, leaving the rest untouched) is unaffected.

Co-authored-by: Claude <[email protected]>
The Perfectionist dylint requires a trailing comma on multi-line macro invocations; add it to the
two format! calls touched in update_packument. Also, reject_packument_integrity_tampering
swallowed a hosted-packument JSON parse error via .ok(), which would silently disable the
dist.integrity immutability gate — propagate it instead (fail closed), addressing the review.

Co-authored-by: Claude <[email protected]>
… too

The guard only locked dist.integrity, so a partial-unpublish PUT could still repoint an
already-published version's dist.tarball basename. Served packuments preserve that basename
(rewrite_tarball_urls keeps it verbatim), so a client resolving the version would fetch a
missing or foreign tarball that can't match the version's immutable integrity — a per-version
install DoS, the same class this guard exists to prevent, while the real tarball sits intact
on disk.

Extend enforce_published_version_integrity (now enforce_published_version_immutability) to
treat dist.tarball like dist.integrity: reject a changed basename and restore an omitted one
from the hosted packument. Factor the "dist must be an object to restore into" check into a
shared require_object_dist helper.

Co-authored-by: Claude <[email protected]>
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 5b3d169

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 5b3d169

enforce_published_version_immutability let the PUT body introduce new version entries. A new
entry could declare a dist.tarball basename colliding with an already-published version;
expected_tarball_dist fails closed on a duplicate basename, so the collision would 502 every
fetch of that filename — a persistent install DoS for the existing version.

Partial-unpublish only removes versions, so reject any incoming version not present in the
hosted packument (a fresh body is still accepted when no hosted packument exists, with its
SRIs validated). Add a regression test that adds a 9.9.9 entry colliding with 1.0.0's tarball
and asserts the PUT is rejected and no version is persisted.

Co-authored-by: Claude <[email protected]>
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 132ab4f

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

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

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

…check

The dist.tarball immutability check compared the incoming basename against tarball_basename of
the *stored* URL, so a published version whose stored dist.tarball had no basename (e.g. a URL
ending in /) was left unprotected: rewrite_tarball_urls serves such a URL under the
version-derived canonical name, so a partial-unpublish PUT could still shift the effective
served basename and redirect installs at a missing/foreign tarball.

Compare against the *served* basename instead via a new served_tarball_basename helper that
mirrors rewrite_tarball_urls' fallback (URL basename, else the version-derived canonical name).
Regression test: stored URL with no basename, PUT repoints it, asserts 400.

Co-authored-by: Claude <[email protected]>
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 4ad3fa2

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

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

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

… packument

When no hosted packument existed, enforce_published_version_immutability accepted the body and
update_packument wrote it as authoritative state. A caller could seed version entries with no
uploaded tarballs, and because publish refuses any version already in the packument, those
versions could never be legitimately published — a durable squat / DoS.

Partial-unpublish only operates on an already-published package, so fail closed (400) when
read_hosted_packument returns no packument. With that, every retained version is necessarily a
published one, so the separate "newly added version" branch collapses into the addition
rejection. Regression test PUTs to a never-published package and asserts 400 with nothing
written.

Co-authored-by: Claude <[email protected]>
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 5834cd5

1 similar comment
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 5834cd5

@zkochan
zkochan enabled auto-merge June 25, 2026 11:21
The guard had accreted a comment per finding, with the same rationale repeated in the doc
comment and inline. Concentrate the why in the function doc (its contract home), drop the inline
blocks that restated it, and shorten the test comments — removing the trailing "stored X must be
untouched" lines that just echoed the following assert. No behavior change.

Co-authored-by: Claude <[email protected]>
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 3fc5203

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

Copy link
Copy Markdown

Looking for bugs?

Check back in a few minutes. Qodo's review agents are on it.

@zkochan
zkochan added this pull request to the merge queue Jun 25, 2026
@zkochan
zkochan removed this pull request from the merge queue due to a manual request Jun 25, 2026
@zkochan
zkochan merged commit 1f462ef into pnpm:main Jun 25, 2026
28 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants