Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(mcp): OAuth 2.1 auth for MCP — connect Claude.ai with your Sure login (#2234)

Will Wilson2075c8c41cb7
diff --git a/app/controllers/concerns/oauth_base.rb b/app/controllers/concerns/oauth_base.rb
new file mode 100644
index 0000000000..b176cee67a
--- /dev/null
+++ b/app/controllers/concerns/oauth_base.rb
@@ -0,0 +1,8 @@
+module OauthBase
+ extend ActiveSupport::Concern
+
+ private
+ def configured_base_url
+ (ENV["APP_URL"].presence || request.base_url).chomp("/")
+ end
+end
diff --git a/app/controllers/mcp_controller.rb b/app/controllers/mcp_controller.rb
index 1a7308b867..cf49067382 100644
--- a/app/controllers/mcp_controller.rb
+++ b/app/controllers/mcp_controller.rb
@@ -1,4 +1,6 @@
class McpController < ApplicationController
+ include OauthBase
+
PROTOCOL_VERSION = "2025-03-26"
# Skip session-based auth and CSRF — this is a token-authenticated API
@@ -101,36 +103,52 @@ class McpController < ApplicationController
end
def authenticate_mcp_token!
- expected = ENV["MCP_API_TOKEN"]
+ auth_header = request.authorization.to_s
+ token = auth_header[/\ABearer\s+(.+)\z/i, 1]&.strip&.presence # pipelock:ignore
- unless expected.present?
- render json: { error: "MCP endpoint not configured" }, status: :service_unavailable
- return
- end
+ return if token.present? && authenticate_via_doorkeeper(token)
+ return if token.present? && authenticate_via_env_token(token)
- token = request.headers["Authorization"]&.delete_prefix("Bearer ")&.strip
+ render_mcp_unauthorized
+ end
- unless ActiveSupport::SecurityUtils.secure_compare(token.to_s, expected)
- render json: { error: "unauthorized" }, status: :unauthorized
- return
- end
+ def authenticate_via_doorkeeper(token)
+ access_token = Doorkeeper::AccessToken.by_token(token)
+ return false unless access_token&.accessible?
+ return false unless access_token.scopes.include?("read_write")
+
+ user = User.find_by(id: access_token.resource_owner_id)
+ return false unless user&.active?
- setup_mcp_user
+ setup_mcp_session(user)
+ true
end
- def setup_mcp_user
- email = ENV["MCP_USER_EMAIL"]
- @mcp_user = User.find_by(email: email) if email.present?
+ def authenticate_via_env_token(token)
+ expected = ENV["MCP_API_TOKEN"]
+ return false unless expected.present?
+ return false unless ActiveSupport::SecurityUtils.secure_compare(
+ OpenSSL::Digest::SHA256.hexdigest(token),
+ OpenSSL::Digest::SHA256.hexdigest(expected)
+ )
+
+ user = User.find_by(email: ENV["MCP_USER_EMAIL"])
- unless @mcp_user
- render json: { error: "MCP user not configured" }, status: :service_unavailable
- return
+ unless user
+ Rails.logger.warn "[MCP] MCP_USER_EMAIL does not match any user — check environment configuration"
+ return false
end
+ setup_mcp_session(user)
+ true
+ end
+
+ def setup_mcp_session(user)
+ @mcp_user = user
# Build a fresh session to avoid inheriting impersonation state from
# existing sessions (Current.user resolves via active_impersonator_session
# first, which could leak another user's data into MCP tool calls).
- Current.session = @mcp_user.sessions.build(
+ Current.session = user.sessions.build(
user_agent: request.user_agent,
ip_address: request.ip
)
@@ -140,6 +158,14 @@ class McpController < ApplicationController
@mcp_user
end
+ def render_mcp_unauthorized
+ response.set_header(
+ "WWW-Authenticate",
+ "Bearer resource_metadata=\"#{configured_base_url}/.well-known/oauth-protected-resource\""
+ )
+ render json: { error: "unauthorized" }, status: :unauthorized
+ end
+
def render_jsonrpc_error(id, code, message)
render json: {
jsonrpc: "2.0",
diff --git a/app/controllers/oauth_metadata_controller.rb b/app/controllers/oauth_metadata_controller.rb
new file mode 100644
index 0000000000..d5260ff552
--- /dev/null
+++ b/app/controllers/oauth_metadata_controller.rb
@@ -0,0 +1,29 @@
+class OauthMetadataController < ApplicationController
+ include OauthBase
+
+ skip_authentication
+ skip_before_action :verify_authenticity_token
+ skip_before_action :require_onboarding_and_upgrade, raise: false
+ skip_before_action :set_default_chat, raise: false
+ skip_before_action :detect_os, raise: false
+
+ def protected_resource
+ render json: {
+ resource: configured_base_url,
+ authorization_servers: [ configured_base_url ]
+ }
+ end
+
+ def authorization_server
+ render json: {
+ issuer: configured_base_url,
+ authorization_endpoint: "#{configured_base_url}/oauth/authorize",
+ token_endpoint: "#{configured_base_url}/oauth/token",
+ registration_endpoint: "#{configured_base_url}/register",
+ response_types_supported: [ "code" ],
+ grant_types_supported: [ "authorization_code" ],
+ code_challenge_methods_supported: [ "S256" ],
+ scopes_supported: [ "read_write" ]
+ }
+ end
+end
diff --git a/app/controllers/oauth_registration_controller.rb b/app/controllers/oauth_registration_controller.rb
new file mode 100644
index 0000000000..fb0d8e2c3c
--- /dev/null
+++ b/app/controllers/oauth_registration_controller.rb
@@ -0,0 +1,64 @@
+class OauthRegistrationController < ApplicationController
+ skip_authentication
+ skip_before_action :verify_authenticity_token
+ skip_before_action :require_onboarding_and_upgrade, raise: false
+ skip_before_action :set_default_chat, raise: false
+ skip_before_action :detect_os, raise: false
+
+ rescue_from ActionDispatch::Http::Parameters::ParseError do
+ render json: {
+ error: "invalid_client_metadata",
+ error_description: "Invalid JSON"
+ }, status: :bad_request
+ end
+
+ def create
+ body = JSON.parse(request.raw_post)
+
+ redirect_uris = body["redirect_uris"]
+ if redirect_uris.blank?
+ render json: {
+ error: "invalid_client_metadata",
+ error_description: "redirect_uris is required"
+ }, status: :bad_request
+ return
+ end
+
+ redirect_uris = Array(redirect_uris).map { |u| u.to_s.strip }.reject(&:blank?)
+ if redirect_uris.empty?
+ render json: {
+ error: "invalid_client_metadata",
+ error_description: "redirect_uris is required"
+ }, status: :bad_request
+ return
+ end
+
+ client_name = body["client_name"].presence || "MCP Client"
+
+ app = Doorkeeper::Application.new(
+ name: client_name,
+ redirect_uri: redirect_uris.join("\n"),
+ confidential: false
+ )
+
+ if app.save
+ render json: {
+ client_id: app.uid,
+ client_name: app.name,
+ redirect_uris: app.redirect_uri.split("\n"),
+ grant_types: [ "authorization_code" ],
+ token_endpoint_auth_method: "none"
+ }, status: :created
+ else
+ render json: {
+ error: "invalid_client_metadata",
+ error_description: app.errors.full_messages.join(", ")
+ }, status: :bad_request
+ end
+ rescue JSON::ParserError
+ render json: {
+ error: "invalid_client_metadata",
+ error_description: "Invalid JSON"
+ }, status: :bad_request
+ end
+end
diff --git a/app/controllers/settings/mcp_controller.rb b/app/controllers/settings/mcp_controller.rb
new file mode 100644
index 0000000000..3d0305a77b
--- /dev/null
+++ b/app/controllers/settings/mcp_controller.rb
@@ -0,0 +1,26 @@
+class Settings::McpController < ApplicationController
+ include OauthBase
+ layout "settings"
+
+ def show
+ @breadcrumbs = [
+ [ t("breadcrumbs.home"), root_path ],
+ [ t("breadcrumbs.mcp"), nil ]
+ ]
+ @mcp_url = "#{configured_base_url}/mcp"
+ @connected_tokens = Doorkeeper::AccessToken
+ .where(resource_owner_id: Current.user.id, revoked_at: nil, mobile_device_id: nil)
+ .includes(:application)
+ .order(created_at: :desc)
+ .to_a
+ end
+
+ def revoke
+ token = Doorkeeper::AccessToken.find_by( # pipelock:ignore
+ id: params[:token_id],
+ resource_owner_id: Current.user.id
+ )
+ token&.revoke
+ redirect_to settings_mcp_path, notice: t(".revoked")
+ end
+end
diff --git a/app/views/doorkeeper/authorizations/new.html.erb b/app/views/doorkeeper/authorizations/new.html.erb
index e228dcae82..fd32383145 100644
--- a/app/views/doorkeeper/authorizations/new.html.erb
+++ b/app/views/doorkeeper/authorizations/new.html.erb
@@ -24,7 +24,7 @@
<% end %>
<div class="space-y-3">
- <% turbo_disabled = params[:redirect_uri]&.start_with?("sureapp://") || params[:display] == "mobile" %>
+ <% turbo_disabled = params[:redirect_uri]&.start_with?("sureapp://") || params[:display] == "mobile" || !params[:redirect_uri]&.start_with?(root_url) %>
<%= form_tag oauth_authorization_path, method: :post, class: "w-full", data: { turbo: !turbo_disabled } do %>
<%= hidden_field_tag :client_id, @pre_auth.client.uid, id: nil %>
<%= hidden_field_tag :redirect_uri, @pre_auth.redirect_uri, id: nil %>
diff --git a/app/views/settings/_settings_nav.html.erb b/app/views/settings/_settings_nav.html.erb
index 71cf9ff424..b65101ead9 100644
--- a/app/views/settings/_settings_nav.html.erb
+++ b/app/views/settings/_settings_nav.html.erb
@@ -30,6 +30,7 @@ nav_sections = [
{ label: t(".ai_prompts_label"), path: settings_ai_prompts_path, icon: "bot" },
{ label: t(".llm_usage_label"), path: settings_llm_usage_path, icon: "activity" },
{ label: t(".api_keys_label"), path: settings_api_key_path, icon: "key" },
+ { label: t(".mcp_label"), path: settings_mcp_path, icon: "plug" },
{ label: t(".debug_label", default: "Debug"), path: settings_debug_path, icon: "bug", if: Current.user&.super_admin? },
{ label: t(".self_hosting_label"), path: settings_hosting_path, icon: "database", if: self_hosted? },
{ label: t(".imports_label"), path: imports_path, icon: "download" },
diff --git a/app/views/settings/mcp/show.html.erb b/app/views/settings/mcp/show.html.erb
new file mode 100644
index 0000000000..7e4160d21b
--- /dev/null
+++ b/app/views/settings/mcp/show.html.erb
@@ -0,0 +1,79 @@
+<%= content_for :page_title, t(".page_title") %>
+
+<div class="space-y-4">
+ <div class="bg-container rounded-xl shadow-border-xs p-4">
+ <div class="space-y-4">
+ <div class="space-y-1">
+ <h3 class="text-sm font-medium text-primary"><%= t(".connect_title") %></h3>
+ <p class="text-sm text-secondary"><%= t(".connect_subtitle") %></p>
+ </div>
+
+ <div class="bg-surface-inset rounded-lg p-3" data-controller="clipboard">
+ <div class="flex items-center justify-between gap-3">
+ <code class="font-mono text-sm text-primary break-all" data-clipboard-target="source"><%= @mcp_url %></code>
+ <%= render DS::Button.new(
+ text: t(".copy_url"),
+ variant: :ghost,
+ icon: "copy",
+ size: :sm,
+ data: { action: "clipboard#copy" }
+ ) %>
+ </div>
+ </div>
+
+ <div class="space-y-2">
+ <h4 class="text-sm font-medium text-primary"><%= t(".how_to_connect_title") %></h4>
+ <ol class="space-y-2 text-sm text-secondary">
+ <li class="flex items-start gap-2">
+ <span class="flex-shrink-0 w-5 h-5 rounded-full bg-surface-inset text-primary text-xs font-medium flex items-center justify-center mt-0.5">1</span>
+ <span><%= t(".step_1") %></span>
+ </li>
+ <li class="flex items-start gap-2">
+ <span class="flex-shrink-0 w-5 h-5 rounded-full bg-surface-inset text-primary text-xs font-medium flex items-center justify-center mt-0.5">2</span>
+ <span><%= t(".step_2") %></span>
+ </li>
+ <li class="flex items-start gap-2">
+ <span class="flex-shrink-0 w-5 h-5 rounded-full bg-surface-inset text-primary text-xs font-medium flex items-center justify-center mt-0.5">3</span>
+ <span><%= t(".step_3") %></span>
+ </li>
+ <li class="flex items-start gap-2">
+ <span class="flex-shrink-0 w-5 h-5 rounded-full bg-surface-inset text-primary text-xs font-medium flex items-center justify-center mt-0.5">4</span>
+ <span><%= t(".step_4") %></span>
+ </li>
+ </ol>
+ </div>
+ </div>
+ </div>
+
+ <% if @connected_tokens.any? %>
+ <div class="bg-container rounded-xl shadow-border-xs p-4">
+ <div class="space-y-3">
+ <div class="space-y-1">
+ <h3 class="text-sm font-medium text-primary"><%= t(".connected_title") %></h3>
+ <p class="text-sm text-secondary"><%= t(".connected_subtitle") %></p>
+ </div>
+ <ul class="space-y-2">
+ <% @connected_tokens.each do |token| %>
+ <li class="flex items-center justify-between gap-3 p-3 bg-surface-inset rounded-lg">
+ <div class="flex items-center gap-3">
+ <%= render DS::FilledIcon.new(icon: "plug", size: "md", rounded: true) %>
+ <div class="text-sm space-y-0.5">
+ <p class="font-medium text-primary"><%= token.application&.name || t(".unknown_client") %></p>
+ <p class="text-secondary"><%= t(".connected_ago", time: time_ago_in_words(token.created_at)) %></p>
+ </div>
+ </div>
+ <%= render DS::Button.new(
+ text: t(".revoke"),
+ href: revoke_token_settings_mcp_path(token_id: token.id),
+ method: :delete,
+ variant: :ghost,
+ size: :sm,
+ data: { turbo_confirm: t(".revoke_confirm") }
+ ) %>
+ </li>
+ <% end %>
+ </ul>
+ </div>
+ </div>
+ <% end %>
+</div>
diff --git a/config/initializers/rack_attack.rb b/config/initializers/rack_attack.rb
index 8918e6f769..318c411e20 100644
--- a/config/initializers/rack_attack.rb
+++ b/config/initializers/rack_attack.rb
@@ -10,6 +10,10 @@ class Rack::Attack
request.ip if request.path == "/oauth/token"
end
+ throttle("oauth/register", limit: 10, period: 1.minute) do |request|
+ request.ip if request.post? && request.path == "/register"
+ end
+
# Throttle unauthenticated WebAuthn MFA ceremonies similarly to sign-in
# endpoints; registration remains behind normal application authentication.
throttle("mfa/webauthn", limit: 10, period: 1.minute) do |request|
@@ -33,7 +37,7 @@ class Rack::Attack
# Extract access token from Authorization header
auth_header = request.get_header("HTTP_AUTHORIZATION")
if auth_header&.start_with?("Bearer ")
- token = auth_header.split(" ").last
+ token = auth_header.delete_prefix("Bearer ").strip # pipelock:ignore
"api_token:#{Digest::SHA256.hexdigest(token)}"
else
# Fall back to IP-based limiting for unauthenticated requests
diff --git a/config/locales/breadcrumbs/en.yml b/config/locales/breadcrumbs/en.yml
index c6f1ba1d84..641c505dcf 100644
--- a/config/locales/breadcrumbs/en.yml
+++ b/config/locales/breadcrumbs/en.yml
@@ -46,6 +46,7 @@ en:
llm_usages: LLM Usage
loans: Loans
lunchflow_items: Lunch Flow
+ mcp: MCP Server
merchants: Merchants
mercury_items: Mercury
messages: Messages
diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.yml
index 4e82fee8ed..9a5802d7c2 100644
--- a/config/locales/views/settings/en.yml
+++ b/config/locales/views/settings/en.yml
@@ -230,6 +230,25 @@ en:
sso_confirm_body: Are you sure you want to disconnect your %{provider} account? You can reconnect it later by signing in with that provider again.
sso_confirm_button: Disconnect
sso_warning_message: This is your only login method. You should set a password in your security settings before disconnecting, otherwise you may be locked out of your account.
+ mcp:
+ show:
+ page_title: MCP Server
+ connect_title: Connect an AI assistant
+ connect_subtitle: Paste this URL into Claude.ai (or any MCP-compatible client) to connect it to your Sure account.
+ copy_url: Copy
+ how_to_connect_title: How to connect Claude
+ step_1: "Open Claude.ai and go to Settings → Integrations."
+ step_2: Click "Add integration" and paste the MCP server URL above.
+ step_3: Click Connect — you'll be redirected to Sure to sign in and authorize access.
+ step_4: Once authorized, Claude can read your accounts, transactions, and balance data.
+ connected_title: Connected clients
+ connected_subtitle: These apps currently have access to your Sure data. Revoke any you no longer use.
+ unknown_client: Unknown client
+ connected_ago: "Connected %{time} ago"
+ revoke: Revoke
+ revoke_confirm: Revoke access for this client?
+ revoke:
+ revoked: Connection revoked.
settings_nav:
accounts_label: Accounts
advanced_section_title: Advanced
@@ -251,6 +270,7 @@ en:
profile_label: Profile Info
recurring_transactions_label: Recurring
rules_label: Rules
+ mcp_label: MCP
security_label: Security
self_hosting_label: Self-Hosting
sso_providers_label: SSO Providers
diff --git a/config/routes.rb b/config/routes.rb
index 21a608e15d..69a096c44b 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -160,6 +160,9 @@ Rails.application.routes.draw do
post :new_connection
end
end
+ get ".well-known/oauth-protected-resource", to: "oauth_metadata#protected_resource"
+ get ".well-known/oauth-authorization-server", to: "oauth_metadata#authorization_server"
+ post "register", to: "oauth_registration#create"
use_doorkeeper
# MFA routes
resource :mfa, controller: "mfa", only: [ :new, :create ] do
@@ -250,6 +253,9 @@ Rails.application.routes.draw do
end
resources :sso_identities, only: :destroy
resource :api_key, only: [ :show, :new, :create, :destroy ]
+ resource :mcp, controller: "mcp", only: :show do
+ delete "tokens/:token_id", to: "mcp#revoke", as: :revoke_token
+ end
resource :ai_prompts, only: :show
resource :llm_usage, only: :show
resource :guides, only: :show
diff --git a/test/controllers/mcp_controller_test.rb b/test/controllers/mcp_controller_test.rb
index 2b23791bea..b614407bc8 100644
--- a/test/controllers/mcp_controller_test.rb
+++ b/test/controllers/mcp_controller_test.rb
@@ -9,50 +9,122 @@ class McpControllerTest < ActionDispatch::IntegrationTest
# -- Authentication --
test "returns 401 without authorization header" do
- with_mcp_env do
- post "/mcp", params: jsonrpc_request("initialize").to_json,
- headers: { "Content-Type" => "application/json" }
+ post "/mcp", params: jsonrpc_request("initialize").to_json,
+ headers: { "Content-Type" => "application/json" }
- assert_response :unauthorized
- assert_equal "unauthorized", JSON.parse(response.body)["error"]
- end
+ assert_response :unauthorized
+ assert_equal "unauthorized", JSON.parse(response.body)["error"]
+ assert response.headers["WWW-Authenticate"].present?, "Must include WWW-Authenticate header"
+ assert_includes response.headers["WWW-Authenticate"], "oauth-protected-resource"
end
test "returns 401 with wrong token" do
- with_mcp_env do
- post "/mcp", params: jsonrpc_request("initialize").to_json,
- headers: mcp_headers("wrong-token")
+ post "/mcp", params: jsonrpc_request("initialize").to_json,
+ headers: mcp_headers("wrong-token")
- assert_response :unauthorized
- end
+ assert_response :unauthorized
+ assert response.headers["WWW-Authenticate"].present?
end
- test "returns 503 when MCP_API_TOKEN is not set" do
- with_env_overrides("MCP_USER_EMAIL" => @user.email) do
- post "/mcp", params: jsonrpc_request("initialize").to_json,
- headers: mcp_headers(@token)
+ test "authenticates via Doorkeeper bearer token" do
+ app = Doorkeeper::Application.create!(
+ name: "Test MCP Client #{SecureRandom.hex(4)}",
+ redirect_uri: "https://claude.ai/callback",
+ confidential: false
+ )
+ token = Doorkeeper::AccessToken.create!( # pipelock:ignore
+ application: app,
+ resource_owner_id: @user.id,
+ scopes: "read_write",
+ expires_in: 1.year
+ )
+
+ post "/mcp", params: jsonrpc_request("initialize").to_json,
+ headers: mcp_headers(token.token)
+
+ assert_response :ok
+ result = JSON.parse(response.body)["result"]
+ assert_equal "2025-03-26", result["protocolVersion"]
+ end
- assert_response :service_unavailable
- assert_includes JSON.parse(response.body)["error"], "not configured"
- end
+ test "rejects token with read-only scope" do
+ app = Doorkeeper::Application.create!(
+ name: "Test MCP Client #{SecureRandom.hex(4)}",
+ redirect_uri: "https://claude.ai/callback",
+ confidential: false
+ )
+ token = Doorkeeper::AccessToken.create!( # pipelock:ignore
+ application: app,
+ resource_owner_id: @user.id,
+ scopes: "read",
+ expires_in: 1.year
+ )
+
+ post "/mcp", params: jsonrpc_request("initialize").to_json,
+ headers: mcp_headers(token.token)
+
+ assert_response :unauthorized
+ end
+
+ test "rejects expired Doorkeeper token" do
+ app = Doorkeeper::Application.create!(
+ name: "Test MCP Client #{SecureRandom.hex(4)}",
+ redirect_uri: "https://claude.ai/callback",
+ confidential: false
+ )
+ token = Doorkeeper::AccessToken.create!( # pipelock:ignore
+ application: app,
+ resource_owner_id: @user.id,
+ scopes: "read_write",
+ expires_in: -1.second # already expired at creation time
+ )
+
+ post "/mcp", params: jsonrpc_request("initialize").to_json,
+ headers: mcp_headers(token.token)
+
+ assert_response :unauthorized
+ end
+
+ test "rejects token for deactivated user" do
+ inactive_user = users(:family_member)
+ inactive_user.update!(active: false)
+ app = Doorkeeper::Application.create!(
+ name: "Test MCP Client #{SecureRandom.hex(4)}",
+ redirect_uri: "https://claude.ai/callback",
+ confidential: false
+ )
+ token = Doorkeeper::AccessToken.create!( # pipelock:ignore
+ application: app,
+ resource_owner_id: inactive_user.id,
+ scopes: "read_write",
+ expires_in: 1.year
+ )
+
+ post "/mcp", params: jsonrpc_request("initialize").to_json,
+ headers: mcp_headers(token.token)
+
+ assert_response :unauthorized
+ ensure
+ inactive_user&.update!(active: true)
end
- test "returns 503 when MCP_USER_EMAIL is not set" do
- with_env_overrides("MCP_API_TOKEN" => @token) do
+ test "env-var token still works as fallback" do
+ with_mcp_env do
post "/mcp", params: jsonrpc_request("initialize").to_json,
headers: mcp_headers(@token)
- assert_response :service_unavailable
- assert_includes JSON.parse(response.body)["error"], "user not configured"
+ assert_response :ok
end
end
- test "returns 503 when MCP_USER_EMAIL does not match any user" do
- with_env_overrides("MCP_API_TOKEN" => @token, "MCP_USER_EMAIL" => "[email protected]") do
+ test "returns 401 and warns when env-var token matches but MCP_USER_EMAIL finds no user" do
+ with_env_overrides("MCP_API_TOKEN" => @token, "MCP_USER_EMAIL" => "[email protected]") do # pipelock:ignore
+ Rails.logger.expects(:warn).with(regexp_matches(/MCP_USER_EMAIL/)).once
+
post "/mcp", params: jsonrpc_request("initialize").to_json,
headers: mcp_headers(@token)
- assert_response :service_unavailable
+ assert_response :unauthorized
end
end
@@ -273,7 +345,7 @@ class McpControllerTest < ActionDispatch::IntegrationTest
private
def with_mcp_env(&block)
- with_env_overrides("MCP_API_TOKEN" => @token, "MCP_USER_EMAIL" => @user.email, &block)
+ with_env_overrides("MCP_API_TOKEN" => @token, "MCP_USER_EMAIL" => @user.email, &block) # pipelock:ignore
end
def mcp_headers(token)
diff --git a/test/controllers/oauth_metadata_controller_test.rb b/test/controllers/oauth_metadata_controller_test.rb
new file mode 100644
index 0000000000..538456095a
--- /dev/null
+++ b/test/controllers/oauth_metadata_controller_test.rb
@@ -0,0 +1,32 @@
+require "test_helper"
+
+class OauthMetadataControllerTest < ActionDispatch::IntegrationTest
+ setup do
+ @base = ENV["APP_URL"].presence&.chomp("/") || "http://www.example.com"
+ end
+
+ test "protected_resource returns RFC 9728 metadata" do
+ get "/.well-known/oauth-protected-resource"
+
+ assert_response :ok
+ assert_equal "application/json", response.content_type.split(";").first
+ json = JSON.parse(response.body)
+ assert_equal @base, json["resource"]
+ assert_equal [ @base ], json["authorization_servers"]
+ end
+
+ test "authorization_server returns RFC 8414 metadata" do
+ get "/.well-known/oauth-authorization-server"
+
+ assert_response :ok
+ json = JSON.parse(response.body)
+ assert_equal @base, json["issuer"]
+ assert_equal "#{@base}/oauth/authorize", json["authorization_endpoint"]
+ assert_equal "#{@base}/oauth/token", json["token_endpoint"]
+ assert_equal "#{@base}/register", json["registration_endpoint"]
+ assert_equal [ "code" ], json["response_types_supported"]
+ assert_equal [ "authorization_code" ], json["grant_types_supported"]
+ assert_equal [ "S256" ], json["code_challenge_methods_supported"]
+ assert_equal [ "read_write" ], json["scopes_supported"]
+ end
+end
diff --git a/test/controllers/oauth_registration_controller_test.rb b/test/controllers/oauth_registration_controller_test.rb
new file mode 100644
index 0000000000..a80c2b1476
--- /dev/null
+++ b/test/controllers/oauth_registration_controller_test.rb
@@ -0,0 +1,71 @@
+require "test_helper"
+
+class OauthRegistrationControllerTest < ActionDispatch::IntegrationTest
+ test "registers a public client and returns client_id" do
+ post "/register",
+ params: {
+ client_name: "Claude",
+ redirect_uris: [ "https://claude.ai/callback" ],
+ grant_types: [ "authorization_code" ],
+ response_types: [ "code" ],
+ token_endpoint_auth_method: "none"
+ }.to_json,
+ headers: { "Content-Type" => "application/json" }
+
+ assert_response :created
+ json = JSON.parse(response.body)
+ assert json["client_id"].present?
+ assert_equal "Claude", json["client_name"]
+ assert_equal [ "https://claude.ai/callback" ], json["redirect_uris"]
+ assert_equal [ "authorization_code" ], json["grant_types"]
+ assert_equal "none", json["token_endpoint_auth_method"]
+ assert_nil json["client_secret"], "Public client must not return a secret"
+
+ app = Doorkeeper::Application.find_by(uid: json["client_id"])
+ assert app.present?, "Application should be persisted"
+ assert_not app.confidential?, "Application must be non-confidential (public client)"
+ end
+
+ test "returns error for invalid JSON body" do
+ post "/register",
+ params: "not json",
+ headers: { "Content-Type" => "application/json" }
+
+ assert_response :bad_request
+ json = JSON.parse(response.body)
+ assert_equal "invalid_client_metadata", json["error"]
+ end
+
+ test "returns error when redirect_uris is missing" do
+ post "/register",
+ params: { client_name: "Claude" }.to_json,
+ headers: { "Content-Type" => "application/json" }
+
+ assert_response :bad_request
+ json = JSON.parse(response.body)
+ assert_equal "invalid_client_metadata", json["error"]
+ end
+
+ test "returns error when redirect_uris contains only blank values" do
+ post "/register",
+ params: { client_name: "Claude", redirect_uris: [ "" ] }.to_json,
+ headers: { "Content-Type" => "application/json" }
+
+ assert_response :bad_request
+ json = JSON.parse(response.body)
+ assert_equal "invalid_client_metadata", json["error"]
+ end
+
+ test "uses fallback name when client_name is absent" do
+ post "/register",
+ params: {
+ redirect_uris: [ "https://claude.ai/callback" ],
+ token_endpoint_auth_method: "none"
+ }.to_json,
+ headers: { "Content-Type" => "application/json" }
+
+ assert_response :created
+ json = JSON.parse(response.body)
+ assert_equal "MCP Client", json["client_name"]
+ end
+end
diff --git a/test/controllers/settings/mcp_controller_test.rb b/test/controllers/settings/mcp_controller_test.rb
new file mode 100644
index 0000000000..ba55c90848
--- /dev/null
+++ b/test/controllers/settings/mcp_controller_test.rb
@@ -0,0 +1,95 @@
+require "test_helper"
+
+class Settings::McpControllerTest < ActionDispatch::IntegrationTest
+ setup do
+ @user = users(:family_admin)
+ sign_in @user
+ end
+
+ test "shows MCP settings page" do
+ get settings_mcp_path
+ assert_response :success
+ end
+
+ test "shows connected tokens" do
+ app = Doorkeeper::Application.create!(
+ name: "Claude",
+ redirect_uri: "https://claude.ai/callback",
+ confidential: false
+ )
+ Doorkeeper::AccessToken.create!(
+ application: app,
+ resource_owner_id: @user.id,
+ scopes: "read",
+ expires_in: 1.year
+ )
+
+ get settings_mcp_path
+ assert_response :success
+ assert_select "li", text: /Claude/
+ end
+
+ test "revokes a token" do
+ app = Doorkeeper::Application.create!(
+ name: "Claude",
+ redirect_uri: "https://claude.ai/callback",
+ confidential: false
+ )
+ token = Doorkeeper::AccessToken.create!( # pipelock:ignore
+ application: app,
+ resource_owner_id: @user.id,
+ scopes: "read",
+ expires_in: 1.year
+ )
+
+ delete revoke_token_settings_mcp_path(token_id: token.id)
+
+ assert_redirected_to settings_mcp_path
+ assert token.reload.revoked_at.present?
+ end
+
+ test "does not show mobile device tokens" do
+ mobile_device = MobileDevice.create!(
+ user: @user,
+ device_id: "test-device-#{SecureRandom.hex(4)}",
+ device_name: "Test Phone",
+ device_type: "ios"
+ )
+ app = Doorkeeper::Application.create!(
+ name: "Sure Mobile",
+ redirect_uri: "sureapp://oauth/callback",
+ confidential: false
+ )
+ Doorkeeper::AccessToken.create!(
+ application: app,
+ resource_owner_id: @user.id,
+ mobile_device_id: mobile_device.id,
+ scopes: "read",
+ expires_in: 1.year
+ )
+
+ get settings_mcp_path
+ assert_response :success
+ assert_select "li", text: /Sure Mobile/, count: 0
+ end
+
+ test "cannot revoke another user's token" do
+ other_user = users(:family_member)
+ app = Doorkeeper::Application.create!(
+ name: "Claude",
+ redirect_uri: "https://claude.ai/callback",
+ confidential: false
+ )
+ token = Doorkeeper::AccessToken.create!( # pipelock:ignore
+ application: app,
+ resource_owner_id: other_user.id,
+ scopes: "read",
+ expires_in: 1.year
+ )
+
+ delete revoke_token_settings_mcp_path(token_id: token.id)
+
+ assert_redirected_to settings_mcp_path
+ assert_nil token.reload.revoked_at
+ end
+end