Repository navigation
fix: flatten remote markdown images - #38895
Conversation
🔒 Aisle Security AnalysisWe found 2 potential security issue(s) in this PR:
1. 🟡 Remote image hardening bypass via reference-style Markdown images in Swift ChatMarkdownPreprocessor
Description
As a result, an attacker/model can embed remote images using reference-style image syntax, which will not be rewritten/removed by the preprocessor, and may still be rendered (and fetched) by the downstream Markdown renderer ( Examples that are not matched by the current regex:
Vulnerable code (only targets private static let markdownImagePattern = #"!\[([^\]]*)\]\(([^)]+)\)"#
...
guard let re = try? NSRegularExpression(pattern: self.markdownImagePattern) else {
return Result(cleaned: self.normalize(withoutTimestamps), images: [])
}Impact (if the renderer supports these syntaxes, as most Markdown parsers do):
RecommendationHandle all Markdown image forms (inline + reference-style) or enforce blocking at the renderer layer. Preferred: use a Markdown parser/AST and remove/replace image nodes regardless of syntax. If staying regex-based, add handling for reference-style images and strip their definitions: // Pseudocode: remove/replace both inline and reference-style images
let inline = try NSRegularExpression(pattern: #"!\[([^\]]*)\]\(([^)]+)\)"#)
let refImg = try NSRegularExpression(pattern: #"!\[([^\]]*)\]\[([^\]]*)\]"#)
let refDef = try NSRegularExpression(pattern: #"(?m)^\[([^\]]+)\]:\s*([^\s]+).*$"#)
// 1) Replace reference-style image uses with fallback label
// 2) Remove reference definitions that resolve to non-data URLs (or remove all image defs)Additionally, consider configuring 2. 🔵 Unbounded data-URI markdown images can cause browser resource-exhaustion in exported HTML
DescriptionThe export-HTML Markdown renderer now explicitly permits inline
Vulnerable code: const INLINE_DATA_IMAGE_RE = /^data:image\/[a-z0-9.+-]+;base64,/i;
...
if (!INLINE_DATA_IMAGE_RE.test(href)) {
return escapeHtml(label);
}
return `<img src="${escapeHtmlAttr(href)}" alt="${escapeHtmlAttr(label)}">`;RecommendationAdd strict validation and size limits for Markdown Suggested approach:
Example (illustrative): const SAFE_MD_IMAGE_MIME_RE = /^image\/(png|jpeg|gif|webp|avif)$/i;
const SAFE_BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/;
const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
function renderMarkdownImage(token) {
const label = normalizeMarkdownImageLabel(token?.text);
const href = typeof token?.href === 'string' ? token.href.trim() : '';
const m = href.match(/^data:([^;]+);base64,(.*)$/i);
if (!m) return escapeHtml(label);
const mime = m[1];
const payload = m[2].replace(/\s+/g, '');
if (!SAFE_MD_IMAGE_MIME_RE.test(mime) || !SAFE_BASE64_RE.test(payload)) {
return escapeHtml(label);
}
const bytes = Math.floor((payload.length * 3) / 4);
if (bytes > MAX_IMAGE_BYTES) {
return escapeHtml(label);
}
return `<img src="${escapeHtmlAttr(`data:${mime};base64,${payload}`)}" alt="${escapeHtmlAttr(label)}">`;
}Analyzed PR: #38895 at commit Last updated on: 2026-03-07T14:37:32Z |
Greptile SummaryThis PR addresses a security concern by preventing remote markdown images in assistant output from triggering network fetches at render time. It consistently applies the fix across three rendering surfaces: the Control UI TypeScript renderer ( Issues found:
Confidence Score: 2/5
Last reviewed commit: de964a8 |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: de964a8f7e
ℹ️ 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".
🔒 Aisle Security AnalysisWe found 3 potential security issue(s) in this PR:
1. 🟡 Unbounded base64 data-URL decoding in markdown image preprocessing can cause memory/CPU DoS
Description
This is risky when the Markdown is untrusted (e.g., content received from a server/assistant/user), because:
An attacker can provide a very large base64 data URL (or many of them) to trigger excessive memory allocation and CPU use, leading to app freezes or crashes. Vulnerable code: let b64 = String(trimmed[trimmed.index(after: comma)...])
let image = Data(base64Encoded: b64).flatMap(OpenClawPlatformImage.init(data:))RecommendationAdd explicit resource limits before attempting to decode base64 or instantiate an image. Suggested defenses (apply at least 1–2 of these):
Example (size + count limits): private static let maxInlineImages = 4
private static let maxBase64Chars = 2_000_000 // ~1.5MB decoded
static func preprocess(markdown raw: String) -> Result {
...
var decodedCount = 0
for match in matches.reversed() {
...
if decodedCount < maxInlineImages,
let inlineImage = self.inlineImage(label: label, source: source) {
images.append(inlineImage)
decodedCount += 1
cleaned.replaceCharacters(in: match.range, with: "")
} else {
cleaned.replaceCharacters(in: match.range, with: self.fallbackImageLabel(label))
}
}
...
}
private static func inlineImage(label: String, source: String) -> InlineImage? {
...
let b64 = String(trimmed[trimmed.index(after: comma)...])
guard b64.count <= maxBase64Chars else { return nil }
guard let data = Data(base64Encoded: b64), data.count <= 1_000_000 else { return nil }
let image = OpenClawPlatformImage(data: data)
return InlineImage(label: label, image: image)
}This ensures untrusted Markdown cannot force the app to allocate arbitrarily large buffers during preprocessing. 2. 🔵 Unrestricted SVG data-URI images allowed in markdown rendering (UI) enabling active content / remote loads
DescriptionThe UI markdown renderer allows any Even with HTML escaping, allowing SVG-as-image is risky because SVG is an active format and may:
Vulnerable code: const INLINE_DATA_IMAGE_RE = /^data:image\/[a-z0-9.+-]+;base64,/i;
...
if (!INLINE_DATA_IMAGE_RE.test(href)) {
return escapeHtml(label);
}
return `<img src="${escapeHtml(href)}" alt="${escapeHtml(label)}">`;RecommendationRestrict inline data-image rendering to safe raster formats and reject SVG. For example: const INLINE_DATA_IMAGE_RE =
/^data:image\/(png|jpeg|gif|webp|bmp|tiff|avif);base64,[A-Za-z0-9+/]+={0,2}$/i;
// Optionally enforce a maximum length to avoid huge HTML/DOM payloads.Add a regression test that 3. 🔵 Potential stored XSS via permissive data:image handling for Markdown images (SVG allowed)
DescriptionThe new Markdown image renderer allows any
Vulnerable code: const INLINE_DATA_IMAGE_RE = /^data:image\/[a-z0-9.+-]+;base64,/i;
...
return `<img src="${escapeHtmlAttr(href)}" alt="${escapeHtmlAttr(label)}">`;RecommendationRestrict Markdown-embedded data images to a strict allowlist of non-active raster formats (and ideally reuse existing validation helpers).
Example: const SAFE_MARKDOWN_IMAGE_MIME_RE = /^data:image\/(png|jpeg|gif|webp|bmp|tiff|avif);base64,/i;
function renderMarkdownImage(token) {
const label = normalizeMarkdownImageLabel(token?.text);
const hrefRaw = typeof token?.href === "string" ? token.href.trim() : "";
if (!SAFE_MARKDOWN_IMAGE_MIME_RE.test(hrefRaw)) {
return escapeHtml(label);
}
// Split and validate base64 payload
const commaIdx = hrefRaw.indexOf(",");
const prefix = hrefRaw.slice(0, commaIdx + 1);
const payload = hrefRaw.slice(commaIdx + 1);
const base64 = sanitizeImageBase64(payload);
if (!base64) return escapeHtml(label);
return `<img src="${escapeHtmlAttr(prefix + base64)}" alt="${escapeHtmlAttr(label)}">`;
}If SVG support is required, sanitize SVG content using a dedicated SVG sanitizer before embedding, and consider adding a restrictive CSP for the exported document. Analyzed PR: #38895 at commit Last updated on: 2026-03-07T14:15:47Z |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: aca1fe6aa9
ℹ️ 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".
| "Chat history since last reply (untrusted, for context):", | ||
| ] | ||
|
|
||
| private static let markdownImagePattern = #"!\[([^\]]*)\]\(([^)]+)\)"# |
There was a problem hiding this comment.
Avoid flattening image syntax inside code blocks
ChatMarkdownPreprocessor.preprocess now runs markdownImagePattern over the raw markdown text, so  inside fenced/inline code is also rewritten to fallback text before markdown rendering. In messages that demonstrate markdown syntax (for example ```md  ```), the code sample is corrupted to plain text even though no image would have rendered there; this regression was introduced when matching was widened from data:image/... to all image URLs.
Useful? React with 👍 / 👎.
aca1fe6 to
062348e
Compare
|
Landed via temp rebase onto main.
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 062348e0d8
ℹ️ 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".
| "Chat history since last reply (untrusted, for context):", | ||
| ] | ||
|
|
||
| private static let markdownImagePattern = #"!\[([^\]]*)\]\(([^)]+)\)"# |
There was a problem hiding this comment.
Parse markdown image URLs with balanced parentheses
The new markdownImagePattern stops href at the first ) ([^)]+), so remote image links that contain parentheses are only partially matched. In Swift chat preprocessing, an input like .png) becomes x.png) after replacement, which corrupts the rendered message and leaves non-flattened URL fragments in output; this regression appears now because the regex was widened from data URLs to all markdown images.
Useful? React with 👍 / 👎.
(cherry picked from commit bdd0f74)
(cherry picked from commit bdd0f74)
Summary
data:image/...markdown images; flatten all other markdown images to alt text orimagein Control UI, exported HTML, and shared Swift chat.Change Type (select all)
Scope (select all touched areas)
Linked Issue/PR
User-visible / Behavior Changes
data:image/...markdown still renders as images.Security Impact (required)
NoNoNoNoNoYes, explain risk + mitigation:Repro + Verification
Environment
Steps
..Expected
Actual
Evidence
Human Verification (required)
What you personally verified (not just CI), and how:
pnpm vitest run src/ui/markdown.test.tsinui/;pnpm exec vitest run src/auto-reply/reply/export-html/template.security.test.ts;swift test --filter ChatMarkdownPreprocessorTestsinapps/shared/OpenClawKitjavascript:image URLs,data:image/...Compatibility / Migration
YesNoNoFailure Recovery (if this breaks)
de964a8f7e5b1a4ef1162753e12c1acc2c2288b0Risks and Mitigations
data:image/...markdown is still supported, and non-data images degrade to readable text.