FEATURE: Can edit category/host relationships for embedding
Tier 2 medium ruby · local · real merged PR from ai-code-review-evaluation/discourse-graphite #10
Ground-truth defects
NoMethodError before_validation in EmbeddableHost
The update and destroy methods in Admin::EmbeddableHostsController do not validate the existence of the EmbeddableHost record retrieved by ID. If EmbeddableHost.where(id: params[:id]).first returns nil (i.e., the host does not exist), attempting to call methods on the nil object (e.g., save_host or destroy) will result in a NoMethodError.
record_for_host compares lower(host) = ? but does not normalize the parameter’s case, so mixed‑case referer hosts may fail to match even though comparison intends to be case‑insensitive.
Because this migration inserts embeddable_hosts rows with raw SQL, any existing embeddable_hosts values that include http:// or /https:// or path segments won’t go through the EmbeddableHost model’s normalization, so the new host lookup (which compares only the bare host) may fail for migrated data. Consider ensuring that migrated hosts are normalized to the same format as newly created EmbeddableHost records so existing embedding configurations keep working.
New migration line 11 does `execute("...INNER JOIN site_settings...WHERE s.name='embed_category'")[0]['id']`, but installs that never overrode the `embed_category` setting (default '') have no such row, so the query returns zero rows and `[0]` raises IndexError, aborting the upgrade migration.
The new migration inserts each newline-split token of the old `embeddable_hosts` site-setting value directly into a raw SQL string: `execute "INSERT INTO embeddable_hosts (host, category_id, created_at, updated_at) VALUES ('#{h}', #{category_id}, ...)"`. `h` is unsanitized admin-controlled free text (the setting had no hostname validation); a value containing a single quote (an accidental typo or a deliberate payload) produces malformed SQL or executes arbitrary statements. Migrations run with DDL-capable database credentials, so the blast radius is large.
The new plural-ID hydration branch in `_hydrateEmbedded` (added alongside the existing singular path) maps a list of ids through `_lookupSubType` and assigns the result unconditionally: `obj[self.pluralize(subType)] = hydrated || []`. `_lookupSubType` returns `undefined` for an id whose root collection or specific id isn't found; since Array.prototype.map always returns an array, `hydrated` is always truthy and the `|| []` fallback never fires, so the resulting array can contain literal `undefined` entries (e.g. [ModelObj, undefined, ModelObj]). This is the reverse of the existing singular path, which correctly guards with `if (hydrated)` before assigning.
The new `EmbeddableHost` model's format validation explicitly accepts a port (`(:[0-9]{1,5})?`), and `before_validation` strips only the scheme and path, so a host entered as `http://example.com:3000` or `example.com:3000` is stored as `example.com:3000`. `record_for_host` compares the port-less `URI#host` of the referer against that stored value, so it can never match, and embedding from that site is silently refused although the admin UI accepted the host.
The change under review
diff (truncated — full diff)
new file mode 100644 @@ -0,0 +1,7 @@ +import RestAdapter from 'discourse/adapters/rest'; + +export default RestAdapter.extend({ + pathFor() { + return "/admin/customize/embedding"; + } +}); new file mode 100644 @@ -0,0 +1,63 @@ +import { bufferedProperty } from 'discourse/mixins/buffered-content'; +import computed from 'ember-addons/ember-computed-decorators'; +import { on, observes } from 'ember-addons/ember-computed-decorators'; +import { popupAjaxError } from 'discourse/lib/ajax-error'; + +export default Ember.Component.extend(bufferedProperty('host'), { + editToggled: false, + tagName: 'tr', + categoryId: null, + + editing: Ember.computed.or('host.isNew', 'editToggled'), + + @on('didInsertElement') + @observes('editing') + _focusOnInput() { + Ember.run.schedule('afterRender', () => { this.$('.host-name').focus(); }); + }, + + @computed('buffered.host', 'host.isSaving') + cantSave(host, isSaving) { + return isSaving || Ember.isEmpty(host); + }, + + actions: { + edit() { + this.set('categoryId', this.get('host.category.id')); + this.set('editToggled', true); + }, + + save() { + if (this.get('cantSave')) { return; } + + const props = this.get('buffered').getProperties('host'); + props.category_id = this.get('categoryId'); + + const host = this.get('host'); + host.save(props).then(() => { + host.set('category', Discourse.Category.findById(this.get('categoryId'))); + this.set('editToggled', false); + }).catch(popupAjaxError); + }, + + delete() { + bootbox.confirm(I18n.t('admin.embedding.confirm_delete'), (result) => { + if (result) { + this.get('host').destroyRecord().then(() => { + this.sendAction('deleteHost', this.get('host')); + }); + } + }); + }, + + cancel() { + const host = this.get('host'); + if (host.get('isNew')) { + this.sendAction('deleteHost', host); + } else { + this.rollbackBuffer(); + this.set('editToggled', false); + } + } + } +}); new file mode 100644 @@ -0,0 +1,18 @@ +export default Ember.Controller.extend({ + embedding: null, + + actions: { + saveChanges() { + this.get('embedding').update({}); + }, + + addHost() { + const host = this.store.createRecord('embeddable-host'); + this.get('embedding.embeddable_hosts').pushObject(host); + }, + + deleteHost(host) { + this.get('embedding.embeddable_hosts').removeObject(host); + } + } +}); new file mode 100644 @@ -0,0 +1,9 @@ +export default Ember.Route.extend({ + model() { + return this.store.find('embedding'); + }, + + setupController(controller, model) { + controller.set('embedding', model); + } +}); @@ -27,6 +27,7 @@ export default { this.resource('adminUserFields', { path: '/user_fields' }); this.resource('adminEmojis', { path: '/emojis' }); this.resource('adminPermalinks', { path: '/permalinks' }); + this.resource('adminEmbedding', { path: '/embedding' }); }); this.route('api'); new file mode 100644 @@ -0,0 +1,19 @@ +{{#if editing}} + <td> + {{input value=buffered.host placeholder="example.com" enter="save" class="host-name"}} + </td> + <td> + {{category-chooser value=categoryId}} + </td> + <td> + {{d-button icon="check" action="save" class="btn-primary" disabled=cantSave}} + {{d-button icon="times" action="cancel" class="btn-danger" disabled=host.isSaving}} + </td> +{{else}} + <td>{{host.host}}</td> + <td>{{category-badge host.category}}</td> + <td> + {{d-button icon="pencil" action="edit"}} + {{d-button icon="trash-o" action="delete" class='btn-danger'}} + </td> +{{/if}} @@ -5,6 +5,7 @@ {{nav-item route='adminUserFields' label='admin.user_fields.title'}} {{nav-item route='adminEmojis' label='admin.emoji.title'}} {{nav-item route='adminPermalinks' label='admin.permalink.title'}} + {{nav-item route='adminEmbedding' label='admin.embedding.title'}} {{/admin-nav}} <div class="admin-container"> new file mode 100644 @@ -0,0 +1,15 @@ +{{#if embedding.embeddable_hosts}} + <table> + <tr> + <th style='width: 50%'>{{i18n "admin.embedding.host"}}</th> + <th style='width: 30%'>{{i18n "admin.embedding.category"}}</th> + <th style='width: 20%'> </th> + </tr> + {{#each embedding.embeddable_hosts as |host|}} + {{embeddable-host host=host deleteHost="deleteHost"}} + {{/each}} + </table> +{{/if}} + +{{d-button label="admin.embedding.add_host" action="addHost" icon="plus" class="btn-primary"}} + @@ -1,4 +1,4 @@ -const ADMIN_MODELS = ['plugin', 'site-customization']; +const ADMIN_MODELS = ['plugin', 'site-customization', 'embeddable-host']; export function Result(payload, responseJson) { this.payload = payload; @@ -19,7 +19,7 @@ function rethrow(error) { export default Ember.Object.extend({ basePath(store, type) { - if (ADMIN_MODELS.indexOf(type) !== -1) { return "/admin/"; } + if (ADMIN_MODELS.indexOf(type.replace('_', '-')) !== -1) { return "/admin/"; } return "/"; }, @@ -189,14 +189,24 @@ export default Ember.Object.extend({ _hydrateEmbedded(type, obj, root) { const self = this; Object.keys(obj).forEach(function(k) { - const m = /(.+)\_id$/.exec(k); + const m = /(.+)\_id(s?)$/.exec(k); if (m) { const subType = m[1]; - const hydrated = self._lookupSubType(subType, type, obj[k], root); - if (hydrated) { - obj[subType] = hydrated; + + if (m[2]) { + const hydrated = obj[k].map(function(id) { + return self._lookupSubType(subType, type, id, root); + }); + obj[self.pluralize(subType)] = hydrated || []; delete obj[k]; + } else { + const hydrated = self._lookupSubType(subType, type, obj[k], root); + if (hydrated) { + obj[subType] = hydrated; + delete obj[k]; + } } + } }); }, new file mode 100644 @@ -0,0 +1,34 @@ +class Admin::EmbeddableHostsController < Admin::AdminController + + before_filter :ensure_logged_in, :ensure_staff + + def create + save_host(EmbeddableHost.new) + end + + def update + host = EmbeddableHost.where(id: params[:id]).first + save_host(host) + end + + def destroy + host = EmbeddableHost.where(id: params[:id]).first + host.destroy + render json: success_json + end + + protected + + def save_host(host) + host.host = params[:embeddable_host][:host] + host.category_id = params[:embeddable_host][:category_id] + host.category_id = SiteSetting.uncategorized_category_id if host.category_id.blank? + + if host.save + render_serialized(host, EmbeddableHostSerializer, root: 'embeddable_host', rest_serializer: true) + else + render_json_error(host) + end + end + +end new file mode 100644 @@ -0,0 +1,21 @@ +class Admin::EmbeddingController < Admin::AdminController + + before_filter :ensure_logged_in, :ensure_staff, :fetch_embedding + + def show + render_serialized(@embedding, EmbeddingSerializer, root: 'embedding', rest_serializer: true) + end + + def update + render_serialized(@embedding, EmbeddingSerializer, root: 'embedding', rest_serializer: true) + end + + protected + + def fetch_embedding + @embedding = OpenStruct.new({ + id: 'default', + embeddable_hosts: EmbeddableHost.all.order(:host) + }) + end +end @@ -58,8 +58,7 @@ class EmbedController < ApplicationController def ensure_embeddable if !(Rails.env.development? && current_user.try(:admin?)) - raise Discourse::InvalidAccess.new('embeddable hosts not set') if SiteSetting.embeddable_hosts.blank? - raise Discourse::InvalidAccess.new('invalid referer host') unless SiteSetting.allows_embeddable_host?(request.referer) + raise Discourse::InvalidAccess.new('invalid referer host') unless EmbeddableHost.host_allowed?(request.referer) end response.headers['X-Frame-Options'] = "ALLOWALL" new file mode 100644 @@ -0,0 +1,24 @@ +class EmbeddableHost < ActiveRecord::Base + validates_format_of :host, :with => /\A[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?\Z/i + belongs_to :category + + before_validation do + self.host.sub!(/^https?:\/\//, '') + self.host.sub!(/\/.*$/, '') + end + + def self.record_for_host(host) + uri = URI(host) rescue nil + return false unless uri.present? + + host = uri.host + return false unless host.present? + + where("lower(host) = ?", host).first + end + + def self.host_allowed?(host) + record_for_host(host).present? + end + +end @@ -68,20 +68,6 @@ class SiteSetting < ActiveRecord::Base @anonymous_menu_items ||= Set.new Discourse.anonymous_filters.map(&:to_s) end - def self.allows_embeddable_host?(host) - return false if embeddable_hosts.blank? - uri = URI(host) rescue nil - return false unless uri.present? - - host = uri.host - return false unless host.present? - - !!embeddable_hosts.split("\n").detect {|h| h.sub(/^https?\:\/\//, '') == host } - - hosts = embeddable_hosts.split("\n").map {|h| (URI(h).host rescue nil) || h } - !!hosts.detect {|h| h == host} - end - def self.anonymous_homepage top_menu_items.map { |item| item.name } .select { |item| anonymous_menu_items.include?(item) } @@ -866,7 +866,7 @@ class Topic < ActiveRecord::Base end def expandable_first_post? - SiteSetting.embeddable_hosts.present? && SiteSetting.embed_truncate? && has_topic_embed? + SiteSetting.embed_truncate? && has_topic_embed? end TIME_TO_FIRST_RESPONSE_SQL ||= <<-SQL @@ -33,12 +33,14 @@ class TopicEmbed < ActiveRecord::Base # If there is no embed, create a topic, post and the embed. if embed.blank? Topic.transaction do + eh = EmbeddableHost.record_for_host(url) + creator = PostCreator.new(user, title: title, raw: absolutize_urls(url, contents), skip_validations: true, cook_method: Post.cook_methods[:raw_html], - category: SiteSetting.embed_category) + category: eh.try(:category_id)) post = creator.create if post.present? TopicEmbed.create!(topic_id: post.topic_id, new file mode 100644 @@ -0,0 +1,16 @@ +class EmbeddableHostSerializer < ApplicationSerializer + attributes :id, :host, :category_id + + def id + object.id + end + + def host + object.host + end + + def category_id + object.category_id + end +end + new file mode 100644 @@ -0,0 +1,8 @@ +class EmbeddingSerializer < ApplicationSerializer + attributes :id + has_many :embeddable_hosts, serializer: EmbeddableHostSerializer, embed: :ids + + def id + object.id + end +end @@ -2491,6 +2491,14 @@ en: image: "Image" delete_confirm: "Are you sure you want to delete the :%{name}: emoji?" + embedding: + confirm_delete: "Are you sure you want to delete that host?" + title: "Embedding" + host: "Allowed Hosts" + edit: "edit" + category: "Post to Category" + add_host: "Add Host" + permalink: title: "Permalinks" url: "URL" @@ -1164,13 +1164,11 @@ en: autohighlight_all_code: "Force apply code highlighting to all preformatted code blocks even when they didn't explicitly specify the language." highlighted_languages: "Included syntax highlighting rules. (Warning: including too many langauges may impact performance) see: https://highlightjs.org/static/demo/ for a demo" - embeddable_hosts: "Host(s) that can embed the comments from this Discourse forum. Hostname only, do not begin with http://" feed_polling_enabled: "EMBEDDING ONLY: Whether to embed a RSS/ATOM feed as posts." feed_polling_url: "EMBEDDING ONLY: URL of RSS/ATOM feed to embed." embed_by_username: "Discourse username of the user who creates the embedded topics." embed_username_key_from_feed: "Key to pull discourse username from feed." embed_truncate: "Truncate the embedded posts." - embed_category: "Category of embedded topics." embed_post_limit: "Maximum number of posts to embed." embed_whitelist_selector: "CSS selector for elements that are allowed in embeds." embed_blacklist_selector: "CSS selector for elements that are removed from embeds." @@ -135,6 +135,8 @@ Discourse::Application.routes.draw do get "customize/css_html/:id/:section" => "site_customizations#index", constraints: AdminConstraint.new get "customize/colors" => "color_schemes#index", constraints: AdminConstraint.new get "customize/permalinks" => "permalinks#index", constraints: AdminConstraint.new + get "customize/embedding" => "embedding#show", constraints: AdminConstraint.new + put "customize/embedding" => "embedding#update", constraints: AdminConstraint.new get "flags" => "flags#index" get "flags/:filter" => "flags#index" post "flags/agree/:id" => "flags#agree" @@ -148,6 +150,7 @@ Discourse::Application.routes.draw do resources :emojis, constraints: AdminConstraint.new
Leaderboard for this case
medium · 3 of 9 bots fully caught it (33% solve rate) · 61% avg coverage.
| # | Bot | Result | Caught | Coverage | Findings | False alarms |
|---|---|---|---|---|---|---|
| 1 | Drape (Deep Review) | solved | 8/8 | 100.0% | 10 | 0 |
| 2 | Drape (Review) | solved | 8/8 | 100.0% | 8 | 0 |
| 3 | Claude Code (Opus 5.5) | solved | 8/8 | 100.0% | 8 | 1 |
| 4 | Cubic | partial | 7/8 | 90.5% | 17 | 3 |
| 5 | Mjolnir (Sonnet 5.5) | partial | 4/8 | 71.4% | 4 | 0 |
| 6 | Mjolnir (Opus 5.5) | partial | 3/8 | 66.7% | 4 | 0 |
| 7 | cursor | partial | 3/8 | 52.4% | 4 | 0 |
| 8 | greptile | partial | 3/8 | 47.6% | 5 | 0 |
| 9 | qodo | miss | 0/8 | 0.0% | 0 | 0 |
Bot results
Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | off by one |
| d2 | low | ✓ | exact |
| d3 | low | ✓ | off by one |
| d4 | medium | ✓ | exact |
| d5 | critical | ✓ | off by one |
| d6 | high | ✓ | off by one |
| d7 | medium | ✓ | off by one |
| d8 | low | ✓ | off by one |
The regex requires a dot followed by a 2–5 letter alphabetic TLD. That rejects localhost, IP addresses and longer TLDs. The migration inserts hosts with raw SQL, which skips this validation, so a migrated host in one of these forms fails validation when it is edited and saved. [grounded: tree app/models/embeddable_host.rb] [consensus 3/3: valid=3]
Every admin model listed has at most one separator, so replacing only the first underscore still matches all of them. The claimed wrong path would only happen if someone later added a model name with more underscores. [invalid: contradiction] [consensus 3/3: invalid=3]
raw comments (8)
`execute(...)[0]['id']` assumes the `embed_category` site setting row exists and names an existing category. On a fresh install, or on any site that never changed `embed_category` (it was left at its default), the INNER JOIN returns no rows. `[0]` then raises IndexError or returns nil, and the migration aborts, so upgrades fail. The `uncategorized_category_id` lookup at line 15 has the same problem when that setting is still at its default and has no row. The fallback can't even be reached: if the first query returns a row, its id is never 0.
Each host value is interpolated straight into the SQL (`'#{h}'`) with no quoting or escaping. Any stored value containing a single quote breaks the migration, and this is SQL injection from stored setting data. The values are also copied raw: they skip the model's normalization (stripping `http://` and paths) and are not trimmed, so a trailing `\r` from a textarea or whitespace is kept. The old code accepted values with a scheme prefix, but after migration those rows never match `uri.host`, so existing embeds silently stop working.
`record_for_host` compares the stored `host` column to `uri.host`, which never includes a port. The validation explicitly allows a port (`(:[0-9]{1,5})?`) and `before_validation` does not strip it. So a host saved as `example.com:8080` passes validation but can never match a referer, and embedding from it is always rejected. The comparison also lowercases only the column, not the incoming `uri.host`, so the match is only one-way case-insensitive.
The new host-format regex requires a dotted name with a 2–5 letter alphabetic TLD. It rejects `localhost`, IP addresses, and longer TLDs such as `.online` or `.technology`, all of which the old setting allowed. Admins can't add these hosts, and existing hosts like these that the migration copies in can't be edited and saved.
`before_validation` calls `self.host.sub!` with no nil check. A create or update request without a `host` param raises NoMethodError (a 500) instead of returning a validation error.
`update` and `destroy` use `where(id:).first` and then call methods on the result. An unknown id raises NoMethodError on nil (500) instead of a 404. `save_host` also reads `params[:embeddable_host][:host]` without checking that the `embeddable_host` key exists.
For `_ids` arrays, `hydrated` is always an array, so `|| []` does nothing. Ids that `_lookupSubType` can't resolve become `undefined` entries in the array. These are later passed to components such as `embeddable-host` and cause errors when rendered.
`type.replace('_', '-')` replaces only the first underscore. Any admin model type with more than one underscore won't be normalized and will resolve to the wrong (non-admin) base path.
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | exact |
| d2 | low | ✓ | off by one |
| d3 | low | ✓ | off by one |
| d4 | medium | ✓ | off by one |
| d5 | critical | ✓ | exact |
| d6 | high | ✓ | exact |
| d7 | medium | ✗ | — |
| d8 | low | ✓ | off by one |
The save success path never calls commitBuffer or rollbackBuffer, so the buffered host value stays in place. If the server changes the value (the model's before_validation strips the scheme and path), reopening the row shows the stale buffered input. [grounded: diff] [consensus 5/5: valid=5]
The singular branch before the change already deleted obj[k] once the association was hydrated, so this behavior is unchanged. [invalid: contradiction] [consensus 5/5: invalid=5]
The private_category fabricator content was moved verbatim from category_fabricator.rb. Its behavior is pre-existing. [invalid: introduced=no] [consensus 5/5: invalid=5]
The new `_ids` regex now matches `category_ids`, which the old pattern left alone. `pluralize` just appends 's', so the records land under `categorys` and the original `category_ids` key is deleted. [grounded: diff] [consensus 3/5: valid=3, uncertain=2]
When no category is chosen, the server falls back to uncategorized_category_id, but the client looks up the null categoryId. The row then shows no or the wrong category. [grounded: diff] [consensus 5/5: valid=5]
The embed_category setting was removed. Feed imports whose host has no EmbeddableHost record now get a nil category and land in Uncategorized, where they previously used the configured category. [grounded: diff] [consensus 5/5: valid=5]
This is a dead-code cleanup suggestion; nothing invokes saveChanges. [grounded: diff] [consensus 5/5: minor=5]
This is a test-quality note: the setup has no effect on expandable_first_post?, but the tests still pass and production code is unaffected. [grounded: tree spec/models/topic_spec.rb] [consensus 5/5: valid=5]
The hardcoded fabricator names were moved unchanged from the original category fabricator file, so this is pre-existing. [invalid: introduced=no] [consensus 5/5: invalid=5]
The /fruits/:id handler always returns fruits[0], so the test requests id 2 but asserts against fruit 1's colors. The test is misleading. [grounded: diff] [consensus 5/5: valid=5]
raw comments (18)
<!-- cubic:v=3474c25a-3314-4a15-8b18-9baf8f92b017 -->
<!-- cubic:review-run=3494190d-a18c-53dd-8247-30dc1fb2ee07 -->
<!-- metadata:{"confidence":10} -->
P0: When `embed_category` is unset or blank, this query returns no rows and `[0]` is `nil`, so the migration aborts before reaching its uncategorized fallback. Read the first row safely before falling back to `uncategorized_category_id`.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At db/migrate/20150818190757_create_embeddable_hosts.rb, line 9:
<comment>When `embed_category` is unset or blank, this query returns no rows and `[0]` is `nil`, so the migration aborts before reaching its uncategorized fallback. Read the first row safely before falling back to `uncategorized_category_id`.</comment>
<file context>
@@ -0,0 +1,33 @@
+ t.timestamps
+ end
+
+ category_id = execute("SELECT c.id FROM categories AS c
+ INNER JOIN site_settings AS s ON s.value = c.name
+ WHERE s.name = 'embed_category'")[0]['id'].to_i
</file context>
```
</details>
<!-- cubic:v=bfd6145e-95fa-42ba-a9b9-1504a3bf4d24 -->
<!-- cubic:review-run=3494190d-a18c-53dd-8247-30dc1fb2ee07 -->
<!-- metadata:{"confidence":9} -->
P1: When an existing host is stored as `https://example.com`, this raw insert preserves the scheme, but `record_for_host` later looks up only `example.com`; the migrated host then stops authorizing embeds. Normalize each legacy value before inserting it.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At db/migrate/20150818190757_create_embeddable_hosts.rb, line 25:
<comment>When an existing host is stored as `https://example.com`, this raw insert preserves the scheme, but `record_for_host` later looks up only `example.com`; the migrated host then stops authorizing embeds. Normalize each legacy value before inserting it.</comment>
<file context>
@@ -0,0 +1,33 @@
+ records = val.split("\n")
+ if records.present?
+ records.each do |h|
+ execute "INSERT INTO embeddable_hosts (host, category_id, created_at, updated_at) VALUES ('#{h}', #{category_id}, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
+ end
+ end
</file context>
```
</details>
```suggestion
host = h.sub(/^https?:\/\//, '').sub(/\/.*$/, '')
execute "INSERT INTO embeddable_hosts (host, category_id, created_at, updated_at) VALUES (#{connection.quote(host)}, #{category_id}, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
```
<!-- cubic:v=ae038043-f66d-4441-abe9-310f84a3a2ef -->
<!-- cubic:review-run=3494190d-a18c-53dd-8247-30dc1fb2ee07 -->
<!-- metadata:{"confidence":9} -->
P1: If a legacy host value contains a quote, this interpolation produces invalid SQL or permits injected SQL during the upgrade. Quote the host through the database connection instead of interpolating it directly.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At db/migrate/20150818190757_create_embeddable_hosts.rb, line 25:
<comment>If a legacy host value contains a quote, this interpolation produces invalid SQL or permits injected SQL during the upgrade. Quote the host through the database connection instead of interpolating it directly.</comment>
<file context>
@@ -0,0 +1,33 @@
+ records = val.split("\n")
+ if records.present?
+ records.each do |h|
+ execute "INSERT INTO embeddable_hosts (host, category_id, created_at, updated_at) VALUES ('#{h}', #{category_id}, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
+ end
+ end
</file context>
```
</details>
```suggestion
execute "INSERT INTO embeddable_hosts (host, category_id, created_at, updated_at) VALUES (#{connection.quote(h)}, #{category_id}, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
```
<!-- cubic:v=0a328879-80ef-4f02-b56c-b55ed73d43b6 -->
<!-- cubic:review-run=3494190d-a18c-53dd-8247-30dc1fb2ee07 -->
<!-- metadata:{"confidence":10} -->
P2: When an update targets a deleted or unknown host ID, `where(...).first` returns `nil` and `save_host` raises `NoMethodError` instead of returning a not-found response. Raise `Discourse::NotFound` or otherwise handle the missing record before calling `save_host`.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At app/controllers/admin/embeddable_hosts_controller.rb, line 10:
<comment>When an update targets a deleted or unknown host ID, `where(...).first` returns `nil` and `save_host` raises `NoMethodError` instead of returning a not-found response. Raise `Discourse::NotFound` or otherwise handle the missing record before calling `save_host`.</comment>
<file context>
@@ -0,0 +1,34 @@
+ end
+
+ def update
+ host = EmbeddableHost.where(id: params[:id]).first
+ save_host(host)
+ end
</file context>
```
</details>
```suggestion
host = EmbeddableHost.where(id: params[:id]).first || raise(Discourse::NotFound)
```
<!-- cubic:v=45c9305f-249b-4d41-92ad-6dbe0f4b3822 -->
<!-- cubic:review-run=3494190d-a18c-53dd-8247-30dc1fb2ee07 -->
<!-- metadata:{"confidence":9} -->
P2: After a successful save, the component leaves the buffered host value active while updating the underlying record from the server response. Discard the buffer after the response so reopening the row reflects the persisted host value.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At app/assets/javascripts/admin/components/embeddable-host.js.es6, line 39:
<comment>After a successful save, the component leaves the buffered host value active while updating the underlying record from the server response. Discard the buffer after the response so reopening the row reflects the persisted host value.</comment>
<file context>
@@ -0,0 +1,63 @@
+ const host = this.get('host');
+ host.save(props).then(() => {
+ host.set('category', Discourse.Category.findById(this.get('categoryId')));
+ this.set('editToggled', false);
+ }).catch(popupAjaxError);
+ },
</file context>
```
</details>
```suggestion
this.rollbackBuffer();
this.set('editToggled', false);
```
<!-- cubic:v=9036186e-b2f6-4b99-aa4f-63157bed72d5 -->
<!-- cubic:review-run=3494190d-a18c-53dd-8247-30dc1fb2ee07 -->
<!-- metadata:{"confidence":8} -->
P2: When a REST-serialized record has a resolvable singular association, this line drops its original `*_id` attribute from the hydrated model. Keep the foreign-key field and add the hydrated association, as the previous singular branch did; queued-post consumers explicitly receive and may use `user_id` and `topic_id`.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At app/assets/javascripts/discourse/models/store.js.es6, line 206:
<comment>When a REST-serialized record has a resolvable singular association, this line drops its original `*_id` attribute from the hydrated model. Keep the foreign-key field and add the hydrated association, as the previous singular branch did; queued-post consumers explicitly receive and may use `user_id` and `topic_id`.</comment>
<file context>
@@ -189,14 +189,24 @@ export default Ember.Object.extend({
+ const hydrated = self._lookupSubType(subType, type, obj[k], root);
+ if (hydrated) {
+ obj[subType] = hydrated;
+ delete obj[k];
+ }
}
</file context>
```
</details>
<!-- cubic:v=38761aae-4cc6-4a8d-abf3-c64f30e91e71 -->
<!-- cubic:review-run=3494190d-a18c-53dd-8247-30dc1fb2ee07 -->
<!-- metadata:{"confidence":8} -->
P2: When a referer contains an uppercase hostname, this query compares `lower(host)` with the still-uppercase parsed host and rejects an allowlisted domain. Lowercase the parsed host before binding it, or lowercase both query operands.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At app/models/embeddable_host.rb, line 17:
<comment>When a referer contains an uppercase hostname, this query compares `lower(host)` with the still-uppercase parsed host and rejects an allowlisted domain. Lowercase the parsed host before binding it, or lowercase both query operands.</comment>
<file context>
@@ -0,0 +1,24 @@
+ host = uri.host
+ return false unless host.present?
+
+ where("lower(host) = ?", host).first
+ end
+
</file context>
```
</details>
```suggestion
where("lower(host) = ?", host.downcase).first
```
<!-- cubic:v=3ac60b86-2e1a-4a79-bf55-6ab3facd4526 -->
<!-- cubic:review-run=3494190d-a18c-53dd-8247-30dc1fb2ee07 -->
<!-- metadata:{"confidence":10} -->
P2: When an allowed host includes a port, `record_for_host` drops the port before querying, so every request for that configured host is rejected. Include the parsed port in the lookup key, or remove port support from validation and normalization.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At app/models/embeddable_host.rb, line 14:
<comment>When an allowed host includes a port, `record_for_host` drops the port before querying, so every request for that configured host is rejected. Include the parsed port in the lookup key, or remove port support from validation and normalization.</comment>
<file context>
@@ -0,0 +1,24 @@
+ uri = URI(host) rescue nil
+ return false unless uri.present?
+
+ host = uri.host
+ return false unless host.present?
+
</file context>
```
</details>
<!-- cubic:v=0f6920bc-eae7-4188-81f9-1266aba59147 -->
<!-- cubic:review-run=3494190d-a18c-53dd-8247-30dc1fb2ee07 -->
<!-- metadata:{"confidence":10} -->
P2: When an admin/API submission omits `host`, this callback calls `sub!` on `nil` before validation, raising `NoMethodError` instead of returning validation errors. Normalize the value with `to_s` or guard the callback so blank hosts reach validation.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At app/models/embeddable_host.rb, line 6:
<comment>When an admin/API submission omits `host`, this callback calls `sub!` on `nil` before validation, raising `NoMethodError` instead of returning validation errors. Normalize the value with `to_s` or guard the callback so blank hosts reach validation.</comment>
<file context>
@@ -0,0 +1,24 @@
+ belongs_to :category
+
+ before_validation do
+ self.host.sub!(/^https?:\/\//, '')
+ self.host.sub!(/\/.*$/, '')
+ end
</file context>
```
</details>
```suggestion
self.host = self.host.to_s.sub(/^https?:\/\//, '')
```
<!-- cubic:v=0599900c-bfea-4bf5-8f1c-30e167e046c4 -->
<!-- cubic:review-run=3494190d-a18c-53dd-8247-30dc1fb2ee07 -->
<!-- metadata:{"confidence":7} -->
P2: The `private_category` fabricator calls `cat.update!` inside `after_build`, which writes to the database during the build phase. `after_build` also runs for `Fabricate.build`, so a caller that only asks for an in-memory category would unexpectedly persist a row, and normal `Fabricate` saves the category twice. Use the model's existing `set_permissions(group => :full)` instead: it sets `read_restricted` itself and `before_save :apply_permissions` builds/persists the category_group on the single fabricator save, matching the pattern used throughout the specs (e.g. `category.set_permissions(group => :full); category.save`).
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At spec/fabricators/embeddable_host_fabricator.rb, line 23:
<comment>The `private_category` fabricator calls `cat.update!` inside `after_build`, which writes to the database during the build phase. `after_build` also runs for `Fabricate.build`, so a caller that only asks for an in-memory category would unexpectedly persist a row, and normal `Fabricate` saves the category twice. Use the model's existing `set_permissions(group => :full)` instead: it sets `read_restricted` itself and `before_save :apply_permissions` builds/persists the category_group on the single fabricator save, matching the pattern used throughout the specs (e.g. `category.set_permissions(group => :full); category.save`).</comment>
<file context>
@@ -0,0 +1,27 @@
+ name 'Private Category'
+ slug 'private'
+ user
+ after_build do |cat, transients|
+ cat.update!(read_restricted: true)
+ cat.category_groups.build(group_id: transients[:group].id, permission_type: CategoryGroup.permission_types[:full])
</file context>
```
</details>
```suggestion
after_build do |cat, transients|
cat.set_permissions(transients[:group] => :full)
end
```
<!-- cubic:v=4f2868c7-cfcd-4b50-b74c-af602f16fb4d -->
<!-- cubic:review-run=3494190d-a18c-53dd-8247-30dc1fb2ee07 -->
<!-- metadata:{"confidence":8} -->
P2: When a REST payload contains `category_ids`, this branch writes the hydrated records to `categorys`, not `categories`, because `Store.pluralize` only appends `s`. It then deletes `category_ids`, so callers lose the relationship; register the irregular plural before hydrating plural IDs.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At app/assets/javascripts/discourse/models/store.js.es6, line 200:
<comment>When a REST payload contains `category_ids`, this branch writes the hydrated records to `categorys`, not `categories`, because `Store.pluralize` only appends `s`. It then deletes `category_ids`, so callers lose the relationship; register the irregular plural before hydrating plural IDs.</comment>
<file context>
@@ -189,14 +189,24 @@ export default Ember.Object.extend({
+ const hydrated = obj[k].map(function(id) {
+ return self._lookupSubType(subType, type, id, root);
+ });
+ obj[self.pluralize(subType)] = hydrated || [];
delete obj[k];
+ } else {
</file context>
```
</details>
<!-- cubic:v=37de73da-085b-49d6-90bd-9d2de625adbb -->
<!-- cubic:review-run=3494190d-a18c-53dd-8247-30dc1fb2ee07 -->
<!-- metadata:{"confidence":9} -->
P2: When a new host uses the default uncategorized value, the server persists an uncategorized `category_id` but this callback looks up the stale `categoryId`. Use the saved `host.category_id` so the new row immediately displays and edits the persisted category.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At app/assets/javascripts/admin/components/embeddable-host.js.es6, line 38:
<comment>When a new host uses the default uncategorized value, the server persists an uncategorized `category_id` but this callback looks up the stale `categoryId`. Use the saved `host.category_id` so the new row immediately displays and edits the persisted category.</comment>
<file context>
@@ -0,0 +1,63 @@
+
+ const host = this.get('host');
+ host.save(props).then(() => {
+ host.set('category', Discourse.Category.findById(this.get('categoryId')));
+ this.set('editToggled', false);
+ }).catch(popupAjaxError);
</file context>
```
</details>
<!-- cubic:v=32fd01e1-95fe-4c2f-a72d-f17518d0b324 -->
<!-- cubic:review-run=3494190d-a18c-53dd-8247-30dc1fb2ee07 -->
<!-- metadata:{"confidence":8} -->
P2: When a feed item has no matching `EmbeddableHost`, `TopicEmbed.import` creates it in Uncategorized instead of the configured embed category. Require a host mapping before importing or retain an explicit category fallback for feed imports.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At app/models/topic_embed.rb, line 43:
<comment>When a feed item has no matching `EmbeddableHost`, `TopicEmbed.import` creates it in Uncategorized instead of the configured embed category. Require a host mapping before importing or retain an explicit category fallback for feed imports.</comment>
<file context>
@@ -33,12 +33,14 @@ def self.import(user, url, title, contents)
skip_validations: true,
cook_method: Post.cook_methods[:raw_html],
- category: SiteSetting.embed_category)
+ category: eh.try(:category_id))
post = creator.create
if post.present?
</file context>
```
</details>
<!-- cubic:v=17672deb-c2b1-4dc6-81c8-2142dc2a7b99 -->
<!-- cubic:review-run=3494190d-a18c-53dd-8247-30dc1fb2ee07 -->
<!-- metadata:{"confidence":10} -->
P3: `saveChanges` is unreachable and sends no data if invoked, so it is misleading dead code. Remove it or wire a real save flow that supplies the fields to persist.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At app/assets/javascripts/admin/controllers/admin-embedding.js.es6, line 5:
<comment>`saveChanges` is unreachable and sends no data if invoked, so it is misleading dead code. Remove it or wire a real save flow that supplies the fields to persist.</comment>
<file context>
@@ -0,0 +1,18 @@
+ embedding: null,
+
+ actions: {
+ saveChanges() {
+ this.get('embedding').update({});
+ },
</file context>
```
</details>
<!-- cubic:v=0ed75053-5f3b-4264-ac3c-51150c2eedee -->
<!-- cubic:review-run=3494190d-a18c-53dd-8247-30dc1fb2ee07 -->
<!-- metadata:{"confidence":9} -->
P3: The new 'with an emeddable host' group Fabricates :embeddable_host, but expandable_first_post? never checks EmbeddableHost — it only reads embed_truncate? and has_topic_embed?. So the setup is a no-op and the 'is true' expectation passes purely from the stubs; the test does not actually verify that an embeddable host makes a topic expandable, and the sibling top-level 'is false if embeddable_host is blank' test passes for the wrong reason (topic has no embed). Either assert the embeddable-host condition explicitly, or drop the EmbeddableHost setup so the tests describe what they exercise.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At spec/models/topic_spec.rb, line 1409:
<comment>The new 'with an emeddable host' group Fabricates :embeddable_host, but expandable_first_post? never checks EmbeddableHost — it only reads embed_truncate? and has_topic_embed?. So the setup is a no-op and the 'is true' expectation passes purely from the stubs; the test does not actually verify that an embeddable host makes a topic expandable, and the sibling top-level 'is false if embeddable_host is blank' test passes for the wrong reason (topic has no embed). Either assert the embeddable-host condition explicitly, or drop the EmbeddableHost setup so the tests describe what they exercise.</comment>
<file context>
@@ -1397,32 +1397,34 @@ def build_topic_with_title(title)
- end
+ describe 'with an emeddable host' do
+ before do
+ Fabricate(:embeddable_host)
+ SiteSetting.embed_truncate = true
+ topic.stubs(:has_topic_embed?).returns(true)
</file context>
```
</details>
<!-- cubic:v=22596083-d915-4a0e-89ac-05e913446ad9 -->
<!-- cubic:review-run=3494190d-a18c-53dd-8247-30dc1fb2ee07 -->
<!-- metadata:{"confidence":6} -->
P3: The `private_category`, `happy_category`, and `diff_category` fabricators hardcode `name`/`slug`, but Category validates name uniqueness (case-insensitive, scoped to parent). Fabricating the same category type twice within one example (e.g. two `Fabricate(:private_category, group: ...)`) raises a uniqueness violation. The base `:category` fabricator avoids this with a sequenced name. If these fabricators may be used multiple times per example, use a slug sequence.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At spec/fabricators/embeddable_host_fabricator.rb, line 21:
<comment>The `private_category`, `happy_category`, and `diff_category` fabricators hardcode `name`/`slug`, but Category validates name uniqueness (case-insensitive, scoped to parent). Fabricating the same category type twice within one example (e.g. two `Fabricate(:private_category, group: ...)`) raises a uniqueness violation. The base `:category` fabricator avoids this with a sequenced name. If these fabricators may be used multiple times per example, use a slug sequence.</comment>
<file context>
@@ -0,0 +1,27 @@
+ transient :group
+
+ name 'Private Category'
+ slug 'private'
+ user
+ after_build do |cat, transients|
</file context>
```
</details>
<!-- cubic:v=1307b420-e72a-4096-a69a-84c05f0a48df -->
<!-- cubic:review-run=3494190d-a18c-53dd-8247-30dc1fb2ee07 -->
<!-- metadata:{"confidence":10} -->
P3: This test requests fruit 2 but the Pretender handler always returns fruit 1, so the color assertions exercise the wrong record and cannot catch ID-specific hydration regressions. Make the fixture select `request.params.id` or request the fixture's actual ID.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At test/javascripts/models/store-test.js.es6, line 111:
<comment>This test requests fruit 2 but the Pretender handler always returns fruit 1, so the color assertions exercise the wrong record and cannot catch ID-specific hydration regressions. Make the fixture select `request.params.id` or request the fixture's actual ID.</comment>
<file context>
@@ -106,19 +106,31 @@ test('destroyRecord when new', function(assert) {
- return store.find('fruit', 1).then(function(f) {
- ok(f.get('farmer'), 'it has the embedded object');
- ok(f.get('category'), 'categories are found automatically');
+ return store.find('fruit', 2).then(function(f) {
+ assert.ok(f.get('farmer'), 'it has the embedded object');
+
</file context>
```
</details>
<!-- cubic:review-summary:start -->
**17 issues found** across 36 files
<!-- cubic:review-summary:end -->
<details>
<summary>Prompt for AI agents (unresolved issues)</summary>
```text
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="app/assets/javascripts/admin/controllers/admin-embedding.js.es6">
<violation number="1" location="app/assets/javascripts/admin/controllers/admin-embedding.js.es6:5">
P3: `saveChanges` is unreachable and sends no data if invoked, so it is misleading dead code. Remove it or wire a real save flow that supplies the fields to persist.</violation>
</file>
<file name="app/controllers/admin/embeddable_hosts_controller.rb">
<violation number="1" location="app/controllers/admin/embeddable_hosts_controller.rb:10">
P2: When an update targets a deleted or unknown host ID, `where(...).first` returns `nil` and `save_host` raises `NoMethodError` instead of returning a not-found response. Raise `Discourse::NotFound` or otherwise handle the missing record before calling `save_host`.</violation>
</file>
<file name="app/assets/javascripts/admin/components/embeddable-host.js.es6">
<violation number="1" location="app/assets/javascripts/admin/components/embeddable-host.js.es6:38">
P2: When a new host uses the default uncategorized value, the server persists an uncategorized `category_id` but this callback looks up the stale `categoryId`. Use the saved `host.category_id` so the new row immediately displays and edits the persisted category.</violation>
<violation number="2" location="app/assets/javascripts/admin/components/embeddable-host.js.es6:39">
P2: After a successful save, the component leaves the buffered host value active while updating the underlying record from the server response. Discard the buffer after the response so reopening the row reflects the persisted host value.</violation>
</file>
<file name="app/assets/javascripts/discourse/models/store.js.es6">
<violation number="1" location="app/assets/javascripts/discourse/models/store.js.es6:200">
P2: When a REST payload contains `category_ids`, this branch writes the hydrated records to `categorys`, not `categories`, because `Store.pluralize` only appends `s`. It then deletes `category_ids`, so callers lose the relationship; register the irregular plural before hydrating plural IDs.</violation>
<violation number="2" location="app/assets/javascripts/discourse/models/store.js.es6:206">
P2: When a REST-serialized record has a resolvable singular association, this line drops its original `*_id` attribute from the hydrated model. Keep the foreign-key field and add the hydrated association, as the previous singular branch did; queued-post consumers explicitly receive and may use `user_id` and `topic_id`.</violation>
</file>
<file name="app/models/embeddable_host.rb">
<violation number="1" location="app/models/embeddable_host.rb:6">
P2: When an admin/API submission omits `host`, this callback calls `sub!` on `nil` before validation, raising `NoMethodError` instead of returning validation errors. Normalize the value with `to_s` or guard the callback so blank hosts reach validation.</violation>
<violation number="2" location="app/models/embeddable_host.rb:14">
P2: When an allowed host includes a port, `record_for_host` drops the port before querying, so every request for that configured host is rejected. Include the parsed port in the lookup key, or remove port support from validation and normalization.</violation>
<violation number="3" location="app/models/embeddable_host.rb:17">
P2: When a referer contains an uppercase hostname, this query compares `lower(host)` with the still-uppercase parsed host and rejects an allowlisted domain. Lowercase the parsed host before binding it, or lowercase both query operands.</violation>
</file>
<file name="spec/models/topic_spec.rb">
<violation number="1" location="spec/models/topic_spec.rb:1409">
P3: The new 'with an emeddable host' group Fabricates :embeddable_host, but expandable_first_post? never checks EmbeddableHost — it only reads embed_truncate? and has_topic_embed?. So the setup is a no-op and the 'is true' expectation passes purely from the stubs; the test does not actually verify that an embeddable host makes a topic expandable, and the sibling top-level 'is false if embeddable_host is blank' test passes for the wrong reason (topic has no embed). Either assert the embeddable-host condition explicitly, or drop the EmbeddableHost setup so the tests describe what they exercise.</violation>
</file>
<file name="spec/fabricators/embeddable_host_fabricator.rb">
<violation number="1" location="spec/fabricators/embeddable_host_fabricator.rb:21">
P3: The `private_category`, `happy_category`, and `diff_category` fabricators hardcode `name`/`slug`, but Category validates name uniqueness (case-insensitive, scoped to parent). Fabricating the same category type twice within one example (e.g. two `Fabricate(:private_category, group: ...)`) raises a uniqueness violation. The base `:category` fabricator avoids this with a sequenced name. If these fabricators may be used multiple times per example, use a slug sequence.</violation>
<violation number="2" location="spec/fabricators/embeddable_host_fabricator.rb:23">
P2: The `private_category` fabricator calls `cat.update!` inside `after_build`, which writes to the database during the build phase. `after_build` also runs for `Fabricate.build`, so a caller that only asks for an in-memory category would unexpectedly persist a row, and normal `Fabricate` saves the category twice. Use the model's existing `set_permissions(group => :full)` instead: it sets `read_restricted` itself and `before_save :apply_permissions` builds/persists the category_group on the single fabricator save, matching the pattern used throughout the specs (e.g. `category.set_permissions(group => :full); category.save`).</violation>
</file>
<file name="test/javascripts/models/store-test.js.es6">
<violation number="1" location="test/javascripts/models/store-test.js.es6:111">
P3: This test requests fruit 2 but the Pretender handler always returns fruit 1, so the color assertions exercise the wrong record and cannot catch ID-specific hydration regressions. Make the fixture select `request.params.id` or request the fixture's actual ID.</violation>
</file>
<file name="db/migrate/20150818190757_create_embeddable_hosts.rb">
<violation number="1" location="db/migrate/20150818190757_create_embeddable_hosts.rb:9">
P0: When `embed_category` is unset or blank, this query returns no rows and `[0]` is `nil`, so the migration aborts before reaching its uncategorized fallback. Read the first row safely before falling back to `uncategorized_category_id`.</violation>
<violation number="2" location="db/migrate/20150818190757_create_embeddable_hosts.rb:25">
P1: When an existing host is stored as `https://example.com`, this raw insert preserves the scheme, but `record_for_host` later looks up only `example.com`; the migrated host then stops authorizing embeds. Normalize each legacy value before inserting it.</violation>
<violation number="3" location="db/migrate/20150818190757_create_embeddable_hosts.rb:25">
P1: If a legacy host value contains a quote, this interpolation produces invalid SQL or permits injected SQL during the upgrade. Quote the host through the database connection instead of interpolating it directly.</violation>
</file>
<file name="app/models/topic_embed.rb">
<violation number="1" location="app/models/topic_embed.rb:43">
P2: When a feed item has no matching `EmbeddableHost`, `TopicEmbed.import` creates it in Uncategorized instead of the configured embed category. Require a host mapping before importing or retain an explicit category fallback for feed imports.</violation>
</file>
```
</details>
<sub>Reply with feedback, questions, or to request a fix.<br /><br />[Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/30/ai_pr_review_github_delivery_262883c95932e5302538ad317aefbe89035817a8596e0cbbafeb3b5f73b10014?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F30)</sub>
<!-- cubic:review-post:ai_pr_review_github_delivery_262883c95932e5302538ad317aefbe89035817a8596e0cbbafeb3b5f73b10014:fbb4837cbc7a5dda54a8da5cbe6972867604e079:3494190d-a18c-53dd-8247-30dc1fb2ee07 -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✗ | — |
| d2 | low | ✗ | — |
| d3 | low | ✓ | off by one |
| d4 | medium | ✓ | off by one |
| d5 | critical | ✓ | off by one |
| d6 | high | ✗ | — |
| d7 | medium | ✗ | — |
| d8 | low | ✗ | — |
For a new host, categoryId starts null and stays null if the admin never picks a category. The server then falls back to uncategorized_category_id, but the client sets category to findById(null), so the category badge renders empty. The citation-check miss is only because the cited path dropped the .es6 suffix; the code itself is in the diff. [grounded: diff] [consensus 5/5: valid=5]
raw comments (5)
### Migration crashes without embed category
**High Severity**
<!-- DESCRIPTION START -->
The migration indexes the first row of the `embed_category` query without checking that a row exists. Discourse only persists site settings that differ from defaults, and `embed_category` defaults to empty, so this query is empty on most sites. That raises on `[0]['id']` and aborts the upgrade before hosts are copied. The `uncategorized_category_id` fallback has the same unguarded `[0]` access.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: 3e13c11b-db0a-4ad7-8875-6e1b4c48a667 -->
<!-- LOCATIONS START
db/migrate/20150818190757_create_embeddable_hosts.rb#L8-L16
LOCATIONS END -->
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmNmN2U0MTI5LWUwNGYtNDJhZi1hYzYxLTc2NzQyNDIyMDc0MiIsImVuY3J5cHRpb25LZXkiOiJYek1MQ3Z4dUh4M0VNUm04NEhxbEotTUhueFh6WnhSZkwwNGtnTXhISHJvIiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTEwIiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmNmN2U0MTI5LWUwNGYtNDJhZi1hYzYxLTc2NzQyNDIyMDc0MiIsImVuY3J5cHRpb25LZXkiOiJYek1MQ3Z4dUh4M0VNUm04NEhxbEotTUhueFh6WnhSZkwwNGtnTXhISHJvIiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTEwIiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwck51bWJlciI6MzEsImNvbW1pdFNoYSI6Ijk5YmM1NTNhNDlhMGI5YTViY2I3NmY4ZWY3OTExZTFkY2M3NWY3N2MiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 99bc553a49a0b9a5bcb76f8ef7911e1dcc75f77c. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
### Migrated hosts keep protocol prefixes
**High Severity**
<!-- DESCRIPTION START -->
The migration inserts raw `embeddable_hosts` setting lines, including `http://` prefixes and paths that the old allowlist accepted. `record_for_host` compares that stored string to `URI#host` (hostname only), so those rows never match. Embedding breaks after upgrade until each host is re-saved through the model, which strips protocol and path in `before_validation`.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: 0d13b369-7f5a-463a-96a3-cb3d7ce99085 -->
<!-- LOCATIONS START
db/migrate/20150818190757_create_embeddable_hosts.rb#L23-L26
app/models/embeddable_host.rb#L9-L18
LOCATIONS END -->
<details>
<summary>Additional Locations (1)</summary>
- [`app/models/embeddable_host.rb#L9-L18`](https://github.com/drape-io/crbench-cursor-2026-09/blob/99bc553a49a0b9a5bcb76f8ef7911e1dcc75f77c/app/models/embeddable_host.rb#L9-L18)
</details>
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmM0OWFiNmVlLWUxZmMtNDMyNS04MGQ4LTY3NmU4N2Q5NDlmYyIsImVuY3J5cHRpb25LZXkiOiJzX0k2SExRU3FQMXdxQ0R4bGhhNXcxZVVPY2I0azZLZnhVZDJXbU1KU1gwIiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTEwIiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmM0OWFiNmVlLWUxZmMtNDMyNS04MGQ4LTY3NmU4N2Q5NDlmYyIsImVuY3J5cHRpb25LZXkiOiJzX0k2SExRU3FQMXdxQ0R4bGhhNXcxZVVPY2I0azZLZnhVZDJXbU1KU1gwIiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTEwIiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwck51bWJlciI6MzEsImNvbW1pdFNoYSI6Ijk5YmM1NTNhNDlhMGI5YTViY2I3NmY4ZWY3OTExZTFkY2M3NWY3N2MiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 99bc553a49a0b9a5bcb76f8ef7911e1dcc75f77c. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
### Host lookup ignores incoming case
**Medium Severity**
<!-- DESCRIPTION START -->
`record_for_host` applies `lower()` to the stored column but binds `uri.host` unchanged. Ruby's `URI#host` preserves the referer's original case, so a mixed-case host does not match a lowercase stored row. `host_allowed?` then denies valid embed requests even though the query was written to be case-insensitive.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: 0b471e4a-1cfc-44ff-ad92-adffa2b7df3a -->
<!-- LOCATIONS START
app/models/embeddable_host.rb#L9-L18
LOCATIONS END -->
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmJjZTQ0YmI5LWNjOGEtNDUxZi05MjZlLTc4YjFiNjk1YzhjZCIsImVuY3J5cHRpb25LZXkiOiJTLTJWenEzNGxXMWtSeVQxVl9nZjRiQmJaQmlOcVdSQUJQbnBRdzBEcFJNIiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTEwIiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmJjZTQ0YmI5LWNjOGEtNDUxZi05MjZlLTc4YjFiNjk1YzhjZCIsImVuY3J5cHRpb25LZXkiOiJTLTJWenEzNGxXMWtSeVQxVl9nZjRiQmJaQmlOcVdSQUJQbnBRdzBEcFJNIiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTEwIiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwck51bWJlciI6MzEsImNvbW1pdFNoYSI6Ijk5YmM1NTNhNDlhMGI5YTViY2I3NmY4ZWY3OTExZTFkY2M3NWY3N2MiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 99bc553a49a0b9a5bcb76f8ef7911e1dcc75f77c. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
### Saved host drops default category
**Low Severity**
<!-- DESCRIPTION START -->
After a successful save, the component sets `category` from `categoryId`, which stays null when the admin never picks a category. The server still assigns `uncategorized_category_id` and returns that id on the record, but the client overwrites `category` with a failed lookup. The category badge stays empty until the page is reloaded.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: efa94fda-2631-4ffd-93ce-751c37411cf1 -->
<!-- LOCATIONS START
app/assets/javascripts/admin/components/embeddable-host.js.es6#L29-L40
LOCATIONS END -->
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjhiMjdhNmNiLWVmZGEtNGI0MS05NWFhLTZmMGFjOTBiMzY0MiIsImVuY3J5cHRpb25LZXkiOiJsYVZnQ0lfTVBoMzZadWRraGx2dFA2STdrS0xGeklsQ3dRZExxZUJkRm1VIiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTEwIiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjhiMjdhNmNiLWVmZGEtNGI0MS05NWFhLTZmMGFjOTBiMzY0MiIsImVuY3J5cHRpb25LZXkiOiJsYVZnQ0lfTVBoMzZadWRraGx2dFA2STdrS0xGeklsQ3dRZExxZUJkRm1VIiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTEwIiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwck51bWJlciI6MzEsImNvbW1pdFNoYSI6Ijk5YmM1NTNhNDlhMGI5YTViY2I3NmY4ZWY3OTExZTFkY2M3NWY3N2MiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 99bc553a49a0b9a5bcb76f8ef7911e1dcc75f77c. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- BUGBOT_REVIEW -->
Cursor Bugbot has reviewed your changes using high effort and found 4 potential issues.
<!-- BUGBOT_FIX_ALL -->
<a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aTowMWVkM2JlOS1jM2E3LTQxODEtYjI2Yi0yOTBiZWZjYTMyNDAiLCJlbmNyeXB0aW9uS2V5IjoiTXhUNldzQzhjcUEzTVlJSjBBeWF4N2hPUngwcUFFTUg3UDlwdWEzanVpSSIsImJyYW5jaCI6InQyLWRpc2NvdXJzZS1ncmFwaGl0ZS0xMCIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>
<!-- /BUGBOT_FIX_ALL -->
<!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_BEGIN -->
<sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_END -->
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 99bc553a49a0b9a5bcb76f8ef7911e1dcc75f77c. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | off by one |
| d2 | low | ✓ | exact |
| d3 | low | ✓ | exact |
| d4 | medium | ✓ | off by one |
| d5 | critical | ✓ | off by one |
| d6 | high | ✓ | wrong severity |
| d7 | medium | ✓ | off by one |
| d8 | low | ✓ | off by one |
The new validation regex requires a dot and a 2–5 letter alphabetic TLD. That rejects localhost, IP addresses, single-label intranet hosts and TLDs longer than 5 letters, all of which the old free-form host_list setting accepted. [grounded: tree app/models/embeddable_host.rb] [consensus 3/3: valid=3]
TopicEmbed.import, which is also called from PollFeed without any host check, used to use SiteSetting.embed_category. Now it takes the category only from a matching EmbeddableHost, and the global setting was removed. Feed articles whose host isn't registered therefore get a nil category and end up in Uncategorized. [grounded: diff] [consensus 3/3: valid=3]
raw comments (10)
**Raw host string interpolated into SQL**
Each host value is put straight into the INSERT string. A value containing a quote breaks the migration or runs arbitrary SQL. Quote the value with `quote(h)` (or ActiveRecord::Base.connection.quote).
```
db/migrate/20150818190757_create_embeddable_hosts.rb:25 execute "INSERT INTO embeddable_hosts (host, category_id, created_at, updated_at) VALUES ('#{h}', #{category_id}, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
```
**Mixed-case referer hosts are rejected**
`record_for_host` lowercases the column but not the incoming `uri.host`, and Ruby's URI keeps the host's case. A referer like `http://Example.com/post` therefore never matches. Downcase the host before comparing: `where('lower(host) = ?', host.downcase)`.
```
app/models/embeddable_host.rb:15 return false unless host.present?
app/models/embeddable_host.rb:17 where("lower(host) = ?", host).first
```
**Hosts saved with a port can never match**
The validation accepts `example.com:8080` and the cleanup only removes the scheme and path, so the port is stored. `record_for_host` compares against `uri.host`, which never includes a port. Strip the port in `before_validation`, or match on host and port together.
```
app/models/embeddable_host.rb:2 validates_format_of :host, :with => /\A[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?\Z/i
app/models/embeddable_host.rb:3 belongs_to :category
app/models/embeddable_host.rb:5 before_validation do
app/models/embeddable_host.rb:6 self.host.sub!(/^https?:\/\//, '')
app/models/embeddable_host.rb:15 return false unless host.present?
app/models/embeddable_host.rb:17 where("lower(host) = ?", host).first
```
**Valid hosts like localhost or long TLDs rejected**
The format regex requires a dot followed by a 2–5 letter TLD. Hosts such as `localhost`, intranet names, IP addresses or `.museum`/`.technology` domains cannot be saved, though the old setting allowed them. Loosen the TLD part, e.g. `[a-z]{2,}` and an optional TLD, or validate with URI parsing.
```
app/models/embeddable_host.rb:2 validates_format_of :host, :with => /\A[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?\Z/i
```
**Blank host request raises a 500**
If `host` is missing, the `before_validation` block calls `sub!` on nil and raises, so the admin gets a server error instead of a validation message. Guard with `if self.host.present?`.
```
app/models/embeddable_host.rb:5 before_validation do
app/models/embeddable_host.rb:6 self.host.sub!(/^https?:\/\//, '')
app/models/embeddable_host.rb:7 self.host.sub!(/\/.*$/, '')
app/models/embeddable_host.rb:8 end
```
**Migrated hosts with http:// or ports stop matching**
The old check accepted entries like `http://example.com` via `URI(h).host`. The migration copies each line unchanged, so these never equal the bare referer host and embedding breaks after upgrade. Strip the scheme, path and whitespace from each value before inserting it.
```
db/migrate/20150818190757_create_embeddable_hosts.rb:22 records = val.split("\n")
db/migrate/20150818190757_create_embeddable_hosts.rb:23 if records.present?
db/migrate/20150818190757_create_embeddable_hosts.rb:24 records.each do |h|
db/migrate/20150818190757_create_embeddable_hosts.rb:25 execute "INSERT INTO embeddable_hosts (host, category_id, created_at, updated_at) VALUES ('#{h}', #{category_id}, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
app/models/site_setting.rb:79 (base) !!embeddable_hosts.split("\n").detect {|h| h.sub(/^https?\:\/\//, '') == host }
app/models/site_setting.rb:81 (base) hosts = embeddable_hosts.split("\n").map {|h| (URI(h).host rescue nil) || h }
app/models/site_setting.rb:82 (base) !!hosts.detect {|h| h == host}
app/models/embeddable_host.rb:17 where("lower(host) = ?", host).first
```
**Store crashes on null or unresolved `_ids` keys**
Every `_ids` key is now treated as a list of embedded ids. A null value throws on `.map`, and ids that aren't sideloaded become `undefined` while the original key is deleted. Hydrate only arrays whose collection was sideloaded.
```
app/assets/javascripts/discourse/models/store.js.es6:192 const m = /(.+)\_id(s?)$/.exec(k);
app/assets/javascripts/discourse/models/store.js.es6:193 if (m) {
app/assets/javascripts/discourse/models/store.js.es6:194 const subType = m[1];
app/assets/javascripts/discourse/models/store.js.es6:196 if (m[2]) {
app/assets/javascripts/discourse/models/store.js.es6:197 const hydrated = obj[k].map(function(id) {
app/assets/javascripts/discourse/models/store.js.es6:198 return self._lookupSubType(subType, type, id, root);
app/assets/javascripts/discourse/models/store.js.es6:199 });
app/assets/javascripts/discourse/models/store.js.es6:200 obj[self.pluralize(subType)] = hydrated || [];
app/assets/javascripts/discourse/models/store.js.es6:201 delete obj[k];
app/assets/javascripts/discourse/models/store.js.es6:167 const pluralType = this.pluralize(subType);
```
**Unknown id crashes update/destroy with 500**
`update` and `destroy` call methods on the result of `.first` without checking it, so a missing id raises NoMethodError instead of returning 404. Use `EmbeddableHost.find(params[:id])` so missing records give 404.
```
app/controllers/admin/embeddable_hosts_controller.rb:9 def update
app/controllers/admin/embeddable_hosts_controller.rb:10 host = EmbeddableHost.where(id: params[:id]).first
app/controllers/admin/embeddable_hosts_controller.rb:11 save_host(host)
app/controllers/admin/embeddable_hosts_controller.rb:12 end
app/controllers/admin/embeddable_hosts_controller.rb:15 host = EmbeddableHost.where(id: params[:id]).first
app/controllers/admin/embeddable_hosts_controller.rb:16 host.destroy
app/controllers/admin/embeddable_hosts_controller.rb:23 host.host = params[:embeddable_host][:host]
```
**Migration crashes when embed_category is unset**
With no `embed_category` row (the default) or on a fresh database, `[0]['id']` / `[0]['value']` read from an empty result and raise, aborting the migration. Check for rows before reading `[0]` and fall back sensibly.
```
db/migrate/20150818190757_create_embeddable_hosts.rb:9 category_id = execute("SELECT c.id FROM categories AS c
db/migrate/20150818190757_create_embeddable_hosts.rb:10 INNER JOIN site_settings AS s ON s.value = c.name
db/migrate/20150818190757_create_embeddable_hosts.rb:11 WHERE s.name = 'embed_category'")[0]['id'].to_i
db/migrate/20150818190757_create_embeddable_hosts.rb:14 if category_id == 0
db/migrate/20150818190757_create_embeddable_hosts.rb:15 category_id = execute("SELECT value FROM site_settings WHERE name = 'uncategorized_category_id'")[0]['value'].to_i
db/migrate/20150818190757_create_embeddable_hosts.rb:16 end
config/site_settings.yml:771 (base) embed_category: ''
```
**Feed-imported topics lose their embed category**
The category now comes only from an `EmbeddableHost` that matches the article's host. Feed articles from unlisted hosts go to Uncategorized instead of the old `embed_category`. Fall back to a default category when no host matches.
```
app/models/topic_embed.rb:36 eh = EmbeddableHost.record_for_host(url)
app/models/topic_embed.rb:38 creator = PostCreator.new(user,
app/models/topic_embed.rb:39 title: title,
app/models/topic_embed.rb:40 raw: absolutize_urls(url, contents),
app/models/topic_embed.rb:43 category: eh.try(:category_id))
config/site_settings.yml:771 (base) embed_category: ''
```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | off by one |
| d2 | low | ✓ | exact |
| d3 | low | ✓ | off by one |
| d4 | medium | ✓ | exact |
| d5 | critical | ✓ | off by one |
| d6 | high | ✓ | off by one |
| d7 | medium | ✓ | off by one |
| d8 | low | ✓ | off by one |
The citation check missed because the reviewer wrote `.js`, but the real file is `app/assets/javascripts/admin/components/embeddable-host.js.es6`, which this change adds. For a new host, `categoryId` stays null because only `edit()` sets it. The server saves `uncategorized_category_id` when no category is sent. The save callback then sets `host.category` from `findById(null)`, which is undefined, so the `{{category-badge host.category}}` cell shows nothing until the page is reloaded. [grounded: diff] [consensus 3/3: valid=3]
raw comments (8)
**Nil host raises in before_validation**
The `before_validation` callback calls `self.host.sub!` with no nil check. `save_host` assigns `params[:embeddable_host][:host]`, so a missing host raises NoMethodError and returns a 500 instead of a validation error. `sub!` also modifies the caller's param string in place. Guard with `self.host = host.to_s.sub(...)` or return if host is nil.
```
app/models/embeddable_host.rb:5 before_validation do
app/models/embeddable_host.rb:6 self.host.sub!(/^https?:\/\//, '')
app/models/embeddable_host.rb:7 self.host.sub!(/\/.*$/, '')
app/models/embeddable_host.rb:8 end
```
**Host lookup mismatches on case and port**
The query compares `lower(host)` to the referer's host without lowercasing it. A mixed-case referer never matches. The validation regex permits a `:port` suffix, but `URI(...).host` drops the port, so a stored `example.com:8080` never matches. Downcase the incoming host, and either strip ports on save or compare against host plus port.
```
app/models/embeddable_host.rb:2 validates_format_of :host, :with => /\A[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?\Z/i
```
**Unknown host id causes 500 error**
`update` and `destroy` call `.first` and then use the result without a nil check. An id that doesn't exist (for example already deleted in another tab) raises NoMethodError instead of returning a 404. Use `find` (or `raise Discourse::NotFound` when nil).
```
app/controllers/admin/embeddable_hosts_controller.rb:9 def update
app/controllers/admin/embeddable_hosts_controller.rb:10 host = EmbeddableHost.where(id: params[:id]).first
app/controllers/admin/embeddable_hosts_controller.rb:11 save_host(host)
app/controllers/admin/embeddable_hosts_controller.rb:12 end
```
**Migration crashes when embed_category is unset**
The category lookup indexes `execute(...)[0]['id']`, but the query returns no rows when `embed_category` was never set (the default). That raises NoMethodError and aborts the migration. The `uncategorized_category_id` lookup has the same problem. Use `.first` with nil-safe handling and fall back to the uncategorized category.
```
db/migrate/20150818190757_create_embeddable_hosts.rb:9 category_id = execute("SELECT c.id FROM categories AS c
db/migrate/20150818190757_create_embeddable_hosts.rb:10 INNER JOIN site_settings AS s ON s.value = c.name
db/migrate/20150818190757_create_embeddable_hosts.rb:11 WHERE s.name = 'embed_category'")[0]['id'].to_i
db/migrate/20150818190757_create_embeddable_hosts.rb:14 if category_id == 0
```
**Migration interpolates hosts into SQL unquoted**
Each old host value goes straight into the INSERT string. A quote in the value breaks the migration, and values like 'http://foo.com' are stored raw, skipping the model's scheme stripping, so they never match. Quote with connection.quote and strip scheme/path before inserting.
```
db/migrate/20150818190757_create_embeddable_hosts.rb:25 execute "INSERT INTO embeddable_hosts (host, category_id, created_at, updated_at) VALUES ('#{h}', #{category_id}, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
```
**Ported hosts are saved but never match**
The validation regex accepts `host:port`, but `record_for_host` compares against `uri.host`, which has no port. A host saved as `example.com:3000` never matches. Disallow ports in validation or compare host plus port.
```
app/models/embeddable_host.rb:2 validates_format_of :host, :with => /\A[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?\Z/i
app/models/embeddable_host.rb:11 uri = URI(host) rescue nil
app/models/embeddable_host.rb:12 return false unless uri.present?
```
**Hydrating `_ids` arrays yields undefined entries**
For any `*_ids` key in a rest-serialized payload, `_hydrateEmbedded` deletes the key even when the sideloaded records are missing, leaving `undefined` entries in the array. Skip undefined results and keep the key unless all ids resolved.
```
app/assets/javascripts/discourse/models/store.js.es6:192 const m = /(.+)\_id(s?)$/.exec(k);
app/assets/javascripts/discourse/models/store.js.es6:193 if (m) {
app/assets/javascripts/discourse/models/store.js.es6:194 const subType = m[1];
app/assets/javascripts/discourse/models/store.js.es6:196 if (m[2]) {
```
**New host shows blank category after saving**
A new host never gets a category picked, so `categoryId` stays null and the server saves Uncategorized. After saving, the component sets `host.category` from `findById(null)`, which is undefined. Use the `category_id` from the save response.
```
app/assets/javascripts/admin/components/embeddable-host.js.es6:25 edit() {
app/assets/javascripts/admin/components/embeddable-host.js.es6:26 this.set('categoryId', this.get('host.category.id'));
app/assets/javascripts/admin/components/embeddable-host.js.es6:27 this.set('editToggled', true);
app/assets/javascripts/admin/components/embeddable-host.js.es6:28 },
```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✗ | — |
| d2 | low | ✗ | — |
| d3 | low | ✓ | wrong severity |
| d4 | medium | ✗ | — |
| d5 | critical | ✓ | off by one |
| d6 | high | ✗ | — |
| d7 | medium | ✗ | — |
| d8 | low | ✓ | wrong severity |
The new model only validates the host's format, and the migration creates no unique index. If the same host is added twice with different categories, `.first` returns whichever row the database happens to return, so imported topics can go to an unintended category. [grounded: tree app/models/embeddable_host.rb] [consensus 3/3: valid=3]
For a new host, `categoryId` stays null unless a category is picked. The server falls back to the uncategorized ID, but the client looks up the category with the null local value, so the badge renders blank until the page is reloaded. [grounded: tree app/assets/javascripts/admin/components/embeddable-host.js.es6] [consensus 3/3: valid=3]
The new delete action has no `.catch`, unlike `save`, which uses `popupAjaxError`. A failed delete gives the admin no feedback and leaves the promise rejection unhandled. [grounded: tree app/assets/javascripts/admin/components/embeddable-host.js.es6] [consensus 3/3: valid=3]
raw comments (6)
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Missing Setting Blocks Migration**
On installations where `embed_category` has no persisted override, or its configured category no longer exists, this query returns no rows. The migration then evaluates `[0]['id']` before reaching the uncategorized fallback, causing the upgrade to fail. Site-setting defaults are held in memory and are not guaranteed to have database rows.
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Valid Hosts Fail Matching**
Port-bearing hosts are accepted and stored with their port, but `URI#host` excludes the port during lookup. A configured `example.com:8080` therefore cannot authorize `http://example.com:8080/...`. The comparison also lowercases only the database value, so a mixed-case hostname in an incoming URL can be rejected even though DNS hostnames are case-insensitive.
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Duplicate Hosts Route Ambiguously**
The new model does not prevent multiple records for the same normalized host. If an administrator adds a host again with another category, `record_for_host(...).first` silently selects one duplicate, so imported topics can be routed to an older or otherwise unintended category. The normalized host needs uniqueness enforcement in both the model and database.
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> **Default Category Displays Blank**
When a new host is saved without selecting a category, the server persists and returns the uncategorized category ID. This callback then overwrites `host.category` using the still-null local `categoryId`, so the row displays a blank category until it is reloaded or edited. The display should use the saved model's returned `category_id`.
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> **Delete Failures Stay Silent**
The new delete flow handles only successful requests. If the request fails because of a network or server error, the row remains without any explanation to the administrator and the rejected promise may go unhandled. Add the same `popupAjaxError` handling used by the save flow.
<h3>Greptile Summary</h3>
This PR replaces the global embedding host/category settings with per-host database records and adds an administrative CRUD interface. It also routes embed authorization and topic categorization through the new model and extends client-side REST hydration for plural embedded IDs.
- Adds per-host category selection and migrates legacy embedding configuration.
- Adds admin routes, controllers, serializers, templates, and client components.
- Updates embed authorization, retrieval, and topic creation to use `EmbeddableHost`.
- Extends REST payload hydration to support `*_ids` associations.
- The migration's missing-setting handling and host identity invariants need correction before merge.
<h3>Confidence Score: 2/5</h3>
This PR is not safe to merge until normal upgrades can complete and embeddable-host records have consistent, unambiguous matching semantics.
The migration can dereference an empty legacy-category query and block deployment, while accepted port-bearing hosts never match and duplicate host records can route imported topics to the wrong category. The admin UI also has lower-impact category-display and deletion-feedback defects.
**Files Needing Attention:** db/migrate/20150818190757_create_embeddable_hosts.rb, app/models/embeddable_host.rb, app/assets/javascripts/admin/components/embeddable-host.js.es6
<details><summary><h3>Important Files Changed</h3></summary>
| Filename | Overview |
|----------|----------|
| db/migrate/20150818190757_create_embeddable_hosts.rb | Creates and populates per-host embedding records, but can abort when the legacy category setting is absent or unmatched. |
| app/models/embeddable_host.rb | Introduces host normalization and authorization lookup, but mishandles ports/case and permits ambiguous duplicate records. |
| app/models/topic_embed.rb | Selects each imported topic's category from its matching embeddable-host record. |
| app/controllers/admin/embeddable_hosts_controller.rb | Adds staff-only CRUD endpoints and defaults blank category selections to uncategorized. |
| app/assets/javascripts/admin/components/embeddable-host.js.es6 | Implements host editing and deletion, with stale default-category display and missing delete-error feedback. |
| app/assets/javascripts/discourse/models/store.js.es6 | Adds plural embedded-ID hydration; inspected payloads follow the expected array-and-root-collection convention. |
| app/controllers/embed_controller.rb | Moves Referer authorization from the removed site setting to the new embeddable-host records. |
</details>
<details open><summary><h3>Flowchart</h3></summary>
```mermaid
%%{init: {'theme': 'neutral'}}%%
flowchart LR
A[Admin embedding settings] --> B[(EmbeddableHost records)]
C[Embed Referer] --> D[EmbedController authorization]
E[Requested article URL] --> F[TopicRetriever]
B --> D
B --> F
F --> G[TopicEmbed import]
B --> G
G --> H[Topic created in host category]
```
</details>
<!-- greptile_other_comments_section -->
<sub>Reviews (1): Last reviewed commit: ["Update app/assets/javascripts/admin/adap..."](https://github.com/drape-io/crbench-greptile-2026-09/commit/bc24da139553cbffc2474e3e356c4fbd1955f029) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=64284342)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✗ | — |
| d2 | low | ✗ | — |
| d3 | low | ✗ | — |
| d4 | medium | ✓ | off by one |
| d5 | critical | ✓ | exact |
| d6 | high | ✓ | off by one |
| d7 | medium | ✗ | — |
| d8 | low | ✗ | — |
Site settings are only stored in the table when they differ from the default. On a default install, or on a fresh database where migrations run before seeds, the embed_category join returns no rows. Indexing [0] on an empty PG::Result then raises an error, which aborts the migration. Further down, the same migration checks cmd_tuples before reading embeddable_hosts, but these two queries have no such guard. [grounded: tree db/migrate/20150818190757_create_embeddable_hosts.rb] [consensus 3/3: valid=3]
raw comments (4)
[P1] Migration crashes when the `embed_category` or `uncategorized_category_id` rows are missing
db/migrate/20150818190757_create_embeddable_hosts.rb:542-549 Site settings are only written to `site_settings` when they differ from the default. `embed_category` defaults to `''`, so on most existing installs the first query returns no rows. On a fresh database, the migrations run before the seeds, so both queries return no rows. In either case, `execute(...)[0]['id']` / `[0]['value']` fails because there is no tuple 0: PG raises an IndexError, or the code ends up calling `nil['id']`. The migration aborts on default installs and on fresh setups, so `rake db:migrate` fails. Check `ntuples`/`cmd_tuples` before indexing, as the code already does further down for `embeddable_hosts`.
[P2] Migrated hosts keep their scheme or path, so existing embeds stop matching
db/migrate/20150818190757_create_embeddable_hosts.rb:555-558 The old `allows_embeddable_host?` explicitly accepted entries like `http://eviltrout.com` or `https://example.com/1234`; the removed specs covered these cases. The migration inserts each line verbatim with raw SQL, so the model's `before_validation` stripping never runs. The new `EmbeddableHost.record_for_host` compares `lower(host)` against the bare `uri.host`. Any site that configured hosts with a scheme or path, or with trailing whitespace or `\r` from the textarea, will have every embed rejected with "invalid referer host" after upgrading. Because the value is interpolated straight into the SQL string, a host containing a `'` will also break the migration.
[P0] Migration crashes when no `embed_category` setting row exists
db/migrate/20150818190757_create_embeddable_hosts.rb:9-11 The query is `execute("SELECT c.id FROM categories ... WHERE s.name = 'embed_category'")[0]['id']`. It indexes row 0 without checking that a row came back. `embed_category` defaulted to `''`, so it only has a row in `site_settings` if an admin changed it, and even then only when the value matches a category name. On a fresh install, and on most existing sites, the result is empty. `PG::Result#[]` then raises IndexError ("Index 0 is out of range"), so the migration aborts and `rake db:migrate` fails. The `cmd_tuples › 0` guard used for `embeddable_hosts` further down is missing here. The fallback lookup of `uncategorized_category_id` makes the same unchecked `[0]` access.
[P1] Migrated hosts are not normalized, so existing embeds stop working after upgrade
db/migrate/20150818190757_create_embeddable_hosts.rb:22-25 The migration inserts each line of the old `embeddable_hosts` setting into the table unchanged. It skips the `before_validation` cleanup in `EmbeddableHost`, which removes the `http(s)://` prefix and any path. The old `SiteSetting.allows_embeddable_host?` accepted entries such as `http://eviltrout.com` or `https://example.com/1234`; the removed specs and the multi-host controller spec covered exactly these. `EmbeddableHost.record_for_host` now compares `lower(host)` with the bare `uri.host`. Any site that configured a scheme-prefixed host, a host with a path, or a line with trailing whitespace or `\r` will have it migrated as a value that never matches. Those sites then get `InvalidAccess` on every embed request, and `TopicRetriever` stops importing. The values should go through the same normalization (strip the scheme, path and whitespace, and skip blank lines) before they are inserted.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✗ | — |
| d2 | low | ✗ | — |
| d3 | low | ✓ | off by one |
| d4 | medium | ✓ | exact |
| d5 | critical | ✓ | off by one |
| d6 | high | ✓ | off by one |
| d7 | medium | ✗ | — |
| d8 | low | ✗ | — |
Site settings left at their default are not stored in site_settings, so the embed_category join returns no rows on most installs. Indexing [0] then raises (IndexError in pg, or NoMethodError on nil['id']), and the new migration aborts. [grounded: tree db/migrate/20150818190757_create_embeddable_hosts.rb] [consensus 3/3: valid=3]
raw comments (4)
[P1] Migration crashes when no embed_category setting exists
The first `execute("SELECT c.id ... WHERE s.name = 'embed_category'")` returns zero rows on any site that never set `embed_category`. The default was '' and no row is stored, and the inner join also matches nothing when the stored name doesn't match a category. `[0]['id']` then raises NoMethodError on nil, so `db:migrate` aborts before the `category_id == 0` fallback can run. Fix by reading the result with `.first`/safe navigation, or by checking `ntuples`, as the `embeddable_hosts` query below it does.
[P2] Embeddable host matching is case-sensitive on input and migrated entries keep their scheme
`record_for_host` runs `where("lower(host) = ?", host)` with `uri.host` un-downcased, so a referer or URL with uppercase letters never matches. Hosts saved with uppercase letters never match either: the validation regex is case-insensitive and nothing downcases the stored value. The migration also inserts the old setting lines verbatim, so a line like `http://example.com` is stored with its scheme. The old `allows_embeddable_host?` stripped `^https?://`, but `before_validation` does not run for raw SQL inserts. Those migrated hosts will therefore never match `uri.host`, and embedding silently stops working for them after upgrade. Fix by normalizing (strip scheme, downcase) both on insert and in the lookup.
[P1] Migration crashes when no embed_category setting row exists
`execute(...)[0]['id']` is called on a query that returns zero rows unless the `embed_category` site setting was explicitly saved with a matching category name. The default was `''` and default settings aren't stored, so on most installs, including fresh DBs, `[0]` is nil (or raises IndexError in newer pg) and the migration aborts with NoMethodError. The fallback query for `uncategorized_category_id` has the same problem when that setting has no row. This blocks `db:migrate` on affected sites. Use `.first`/`cmd_tuples` guards and fall back to `SiteSetting.uncategorized_category_id`.
[P2] Migrated hosts keep their scheme or whitespace and no longer match
The old `embeddable_hosts` setting accepted entries like `http://example.com`, and the removed `allows_embeddable_host?` stripped the scheme before comparing. The migration inserts each line verbatim via raw SQL, bypassing the model's `before_validation` that strips `http(s)://` and paths. `EmbeddableHost.record_for_host` compares `lower(host)` to the bare referer host, so any such migrated entry never matches and embedding silently breaks for that host after upgrade. The raw string interpolation is also not SQL-escaped, so a value containing a quote will break the INSERT. Normalize and quote each host (strip the scheme, trim, downcase) before inserting.
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✗ | — |
| d2 | low | ✗ | — |
| d3 | low | ✗ | — |
| d4 | medium | ✗ | — |
| d5 | critical | ✗ | — |
| d6 | high | ✗ | — |
| d7 | medium | ✗ | — |
| d8 | low | ✗ | — |
raw comments (2)
<h3>Qodo is busy working</h3>
Check back in a few minutes. Qodo's code review agents are on it.
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<img src="https://www.qodo.ai/wp-content/uploads/2026/01/anteater-looking-at-ants-01-transparent-bg-croped-ezgif.com-optimize-1.gif" width="30%">
<h3>PR Summary by Qodo</h3>
Add database-backed embedding host administration and category routing
<code>✨ Enhancement</code> <code>⚙️ Configuration changes</code> <code>🧪 Tests</code> <code>🕐 40+ Minutes</code>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<details>
<summary>AI Description</summary>
<dl>
<dd>
<br/>
><pre>
>• Replaces global embedding settings with database-backed host-to-category mappings.
>• Adds an admin interface and API for managing allowed embedding hosts.
>• Routes imported topics into the category configured for their source host.
></pre>
</dd>
</dl>
</details>
<details>
<summary>Diagram</summary>
<dl>
<dd>
<br/>
```mermaid
graph TD
AdminUI["Embedding Admin"] --> AdminAPI["Admin API"] --> HostRecords[("Host Records")] --> Category["Target Category"]
EmbedRequest["Embed Request"] --> EmbedController["Embed Controller"] --> HostRecords
TopicRetriever["Topic Retriever"] --> HostRecords
TopicImport["Topic Import"] --> HostRecords
```
</dd>
</dl>
</details>
<details>
<summary>High-Level Assessment</summary>
<dl>
<dd>
<br/>
>The following are alternative approaches to this PR:
<details>
<summary><b>1. Structured site setting</b></summary>
<dl>
<dd>
- ➕ Avoids a new table and CRUD resource
- ➕ Keeps all embedding configuration in the existing settings system
- ➖ Provides weak host-to-category relationship modeling
- ➖ Makes validation, incremental edits, and admin UI behavior more complex
- ➖ Does not provide normal relational integrity
</dd>
</dl>
</details>
<details>
<summary><b>2. Single default category with host allowlist</b></summary>
<dl>
<dd>
- ➕ Requires less migration and administration
- ➕ Preserves the previous global configuration model
- ➖ Cannot route content from different hosts to separate categories
- ➖ Retains newline-delimited host parsing and normalization concerns
</dd>
</dl>
</details>
>**Recommendation:** Use the PR's relational EmbeddableHost model because per-host category routing is inherently structured data and benefits from validation, CRUD endpoints, and associations. The migration and normalization behavior deserve careful review, but retaining site settings would limit extensibility and administrative usability.
</dd>
</dl>
</details>
<details>
<summary> Files changed (36) <code> +449 / -127 </code> </summary>
<dl>
<dd>
<br/>
<details>
<summary>Enhancement (18) <code> +257 / -11 </code></summary>
<dl>
<dd>
<details>
<summary>embedding.js.es6<code>Route embedding model requests to the admin endpoint</code> <code>+7/-0</code></summary>
<br/>
>Route embedding model requests to the admin endpoint
>
><pre>
>• Adds a REST adapter that resolves embedding model operations through '/admin/customize/embedding'.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-3ed3b289628bb5111994658cb2740292927bc5b877b8bdc1c106e879aebc2c64'>app/assets/javascripts/admin/adapters/embedding.js.es6</a>
</details>
<details>
<summary>embeddable-host.js.es6<code>Add editable embeddable-host table rows</code> <code>+63/-0</code></summary>
<br/>
>Add editable embeddable-host table rows
>
><pre>
>• Implements buffered host editing, category selection, save and rollback behavior, deletion confirmation, and input focus management.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-e9400716d9b5379539a868d455efbb604b9bfdfa1b194ec3a75be248dc4b08bd'>app/assets/javascripts/admin/components/embeddable-host.js.es6</a>
</details>
<details>
<summary>admin-embedding.js.es6<code>Manage embedding configuration and host rows</code> <code>+18/-0</code></summary>
<br/>
>Manage embedding configuration and host rows
>
><pre>
>• Adds controller actions to save configuration and add or remove embeddable-host records from the displayed collection.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-298afe2916ab6aae91feef55fe9e4f7237a1dccaa7f67f90b0be43d049ac8e91'>app/assets/javascripts/admin/controllers/admin-embedding.js.es6</a>
</details>
<details>
<summary>admin-embedding.js.es6<code>Load embedding configuration for administration</code> <code>+9/-0</code></summary>
<br/>
>Load embedding configuration for administration
>
><pre>
>• Fetches the embedding model and assigns it to the admin embedding controller.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-e971c7eae1d38008be85388828711c0a9cb62ca585bba28fa5463ef6bbc65caf'>app/assets/javascripts/admin/routes/admin-embedding.js.es6</a>
</details>
<details>
<summary>embeddable-host.hbs<code>Render embeddable-host editing controls</code> <code>+19/-0</code></summary>
<br/>
>Render embeddable-host editing controls
>
><pre>
>• Adds editable and read-only row states with host input, category chooser, and save, cancel, edit, and delete controls.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-27c515c62f18ed101d862deaf77dd1357e2717c3cf5d37cf2beb9b865902b6c9'>app/assets/javascripts/admin/templates/components/embeddable-host.hbs</a>
</details>
<details>
<summary>customize.hbs<code>Expose embedding in the Customize navigation</code> <code>+1/-0</code></summary>
<br/>
>Expose embedding in the Customize navigation
>
><pre>
>• Adds an Embedding navigation item to the administration Customize section.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-9babcd6afaf3b10a6049a89018d7106b0bee0ea424d3215e0dd1e962aba5d2bd'>app/assets/javascripts/admin/templates/customize.hbs</a>
</details>
<details>
<summary>embedding.hbs<code>Render the embedding host management table</code> <code>+15/-0</code></summary>
<br/>
>Render the embedding host management table
>
><pre>
>• Displays configured hosts and categories through embeddable-host components and provides an Add Host action.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-37638378e724231418ad4c15273bbd14d4c3a30d7e9e500fde7446cb3eea002a'>app/assets/javascripts/admin/templates/embedding.hbs</a>
</details>
<details>
<summary>rest.js.es6<code>Treat embeddable hosts as admin REST models</code> <code>+2/-2</code></summary>
<br/>
>Treat embeddable hosts as admin REST models
>
><pre>
>• Adds embeddable-host to the admin model list and normalizes underscored model names before selecting the admin base path.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-8b1f498c45561705a344f917d8a2c16bf6101c7a50fdbcd53c3c5d3445ea3193'>app/assets/javascripts/discourse/adapters/rest.js.es6</a>
</details>
<details>
<summary>store.js.es6<code>Hydrate arrays of embedded model IDs</code> <code>+14/-4</code></summary>
<br/>
>Hydrate arrays of embedded model IDs
>
><pre>
>• Extends embedded relationship hydration to recognize '_ids' fields and resolve them into pluralized model collections. This supports serialized embeddable-host relationships and other to-many associations.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-314f6f9092cf273a10892197cbe8cb6b7c6bce8636130d482d126a6a1c6aae72'>app/assets/javascripts/discourse/models/store.js.es6</a>
</details>
<details>
<summary>embeddable_hosts_controller.rb<code>Add staff-only embeddable-host CRUD endpoints</code> <code>+34/-0</code></summary>
<br/>
>Add staff-only embeddable-host CRUD endpoints
>
><pre>
>• Creates, updates, and deletes host-to-category records, defaulting blank categories to uncategorized and returning serialized validation results.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-5c5e789e83d0101ee027f120c1d48fa872972ae8f9c8562e18b00518c8b0c617'>app/controllers/admin/embeddable_hosts_controller.rb</a>
</details>
<details>
<summary>embedding_controller.rb<code>Expose aggregate embedding configuration</code> <code>+21/-0</code></summary>
<br/>
>Expose aggregate embedding configuration
>
><pre>
>• Returns a staff-only embedding resource containing all embeddable hosts ordered by hostname.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-5d2ba8046a1ed5bd2aac63dc38214f618a9f70f0af430a6e260ef7cef7d34cee'>app/controllers/admin/embedding_controller.rb</a>
</details>
<details>
<summary>embed_controller.rb<code>Authorize embeds using persisted host records</code> <code>+1/-2</code></summary>
<br/>
>Authorize embeds using persisted host records
>
><pre>
>• Replaces site-setting host checks with 'EmbeddableHost.host_allowed?' when validating embed referrers.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-595b525906799e0daab45625514da7ffa4536c3091aee28f712120deaeec4490'>app/controllers/embed_controller.rb</a>
</details>
<details>
<summary>embeddable_host.rb<code>Model allowed hosts and category mappings</code> <code>+24/-0</code></summary>
<br/>
>Model allowed hosts and category mappings
>
><pre>
>• Adds hostname validation and normalization, category association, URL-to-record lookup, and host authorization helpers.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-f429a047bc41e7f121c4b192f1faf57d2e8647643fdc8f65758e5cebb7cc6941'>app/models/embeddable_host.rb</a>
</details>
<details>
<summary>topic.rb<code>Decouple embed expansion from removed host settings</code> <code>+1/-1</code></summary>
<br/>
>Decouple embed expansion from removed host settings
>
><pre>
>• Determines first-post expansion from truncation and topic embedding state without checking the removed global host setting.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-b3c70feba88e3827d9d1f8d6aed4b97adad78fb3c4f532d6b98183f1b56458c5'>app/models/topic.rb</a>
</details>
<details>
<summary>topic_embed.rb<code>Assign imported topics by source host</code> <code>+3/-1</code></summary>
<br/>
>Assign imported topics by source host
>
><pre>
>• Looks up the URL's embeddable-host record and passes its category to 'PostCreator' when creating an imported topic.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-a9aa56fcefb13804a057905bdd06a402290431de865469884df64a9585b4206e'>app/models/topic_embed.rb</a>
</details>
<details>
<summary>embeddable_host_serializer.rb<code>Serialize embeddable-host attributes</code> <code>+16/-0</code></summary>
<br/>
>Serialize embeddable-host attributes
>
><pre>
>• Exposes each host record's ID, normalized hostname, and category ID to REST clients.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-0919d073decc773e8d3f1edf938f038d267a127f9cb852eaed5ebb49b3a59b20'>app/serializers/embeddable_host_serializer.rb</a>
</details>
<details>
<summary>embedding_serializer.rb<code>Serialize aggregate embedding configuration</code> <code>+8/-0</code></summary>
<br/>
>Serialize aggregate embedding configuration
>
><pre>
>• Serializes the embedding resource and its embeddable hosts as an embedded ID relationship.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-194cb766171807660dacfecc78b47e73ee757bd62e0e33cf6f80824267dc771e'>app/serializers/embedding_serializer.rb</a>
</details>
<details>
<summary>topic_retriever.rb<code>Validate retrieval URLs against host records</code> <code>+1/-1</code></summary>
<br/>
>Validate retrieval URLs against host records
>
><pre>
>• Uses the persisted embeddable-host allowlist instead of the removed site-setting helper when rejecting invalid sources.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-9673cf0c0ab86eae9fb20c50f479aca5807c92d698e5f9d2e24f29a26d673c1f'>lib/topic_retriever.rb</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Refactor (1) <code> +0 / -14 </code></summary>
<dl>
<dd>
<details>
<summary>site_setting.rb<code>Remove site-setting host authorization logic</code> <code>+0/-14</code></summary>
<br/>
>Remove site-setting host authorization logic
>
><pre>
>• Deletes the newline-delimited embeddable-host parsing and authorization helper now owned by 'EmbeddableHost'.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-914096985eae8d6a56d22281feeebfe4240dfc0ee5503a9d860fb5ce7b0c043a'>app/models/site_setting.rb</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Tests (11) <code> +147 / -96 </code></summary>
<dl>
<dd>
<details>
<summary>embeddable_hosts_controller_spec.rb<code>Add embeddable-host controller inheritance coverage</code> <code>+9/-0</code></summary>
<br/>
>Add embeddable-host controller inheritance coverage
>
><pre>
>• Verifies that the new CRUD controller inherits from the protected admin controller.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-8b1d8b8910146c055750b50a37278c6e0768d872794be6ca0d257b85616a058e'>spec/controllers/admin/embeddable_hosts_controller_spec.rb</a>
</details>
<details>
<summary>embedding_controller_spec.rb<code>Add embedding controller inheritance coverage</code> <code>+9/-0</code></summary>
<br/>
>Add embedding controller inheritance coverage
>
><pre>
>• Verifies that the aggregate embedding controller inherits from the protected admin controller.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-f69e33c8daac11f671d5dd907e58d30fac48f2370c2256806a67b8db14ee928a'>spec/controllers/admin/embedding_controller_spec.rb</a>
</details>
<details>
<summary>embed_controller_spec.rb<code>Exercise embed authorization with persisted hosts</code> <code>+5/-6</code></summary>
<br/>
>Exercise embed authorization with persisted hosts
>
><pre>
>• Replaces site-setting setup with embeddable-host records across missing, valid, and multiple-host controller scenarios.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-ae3cad89fa5c6a2640229505997ffa6da382b6afdfb7b62c24831abd9a7c48d4'>spec/controllers/embed_controller_spec.rb</a>
</details>
<details>
<summary>category_fabricator.rb<code>Define the embeddable-host test factory</code> <code>+3/-26</code></summary>
<br/>
>Define the embeddable-host test factory
>
><pre>
>• Replaces this file's category factories with an embeddable-host factory using a default hostname and associated category.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-43d2e4ea376953b568489bf27dcb32f9c99675a473e5e7c952e527a0a636a1cb'>spec/fabricators/category_fabricator.rb</a>
</details>
<details>
<summary>embeddable_host_fabricator.rb<code>Relocate category test factories</code> <code>+27/-0</code></summary>
<br/>
>Relocate category test factories
>
><pre>
>• Adds the category, alternate category, happy category, and private category fabricators previously defined in the category fabricator file.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-a9650a4dcce229effb4485851613d394c64032c9a930bc1d2217939e27299393'>spec/fabricators/embeddable_host_fabricator.rb</a>
</details>
<details>
<summary>embeddable_host_spec.rb<code>Test host normalization and authorization</code> <code>+40/-0</code></summary>
<br/>
>Test host normalization and authorization
>
><pre>
>• Covers removal of URL schemes and paths plus matching and rejecting URLs against one or more persisted hosts.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-001656b4f7c84dea8baf7130f9ca1abbb3866ddf97372da0797ad3b7f6631b15'>spec/models/embeddable_host_spec.rb</a>
</details>
<details>
<summary>site_setting_spec.rb<code>Remove obsolete host-setting specifications</code> <code>+0/-30</code></summary>
<br/>
>Remove obsolete host-setting specifications
>
><pre>
>• Deletes tests for the removed 'SiteSetting.allows_embeddable_host?' implementation.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-3e7032cd3c22ee4bea4f13c52380bc8d7bb3693900ca45c68f00633820650b09'>spec/models/site_setting_spec.rb</a>
</details>
<details>
<summary>topic_embed_spec.rb<code>Verify host-specific category assignment</code> <code>+3/-0</code></summary>
<br/>
>Verify host-specific category assignment
>
><pre>
>• Creates an embeddable-host mapping for imports and asserts that the resulting topic uses the mapped category.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-02a8c03adb3939df5cc5c9ae225f5b4b2a9ff9e5f5246949b37c7af2a6ffb293'>spec/models/topic_embed_spec.rb</a>
</details>
<details>
<summary>topic_spec.rb<code>Adapt topic tests to database-backed embedding</code> <code>+22/-20</code></summary>
<br/>
>Adapt topic tests to database-backed embedding
>
><pre>
>• Reworks expandable-first-post setup around an embeddable-host record and removes two unused local assignments in digest tests.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-da7d942ae90f8f5d8da67b7c75eba463685b90e45919e0547ba1d17a810e27e7'>spec/models/topic_spec.rb</a>
</details>
<details>
<summary>create-pretender.js.es6<code>Add to-many embedded relationship fixtures</code> <code>+9/-6</code></summary>
<br/>
>Add to-many embedded relationship fixtures
>
><pre>
>• Adds color IDs and color payloads to fruit responses so the store can be tested against serialized ID arrays.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-aa8c633683cd0c4d45aa49a66942cdb75350a6fd86cdf18e7a6f9e5b96cc55ce'>test/javascripts/helpers/create-pretender.js.es6</a>
</details>
<details>
<summary>store-test.js.es6<code>Test hydration of embedded ID arrays</code> <code>+20/-8</code></summary>
<br/>
>Test hydration of embedded ID arrays
>
><pre>
>• Extends single-record and collection tests to verify '_ids' relationships hydrate into ordered model collections while preserving existing belongs-to behavior.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-a3fcb07d358280bbb7564695ad2e441e0e26510dbc89e216f4427c77594d2efa'>test/javascripts/models/store-test.js.es6</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Documentation (1) <code> +8 / -0 </code></summary>
<dl>
<dd>
<details>
<summary>client.en.yml<code>Add embedding administration translations</code> <code>+8/-0</code></summary>
<br/>
>Add embedding administration translations
>
><pre>
>• Adds English labels for the embedding page, host table, category field, add action, and delete confirmation.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-d311cd526428b83a1ebb9ed9b457fb210800cc5f0e8188af7de7b5ce86aa5315'>config/locales/client.en.yml</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Other (5) <code> +37 / -6 </code></summary>
<dl>
<dd>
<details>
<summary>admin-route-map.js.es6<code>Register the embedding administration route</code> <code>+1/-0</code></summary>
<br/>
>Register the embedding administration route
>
><pre>
>• Adds '/admin/customize/embedding' to the admin route map.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-df5b90c9327394842bf84c3952d2a1b8756aa10bbd43648fafc163847b20012c'>app/assets/javascripts/admin/routes/admin-route-map.js.es6</a>
</details>
<details>
<summary>server.en.yml<code>Remove obsolete embedding setting descriptions</code> <code>+0/-2</code></summary>
<br/>
>Remove obsolete embedding setting descriptions
>
><pre>
>• Deletes descriptions for the retired 'embeddable_hosts' and 'embed_category' site settings.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-333c4c8cacc2f84633d4894f2aaddb130a6d74f42dd63199462b3d66278f6ce8'>config/locales/server.en.yml</a>
</details>
<details>
<summary>routes.rb<code>Register embedding configuration and host APIs</code> <code>+3/-0</code></summary>
<br/>
>Register embedding configuration and host APIs
>
><pre>
>• Adds staff-constrained show and update routes for embedding configuration plus RESTful embeddable-host routes.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-959bc9abc46a55332bb64d5155a79323afa75a50ec1a2137ddd22d926f62c6c5'>config/routes.rb</a>
</details>
<details>
<summary>site_settings.yml<code>Retire global host and category settings</code> <code>+0/-4</code></summary>
<br/>
>Retire global host and category settings
>
><pre>
>• Removes the newline-delimited host allowlist and single embedding category settings, which are replaced by database records.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-bff2842c9891df212adcbe8eb22a4a17c9644c676260a0cfa6e7a3953852c5e8'>config/site_settings.yml</a>
</details>
<details>
<summary>20150818190757_create_embeddable_hosts.rb<code>Migrate embedding settings into host records</code> <code>+33/-0</code></summary>
<br/>
>Migrate embedding settings into host records
>
><pre>
>• Creates the embeddable-hosts table, migrates existing hosts with their configured or uncategorized category, and deletes the superseded site-setting rows.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/30/files#diff-a8a4829637117e56ce5b7643d6242585bc0830392166c33fe66b7bb109af3d8c'>db/migrate/20150818190757_create_embeddable_hosts.rb</a>
</details>
</dd>
</dl>
</details>
</dd>
</dl>
</details>