Skip to content

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

FIX: Do not hang non-GET requests when the CSRF preflight fails

Régis Hanol88f94c2cac4b
diff --git a/frontend/discourse/app/lib/ajax.js b/frontend/discourse/app/lib/ajax.js
index 55b5c31ece2..a13ef58bc12 100644
--- a/frontend/discourse/app/lib/ajax.js
+++ b/frontend/discourse/app/lib/ajax.js
@@ -244,9 +244,7 @@ export function ajax() {
!Session.currentProp("csrfToken")
) {
promise = new Promise((resolve, reject) => {
- ajaxObj = updateCsrfToken().then(() => {
- performAjax(resolve, reject);
- });
+ updateCsrfToken().then(() => performAjax(resolve, reject), reject);
});
} else {
promise = new Promise(performAjax);
diff --git a/frontend/discourse/tests/unit/lib/ajax-test.js b/frontend/discourse/tests/unit/lib/ajax-test.js
new file mode 100644
index 00000000000..44871c2e2e6
--- /dev/null
+++ b/frontend/discourse/tests/unit/lib/ajax-test.js
@@ -0,0 +1,37 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import { ajax } from "discourse/lib/ajax";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+
+const INTERNAL_SERVER_ERROR = 500;
+
+module("Unit | Lib | ajax", function (hooks) {
+ setupTest(hooks);
+
+ test("rejects when the CSRF token request fails", async function (assert) {
+ pretender.get("/session/csrf", () => response(INTERNAL_SERVER_ERROR, {}));
+
+ const error = await ajax("/posts", { type: "POST" }).then(
+ () => "resolved",
+ (rejection) => rejection
+ );
+
+ assert.strictEqual(
+ error.jqXHR.status,
+ INTERNAL_SERVER_ERROR,
+ "the promise settles with the CSRF failure"
+ );
+ });
+
+ test("aborting before the CSRF token resolves does not throw", async function (assert) {
+ assert.expect(0);
+ pretender.get("/session/csrf", () => response({ csrf: "csrf-token" }));
+ pretender.post("/posts", () => response({}));
+
+ const promise = ajax("/posts", { type: "POST" });
+
+ promise.abort();
+
+ await promise;
+ });
+});