Files
sure/config/initializers/rack_attack.rb
Will Wilson 2075c8c41c feat(mcp): OAuth 2.1 auth for MCP — connect Claude.ai with your Sure login (#2234)
* feat(mcp): add OAuth well-known discovery endpoints (RFC 8414 + RFC 9728)

Serves /.well-known/oauth-protected-resource (RFC 9728) and
/.well-known/oauth-authorization-server (RFC 8414) so MCP clients
can auto-discover the authorization server. Both endpoints are
unauthenticated and respect APP_URL for reverse-proxy deployments.

* feat(mcp): add dynamic client registration endpoint (RFC 7591)

POST /register creates a public Doorkeeper::Application on demand so
MCP clients (e.g. Claude.ai) can self-register without manual setup.
Validates redirect_uris (including blank entries), falls back to
"MCP Client" name, returns no client_secret (public client, PKCE only).
Rate-limited to 10 registrations/min/IP via Rack::Attack.

* feat(mcp): authenticate via Doorkeeper OAuth2, keep MCP_API_TOKEN as fallback

MCP endpoint now accepts OAuth2 Bearer tokens issued by Doorkeeper.
Falls back to the existing MCP_API_TOKEN env-var flow so self-hosted
deployments are not broken. Requires MCP_OAUTH_ENABLED or MCP_API_TOKEN
to be set — the endpoint returns 503 otherwise.

- OauthBase concern provides APP_URL-aware configured_base_url (trailing
  slash stripped to prevent double-slash URLs)
- Bearer scheme parsed case-insensitively (RFC 7235)
- Only read_write scope accepted — read scope would allow mutating tools
  (CreateGoal, ImportBankStatement), so read-only tokens are rejected
- Deactivated users rejected even with a valid Doorkeeper token
- WWW-Authenticate header on 401 points to RFC 9728 resource metadata
- SHA-256 digest used for constant-time env-var comparison
- Rack::Attack throttle added for POST /register
- Routes wired: /.well-known/*, /register, use_doorkeeper

* fix(mcp): disable Turbo on OAuth consent form for external redirect URIs

Turbo was intercepting the authorization form POST and XHR-fetching
the redirect_uri (e.g. https://claude.ai/api/mcp/auth_callback),
which CORS blocks. Extend the existing turbo_disabled guard to cover
any redirect_uri that doesn't originate from the app itself.

* feat(mcp): add Settings::McpController with connected clients view

- Settings > MCP page (under Advanced) shows the MCP server URL with
  copy button and step-by-step instructions for connecting Claude.ai
- Lists active non-mobile OAuth tokens with app name and revoke action;
  mobile device tokens are excluded to prevent accidental disconnection
- Removes the MCP_OAUTH_ENABLED env-var gate — OAuth auth is always
  available since Doorkeeper handles consent; MCP_API_TOKEN remains
  as a self-hosted fallback

* fix(mcp): remove client_credentials from grant_types_supported metadata

Only authorization_code is supported by the registration endpoint.
Advertising client_credentials was misleading — a client that reads
the metadata and attempts that flow would get an application with the
wrong grant type.
2026-06-11 16:19:58 +02:00

89 lines
2.9 KiB
Ruby

# frozen_string_literal: true
class Rack::Attack
# Enable Rack::Attack only in production and staging (disable in test/development to avoid rate-limit flakiness)
enabled = Rails.env.production? || Rails.env.staging?
self.enabled = enabled
# Throttle requests to the OAuth token endpoint
throttle("oauth/token", limit: 10, period: 1.minute) do |request|
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|
if request.post? && request.path.in?(%w[/mfa/webauthn_options /mfa/verify_webauthn])
request.ip
end
end
# Throttle admin endpoints to prevent brute-force attacks
# More restrictive than general API limits since admin access is sensitive
throttle("admin/ip", limit: 10, period: 1.minute) do |request|
request.ip if request.path.start_with?("/admin/")
end
# Determine limits based on self-hosted mode
self_hosted = Rails.application.config.app_mode.self_hosted?
# Throttle API requests per access token
throttle("api/requests", limit: self_hosted ? 10_000 : 100, period: 1.hour) do |request|
if request.path.start_with?("/api/")
# Extract access token from Authorization header
auth_header = request.get_header("HTTP_AUTHORIZATION")
if auth_header&.start_with?("Bearer ")
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
"api_ip:#{request.ip}"
end
end
end
# More permissive throttling for API requests by IP (for development/testing)
throttle("api/ip", limit: self_hosted ? 20_000 : 200, period: 1.hour) do |request|
request.ip if request.path.start_with?("/api/")
end
# Block requests that appear to be malicious
blocklist("block malicious requests") do |request|
# Block requests with suspicious user agents
suspicious_user_agents = [
/sqlmap/i,
/nmap/i,
/nikto/i,
/masscan/i
]
user_agent = request.user_agent
suspicious_user_agents.any? { |pattern| user_agent =~ pattern } if user_agent
end
# Configure response for throttled requests
self.throttled_responder = lambda do |request|
[
429, # status
{
"Content-Type" => "application/json",
"Retry-After" => "60"
},
[ { error: "Rate limit exceeded. Try again later." }.to_json ]
]
end
# Configure response for blocked requests
self.blocklisted_responder = lambda do |request|
[
403, # status
{ "Content-Type" => "application/json" },
[ { error: "Request blocked." }.to_json ]
]
end
end