Repository navigation
fix(gateway): persist webchat images as managed media - #70719
Conversation
🔒 Aisle Security AnalysisWe found 5 potential security issue(s) in this PR:
1. 🟠 Unbounded disk consumption via persisted managed outgoing images (no quota / retention pruning)
DescriptionThe gateway persists assistant image attachments to disk under
When a transcript message is committed,
So an authenticated attacker (or a compromised client/operator token) can repeatedly generate messages with many images (each up to ~12MiB by default) and quickly exhaust disk, causing denial of service and potential data loss. Vulnerable code (persistence + history retention): const record: ManagedImageRecord = {
attachmentId: randomUUID(),
sessionKey,
messageId: params.messageId ?? null,
createdAt: new Date().toISOString(),
retentionClass: params.messageId ? "history" : "transient",
...
};
await writeManagedImageRecord(record, stateDir);await writeManagedImageRecord({
...record,
messageId,
retentionClass: "history",
updatedAt: new Date().toISOString(),
});Cleanup does not enforce any storage budget: } else if (record.messageId) {
shouldDelete = !(await recordMatchesTranscriptMessage(record, ...));
}RecommendationAdd storage quotas and enforce them at creation time. Suggested mitigations (can be combined):
Example (limit number of image URLs processed): const MAX_IMAGES_PER_MESSAGE = 4;
const mediaUrls = asArray(params.mediaUrls).slice(0, MAX_IMAGES_PER_MESSAGE);Example (refuse when session exceeds a byte budget): const SESSION_IMAGE_BUDGET_BYTES = 200 * 1024 * 1024; // 200MiB
const usedBytes = await sumManagedOutgoingBytesForSession(sessionKey, stateDir);
if (usedBytes + savedOriginal.size > SESSION_IMAGE_BUDGET_BYTES) {
throw createManagedImageAttachmentError("Managed image attachment budget exceeded");
}2. 🟠 IDOR: Managed outgoing image media endpoint bypasses session ownership for non-shared-secret auth methods
DescriptionThe
Impact:
Vulnerable code: const privilegedAccess =
requestAuth.trustDeclaredOperatorScopes || requestAuth.authMethod === "device-token";
...
if (!privilegedAccess) {
const requesterSessionKey = resolveRequesterSessionKey(req);
...
const ownsSession = await requesterOwnsManagedImageSession({ ... });
if (!ownsSession) { ... }
}RecommendationDo not equate Safer options:
Example fix (require session ownership unless const requestedScopes = resolveOpenAiCompatibleHttpOperatorScopes(req, requestAuth);
const isAdmin = requestedScopes.includes(ADMIN_SCOPE);
if (!isAdmin) {
const requesterSessionKey = resolveRequesterSessionKey(req);
if (!requesterSessionKey) {
sendJson(res, 403, { ok: false, error: { type: "forbidden", message: "requester session ownership required" } });
return true;
}
const ownsSession = await requesterOwnsManagedImageSession({
requesterSessionKey,
targetSessionKey: record.sessionKey,
});
if (!ownsSession) {
sendJson(res, 403, { ok: false, error: { type: "forbidden", message: "requester session does not own attachment session" } });
return true;
}
}Additionally, consider requiring a dedicated media scope (separate from 3. 🟡 Long-lived client-side caching of authenticated managed images (Cache-Control: private, max-age=31536000, immutable)
Description
This can lead to information disclosure on shared machines/profiles (e.g., another OS user, someone with access to the browser profile/disk, or a kiosk scenario) and makes incident response harder because cached artifacts persist for up to a year. Vulnerable code: res.setHeader("cache-control", "private, max-age=31536000, immutable");RecommendationTreat authenticated/media responses as sensitive and avoid long-lived caching. Safer default (recommended for authenticated resources): res.setHeader("Cache-Control", "no-store");
// (Optionally) res.setHeader("Pragma", "no-cache");If you need conditional caching for performance, prefer short-lived private caching and revalidation, and ensure caches key on auth: res.setHeader("Cache-Control", "private, max-age=0, must-revalidate");
res.setHeader("Vary", "Authorization, X-Openclaw-Requester-Session-Key");
// plus an ETag/Last-Modified implementation if you want 304 responsesAlso consider making the cache behavior configurable (e.g., disable caching when 4. 🟡 Managed outgoing image fetch ignores configured maxBytes and may download up to MEDIA_MAX_BYTES per URL (DoS risk)
Description
Vulnerable code: return await saveMediaSource(
mediaUrl,
undefined,
"outgoing/originals",
Math.max(limits.maxBytes, MEDIA_MAX_BYTES),
);RecommendationEnforce the managed-image limit at download time.
Example fix: return await saveMediaSource(
mediaUrl,
undefined,
"outgoing/originals",
limits.maxBytes,
);5. 🟡 Arbitrary file read via unvalidated on-disk managed image record path
DescriptionThe managed outgoing media handler reads a filesystem path directly from an on-disk JSON record and returns its bytes in an HTTP response.
Vulnerable code: body = await fs.readFile(record.original.path);While record files are normally written by the server, this is a security boundary issue in deployments where the records directory is writable by another process/user/tenant, or if another bug allows record modification. The read path contains no defense-in-depth checks (e.g., ensuring the path is under the managed originals directory and not a symlink). RecommendationAdd defense-in-depth validation before reading:
Example fix: const originalsDir = resolveOutgoingOriginalsDir(opts.stateDir ?? resolveStateDir());
const candidate = path.resolve(originalsDir, record.original.filename ?? "");
if (!candidate.startsWith(originalsDir + path.sep)) {
sendStatus(res, 404, "not found");
return true;
}
const st = await fs.lstat(candidate);
if (!st.isFile() || st.isSymbolicLink()) {
sendStatus(res, 404, "not found");
return true;
}
const body = await fs.readFile(candidate);(Alternatively reuse a helper like Analyzed PR: #70719 at commit Last updated on: 2026-04-23T19:13:51Z |
PR SummaryMedium Risk Overview Gateway adds Control UI rendering detects these managed-image URLs and fetches them with auth + requester session headers to render blob previews (avoiding Reviewed by Cursor Bugbot for commit b542446. Bugbot is set up for automated code reviews on this repo. Configure here. |
Greptile SummaryThis PR fixes a real regression where assistant/generated images disappeared from the Control UI chat history on reload. It introduces a managed media layer ( Confidence Score: 5/5Safe to merge; the two remaining findings are both P2 style/hardening concerns that do not block correctness. Auth, session ownership, scope, UUID validation, and transcript-reference checks are all in place. The commit ordering in chat.ts ensures records are committed before the UI receives managed image URLs. All remaining findings are P2 (blob URL cache memory pressure and a missing containment assertion on the served file path). No P0/P1 issues found. ui/src/ui/chat/grouped-render.ts (blob URL cache cleanup) and src/gateway/managed-image-attachments.ts (path containment on serve) Prompt To Fix All With AIThis is a comment left during a code review.
Path: ui/src/ui/chat/grouped-render.ts
Line: 80-83
Comment:
**Blob URL cache lacks production cleanup**
`managedImageBlobUrlResolvedCache` accumulates `URL.createObjectURL` blob URLs indefinitely — there is no revocation in production paths (only in `resetAssistantAttachmentAvailabilityCacheForTest`). In long-lived Control UI sessions with many assistant images, each unique image URL creates a new `Blob` reference that is never released, leaking memory proportional to the number of images rendered.
Consider adding a maximum cache size with LRU eviction, calling `URL.revokeObjectURL` on evicted entries, or revoking on session reset/navigation events.
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/gateway/managed-image-attachments.ts
Line: 1079-1085
Comment:
**No path-containment assertion before serving record file**
`record.original.path` is read from a JSON file on disk and passed directly to `fs.readFile` without verifying it stays within `stateDir/media/outgoing/originals/`. In practice, all records are written by `writeManagedImageRecord` which always places files under that subdirectory, so this is low risk. However, adding a containment assertion (`path.startsWith(resolveOutgoingOriginalsDir(opts.stateDir))`) would provide defense-in-depth against corrupt or manually tampered record files that could cause the handler to serve arbitrary filesystem paths.
How can I resolve this? If you propose a fix, please make it concise.Reviews (1): Last reviewed commit: "fix(gateway): persist webchat images as ..." | Re-trigger Greptile |
| const managedImageBlobUrlCache = new Map<string, Promise<string | null>>(); | ||
| const managedImageBlobUrlResolvedCache = new Map<string, string>(); | ||
| const managedImageBlobUrlMissCache = new Map<string, number>(); | ||
| const MANAGED_IMAGE_BLOB_URL_MISS_RETRY_MS = 5_000; |
There was a problem hiding this comment.
Blob URL cache lacks production cleanup
managedImageBlobUrlResolvedCache accumulates URL.createObjectURL blob URLs indefinitely — there is no revocation in production paths (only in resetAssistantAttachmentAvailabilityCacheForTest). In long-lived Control UI sessions with many assistant images, each unique image URL creates a new Blob reference that is never released, leaking memory proportional to the number of images rendered.
Consider adding a maximum cache size with LRU eviction, calling URL.revokeObjectURL on evicted entries, or revoking on session reset/navigation events.
Prompt To Fix With AI
This is a comment left during a code review.
Path: ui/src/ui/chat/grouped-render.ts
Line: 80-83
Comment:
**Blob URL cache lacks production cleanup**
`managedImageBlobUrlResolvedCache` accumulates `URL.createObjectURL` blob URLs indefinitely — there is no revocation in production paths (only in `resetAssistantAttachmentAvailabilityCacheForTest`). In long-lived Control UI sessions with many assistant images, each unique image URL creates a new `Blob` reference that is never released, leaking memory proportional to the number of images rendered.
Consider adding a maximum cache size with LRU eviction, calling `URL.revokeObjectURL` on evicted entries, or revoking on session reset/navigation events.
How can I resolve this? If you propose a fix, please make it concise.| let body: Buffer; | ||
| try { | ||
| body = await fs.readFile(record.original.path); | ||
| } catch { | ||
| sendStatus(res, 404, "not found"); | ||
| return true; | ||
| } |
There was a problem hiding this comment.
No path-containment assertion before serving record file
record.original.path is read from a JSON file on disk and passed directly to fs.readFile without verifying it stays within stateDir/media/outgoing/originals/. In practice, all records are written by writeManagedImageRecord which always places files under that subdirectory, so this is low risk. However, adding a containment assertion (path.startsWith(resolveOutgoingOriginalsDir(opts.stateDir))) would provide defense-in-depth against corrupt or manually tampered record files that could cause the handler to serve arbitrary filesystem paths.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/gateway/managed-image-attachments.ts
Line: 1079-1085
Comment:
**No path-containment assertion before serving record file**
`record.original.path` is read from a JSON file on disk and passed directly to `fs.readFile` without verifying it stays within `stateDir/media/outgoing/originals/`. In practice, all records are written by `writeManagedImageRecord` which always places files under that subdirectory, so this is low risk. However, adding a containment assertion (`path.startsWith(resolveOutgoingOriginalsDir(opts.stateDir))`) would provide defense-in-depth against corrupt or manually tampered record files that could cause the handler to serve arbitrary filesystem paths.
How can I resolve this? If you propose a fix, please make it concise.| const managedImageBlobUrlCache = new Map<string, Promise<string | null>>(); | ||
| const managedImageBlobUrlResolvedCache = new Map<string, string>(); | ||
| const managedImageBlobUrlMissCache = new Map<string, number>(); | ||
| const MANAGED_IMAGE_BLOB_URL_MISS_RETRY_MS = 5_000; |
There was a problem hiding this comment.
Managed image blob URLs never revoked causing memory leak
Low Severity
managedImageBlobUrlResolvedCache accumulates blob URLs created via URL.createObjectURL but never revokes them outside of the test-only reset function. Each blob URL holds a reference to the full image binary data in browser memory. In long-lived sessions with many generated images, this causes unbounded memory growth.
Reviewed by Cursor Bugbot for commit ef180f1c0773fb5d760c44fb287aacbe13ba064d. Configure here.
ef180f1 to
55b3bb3
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ef180f1c07
ℹ️ About Codex in GitHub
Your team has set up Codex to 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 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const normalizedBasePath = | ||
| basePath && basePath !== "/" ? (basePath.endsWith("/") ? basePath.slice(0, -1) : basePath) : ""; | ||
| return `${normalizedBasePath}${source}`; |
There was a problem hiding this comment.
Stop prefixing managed image API URLs with control-ui basePath
Managed image URLs are persisted as absolute /api/chat/media/outgoing/... paths, but this helper now prepends basePath to any leading-slash source. In deployments where Control UI is mounted under a subpath (for example /openclaw), the browser fetches /openclaw/api/chat/media/outgoing/..., while the new gateway handler only matches /api/chat/media/outgoing/...; the fetch then misses the media handler and image history previews fail after reload for those installs.
Useful? React with 👍 / 👎.
| const blobUrl = URL.createObjectURL(blob); | ||
| managedImageBlobUrlResolvedCache.set(cacheKey, blobUrl); |
There was a problem hiding this comment.
Revoke managed image blob URLs to avoid unbounded UI memory growth
Each successful managed-image fetch creates an object URL and stores it in managedImageBlobUrlResolvedCache, but production code never revokes these URLs or evicts the cache; revocation currently only happens in a test-reset helper. In long-lived chats with many distinct generated images, this causes renderer memory to grow indefinitely until a full page reload.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
There are 3 total unresolved issues (including 2 from previous reviews).
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 8cf9640. Configure here.
| return path.resolve(trimmed); | ||
| } | ||
| return undefined; | ||
| } |
There was a problem hiding this comment.
Duplicated resolveLocalMediaPath utility across two files
Low Severity
The resolveLocalMediaPath function in managed-image-attachments.ts is nearly identical to the private resolveLocalMediaPath in media/local-roots.ts. Both handle data: URLs, file://, ~, absolute paths, and Windows drive prefixes in the same way. Maintaining two copies risks them drifting apart over time and makes security-sensitive path resolution harder to audit.
Reviewed by Cursor Bugbot for commit 8cf9640. Configure here.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8cf964058d
ℹ️ About Codex in GitHub
Your team has set up Codex to 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 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| function isManagedOutgoingImageSource(source: string): boolean { | ||
| try { | ||
| const parsed = new URL(source, window.location.origin); | ||
| return parsed.pathname.startsWith("/api/chat/media/outgoing/"); |
There was a problem hiding this comment.
Reject cross-origin managed-image URLs before auth fetch
isManagedOutgoingImageSource treats any URL whose pathname starts with /api/chat/media/outgoing/ as managed, even when the origin is different. That lets a crafted image block like https://attacker.example/api/chat/media/outgoing/... enter the managed fetch path, where resolveManagedOutgoingImageBlobUrl adds Authorization and requester-session headers, leaking credentials to the attacker origin. Restrict managed-image detection/fetching to same-origin (or relative) URLs before attaching auth headers.
Useful? React with 👍 / 👎.
| const localMediaPath = resolveLocalMediaPath(mediaUrl); | ||
| if (localMediaPath) { | ||
| await assertLocalMediaAllowed(localMediaPath, params.localRoots); | ||
| } | ||
| return await saveMediaSource( |
There was a problem hiding this comment.
Enforce localRoots for relative managed image paths
The local-path allowlist check is conditional on resolveLocalMediaPath(mediaUrl) returning a path, but that helper returns undefined for relative filesystem paths. As a result, relative sources (for example ../secret.png) skip assertLocalMediaAllowed and are still handed to saveMediaSource, which can read host files outside configured localRoots if the path resolves on disk. Relative local paths should be resolved and validated against localRoots (or rejected) before ingestion.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d018fe770e
ℹ️ About Codex in GitHub
Your team has set up Codex to 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 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (normalized.length === 0) { | ||
| return rawTextPayloadCount > 0 ? [{ type: "text", text: "" }] : undefined; |
There was a problem hiding this comment.
Avoid creating empty content for dropped silent replies
When normalizeReplyPayloadsForDelivery filters out a payload (for example a NO_REPLY-only final payload), this branch still manufactures an empty text block. Downstream, chat.send treats assistantContent?.length as truthy and attempts a transcript append even though transcriptReply is empty, which can produce phantom assistant entries (blank/"undefined") instead of suppressing the reply. This regresses silent-reply behavior and pollutes chat.history for runs that intentionally emit no visible assistant text.
Useful? React with 👍 / 👎.
10373a1 to
b542446
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b54244688f
ℹ️ About Codex in GitHub
Your team has set up Codex to 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 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| hasSensitiveMedia | ||
| ? await buildAssistantDisplayContentFromReplyPayloads({ | ||
| sessionKey, | ||
| payloads: finalPayloads, | ||
| managedImageLocalRoots: mediaLocalRoots, |
There was a problem hiding this comment.
Reuse prepared managed image blocks for mixed-sensitivity replies
When hasSensitiveMedia is true, this branch calls buildAssistantDisplayContentFromReplyPayloads a second time even though assistantContent was already prepared earlier in the same flow. That second call creates a new set of managed image attachment IDs, so the transcript is appended with one set of URLs while attachManagedOutgoingImagesToMessage later marks the first set as history-linked; in mixed payloads (at least one sensitive media payload plus at least one non-sensitive image payload), the persisted image URLs can point to records that remain transient and then 404 on fetch.
Useful? React with 👍 / 👎.
| const localMediaPath = resolveLocalMediaPath(mediaUrl); | ||
| if (localMediaPath) { | ||
| await assertLocalMediaAllowed(localMediaPath, params.localRoots); | ||
| } | ||
| return await saveMediaSource( |
There was a problem hiding this comment.
Save resolved local image path instead of raw source string
This code resolves local paths (including file:// and ~) into localMediaPath for access checks, but still passes the original mediaUrl to saveMediaSource. For non-HTTP local formats, saveMediaSource treats that raw string as a filesystem path literal, so valid allowed images like file:///.../image.png or ~/image.png fail to ingest and are silently dropped when continueOnPrepareError is enabled.
Useful? React with 👍 / 👎.
* fix(gateway): persist webchat images as managed media * fix(ui): keep managed image auth same-origin * docs: note managed webchat image fix
* fix(gateway): persist webchat images as managed media * fix(ui): keep managed image auth same-origin * docs: note managed webchat image fix
* fix(gateway): persist webchat images as managed media * fix(ui): keep managed image auth same-origin * docs: note managed webchat image fix
* fix(gateway): persist webchat images as managed media * fix(ui): keep managed image auth same-origin * docs: note managed webchat image fix
* fix(gateway): persist webchat images as managed media * fix(ui): keep managed image auth same-origin * docs: note managed webchat image fix
* fix(gateway): persist webchat images as managed media * fix(ui): keep managed image auth same-origin * docs: note managed webchat image fix
* fix(gateway): persist webchat images as managed media * fix(ui): keep managed image auth same-origin * docs: note managed webchat image fix


Summary
/api/chat/media/outgoing/.../fullroute, and rendered by the Control UI through authenticated blob fetches.Change Type (select all)
Scope (select all touched areas)
Linked Issue/PR
Root Cause (if applicable)
chat.historyintentionally strips large inline image payloads for safety.chat.send -> transcript persistence -> chat.history -> Control UI render.Regression Test Plan (if applicable)
src/gateway/server.chat.gateway-server-chat.test.tssrc/gateway/managed-image-attachments.test.tsui/src/ui/chat/grouped-render.test.tschat.history, raw base64 is absent from history payloads, and the UI fetches managed image URLs with auth/session headers before rendering.User-visible / Behavior Changes
Control UI chat reloads can display assistant/generated images through durable managed media URLs instead of depending on inline base64 history payloads.
Diagram (if applicable)
Security Impact (required)
Yes, explain risk + mitigation: the new media route serves only managed image records. It requires gateway HTTP auth,chat.historyscope, requester session ownership for non-privileged auth, UUID attachment ids, and verifies the attachment is still referenced by the transcript before serving bytes.Repro + Verification
Environment
Steps
mediaUrls: [data:image/png;base64,...].chat.history./api/chat/media/outgoing/.../fullimage blocks and no raw base64.Expected
Actual
Evidence
Human Verification (required)
What you personally verified (not just CI), and how:
pnpm test src/gateway/managed-image-attachments.test.ts src/gateway/server.chat.gateway-server-chat.test.ts ui/src/ui/chat/grouped-render.test.tspnpm test src/gateway/server-methods/chat.directive-tags.test.ts src/gateway/managed-image-attachments.test.ts src/gateway/server.chat.gateway-server-chat.test.ts ui/src/ui/chat/grouped-render.test.tspnpm check:changedpnpm buildpnpm openclaw qa suite --provider-mode mock-openai --scenario control-ui-qa-channel-image-roundtrip --output-dir .artifacts/qa-e2e/managed-images-control-ui-pr70719 --concurrency 1Review Conversations
Compatibility / Migration
Risks and Mitigations
chat.history, transient records expire, and the media route refuses records no longer referenced by transcript history.<img>tags.