Repository navigation
fix(plugins): guard marketplace archive downloads - #58267
Conversation
Greptile SummaryThis PR guards marketplace archive downloads behind Key changes:
Confidence Score: 5/5Safe to merge — all findings are P2 hardening suggestions, not blocking defects. The core change (replacing bare fetch with fetchWithSsrFGuard) is correct and well-tested. The two issues flagged are pre-existing edge cases or very-low-likelihood scenarios. Neither was introduced by this PR and neither constitutes a blocking defect. The finally { await release() } block in src/plugins/marketplace.ts deserves a second look for the .catch(() => undefined) guard.
|
| Filename | Overview |
|---|---|
| src/plugins/marketplace.ts | Replaces bare fetch() in downloadUrlToTempFile with fetchWithSsrFGuard, adds finalUrl-derived filename and proper release() cleanup; two minor P2 hardening opportunities around tmpDir cleanup on pipeTo() failure and release() exception shadowing a successful result. |
| src/plugins/marketplace.test.ts | Adds mock for fetchWithSsrFGuard, upgrades the empty-body test to verify release is called, and adds two new focused tests for the success path and SSRF-guard-rejection path; coverage looks complete for the changed behaviour. |
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/plugins/marketplace.ts
Line: 608-621
Comment:
**`tmpDir` leaked when `pipeTo()` throws**
If `response.body.pipeTo()` throws (e.g. network reset mid-stream), the `finally` block correctly calls `release()`, but the `tmpDir` that was already created on line 608 is never removed — the outer `catch` returns `{ ok: false }` without a cleanup closure. This is a pre-existing behaviour that predates this PR, but the new outer `try/catch` now silently swallows the throw, making the leak harder to spot.
Alternatively, track `tmpDir` in the outer scope and clean it up in the `catch` block.
How can I resolve this? If you propose a fix, please make it concise.
---
This is a comment left during a code review.
Path: src/plugins/marketplace.ts
Line: 619-626
Comment:
**`release()` error can shadow a successful download**
`await release()` sits in the `finally` block, which means a thrown error from `closeDispatcher` (however unlikely) will propagate past the successful `{ ok: true }` return and be caught by the outer `catch`, returning `{ ok: false }` to the caller. The successfully-written `tmpDir` would also be leaked in that scenario since the `cleanup` closure is never returned.
Wrapping the `release()` call with a `.catch(() => undefined)` would match the already-defensive cleanup pattern used elsewhere in this file and avoid the result shadowing:
```suggestion
} finally {
await release().catch(() => undefined);
}
```
How can I resolve this? If you propose a fix, please make it concise.Reviews (1): Last reviewed commit: "Plugins: guard marketplace archive downl..." | Re-trigger Greptile
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 47c8fa4d6f
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
🔒 Aisle Security AnalysisWe found 3 potential security issue(s) in this PR:
1. 🟠 readResponseWithLimit maxBytes bypass via arrayBuffer fallback causes memory DoS
Description
Vulnerable code: const fallback = Buffer.from(await res.arrayBuffer());
if (fallback.length > maxBytes) {
return {
buffer: fallback.subarray(0, maxBytes),
size: fallback.length,
truncated: true,
};
}RecommendationEnsure Options:
if (!body || typeof body.getReader !== "function") {
// If we can't stream, don't risk buffering an unbounded response.
const cl = res.headers.get("content-length");
if (!cl) throw new Error("Missing Content-Length for non-streaming response");
const size = Number(cl);
if (!Number.isFinite(size) || size > maxBytes) {
throw new Error(`Content too large: ${cl} (limit: ${maxBytes})`);
}
return { buffer: Buffer.from(await res.arrayBuffer()), size, truncated: false };
}
2. 🟡 NaN timeout disables download timeouts in marketplace archive fetch (potential hang/DoS)
Description
This can allow a malicious/slow remote server to keep the connection open indefinitely (slowloris-style), causing the plugin install/update process to hang and potentially leading to denial of service. Vulnerable code: const downloadTimeoutMs = Math.max(
1_000,
Math.floor(timeoutMs ?? DEFAULT_MARKETPLACE_DOWNLOAD_TIMEOUT_MS),
);
...
timeoutMs: downloadTimeoutMs,
...
chunkTimeoutMs: downloadTimeoutMs,RecommendationValidate/coerce the timeout to a finite, positive integer before use, and fall back to the default if invalid. For example: const resolvedTimeout =
typeof timeoutMs === "number" && Number.isFinite(timeoutMs)
? timeoutMs
: DEFAULT_MARKETPLACE_DOWNLOAD_TIMEOUT_MS;
const downloadTimeoutMs = Math.max(1_000, Math.floor(resolvedTimeout));Additionally, consider making 3. 🟡 Unsanitized URL and error message reflected to CLI stderr (info disclosure + terminal/log injection)
Description
Impacts:
Vulnerable code: return {
ok: false,
error: `failed to download ${url}: ${error instanceof Error ? error.message : String(error)}`,
};Recommendation
Example approach: function safeUrlForLogs(raw: string): string {
const u = new URL(raw);
u.username = "";
u.password = "";
u.search = ""; // or keep allowlisted params
u.hash = "";
return u.toString().replace(/[\x00-\x1F\x7F]/g, "?");
}
// ...
const safeUrl = safeUrlForLogs(url);
const safeMsg = String(error instanceof Error ? error.message : error)
.replace(/[\x00-\x1F\x7F]/g, "?");
return { ok: false, error: `failed to download ${safeUrl}: ${safeMsg}` };Also consider returning structured error codes (e.g. Analyzed PR: #58267 at commit Last updated on: 2026-03-31T09:46:37Z |
47c8fa4 to
b50b7a9
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 53e49f14ed
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
sharkqwy
left a comment
There was a problem hiding this comment.
Review: marketplace archive download hardening
Thorough security improvement. Walking through the changes:
What this fixes well
-
SSRF guard integration — Downloads now route through
fetchWithSsrFGuardwith an explicitauditContext, which means SSRF protections (hostname blocking, redirect following) apply to marketplace archive fetches. The test for169.254.169.254rejection confirms the guard is wired in. -
Size enforcement — Two-layer size check:
Content-Lengthheader pre-check andreadResponseWithLimitduring streaming. This prevents both declared-large and drip-feed-large payloads. -
Filename sanitization —
resolveSafeMarketplaceDownloadFileNamestrips traversal vectors, and thepath.relativecheck afterpath.resolveis good defense-in-depth even thoughbasenameshould already be safe. -
Temp dir cleanup — The outer
catchnow cleans uptmpDiron any failure path, and the testlistMarketplaceDownloadTempDirsassertion confirms no leaked directories. The old code had no cleanup on streaming errors. -
Timeout propagation —
downloadTimeoutMsflows through to both the fetch guard and the chunk idle timeout, so slow-loris style attacks are bounded.
One trade-off worth noting
The switch from response.body.pipeTo(Writable.toWeb(fileStream)) to readResponseWithLimit (buffer-in-memory then writeFile) means the full archive (up to 256 MB) is held in a Node.js Buffer before writing to disk. The old streaming approach had lower peak RSS. For the marketplace download use case this is likely fine — plugin archives are typically small — but if MAX_MARKETPLACE_ARCHIVE_BYTES ever increases, the memory pressure could matter on constrained hosts (e.g., Raspberry Pi). A future follow-up could use a streaming Transform that counts bytes and aborts on overflow, keeping the size enforcement without the memory spike.
Minor nit
resolveSafeMarketplaceDownloadFileName is called twice on the happy path — once with the original URL and once with finalUrl after redirect. The first call's result is only used as a fallback for the second. This is correct but could be clearer with a comment explaining why both are needed (the redirect target may change the extension, e.g., CDN rewrites .tgz → blob hash).
Overall this is solid hardening. 👍
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c00852a06e
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
* Plugins: guard marketplace archive downloads * Plugins: harden marketplace download cleanup * Plugins: bound marketplace archive downloads * Plugins: harden marketplace archive failures * Plugins: reject drive-relative marketplace archives * Plugins: stream marketplace archive downloads
* Plugins: guard marketplace archive downloads * Plugins: harden marketplace download cleanup * Plugins: bound marketplace archive downloads * Plugins: harden marketplace archive failures * Plugins: reject drive-relative marketplace archives * Plugins: stream marketplace archive downloads
* Plugins: guard marketplace archive downloads * Plugins: harden marketplace download cleanup * Plugins: bound marketplace archive downloads * Plugins: harden marketplace archive failures * Plugins: reject drive-relative marketplace archives * Plugins: stream marketplace archive downloads
* Plugins: guard marketplace archive downloads * Plugins: harden marketplace download cleanup * Plugins: bound marketplace archive downloads * Plugins: harden marketplace archive failures * Plugins: reject drive-relative marketplace archives * Plugins: stream marketplace archive downloads
* Plugins: guard marketplace archive downloads * Plugins: harden marketplace download cleanup * Plugins: bound marketplace archive downloads * Plugins: harden marketplace archive failures * Plugins: reject drive-relative marketplace archives * Plugins: stream marketplace archive downloads
* Plugins: guard marketplace archive downloads * Plugins: harden marketplace download cleanup * Plugins: bound marketplace archive downloads * Plugins: harden marketplace archive failures * Plugins: reject drive-relative marketplace archives * Plugins: stream marketplace archive downloads
* Plugins: guard marketplace archive downloads * Plugins: harden marketplace download cleanup * Plugins: bound marketplace archive downloads * Plugins: harden marketplace archive failures * Plugins: reject drive-relative marketplace archives * Plugins: stream marketplace archive downloads
* Plugins: guard marketplace archive downloads * Plugins: harden marketplace download cleanup * Plugins: bound marketplace archive downloads * Plugins: harden marketplace archive failures * Plugins: reject drive-relative marketplace archives * Plugins: stream marketplace archive downloads
* Plugins: guard marketplace archive downloads * Plugins: harden marketplace download cleanup * Plugins: bound marketplace archive downloads * Plugins: harden marketplace archive failures * Plugins: reject drive-relative marketplace archives * Plugins: stream marketplace archive downloads
* Plugins: guard marketplace archive downloads * Plugins: harden marketplace download cleanup * Plugins: bound marketplace archive downloads * Plugins: harden marketplace archive failures * Plugins: reject drive-relative marketplace archives * Plugins: stream marketplace archive downloads
* Plugins: guard marketplace archive downloads * Plugins: harden marketplace download cleanup * Plugins: bound marketplace archive downloads * Plugins: harden marketplace archive failures * Plugins: reject drive-relative marketplace archives * Plugins: stream marketplace archive downloads
* Plugins: guard marketplace archive downloads * Plugins: harden marketplace download cleanup * Plugins: bound marketplace archive downloads * Plugins: harden marketplace archive failures * Plugins: reject drive-relative marketplace archives * Plugins: stream marketplace archive downloads
Summary
fetchWithSsrFGuard, derive temp filenames from the resolved final URL, and convert guarded-fetch failures into the normal structured install error shape.Change Type (select all)
Scope (select all touched areas)
Linked Issue/PR
Root Cause / Regression History (if applicable)
fetch()path while other remote download flows had already moved to the shared guarded fetch helper.git blame, prior PR, issue, or refactor if known): this path lagged behind the broader guarded-fetch rollout in the repo.Regression Test Plan (if applicable)
src/plugins/marketplace.test.tsUser-visible / Behavior Changes
Diagram (if applicable)
N/A
Security Impact (required)
NoNoNoNoNoYes, explain risk + mitigation:N/ARepro + Verification
Environment
Steps
pnpm test -- src/plugins/marketplace.test.ts.pnpm check.claude -p "/review"and apply any actionable feedback.Expected
Actual
pnpm test -- src/plugins/marketplace.test.tspassed.pnpm checkpassed.Evidence
Attach at least one:
Human Verification (required)
finalUrl; release handle cleanup on success and failure.Review Conversations
Compatibility / Migration
YesNoNoN/ARisks and Mitigations
pnpm checkgate.