Skip to content

A platform for community discussion. Free, open, simple.

FIX: Consolidate permalink behavior between in-app vs full page load (#43312)

Chris Alberti02e1115201f0
diff --git a/app/controllers/topics_controller.rb b/app/controllers/topics_controller.rb
index 0bcd21bba9b..802a2fe7da3 100644
--- a/app/controllers/topics_controller.rb
+++ b/app/controllers/topics_controller.rb
@@ -57,9 +57,13 @@ class TopicsController < ApplicationController
skip_before_action :check_xhr, only: %i[show feed]
def id_for_slug
- topic = Topic.find_by_slug(params[:slug])
+ # a deleted topic with the same slug must not shadow the live one
+ topic = Topic.find_by_slug(params[:slug]) || Topic.with_deleted.find_by_slug(params[:slug])
+ raise Discourse::NotFound if topic.blank?
+
+ raise Discourse::NotFound if !guardian.can_see?(topic) && deleted_for_permalink?(topic)
+
guardian.ensure_can_see!(topic)
- raise Discourse::NotFound unless topic
render json: { slug: topic.slug, topic_id: topic.id, url: topic.url }
end
@@ -149,9 +153,7 @@ class TopicsController < ApplicationController
# If the user can't see the topic, clean up notifications for it.
Notification.remove_for(current_user.id, params[:topic_id]) if current_user
- deleted =
- guardian.can_see_topic?(ex.obj, false) ||
- (!guardian.can_see_topic?(ex.obj) && ex.obj&.access_topic_via_group && ex.obj.deleted_at)
+ deleted = deleted_for_permalink?(ex.obj)
if SiteSetting.detailed_404
if deleted
@@ -1383,6 +1385,11 @@ class TopicsController < ApplicationController
topic_id.to_s if topic_id.to_s.match?(/\A\d+\z/)
end
+ def deleted_for_permalink?(topic)
+ guardian.can_see_topic?(topic, false) ||
+ (!guardian.can_see_topic?(topic) && topic&.access_topic_via_group && topic.deleted_at)
+ end
+
def render_topic_with_tags(topic)
payload = serialize_data(topic, BasicTopicSerializer)
payload[:tags] = topic
diff --git a/frontend/discourse/app/lib/permalink-check.js b/frontend/discourse/app/lib/permalink-check.js
new file mode 100644
index 00000000000..7b9b5252c15
--- /dev/null
+++ b/frontend/discourse/app/lib/permalink-check.js
@@ -0,0 +1,39 @@
+import { ajax } from "discourse/lib/ajax";
+import EmbedMode from "discourse/lib/embed-mode";
+import DiscourseURL from "discourse/lib/url";
+
+/**
+ * Looks up a permalink for `path` and redirects to its target. Returns
+ * `{ type: "redirect" }` once handled, or `{ type: "not-found", html }`
+ * carrying the server-rendered 404 page.
+ *
+ * Redirects replace the permalink URL in the back stack: internal targets
+ * navigate within the router, external ones full-page (new tab when embedded).
+ */
+export default async function resolvePermalink(path, transition, router) {
+ const results = await ajax("/permalink-check.json", { data: { path } });
+
+ if (!results.found) {
+ return { type: "not-found", html: results.html };
+ }
+
+ let url = results.target_url;
+ if (transition?._discourse_anchor) {
+ // Keep the navigation anchor over any anchor already in the target
+ url = url.split("#")[0] + `#${transition._discourse_anchor}`;
+ }
+
+ if (results.internal) {
+ router.replaceWith(url);
+ return { type: "redirect" };
+ }
+
+ transition?.abort();
+ if (EmbedMode.enabled) {
+ DiscourseURL.routeTo(url);
+ } else {
+ DiscourseURL.redirectAbsolute(url, { replace: true });
+ }
+
+ return { type: "redirect" };
+}
diff --git a/frontend/discourse/app/routes/build-category-route.js b/frontend/discourse/app/routes/build-category-route.js
index 649c1e2f0a2..64e955bb9a5 100644
--- a/frontend/discourse/app/routes/build-category-route.js
+++ b/frontend/discourse/app/routes/build-category-route.js
@@ -2,6 +2,7 @@ import { action } from "@ember/object";
import { service } from "@ember/service";
import { queryParams, resetParams } from "discourse/controllers/discovery/list";
import { disableImplicitInjections } from "discourse/lib/implicit-injections";
+import resolvePermalink from "discourse/lib/permalink-check";
import PreloadStore from "discourse/lib/preload-store";
import { setTopicList } from "discourse/lib/topic-list-tracker";
import Category from "discourse/models/category";
@@ -29,14 +30,29 @@ class AbstractCategoryRoute extends DiscourseRoute {
templateName = "discovery/list";
async model(params, transition) {
- const category = this.site.lazy_load_categories
- ? await Category.asyncFindBySlugPathWithID(
- params.category_slug_path_with_id
- )
- : Category.findBySlugPathWithID(params.category_slug_path_with_id);
+ let category;
+
+ try {
+ category = this.site.lazy_load_categories
+ ? await Category.asyncFindBySlugPathWithID(
+ params.category_slug_path_with_id
+ )
+ : Category.findBySlugPathWithID(params.category_slug_path_with_id);
+ } catch (error) {
+ if (error?.jqXHR?.status !== 404) {
+ throw error;
+ }
+ }
if (!category) {
- this.router.replaceWith("/404");
+ const result = await resolvePermalink(
+ `/c/${params.category_slug_path_with_id}`,
+ transition,
+ this.router
+ ).catch(() => null);
+ if (result?.type !== "redirect") {
+ this.router.replaceWith("/404");
+ }
return;
}
diff --git a/frontend/discourse/app/routes/topic-by-slug-or-id.js b/frontend/discourse/app/routes/topic-by-slug-or-id.js
index ae71e14bece..7afb0b96081 100644
--- a/frontend/discourse/app/routes/topic-by-slug-or-id.js
+++ b/frontend/discourse/app/routes/topic-by-slug-or-id.js
@@ -1,21 +1,38 @@
import { service } from "@ember/service";
+import resolvePermalink from "discourse/lib/permalink-check";
import Topic, { ID_CONSTRAINT } from "discourse/models/topic";
import DiscourseRoute from "discourse/routes/discourse";
export default class TopicBySlugOrId extends DiscourseRoute {
@service router;
- model(params) {
+ afterModel(result) {
+ if (result?.url) {
+ this.router.transitionTo(result.url);
+ }
+ }
+
+ async model(params, transition) {
if (params.slug_or_id.match(ID_CONSTRAINT)) {
return { url: `/t/topic/${params.slug_or_id}` };
- } else {
- return Topic.idForSlug(params.slug_or_id).then((data) => {
- return { url: `/t/${data.slug}/${data.topic_id}` };
- });
}
- }
- afterModel(result) {
- this.router.transitionTo(result.url);
+ try {
+ const { slug, topic_id } = await Topic.idForSlug(params.slug_or_id);
+ return { url: `/t/${slug}/${topic_id}` };
+ } catch (error) {
+ if (error?.jqXHR?.status !== 404) {
+ throw error;
+ }
+ const permalink = await resolvePermalink(
+ `/t/${params.slug_or_id}`,
+ transition,
+ this.router
+ ).catch(() => null);
+ if (permalink?.type === "redirect") {
+ return {};
+ }
+ throw error;
+ }
}
}
diff --git a/frontend/discourse/app/routes/topic/from-params.js b/frontend/discourse/app/routes/topic/from-params.js
index 0da61a153be..9b029c0241e 100644
--- a/frontend/discourse/app/routes/topic/from-params.js
+++ b/frontend/discourse/app/routes/topic/from-params.js
@@ -17,6 +17,7 @@ import {
isValidNestedViewCacheSnapshot,
NESTED_VIEW_CACHE_FORMAT_VERSION,
} from "discourse/lib/nested-view-cache-snapshot";
+import resolvePermalink from "discourse/lib/permalink-check";
import PreloadStore from "discourse/lib/preload-store";
import { registerPostInTopicPostStream } from "discourse/lib/process-node";
import DiscourseURL from "discourse/lib/url";
@@ -35,6 +36,15 @@ export function nestedQueryString(params) {
return query.toString();
}
+function originalTopicPath(topic, params) {
+ let path = `/t/${topic.slug}/${topic.id}`;
+ const nearPost = params.nearPost;
+ if (nearPost && nearPost !== "last" && nearPost !== 999999999) {
+ path += `/${nearPost}`;
+ }
+ return path;
+}
+
// This route is used for retrieving a topic based on params
export default class TopicFromParams extends DiscourseRoute {
@service appEvents;
@@ -89,11 +99,25 @@ export default class TopicFromParams extends DiscourseRoute {
}
return params;
})
- .catch((e) => {
+ .catch(async (e) => {
if (!isTesting()) {
// eslint-disable-next-line no-console
console.log("Could not view topic", e);
}
+
+ // The id-only topic JSON drops the slug, so the server can't match a
+ // permalink for the original URL; resolve it here instead.
+ if (topic.errorHtml) {
+ const result = await resolvePermalink(
+ originalTopicPath(topic, params),
+ transition,
+ this.router
+ ).catch(() => null);
+ if (result?.type === "redirect") {
+ return params;
+ }
+ }
+
params._loading_error = true;
return params;
});
diff --git a/frontend/discourse/app/routes/unknown.js b/frontend/discourse/app/routes/unknown.js
index 8351c07b032..a55c3e8a53e 100644
--- a/frontend/discourse/app/routes/unknown.js
+++ b/frontend/discourse/app/routes/unknown.js
@@ -1,6 +1,6 @@
import { service } from "@ember/service";
-import { ajax } from "discourse/lib/ajax";
-import DiscourseURL, { rewritePath } from "discourse/lib/url";
+import resolvePermalink from "discourse/lib/permalink-check";
+import { rewritePath } from "discourse/lib/url";
import DiscourseRoute from "discourse/routes/discourse";
export default class UnknownRoute extends DiscourseRoute {
@@ -19,33 +19,8 @@ export default class UnknownRoute extends DiscourseRoute {
return;
}
- const permalinkResults = await ajax("/permalink-check.json", {
- data: { path },
- });
-
- if (permalinkResults.found) {
- let url = permalinkResults.target_url;
-
- if (transition._discourse_anchor) {
- // Remove the anchor from the permalink if present
- url = url.split("#")[0];
-
- // Add the anchor from the transition
- url += `#${transition._discourse_anchor}`;
- }
-
- if (permalinkResults.internal) {
- // Redirect within the routing system so the transition is tracked
- return this.router.replaceWith(url);
- }
-
- // Avoid polluting the history stack for external links
- transition.abort();
- DiscourseURL.routeTo(url);
- return "";
- } else {
- // 404 body HTML
- return permalinkResults.html;
- }
+ const result = await resolvePermalink(path, transition, this.router);
+ // 404 body HTML, unless the permalink redirect already took over
+ return result.type === "redirect" ? "" : result.html;
}
}
diff --git a/frontend/discourse/tests/acceptance/permalink-redirect-test.js b/frontend/discourse/tests/acceptance/permalink-redirect-test.js
index aae0c8738d6..0bb6d6e8459 100644
--- a/frontend/discourse/tests/acceptance/permalink-redirect-test.js
+++ b/frontend/discourse/tests/acceptance/permalink-redirect-test.js
@@ -1,9 +1,25 @@
-import { visit } from "@ember/test-helpers";
+import { currentURL, settled, visit } from "@ember/test-helpers";
import { test } from "qunit";
import sinon from "sinon";
+import EmbedMode from "discourse/lib/embed-mode";
import DiscourseURL from "discourse/lib/url";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+/**
+ * Workaround for https://github.com/tildeio/router.js/pull/335
+ */
+async function visitWithRedirects(url) {
+ try {
+ await visit(url);
+ } catch (error) {
+ const { message } = error;
+ if (message !== "TransitionAborted") {
+ throw error;
+ }
+ await settled();
+ }
+}
+
acceptance("External Permalink Redirect via XHR", function (needs) {
needs.pretender((server) => {
server.get("/t/99.json", () => [
@@ -25,3 +41,263 @@ acceptance("External Permalink Redirect via XHR", function (needs) {
);
});
});
+
+acceptance("Permalink redirect for /t/:slug_or_id", function (needs) {
+ needs.pretender((server, helper) => {
+ server.get("/t/id_for/:slug", () => helper.response(404, {}));
+ server.get("/permalink-check.json", () =>
+ helper.response({
+ found: true,
+ target_url: "https://www.example.com",
+ })
+ );
+ });
+
+ test("redirects when the slug matches a permalink", async function (assert) {
+ sinon.stub(DiscourseURL, "redirectAbsolute");
+
+ await visitWithRedirects("/t/some-slug-that-does-not-exist");
+
+ assert.true(
+ DiscourseURL.redirectAbsolute.calledWith("https://www.example.com", {
+ replace: true,
+ })
+ );
+ });
+});
+
+acceptance("Permalink check failure for /t/:slug_or_id", function (needs) {
+ needs.pretender((server, helper) => {
+ server.get("/t/id_for/:slug", () => helper.response(404, {}));
+ let permalinkRequests = 0;
+ server.get("/permalink-check.json", () => {
+ permalinkRequests++;
+ if (permalinkRequests === 1) {
+ return helper.response(500, {});
+ }
+ return helper.response({
+ found: false,
+ html: "<div class='page-not-found'>not found</div>",
+ });
+ });
+ });
+
+ test("falls back to the original 404 when the permalink check fails", async function (assert) {
+ await visit("/t/some-slug-that-does-not-exist");
+
+ assert.dom(".page-not-found").exists("the not found page is rendered");
+ });
+});
+
+acceptance("Permalink redirect for /t/:slug (embedded)", function (needs) {
+ needs.pretender((server, helper) => {
+ server.get("/t/id_for/:slug", () => helper.response(404, {}));
+ server.get("/permalink-check.json", () =>
+ helper.response({
+ found: true,
+ target_url: "https://www.example.com",
+ })
+ );
+ });
+
+ test("opens the external permalink in a new tab when embedded", async function (assert) {
+ const originalEmbedMode = EmbedMode.enabled;
+ EmbedMode.enabled = true;
+
+ try {
+ const open = sinon.stub(window, "open").returns(null);
+ const redirectAbsolute = sinon.stub(DiscourseURL, "redirectAbsolute");
+
+ await visitWithRedirects("/t/some-slug-that-does-not-exist");
+
+ assert.true(open.calledWith("https://www.example.com", "_blank"));
+ assert.false(redirectAbsolute.called);
+ } finally {
+ EmbedMode.enabled = originalEmbedMode;
+ }
+ });
+});
+
+acceptance("Permalink redirect for /t/:slug/:id", function (needs) {
+ let requestedPath;
+
+ needs.pretender((server, helper) => {
+ server.get("/t/999999.json", () =>
+ helper.response(404, {
+ extras: { html: "<div class='page-not-found'>not found</div>" },
+ })
+ );
+ server.get("/permalink-check.json", (request) => {
+ requestedPath = request.queryParams.path;
+ return helper.response({
+ found: true,
+ target_url: "https://www.example.com",
+ });
+ });
+ });
+
+ test("redirects when the id-only lookup is a permalink hit", async function (assert) {
+ sinon.stub(DiscourseURL, "redirectAbsolute");
+
+ await visitWithRedirects("/t/some-slug-that-does-not-exist/999999");
+
+ assert.strictEqual(
+ requestedPath,
+ "/t/some-slug-that-does-not-exist/999999"
+ );
+ assert.true(
+ DiscourseURL.redirectAbsolute.calledWith("https://www.example.com", {
+ replace: true,
+ })
+ );
+ });
+});
+
+acceptance("Permalink redirect for /t/:slug/:id (internal)", function (needs) {
+ needs.pretender((server, helper) => {
+ server.get("/t/999999.json", () =>
+ helper.response(404, {
+ extras: { html: "<div class='page-not-found'>not found</div>" },
+ })
+ );
+ server.get("/permalink-check.json", () =>
+ helper.response({
+ found: true,
+ internal: true,
+ target_url: "/t/internationalization-localization/280",
+ })
+ );
+ });
+
+ test("redirects within the router when the permalink targets an internal URL", async function (assert) {
+ const redirect = sinon.stub(DiscourseURL, "redirectAbsolute");
+
+ await visit("/t/some-slug-that-does-not-exist/999999");
+
+ assert.strictEqual(
+ currentURL(),
+ "/t/internationalization-localization/280"
+ );
+ assert.false(
+ redirect.called,
+ "internal permalinks must not trigger a full-page redirect"
+ );
+ });
+});
+
+acceptance("Permalink not found for /t/:slug/:id", function (needs) {
+ needs.pretender((server, helper) => {
+ server.get("/t/999999.json", () =>
+ helper.response(404, {
+ extras: { html: "<div class='page-not-found'>not found</div>" },
+ })
+ );
+ });
+
+ test("renders the server 404 page when no permalink matches", async function (assert) {
+ await visit("/t/some-slug-that-does-not-exist/999999");
+
+ assert.dom(".not-found").exists("the not found page is rendered");
+ });
+});
+
+acceptance("Permalink check failure for /t/:slug/:id", function (needs) {
+ needs.pretender((server, helper) => {
+ server.get("/t/999999.json", () =>
+ helper.response(404, {
+ extras: { html: "<div class='page-not-found'>not found</div>" },
+ })
+ );
+ server.get("/permalink-check.json", () => helper.response(500, {}));
+ });
+
+ test("renders the server 404 page when the permalink check fails", async function (assert) {
+ await visit("/t/some-slug-that-does-not-exist/999999");
+
+ assert.dom(".not-found").exists("the not found page is rendered");
+ });
+});
+
+acceptance("Permalink redirect for /c/:slug", function (needs) {
+ let requestedPath;
+
+ needs.pretender((server, helper) => {
+ server.get("/permalink-check.json", (request) => {
+ requestedPath = request.queryParams.path;
+ return helper.response({
+ found: true,
+ target_url: "https://www.example.com",
+ });
+ });
+ });
+
+ test("redirects when the category slug matches a permalink", async function (assert) {
+ sinon.stub(DiscourseURL, "redirectAbsolute");
+
+ await visitWithRedirects("/c/some-category-that-does-not-exist");
+
+ assert.strictEqual(requestedPath, "/c/some-category-that-does-not-exist");
+ assert.true(
+ DiscourseURL.redirectAbsolute.calledWith("https://www.example.com", {
+ replace: true,
+ })
+ );
+ });
+});
+
+acceptance("Permalink redirect for /c/:slug/:id", function (needs) {
+ let requestedPath;
+
+ needs.pretender((server, helper) => {
+ server.get("/permalink-check.json", (request) => {
+ requestedPath = request.queryParams.path;
+ return helper.response({
+ found: true,
+ target_url: "https://www.example.com",
+ });
+ });
+ });
+
+ test("redirects when the category slug/id matches a permalink", async function (assert) {
+ sinon.stub(DiscourseURL, "redirectAbsolute");
+
+ await visitWithRedirects("/c/some-category-that-does-not-exist/999999");
+
+ assert.strictEqual(
+ requestedPath,
+ "/c/some-category-that-does-not-exist/999999"
+ );
+ assert.true(
+ DiscourseURL.redirectAbsolute.calledWith("https://www.example.com", {
+ replace: true,
+ })
+ );
+ });
+});
+
+acceptance("Permalink not found for /c/:slug", function () {
+ test("shows the 404 page when no permalink matches", async function (assert) {
+ await visit("/c/some-category-that-does-not-exist/999999");
+
+ assert.strictEqual(currentURL(), "/404");
+ });
+});
+
+acceptance("Permalink check failure for /c/:slug", function (needs) {
+ needs.pretender((server, helper) => {
+ let permalinkRequests = 0;
+ server.get("/permalink-check.json", () => {
+ permalinkRequests++;
+ if (permalinkRequests === 1) {
+ return helper.response(500, {});
+ }
+ return helper.response({ found: false });
+ });
+ });
+
+ test("shows the 404 page when the permalink check fails", async function (assert) {
+ await visit("/c/some-category-that-does-not-exist");
+
+ assert.strictEqual(currentURL(), "/404");
+ });
+});
diff --git a/spec/requests/topics_controller_spec.rb b/spec/requests/topics_controller_spec.rb
index 640ae8f8458..aa3d74e8e6f 100644
--- a/spec/requests/topics_controller_spec.rb
+++ b/spec/requests/topics_controller_spec.rb
@@ -2301,6 +2301,52 @@ RSpec.describe TopicsController do
get "/t/id_for/#{pm.slug}.json"
expect(response).to be_forbidden
end
+
+ it "returns 404 when no topic matches the slug" do
+ get "/t/id_for/a-slug-that-does-not-exist.json"
+ expect(response).to be_not_found
+ end
+
+ context "with a deleted topic" do
+ it "returns 404" do
+ deleted_topic = Fabricate(:deleted_topic)
+ get "/t/id_for/#{deleted_topic.slug}.json"
+ expect(response).to be_not_found
+ end
+
+ it "returns 200 for staff" do
+ deleted_topic = Fabricate(:deleted_topic)
+ sign_in(admin)
+
+ get "/t/id_for/#{deleted_topic.slug}.json"
+ expect(response).to be_successful
+ end
+
+ it "returns 403 for a deleted topic in a category the user cannot see" do
+ group = Fabricate(:group)
+ category = Fabricate(:category)
+ category.set_permissions(group => :full)
+ category.save!
+ deleted_topic = Fabricate(:topic, category: category, deleted_at: 1.day.ago)
+
+ get "/t/id_for/#{deleted_topic.slug}.json"
+ expect(response).to be_forbidden
+ end
+ end
+
+ context "when a deleted topic and a live topic share a slug" do
+ it "returns the live topic" do
+ deleted_topic = Fabricate(:deleted_topic, title: "Shadowed Topic A")
+ deleted_topic.update_column(:slug, "shadowed-slug")
+ live_topic = Fabricate(:topic, title: "Shadowed Topic B")
+ live_topic.update_column(:slug, "shadowed-slug")
+
+ get "/t/id_for/shadowed-slug.json"
+
+ expect(response).to be_successful
+ expect(response.parsed_body["topic_id"]).to eq(live_topic.id)
+ end
+ end
end
describe "#update" do