discourse/spec/serializers/topic_link_serializer_spec.rb
Alan Guo Xiang Tan 63ca5673df
FIX: Filter orphaned TopicLinks and normalize http URLs to https (#37098)
What is the problem?

`TopicLink` records can reference deleted topics or posts. When a topic
or the target post being linked to is deleted, these orphaned links
continue to appear in topic maps and post link counts.

Note that `TopicLink` records are already deleted when the source post
containing the link is trashed (see `Post#trash!`), so we only need to
filter for deleted target topics/posts.

Additionally, internal links stored with http:// are not normalized to
https:// when `force_https` site setting is enabled.

---

What is the solution?

Extend filtering in `TopicLink.topic_map` and `TopicLink.counts_for` to
exclude links where the target topic or target post is deleted. Extract
common visibility filters into `TopicLink.apply_link_visibility_filters`
helper method.

Normalize internal http:// URLs to https:// in `TopicLinkSerializer#url`
when `force_https` is enabled.
2026-01-15 12:12:34 +08:00

50 lines
1.6 KiB
Ruby

# frozen_string_literal: true
RSpec.describe TopicLinkSerializer do
it "correctly serializes the topic link" do
post = Fabricate(:post, raw: "https://meta.discourse.org/")
TopicLink.extract_from(post)
serialized = described_class.new(post.topic_links.first, root: false).as_json
expect(serialized[:domain]).to eq("meta.discourse.org")
expect(serialized[:root_domain]).to eq("discourse.org")
end
describe "#url" do
it "normalizes internal http:// URLs to https:// when force_https is enabled" do
SiteSetting.force_https = true
topic_link =
Fabricate(:topic_link, url: "http://example.com/t/test-topic/123", internal: true)
serialized = described_class.new(topic_link, root: false).as_json
expect(serialized[:url]).to eq("https://example.com/t/test-topic/123")
end
it "does not modify external http:// URLs" do
SiteSetting.force_https = true
topic_link =
Fabricate(
:topic_link,
url: "http://external-site.com/page",
domain: "external-site.com",
internal: false,
)
serialized = described_class.new(topic_link, root: false).as_json
expect(serialized[:url]).to eq("http://external-site.com/page")
end
it "does not modify internal URLs when force_https is disabled" do
SiteSetting.force_https = false
topic_link =
Fabricate(:topic_link, url: "http://example.com/t/test-topic/123", internal: true)
serialized = described_class.new(topic_link, root: false).as_json
expect(serialized[:url]).to eq("http://example.com/t/test-topic/123")
end
end
end