Amazon Ergo 1.0 · Heavy

enhance-embed-url-handling-and-validation-system-discourse-cursor

Discourse · Ruby · M · 100–299 lines · 6 files

The generalist plus 9 specialist lens agents in parallel, then the same verify and dedup steps. Judge: Claude Opus 5.5.

Gold bugs found
13 of 30
Comments published
18
Comments matching a bug
13
Comments not matching
5
Cost of this PR
$5.323

Published comments (18)

criticalsecurityapp/models/topic_embed.rb:13

Imported-from URL is not HTML-escaped, allowing stored XSS — A `'` in the URL can break out of the `href` attribute and inject event handlers; because imported posts are rendered with `raw`/`html_safe`, this becomes stored XSS on the forum origin. Escape the URL in both the attribute and link text, or build the link with a tag helper.

criticalsecurityapp/models/topic_embed.rb:22-23

Imported embed HTML is stored without sanitization — Feed or remote HTML can contain `<script>` or event-handler attributes that execute for every embed viewer because `cook_method: raw_html` and `raw post.cooked` bypass Discourse's normal sanitization; `absolutize_urls` does not remove active content. Sanitize imported HTML with a whitelist before storing it.

highsecurityapp/models/topic_embed.rb:48

SSRF via redirect following in TopicEmbed.import_remote — An allowlisted URL can redirect `open(url)` to an internal or link-local address, bypassing `TopicRetriever#invalid_host?` and fetching the response server-side. Disable redirects or re-validate every redirect target.

highbugdb/migrate/20131217174004_create_topic_embeds.rb:6

embed_url column rejects valid URLs longer than 255 characters — Valid URLs over 255 characters fail on insert with a truncation error, or are silently truncated under permissive MySQL settings, so they cannot be imported reliably. Change `embed_url` from `varchar(255)` to a `text` column.

highbugapp/views/embed/best.html.erb:2-6

Malformed `<%- end if %>` breaks the embed view — The successful embed path cannot render because Ruby parses the trailing `if` in `<%- end if %>` as a modifier conditional without a condition, making the ERB template a syntax error. Replace it with `<%- end %>`.

highbuglib/tasks/disqus.thor:148-149

One bad Disqus link aborts the entire import — A dead or malformed `t[:link]` now raises `OpenURI::HTTPError`, `SocketError`, or `URI::InvalidURIError` during the `open` in `TopicEmbed.import_remote`, aborting the whole Disqus import before the `post.present?` fallback. Rescue these fetch errors and skip the link, or make `import_remote` return `nil`.

highbugapp/jobs/scheduled/poll_feed.rb:35

Nil RSS item content aborts the entire feed poll — RSS items that only provide `description` leave `i.content` nil, so `i.content.scrub` raises `NoMethodError` and aborts the whole poll, including any `TopicRetriever` call that invoked it. Use `i.content.to_s.scrub` or fall back to `i.description`.

mediumbugapp/models/topic_embed.rb:32-36

Trashed embedded post causes NoMethodError during import — The `Trashable` default scope makes `embed.post` `nil` for trashed posts, so `PostRevisor.new(nil).revise!` calls `@post.raw` in `should_revise?` and raises `NoMethodError`, breaking later updates and polls. Check `post.present?` before revising.

mediumperformancelib/topic_retriever.rb:41-42

Every new embed URL triggers a synchronous full-feed poll — A burst of distinct embed pages can multiply full-feed downloads, parsing, and re-imports into substantial network and database load because throttling is per exact URL. Remove the inline `Jobs::PollFeed` call and rely on the scheduled poll, or use conditional/cached fetching.

mediumbuglib/topic_retriever.rb:27-28

Non-atomic throttle key setup can block an embed URL forever — If the process stops between `$redis.setnx` and `$redis.expire`, or the expiration fails, the key never expires and `retrieved_recently?` returns true forever, permanently blocking that URL. Use `$redis.set` with `nx: true, ex: 60` to set the value and TTL atomically.

mediumbugapp/models/topic_embed.rb:15-29

Concurrent imports can abort on the unique embed_url index — Rescue the conflict and run the update path, or serialize imports per URL.

mediumsecurityapp/assets/javascripts/embed.js:15-17

Substring-based postMessage origin check allows spoofed resize messages — An unrelated iframe, popup, or ad whose origin string occurs inside `discourseUrl` can pass `discourseUrl.indexOf(e.origin)` and send a `discourse-resize` message with an attacker-chosen height. Require `e.origin === new URL(discourseUrl).origin` and verify `e.source === iframe.contentWindow`.

mediumbugspec/controllers/embed_controller_spec.rb:8-11

Missing embed_url test passes without reaching the action — `ensure_embeddable` rejects the request before `params.require(:embed_url)` because `embeddable_host` is blank and there is no referer, so this test stays green even if the required-parameter handling is removed. Set a valid `embeddable_host` and matching referer, then assert the 400 response.

mediumbugspec/jobs/poll_feed_spec.rb:12-16

Test passes even if the feed_polling_enabled? guard is removed — Blank feed settings let the example pass without exercising the enabled guard, so removing it would go unnoticed. Stub `feed_polling_url` and `embed_by_username` to present values while `feed_polling_enabled?` is false so `poll_feed` is blocked only by that guard.

mediumbugspec/jobs/poll_feed_spec.rb:18-22

feed_polling_url test does not exercise the URL guard — With `feed_polling_enabled?` defaulting to false, the `&&` short-circuits before `feed_polling_url.present?`, so removing that guard would leave this test green. Enable polling and stub `embed_by_username` so the URL check is the only condition preventing `poll_feed`.

mediumbugspec/jobs/poll_feed_spec.rb:24-28

Test passes without exercising the embed_by_username guard — The default-disabled polling setting and blank feed URL prevent `poll_feed` before the `embed_by_username.present?` check, so this test would survive removing that guard. Enable polling and stub `feed_polling_url` to a present value to isolate the username condition.

mediumbugapp/models/topic_embed.rb:56-59

Malformed feed URLs abort the entire import — Feed links can pass the `http(s)://` prefix check yet make `URI(url)` in `absolutize_urls` raise `URI::InvalidURIError`, aborting the entire poll or import. Rescue `URI::Error` around `URI.parse` and skip invalid items or return the content unchanged. **Also found in:** - `app/models/topic_embed.rb:11-11`

mediumbugapp/models/topic_embed.rb:62-72

absolutize_urls mishandles relative and protocol-relative URLs — Relative references such as `images/photo.jpg` resolve against the Discourse embed URL, while `//cdn.example.com/x.jpg` is rewritten as a feed-host path, breaking imported links and images. Use `URI.join(url, href)` or `URI.join(url, src)` for non-protocol-relative references and leave `//` URLs intact.

Gold bugs found (13)

mediumThe postMessage handler in embed.js checks the sender with discourseUrl.indexOf(e.origin), a substring test instead of exact origin equality, so a page on an origin that is a substring of the Discourse URL can send forged discourse-resize messages to the embedding page.
highPollFeed reads i.content.scrub for every feed item, so items without a content element (common in RSS feeds that only have description) raise NoMethodError and abort the import of the remaining items.
criticalTopicEmbed.import appends a footer that interpolates the URL unescaped into an <a href='...'> tag in raw HTML that is later rendered unsanitized, so a crafted URL can inject markup; it also appends to contents with << without handling nil.
highWhen the embedded post has been deleted, TopicEmbed.import's update path passes a nil embed.post to PostRevisor and crashes on every later import of that URL.
mediumabsolutize_urls only handles root-relative paths: protocol-relative URLs like //cdn.example.com/x.png are rewritten to http://host/cdn.example.com/x.png and path-relative links are left unresolved, breaking links and images in imported posts.
highThe Disqus importer now creates topics through TopicEmbed.import_remote, dropping the thread's created_at and the category option and requiring a live HTTP fetch per thread, so imported topics get wrong dates/categories and a dead link aborts the import.
mediumEvery retrieval of an article not yet embedded synchronously polls and imports the entire RSS feed, and since throttling is per URL, many different article requests repeat the full feed download and processing.
mediumThe 'is 404 without an embed_url' spec never sets an embeddable host, so the request is rejected by ensure_embeddable before the embed_url check runs, and the test would pass even without that check.
mediumThe 'requires feed_polling_url' and 'requires embed_by_username' specs leave feed_polling_enabled at its false default, so they never reach the condition they name and would pass with those checks deleted.
mediumembed_url is a varchar(255) column, so importing/embedding a URL longer than 255 characters fails on insert and that page can never get its discussion topic.
high`import_remote` fetches the embed URL with open-uri, which follows redirects, so the embeddable-host check on the initial URL can be bypassed to reach internal services (SSRF).
mediumThe "requires feed_polling_enabled?" spec leaves feed_polling_url and embed_by_username at their blank defaults, so poll_feed is skipped regardless and the test would pass even without the enabled check.
mediumabsolutize_urls calls URI(url) without a rescue, so a malformed URL that passes the http regex raises URI::InvalidURIError and aborts the PollFeed import.

Gold bugs missed (17)

highThe referer and embed_url host checks compare against SiteSetting.embeddable_host case-sensitively, so a host differing only in case is rejected even though hostnames are case-insensitive.
mediumClaims import_remote crashes on unparseable pages (nil content) and dead URLs because it does no nil check or network error handling around open(url).read.
lowThe embed view formats post dates with a hard-coded strftime pattern, so users in non-English locales see English month names and a fixed order while the rest of the view is translated.
mediumPostMover#copy recreates the first post via PostCreator without passing cook_method, so a moved raw_html (embedded/imported) first post is re-cooked through the markdown pipeline and its content changes.
mediumEmbedController#best renders the 'loading' placeholder and still calls discourse_expires_in 1.minute, so the anonymous cache stores the placeholder under the embed URL and visitors keep seeing 'Loading Discussion...' for up to a minute after the topic exists.
mediumTopicEmbed.import wraps PostCreator#create in Topic.transaction, so PostCreator's post-transaction job enqueueing (process_post, feature_topic_users, etc.) runs before the outer transaction commits, and a worker that picks up ProcessPost early finds no post and skips post-processing for the imported topic.
mediumTopicEmbed.import_remote fetches the embed URL with open(url).read and no timeout or size limit, so a slow or huge remote page can block the background job and exhaust memory.
mediumThe retrieve throttle is keyed by the full embed URL, so an anonymous client can vary the query string on the embeddable host to bypass it and make the server create an unbounded number of topics.
highThe embed layout references the 'embed' stylesheet and embed.js, but neither is in config.assets.precompile, so with precompiled assets in production the embed page fails to load them.
highThe embed layout writes the full request.referer into the page, and the page is anon-cached for a minute under a key without the referer. One embedding page's full URL, including query secrets, can be served to other visitors.
mediumTopicEmbed.import checks post.present? after PostCreator#create, but PostCreator returns an unsaved post when it rolls back on host spam. TopicEmbed.create! then runs with nil ids and raises, which aborts the import.
mediumtopic_id_for_embed returns the stored topic_id even after the topic is deleted, and topic_embeds rows are never removed. /embed/best errors permanently for that URL, and TopicRetriever never re-creates the topic.
highPollFeed always HTML-unescapes item content, so feeds that already carry literal HTML (CDATA) get their escaped entities decoded a second time. Escaped code samples become live markup in the raw_html post.
mediumEmbedController#best's anonymous cache key leaves out the referer. Within the cache window, a request from a non-embeddable or missing referer gets the cached page, including X-Frame-Options ALLOWALL, without ensure_embeddable running.
mediumTopicRetriever#perform_retrieve runs PollFeed inline without a rescue, so a failing or malformed feed raises and aborts retrieval before the fetch_http fallback runs.
highPollFeed fetches feed_polling_url with Kernel#open, so a setting value starting with '|' runs a shell command on the job server. Anyone who can edit site settings gets command execution.
mediumPost#cook returns self.raw for raw_html posts and ignores the text it is given. Callers that cook different text, such as add_topic_to_quotes.rake, store cooked output that does not match the new raw.