Skip to content

fix(plugins): guard marketplace archive downloads - #58267

Merged
jacobtomlinson merged 6 commits into
openclaw:mainfrom
jacobtomlinson:fix/fix-153
Mar 31, 2026
Merged

jacobtomlinson merged 6 commits into
openclaw:mainfrom
jacobtomlinson:fix/fix-153

Conversation

@jacobtomlinson

Copy link
Copy Markdown
Contributor

Summary

  • Problem: marketplace archive installs fetched remote archives directly instead of using the shared guarded fetch helper used by other download flows.
  • Why it matters: this path behaved differently from the rest of the download stack and surfaced remote download failures less consistently.
  • What changed: marketplace archive downloads now use fetchWithSsrFGuard, derive temp filenames from the resolved final URL, and convert guarded-fetch failures into the normal structured install error shape.
  • What did NOT change (scope boundary): marketplace source validation, git clone flows, and plugin install behavior outside archive downloads.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

  • Closes #: N/A
  • Related #: N/A
  • This PR fixes a bug or regression

Root Cause / Regression History (if applicable)

  • Root cause: the marketplace archive download helper kept a direct fetch() path while other remote download flows had already moved to the shared guarded fetch helper.
  • Missing detection / guardrail: the marketplace archive path did not have a regression test asserting that archive downloads go through the guarded fetch helper.
  • Prior context (git blame, prior PR, issue, or refactor if known): this path lagged behind the broader guarded-fetch rollout in the repo.
  • Why this regressed now: N/A
  • If unknown, what was ruled out: N/A

Regression Test Plan (if applicable)

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file: src/plugins/marketplace.test.ts
  • Scenario the test should lock in: archive marketplace downloads use the guarded fetch helper, release it on success and empty-body failures, and surface rejected guarded fetches as structured install errors.
  • Why this is the smallest reliable guardrail: it exercises the exact marketplace archive path without needing live network access.
  • Existing test that already covers this (if any): updated empty-body archive download coverage in the same file.
  • If no new test is added, why not: N/A

User-visible / Behavior Changes

  • Marketplace archive install failures now return structured download errors when the guarded fetch helper rejects the URL.
  • Redirected archive downloads now derive their temp filename from the final resolved URL.

Diagram (if applicable)

N/A

Security Impact (required)

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? No
  • New/changed network calls? No
  • Command/tool execution surface changed? No
  • Data access scope changed? No
  • If any Yes, explain risk + mitigation: N/A

Repro + Verification

Environment

  • OS: Ubuntu
  • Runtime/container: Node 22 / pnpm workspace
  • Model/provider: N/A
  • Integration/channel (if any): marketplace plugin install path
  • Relevant config (redacted): default local dev setup

Steps

  1. Run pnpm test -- src/plugins/marketplace.test.ts.
  2. Run pnpm check.
  3. Run claude -p "/review" and apply any actionable feedback.

Expected

  • Marketplace archive downloads use the guarded fetch helper and return structured errors on failures.

Actual

  • pnpm test -- src/plugins/marketplace.test.ts passed.
  • pnpm check passed.
  • Local review flagged the rejected-guarded-fetch error path; this PR now returns a structured install error for that case and the targeted tests were rerun.

Evidence

Attach at least one:

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Human Verification (required)

  • Verified scenarios: successful archive download path uses the guarded fetch helper; empty-body responses still return the expected structured error; guarded-fetch rejection now returns a structured install error instead of throwing.
  • Edge cases checked: redirect-derived filename selection via finalUrl; release handle cleanup on success and failure.
  • What you did not verify: live marketplace installs against an external registry.

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

Compatibility / Migration

  • Backward compatible? Yes
  • Config/env changes? No
  • Migration needed? No
  • If yes, exact upgrade steps: N/A

Risks and Mitigations

  • Risk: marketplace installs that previously surfaced raw thrown errors now return a structured download failure instead.
    • Mitigation: added targeted unit coverage for empty-body and rejected-guarded-fetch paths, plus the normal pnpm check gate.

@openclaw-barnacle openclaw-barnacle Bot added size: S maintainer Maintainer-authored PR labels Mar 31, 2026
@greptile-apps

greptile-apps Bot commented Mar 31, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR guards marketplace archive downloads behind fetchWithSsrFGuard, bringing the marketplace path into line with the rest of the guarded-fetch rollout in the repo. It also derives the temp filename from the resolved finalUrl (post-redirect) rather than the original URL, and wraps all guarded-fetch failures into the standard structured { ok: false, error } shape.

Key changes:

  • downloadUrlToTempFile in src/plugins/marketplace.ts replaces the bare fetch() call with fetchWithSsrFGuard and manages the returned release handle in a finally block.
  • Two new targeted unit tests cover the happy path and SSRF-guard-rejection path; the existing empty-body test is upgraded to assert release is called exactly once.
  • Two minor hardening opportunities remain: (1) if response.body.pipeTo() throws mid-stream the tmpDir is not cleaned up (pre-existing, but now silently swallowed by the outer catch), and (2) a release() error thrown in the finally block can shadow an otherwise-successful write result and leak tmpDir — wrapping release() in .catch(() => undefined) would eliminate both risks for the success path.

Confidence Score: 5/5

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

Important Files Changed

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

Comment thread src/plugins/marketplace.ts Resolved
Comment thread src/plugins/marketplace.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 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".

Comment thread src/plugins/marketplace.ts Resolved
@aisle-research-bot

aisle-research-bot Bot commented Mar 31, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 3 potential security issue(s) in this PR:

# Severity Title
1 🟠 High readResponseWithLimit maxBytes bypass via arrayBuffer fallback causes memory DoS
2 🟡 Medium NaN timeout disables download timeouts in marketplace archive fetch (potential hang/DoS)
3 🟡 Medium Unsanitized URL and error message reflected to CLI stderr (info disclosure + terminal/log injection)
1. 🟠 readResponseWithLimit maxBytes bypass via arrayBuffer fallback causes memory DoS
Property Value
Severity High
CWE CWE-770
Location src/media/read-response-with-limit.ts:59-70

Description

readResponseWithLimit() is intended to enforce a maximum download size, but when res.body is missing or does not implement getReader(), it falls back to await res.arrayBuffer().

  • Response.arrayBuffer() buffers the entire response body in memory.
  • The size check/truncation happens after buffering, so an attacker-controlled endpoint can return a very large payload and cause high memory usage / OOM even when maxBytes is small.
  • This is especially risky because callers (e.g., marketplace archive download) rely on maxBytes as a hard limit to prevent resource exhaustion.

Vulnerable code:

const fallback = Buffer.from(await res.arrayBuffer());
if (fallback.length > maxBytes) {
  return {
    buffer: fallback.subarray(0, maxBytes),
    size: fallback.length,
    truncated: true,
  };
}

Recommendation

Ensure maxBytes is enforced during reading, not after full buffering.

Options:

  1. Fail closed when streaming APIs aren’t available:
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 };
}
  1. Preferably, implement a streaming reader for the fallback case as well (e.g., by converting the body to a stream/async-iterable and accumulating up to maxBytes), so the cap is always enforced regardless of response type.
2. 🟡 NaN timeout disables download timeouts in marketplace archive fetch (potential hang/DoS)
Property Value
Severity Medium
CWE CWE-20
Location src/plugins/marketplace.ts:615-624

Description

downloadUrlToTempFile() derives downloadTimeoutMs from the optional timeoutMs parameter, but does not validate that the value is a finite number.

  • If a caller passes NaN (or another non-finite value), Math.floor(NaN) becomes NaN and Math.max(1000, NaN) also becomes NaN.
  • downloadTimeoutMs is then passed to:
    • fetchWithSsrFGuard({ timeoutMs }) → buildTimeoutAbortSignal() treats falsy timeoutMs (including NaN) as “no timeout” and returns no timeout signal.
    • readResponseWithLimit(..., { chunkTimeoutMs }) → the code uses chunkTimeoutMs ? ... : reader.read(), so NaN disables the idle timeout as well.

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,

Recommendation

Validate/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 buildTimeoutAbortSignal() treat NaN/non-finite values as invalid rather than as “no timeout”.

3. 🟡 Unsanitized URL and error message reflected to CLI stderr (info disclosure + terminal/log injection)
Property Value
Severity Medium
CWE CWE-117
Location src/plugins/marketplace.ts:670-677

Description

downloadUrlToTempFile() embeds the full, potentially user-controlled URL and the raw error.message into a returned error string. The CLI prints this string directly via defaultRuntime.error(...) (which calls console.error), without redaction or control-character neutralization.

Impacts:

  • Sensitive data exposure: URLs may contain credentials/tokens in the userinfo or query/fragment (e.g. https://user:pass@​host/... or ...?token=...). These secrets can be leaked to terminal output, logs, CI artifacts, or telemetry that captures stderr.
  • Terminal/log injection: a crafted URL can include control characters (e.g. \r, \n, ANSI escapes) which, when printed, can forge log lines, spoof messages, or manipulate terminal output.
  • Internal security detail leakage: SSRF-guard rejections and network stack errors are forwarded verbatim (e.g. allowlist/blocked host diagnostics), potentially disclosing internal policy details.

Vulnerable code:

return {
  ok: false,
  error: `failed to download ${url}: ${error instanceof Error ? error.message : String(error)}`,
};

Recommendation

  • Redact and sanitize before returning/printing:
    • Strip URL userinfo (username:password@) and consider omitting or redacting query/fragment.
    • Neutralize control characters before logging (replace \r, \n, \t, and ASCII control chars; optionally strip ANSI escapes).
  • Avoid echoing low-level SSRF-guard diagnostics to end users. Map known rejection reasons to a generic message, while keeping detailed diagnostics in structured debug logs accessible only to operators.

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. code: 'SSRF_BLOCKED') and letting the CLI decide how much detail to print.


Analyzed PR: #58267 at commit 53e49f1

Last updated on: 2026-03-31T09:46:37Z

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 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".

Comment thread src/plugins/marketplace.ts Resolved

@sharkqwy sharkqwy left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Review: marketplace archive download hardening

Thorough security improvement. Walking through the changes:

What this fixes well

  1. SSRF guard integration — Downloads now route through fetchWithSsrFGuard with an explicit auditContext, which means SSRF protections (hostname blocking, redirect following) apply to marketplace archive fetches. The test for 169.254.169.254 rejection confirms the guard is wired in.

  2. Size enforcement — Two-layer size check: Content-Length header pre-check and readResponseWithLimit during streaming. This prevents both declared-large and drip-feed-large payloads.

  3. Filename sanitization — resolveSafeMarketplaceDownloadFileName strips traversal vectors, and the path.relative check after path.resolve is good defense-in-depth even though basename should already be safe.

  4. Temp dir cleanup — The outer catch now cleans up tmpDir on any failure path, and the test listMarketplaceDownloadTempDirs assertion confirms no leaked directories. The old code had no cleanup on streaming errors.

  5. Timeout propagation — downloadTimeoutMs flows 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. 👍

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 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".

Comment thread src/plugins/marketplace.ts Resolved
@jacobtomlinson
jacobtomlinson merged commit 2ce44ca into openclaw:main Mar 31, 2026
52 of 54 checks passed
@jacobtomlinson
jacobtomlinson deleted the fix/fix-153 branch March 31, 2026 11:59
singleGanghood pushed a commit to singleGanghood/openclaw that referenced this pull request Mar 31, 2026
* 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
vincentkoc pushed a commit that referenced this pull request Mar 31, 2026
* 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
steipete pushed a commit to Mlightsnow/openclaw that referenced this pull request Apr 1, 2026
* 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
lovewanwan pushed a commit to lovewanwan/openclaw that referenced this pull request Apr 28, 2026
* 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
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
* 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
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
* 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
Nachx639 pushed a commit to Nachx639/clawdbot that referenced this pull request Jun 17, 2026
* 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
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
* 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
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
* 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
zooqueen pushed a commit to zooqueen/openclaw that referenced this pull request Sep 11, 2026
* 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
globalcaos pushed a commit to globalcaos/tinkerclaw that referenced this pull request Sep 29, 2026
* 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
lhfer pushed a commit to lhfer/openclaw that referenced this pull request Oct 11, 2026
* 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

maintainer Maintainer-authored PR size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants