Skip to content

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

FIX: Handle missing OAuth2 state parameter more gracefully (#43588)

David Taylor1ad20f52f083
diff --git a/lib/freedom_patches/omniauth_oauth2_state.rb b/lib/freedom_patches/omniauth_oauth2_state.rb
new file mode 100644
index 00000000000..33d6c9861ff
--- /dev/null
+++ b/lib/freedom_patches/omniauth_oauth2_state.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+require "omniauth-oauth2"
+
+# `secure_compare` calls `bytesize` on both sides, so a callback that arrives
+# with no `omniauth.state` in the session raises instead of failing the CSRF
+# check. https://github.com/omniauth/omniauth-oauth2/pull/186 fixes it upstream.
+module OmniAuthOAuth2StatePatch
+ def secure_compare(string_a, string_b)
+ return false if string_a.to_s.empty? || string_b.to_s.empty?
+ super
+ end
+end
+
+OmniAuth::Strategies::OAuth2.prepend(OmniAuthOAuth2StatePatch)
diff --git a/spec/integration/omniauth_state_spec.rb b/spec/integration/omniauth_state_spec.rb
new file mode 100644
index 00000000000..72d2fd12560
--- /dev/null
+++ b/spec/integration/omniauth_state_spec.rb
@@ -0,0 +1,16 @@
+# frozen_string_literal: true
+
+describe "OAuth2 callback state validation" do
+ before do
+ SiteSetting.discord_client_id = "abcdef11223344"
+ SiteSetting.discord_secret = "adddcccdddd99922"
+ SiteSetting.enable_discord_logins = true
+ end
+
+ it "fails gracefully when the session has no state" do
+ post "/auth/discord/callback", params: { state: "somestate", code: "somecode" }
+
+ expect(response.status).to eq(302)
+ expect(response.location).to eq("/auth/failure?message=csrf_detected&strategy=discord")
+ end
+end