Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Harden OAuth client registration: reserve "Sure" client names, require https redirect URIs (#4193)

GFRba4086fd6be2
diff --git a/app/controllers/oauth_registration_controller.rb b/app/controllers/oauth_registration_controller.rb
index 5b5c2f33fb..90d562c1d5 100644
--- a/app/controllers/oauth_registration_controller.rb
+++ b/app/controllers/oauth_registration_controller.rb
@@ -4,6 +4,16 @@ class OauthRegistrationController < ApplicationController
# or are not OAuth redirects.
FORBIDDEN_SCHEMES = %w[javascript data file about blob ws wss ftp mailto tel sms intent].freeze
SCHEME_PATTERN = /\A[a-z][a-z0-9+\-.]*\z/.freeze
+ # Client names containing the word "Sure" are reserved for first-party apps
+ # (e.g. "Sure Mobile"), so a registered client cannot pose as one on the
+ # consent screen or share the mobile app's name.
+ RESERVED_CLIENT_NAME_WORD = "sure"
+ # Lowercase Cyrillic, Greek and Armenian letters that look like the Latin
+ # letters of "sure mobile" (NFKC keeps them apart), e.g. "Ѕurе" with a
+ # Cyrillic Ѕ and е. Uppercase look-alikes such as М and В arrive here
+ # already downcased.
+ CONFUSABLE_LETTERS = "ѕսυуеοоіιӏмвг"
+ CONFUSABLE_LATIN = "suuueooiilmbr"
skip_authentication
skip_before_action :verify_authenticity_token
@@ -50,6 +60,25 @@ class OauthRegistrationController < ApplicationController
client_name = body["client_name"].presence || "MCP Client"
+ # Bidi controls can make the consent screen show a name that differs from
+ # the stored text (e.g. U+202E "eruS" renders as "Sure"), so reject them
+ # instead of stripping them.
+ if client_name.to_s.match?(/\p{Bidi_Control}/)
+ render json: {
+ error: "invalid_client_metadata",
+ error_description: t("oauth.registration.invalid_client_name")
+ }, status: :bad_request
+ return
+ end
+
+ if reserved_client_name?(client_name)
+ render json: {
+ error: "invalid_client_metadata",
+ error_description: t("oauth.registration.reserved_client_name")
+ }, status: :bad_request
+ return
+ end
+
app = Doorkeeper::Application.new(
name: client_name,
redirect_uri: redirect_uris.join("\n"),
@@ -83,6 +112,32 @@ class OauthRegistrationController < ApplicationController
private
+ # Matches "Sure" as a whole word, ignoring case, punctuation, invisible
+ # characters (format characters plus every default-ignorable code point,
+ # such as the combining grapheme joiner, variation selectors and Hangul
+ # fillers), combining marks NFKC cannot compose (e.g. U+0332 after "S"), full-width
+ # letters and common look-alike letters, plus words starting with
+ # "SureMobile". Consecutive words are joined too, so separators inside the
+ # word ("S u r e", "S.u.r.e", "S-u-r-e") do not get around the check.
+ # "Surefire" or "Measure Mobile" stay allowed.
+ def reserved_client_name?(name)
+ normalized = name.to_s.unicode_normalize(:nfkc).downcase.gsub(/[\p{Cf}\p{Mn}\p{Me}\p{Default_Ignorable_Code_Point}]/, "")
+ .tr(CONFUSABLE_LETTERS, CONFUSABLE_LATIN)
+ words = normalized.scan(/[[:alnum:]]+/)
+ reserved_prefix = "#{RESERVED_CLIENT_NAME_WORD}mobile"
+
+ words.each_index do |start|
+ joined = +""
+ words.drop(start).each do |word|
+ joined << word
+ return true if joined == RESERVED_CLIENT_NAME_WORD || joined.start_with?(reserved_prefix)
+ break unless reserved_prefix.start_with?(joined)
+ end
+ end
+
+ false
+ end
+
# Returns true for https, loopback http, and RFC 8252 private-use schemes
# (cursor://, vscode://). Rejects fragments, userinfo, handler schemes, and
# non-loopback http.
diff --git a/app/models/mobile_device.rb b/app/models/mobile_device.rb
index f24c0b904a..af70fd043e 100644
--- a/app/models/mobile_device.rb
+++ b/app/models/mobile_device.rb
@@ -15,18 +15,21 @@ class MobileDevice < ApplicationRecord
before_validation :set_last_seen_at, on: :create
CALLBACK_URL = "sureapp://oauth/callback"
+ OAUTH_APPLICATION_NAME = "Sure Mobile"
scope :active, -> { where("last_seen_at > ?", 90.days.ago) }
def self.shared_oauth_application
+ # Matches on the app's callback too and lets the oldest row win, so a
+ # same-named client from dynamic registration (before names were reserved)
+ # with its own redirect URI is never picked as the mobile app.
@shared_oauth_application ||= begin
- Doorkeeper::Application.find_or_create_by!(name: "Sure Mobile") do |app|
- app.redirect_uri = CALLBACK_URL
+ Doorkeeper::Application.order(:created_at, :id).find_or_create_by!(name: OAUTH_APPLICATION_NAME, redirect_uri: CALLBACK_URL) do |app|
app.scopes = "read_write"
app.confidential = false
end
rescue ActiveRecord::RecordNotUnique
- Doorkeeper::Application.find_by!(name: "Sure Mobile")
+ Doorkeeper::Application.order(:created_at, :id).find_by!(name: OAUTH_APPLICATION_NAME, redirect_uri: CALLBACK_URL)
end
end
diff --git a/config/initializers/doorkeeper.rb b/config/initializers/doorkeeper.rb
index 2b53e4c74d..5d2a1fdfd6 100644
--- a/config/initializers/doorkeeper.rb
+++ b/config/initializers/doorkeeper.rb
@@ -321,8 +321,12 @@ Doorkeeper.configure do
# #call can be used in order to allow conditional checks (to allow non-SSL
# redirects to localhost for example).
#
- # Allow custom URL schemes for mobile apps
- force_ssl_in_redirect_uri false
+ # Doorkeeper only enforces this for the http scheme, so custom mobile schemes
+ # (sureapp://) are unaffected. Plain http stays allowed for loopback hosts
+ # (RFC 8252 native clients) and in development.
+ force_ssl_in_redirect_uri do |uri|
+ !Rails.env.development? && !uri.host.to_s.downcase.delete_prefix("[").delete_suffix("]").in?(OauthRegistrationController::LOOPBACK_HOSTS)
+ end
# Specify what redirect URI's you want to block during Application creation.
# Any redirect URI is allowed by default.
diff --git a/config/locales/defaults/ca.yml b/config/locales/defaults/ca.yml
index 6a130664c3..27bdc97d7a 100644
--- a/config/locales/defaults/ca.yml
+++ b/config/locales/defaults/ca.yml
@@ -237,3 +237,5 @@ ca:
oauth:
registration:
invalid_redirect_uris: redirect_uris ha d'utilitzar https, http de loopback o un esquema d'URI d'aplicació nativa
+ invalid_client_name: client_name no pot contenir caràcters de control bidireccionals
+ reserved_client_name: client_name està reservat per a les aplicacions pròpies
diff --git a/config/locales/defaults/de.yml b/config/locales/defaults/de.yml
index 8c09479e94..9b508f9ce2 100644
--- a/config/locales/defaults/de.yml
+++ b/config/locales/defaults/de.yml
@@ -7,6 +7,11 @@ de:
close: Schließen
global:
expand: "Aufklappen"
+ oauth:
+ registration:
+ invalid_redirect_uris: "redirect_uris müssen https, loopback-http oder ein URI-Schema einer nativen App verwenden"
+ invalid_client_name: "client_name darf keine bidirektionalen Steuerzeichen enthalten"
+ reserved_client_name: "client_name ist für eigene Apps reserviert"
activerecord:
errors:
messages:
diff --git a/config/locales/defaults/en.yml b/config/locales/defaults/en.yml
index 44f417a5d1..a8475a5728 100644
--- a/config/locales/defaults/en.yml
+++ b/config/locales/defaults/en.yml
@@ -14,6 +14,8 @@ en:
oauth:
registration:
invalid_redirect_uris: "redirect_uris must use https, loopback http, or a native app URI scheme"
+ invalid_client_name: "client_name must not contain bidirectional control characters"
+ reserved_client_name: "client_name is reserved for first-party apps"
activerecord:
errors:
messages:
diff --git a/config/locales/defaults/pl.yml b/config/locales/defaults/pl.yml
index bf8f5648cf..d55c36f83a 100644
--- a/config/locales/defaults/pl.yml
+++ b/config/locales/defaults/pl.yml
@@ -252,6 +252,8 @@ pl:
registration:
invalid_redirect_uris: redirect_uris musi używać https, loopback http lub schematu
URI aplikacji natywnej
+ invalid_client_name: client_name nie może zawierać dwukierunkowych znaków sterujących
+ reserved_client_name: client_name jest zarezerwowane dla własnych aplikacji
support:
array:
last_word_connector: " oraz "
diff --git a/config/locales/defaults/ru.yml b/config/locales/defaults/ru.yml
index 0bdd573bbb..4a306295f5 100644
--- a/config/locales/defaults/ru.yml
+++ b/config/locales/defaults/ru.yml
@@ -283,3 +283,5 @@ ru:
oauth:
registration:
invalid_redirect_uris: redirect_uris должны использовать HTTPS, HTTP для loopback-адреса или URI-схему нативного приложения
+ invalid_client_name: client_name не должно содержать управляющие символы направления текста
+ reserved_client_name: client_name зарезервировано для собственных приложений
diff --git a/config/locales/defaults/tr.yml b/config/locales/defaults/tr.yml
index 29421e4a06..c8dff96f63 100644
--- a/config/locales/defaults/tr.yml
+++ b/config/locales/defaults/tr.yml
@@ -234,3 +234,5 @@ tr:
oauth:
registration:
invalid_redirect_uris: redirect_uris yalnızca https, loopback http veya yerel uygulama URI şeması kullanabilir
+ invalid_client_name: client_name çift yönlü kontrol karakterleri içeremez
+ reserved_client_name: client_name kendi uygulamalarımız için ayrılmıştır
diff --git a/config/locales/defaults/uk.yml b/config/locales/defaults/uk.yml
index 6ffcfe82cf..4cdde3c477 100644
--- a/config/locales/defaults/uk.yml
+++ b/config/locales/defaults/uk.yml
@@ -286,4 +286,6 @@ uk:
unsupported_protocol_version: 'Непідтримувана версія протоколу MCP: %{version}'
oauth:
registration:
- invalid_redirect_uris: redirect_uris мають використовувати https, loopback http або URI-схему нативного застосунку
\ No newline at end of file
+ invalid_redirect_uris: redirect_uris мають використовувати https, loopback http або URI-схему нативного застосунку
+ invalid_client_name: client_name не може містити керівні символи напрямку тексту
+ reserved_client_name: client_name зарезервовано для власних застосунків
diff --git a/db/seeds/oauth_applications.rb b/db/seeds/oauth_applications.rb
index 40d1d187e0..93dabde9a6 100644
--- a/db/seeds/oauth_applications.rb
+++ b/db/seeds/oauth_applications.rb
@@ -2,11 +2,7 @@
# These are the only OAuth apps that will exist - external developers use API keys
# Sure Mobile App (shared across iOS and Android)
-mobile_app = Doorkeeper::Application.find_or_create_by(name: "Sure Mobile") do |app|
- app.redirect_uri = "sureapp://oauth/callback"
- app.scopes = "read_write"
- app.confidential = false # Public client (mobile app)
-end
+mobile_app = MobileDevice.shared_oauth_application
puts "Created OAuth applications:"
puts "Mobile App - Client ID: #{mobile_app.uid}"
diff --git a/test/controllers/oauth_registration_controller_test.rb b/test/controllers/oauth_registration_controller_test.rb
index bc2eaf2b82..0683712652 100644
--- a/test/controllers/oauth_registration_controller_test.rb
+++ b/test/controllers/oauth_registration_controller_test.rb
@@ -336,4 +336,49 @@ class OauthRegistrationControllerTest < ActionDispatch::IntegrationTest
assert_equal [ redirect_uri ], json["redirect_uris"]
end
end
+
+ test "rejects client names reserved for first-party apps" do
+ [
+ "Sure Mobile", "sure mobile", "SURE-Mobile", "Sure", "Official Sure App", "SureMobile", "SureMobileApp",
+ "Su\u200Bre Mobile", "Su\u034Fre Mobile", "Su\uFE0Fre Mobile", "Su\u3164re Mobile", "S\u0332ure Mobile", "\uFF33\uFF55\uFF52\uFF45 Mobile",
+ "\u0405ur\u0435 Mobile", "S\u057Dre", "\u0405URE \u041C\u041EBILE", "Su\u0433e Mobile", "S\u0443re Mobile", "S u r e Mobile", "S.u.r.e", "S-u-r-e Mobile", "SureMo bile App"
+ ].each do |client_name|
+ assert_no_difference "Doorkeeper::Application.count", client_name do
+ post "/register",
+ params: { client_name: client_name, redirect_uris: [ "https://evil.example/callback" ] }.to_json,
+ headers: { "Content-Type" => "application/json" }
+ end
+
+ assert_response :bad_request, client_name
+ json = JSON.parse(response.body)
+ assert_equal "invalid_client_metadata", json["error"]
+ assert_equal I18n.t("oauth.registration.reserved_client_name"), json["error_description"]
+ end
+ end
+
+ test "allows client names that only contain sure inside another word" do
+ [ "Measure MCP", "Measure Mobile", "Surefire Agent", "Su Pre Agent", "Sur Ely", "S\u00FCre Notes", "\u041C\u043E\u0439 \u043A\u043B\u0438\u0435\u043D\u0442" ].each do |client_name|
+ post "/register",
+ params: { client_name: client_name, redirect_uris: [ "https://claude.ai/callback" ] }.to_json,
+ headers: { "Content-Type" => "application/json" }
+
+ assert_response :created, client_name
+ assert_equal client_name, JSON.parse(response.body)["client_name"]
+ end
+ end
+
+ test "rejects client names with bidirectional control characters" do
+ [ "\u202Eelibom erus", "Claude\u2066 Agent\u2069", "Agent\u200F" ].each do |client_name|
+ assert_no_difference "Doorkeeper::Application.count", client_name do
+ post "/register",
+ params: { client_name: client_name, redirect_uris: [ "https://evil.example/callback" ] }.to_json,
+ headers: { "Content-Type" => "application/json" }
+ end
+
+ assert_response :bad_request, client_name
+ json = JSON.parse(response.body)
+ assert_equal "invalid_client_metadata", json["error"]
+ assert_equal I18n.t("oauth.registration.invalid_client_name"), json["error_description"]
+ end
+ end
end
diff --git a/test/initializers/doorkeeper_redirect_uri_test.rb b/test/initializers/doorkeeper_redirect_uri_test.rb
new file mode 100644
index 0000000000..17b4795856
--- /dev/null
+++ b/test/initializers/doorkeeper_redirect_uri_test.rb
@@ -0,0 +1,25 @@
+require "test_helper"
+
+class DoorkeeperRedirectUriTest < ActiveSupport::TestCase
+ test "rejects plain http redirect uris for non-loopback hosts" do
+ app = Doorkeeper::Application.new(name: "Http client", redirect_uri: "http://example.com/callback")
+
+ assert_not app.valid?
+ assert app.errors[:redirect_uri].any?
+ end
+
+ test "allows https, loopback http and custom app schemes" do
+ [
+ "https://example.com/callback",
+ "http://localhost:8787/callback",
+ "http://LocalHost:8787/callback",
+ "http://127.0.0.1/callback",
+ "http://[::1]:3000/callback",
+ MobileDevice::CALLBACK_URL
+ ].each do |uri|
+ app = Doorkeeper::Application.new(name: "Client", redirect_uri: uri)
+
+ assert app.valid?, "#{uri} should be allowed: #{app.errors.full_messages.to_sentence}"
+ end
+ end
+end
diff --git a/test/models/mobile_device_test.rb b/test/models/mobile_device_test.rb
index a0d2c981b0..7bfaf8b008 100644
--- a/test/models/mobile_device_test.rb
+++ b/test/models/mobile_device_test.rb
@@ -21,6 +21,44 @@ class MobileDeviceTest < ActiveSupport::TestCase
end
end
+ test "shared_oauth_application ignores a same-named client with another redirect uri" do
+ Doorkeeper::Application.where(name: "Sure Mobile").destroy_all
+ # Registered before the real app, e.g. via dynamic client registration on
+ # an instance where nobody had signed in on mobile yet.
+ impostor = Doorkeeper::Application.create!(
+ name: "Sure Mobile",
+ redirect_uri: "https://evil.example/callback",
+ scopes: "read_write",
+ confidential: false,
+ created_at: 3.days.ago
+ )
+ real = Doorkeeper::Application.create!(
+ name: "Sure Mobile",
+ redirect_uri: MobileDevice::CALLBACK_URL,
+ scopes: "read_write",
+ confidential: false,
+ created_at: 2.days.ago
+ )
+
+ assert_equal real, MobileDevice.shared_oauth_application
+ assert_not_equal impostor, MobileDevice.shared_oauth_application
+ end
+
+ test "shared_oauth_application creates the real app when only an impostor exists" do
+ Doorkeeper::Application.where(name: "Sure Mobile").destroy_all
+ impostor = Doorkeeper::Application.create!(
+ name: "Sure Mobile",
+ redirect_uri: "https://evil.example/callback",
+ scopes: "read_write",
+ confidential: false
+ )
+
+ app = MobileDevice.shared_oauth_application
+
+ assert_not_equal impostor, app
+ assert_equal MobileDevice::CALLBACK_URL, app.redirect_uri
+ end
+
test "inactive users cannot receive new mobile tokens" do
user = users(:family_member)
device = user.mobile_devices.create!(