GLM-5.3 Flash · 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
5 of 30
Comments published
11
Comments matching a bug
5
Comments not matching
6
Cost of this PR
$0.261

Published comments (11)

criticalsecurityapp/models/topic_embed.rb:20-30

Imported HTML is persisted unsanitized, enabling stored XSS — Untrusted HTML from the feed or article lands in post content as-is, so script and event-handler payloads execute on the forum origin, and the `embed.imported_from` footer interpolates `#{url}` unescaped. Sanitize the fragment with a Nokogiri tag/attribute whitelist before persisting and escape the URL.

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

Invalid `<%- end if %>` causes syntax error compiling embed/best template — Every `embed/best` request 500s once a topic exists because the compiled template has an unmatched `if`, and controller specs don't render views, so tests stay green. Replace `<%- end if %>` with `<%- end %>`.

highperformanceapp/controllers/embed_controller.rb:15

Unthrottled enqueue of RetrieveTopic jobs for unknown embed URLs — Since the 60-second throttle lives inside `TopicRetriever#retrieved_recently?`, every unauthenticated request — and each open tab's 30-second reload — enqueues a `Jobs.enqueue` call and runs `topic_id_for_embed` forever when the article can't be imported. Check the throttle before enqueueing or dedupe pending retrievals per embed_url.

highperformancedb/migrate/20131219203905_add_cook_method_to_posts.rb:3

NOT NULL column with default rewrites hot posts table under exclusive lock — Adding `cook_method` with a default on PostgreSQL < 11 rewrites every `posts` row under an ACCESS EXCLUSIVE lock, blocking all reads and writes to the site's hottest table for the deploy. Add it nullable, backfill in batches, then apply the NOT NULL constraint.

highbuglib/topic_retriever.rb:26-30

Non-atomic SETNX+EXPIRE can leave throttle key with no TTL — If the worker dies between `$redis.setnx` and `$redis.expire`, the key `retrieved:<embed_url>` persists forever and that embed URL is never imported again, leaving the widget stuck on 'Loading Discussion...'. Set the TTL atomically with `SET key value EX 60 NX` or a MULTI/EXEC pipeline.

highbugapp/jobs/scheduled/poll_feed.rb:35

String#scrub unavailable on Ruby 2.0 and i.content may be missing — `i.content.scrub` raises NoMethodError on the pinned Ruby 2.0 (`String#scrub` arrived in 2.1) and when feeds carry only `description`, so with `retry: false` the hourly job dies and imports never work. Use `(i.content || i.description).to_s` instead.

mediumbugapp/jobs/scheduled/poll_feed.rb:20-22

feed_key is dead code; feed modification check never wired into polling — Nothing ever calls `PollFeed#feed_key`, so the feed-modification check was never wired in and the hourly job unconditionally re-imports the whole feed. Either skip re-polling when the digest is unchanged or remove `feed_key` and the now-unused `require 'digest/sha1'`.

mediumbugspec/jobs/poll_feed_spec.rb:12-16

Test for feed_polling_enabled? passes even without the guard due to other defaults — This test still passes if the `SiteSetting.feed_polling_enabled?` guard were removed, because unstubbed `feed_polling_url` and `embed_by_username` default to '' and short-circuit execution. Stub both settings so execution actually reaches the condition under test.

mediumsecurityapp/views/layouts/embed.html.erb:6-15

Embed layout leaks full referer URL into cacheable response body — The full `request.referer`, including path and query string that can carry tokens or session ids, is echoed into responses `EmbedController#best` marks cacheable, so a shared cache can serve one embedder's URL to another. Send only the referer origin as the postMessage targetOrigin, or skip caching these responses.

mediumsecurityapp/assets/javascripts/embed.js:17

Origin check uses substring containment, allowing forged origins — `discourseUrl.indexOf(e.origin)` accepts any origin string contained anywhere in `discourseUrl`, letting a forged frame send resize messages that control the embed iframe's height. Compare origins strictly, e.g. a prefix match, rather than with `indexOf` containment.

mediumbugspec/jobs/poll_feed_spec.rb:18-22

Test doesn't enable feed_polling_enabled? so feed_polling_url check is never reached — `Jobs::PollFeed#execute` short-circuits at `SiteSetting.feed_polling_enabled?` (false by default in site_settings.yml) before reading `feed_polling_url`, so this test would pass even without the guard it claims to cover. Stub `feed_polling_enabled?` to true and `embed_by_username` present so the `feed_polling_url` condition is actually exercised. **Also found in:** - `spec/jobs/poll_feed_spec.rb:24-28`

Gold bugs found (5)

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

Gold bugs missed (25)

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