mirror of
https://github.com/we-promise/sure.git
synced 2026-09-03 22:01:16 +00:00
* feat(auth): sign in with a passkey, without a password Passkeys could only ever replace the TOTP code: registration required 2FA to already be on, and the WebAuthn ceremony was reachable only after User.authenticate_by had succeeded. A registered passkey can now complete sign-in on its own, from the login page. The ceremony requests userVerification: "required", so the authenticator has to confirm the person as well as the device. That makes a lone passkey two independent factors, the same bar as the password plus TOTP flow it replaces, which is why this path deliberately skips the TOTP step. A credential that can only prove presence is rejected here and still works as a second factor. Sign-in is usernameless: no email is submitted, because the browser returns the account handle with the assertion. Nothing on this path can be probed to learn whether an account exists. Registration now asks for a discoverable credential with residentKey: "preferred" so the key is offered by the picker, while authenticators without a free resident-key slot still register as a second factor. Where conditional mediation is available, saved passkeys appear in the email field's autofill menu; everywhere else the button covers it. The automatic challenge request that conditional mediation makes on every page load gets its own looser Rack::Attack budget, so ordinary page views can no longer exhaust the limit that protects the MFA endpoints. Set AUTH_PASSKEY_LOGIN_ENABLED=false to keep passkeys as a second factor only. Passkey sign-in follows the same policy as local login, so it stays closed to regular users when AUTH_LOCAL_LOGIN_ENABLED is false. * refactor(auth): group the passkey button with the other sign-in methods It sat directly under the password fields, so the forgot-password link split it from the identical SSO buttons. It is an alternative to the credential form rather than part of it. * fix(auth): close the passkey challenge races and document the upgrade Three review passes converged on the conditional-mediation flow. The AbortController was created after `isConditionalMediationAvailable()` resolved, so a button click or a Turbo disconnect landing in that window found nothing to abort: the conditional task carried on, re-minted the challenge, and the assertion the user was about to produce verified against a challenge the server had already replaced. It is created before the first await now, and held in a local, because `abortConditionalMediation()` nulls the field. Checking that one signal after each await covers both triggers, so no separate connected flag is needed. The same symptom had a second cause nobody flagged: `authenticate()` was not re-entrant. A double-click minted a fresh challenge under an open authenticator prompt and rejected a perfectly valid passkey, with no race window at all — and it was live on the MFA step-up too, which shares the method. The conditional catch was silent for every failure, including a rejected assertion the user had deliberately chosen from the autofill menu. Splitting the try draws the line where it belongs: silence before the user has been asked anything, feedback once they have picked a passkey. Filtering on `error.name` cannot draw it, since `fetchOptions` and `verifyCredential` both raise a plain Error. Also documents the upgrade: passwordless is on by default and applies to already-registered credentials, so a passkey added purely as a second factor can now sign its owner in alone. Nothing in the schema marks a credential discoverable — the authenticator decides — and the opt-out is instance-wide. The invitation test is a guard, not coverage for this change. The pending token lives in the Rack session and `complete_sign_in` reads it right after creating the session, so a `reset_session` dropped in between strands the invitee in their own family, silently and with every existing test still green. * fix(auth): cancel the in-flight conditional options request Aborting the conditional flow did not cancel its options request, because `fetchOptions` never received the signal. A click landing while that POST was in flight left it to finish, and its response could apply last. The challenge rides in the session cookie, so "the server wrote it" only counts if the Set-Cookie reaches the browser. Threading the signal means an aborted request's response is discarded, which closes the window without needing the server to hold two challenges open. Also drops the absolute claim about which existing credentials gain passwordless sign-in. `residentKey: "preferred"` is a request an authenticator may decline, and nothing records what it decided, so the honest statement is that password managers and platform authenticators generally store discoverable credentials rather than always.
111 lines
4.0 KiB
Ruby
111 lines
4.0 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 ceremonies similarly to sign-in
|
|
# endpoints; registration remains behind normal application authentication.
|
|
# Covers both the MFA step-up and passwordless passkey sign-in.
|
|
throttle("mfa/webauthn", limit: 10, period: 1.minute) do |request|
|
|
if request.post? && request.path.in?(%w[
|
|
/mfa/webauthn_options
|
|
/mfa/verify_webauthn
|
|
/sessions/passkey
|
|
])
|
|
request.ip
|
|
end
|
|
end
|
|
|
|
# The passwordless challenge endpoint gets its own, looser budget: browsers
|
|
# that support conditional mediation call it automatically on every login
|
|
# page load, so sharing the limit above would let ordinary page views lock a
|
|
# shared NAT out of MFA. Minting a challenge touches no credential and
|
|
# reveals nothing, and the assertion it produces is still verified under the
|
|
# stricter limit.
|
|
throttle("passkey/options", limit: 30, period: 1.minute) do |request|
|
|
request.ip if request.post? && request.path == "/sessions/passkey_options"
|
|
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
|
|
|
|
# The background jobs console lives under /settings (so its polling GET
|
|
# isn't throttled), but its mutation is destructive and super-admin only —
|
|
# rate limit it independently.
|
|
throttle("background_jobs_console/ip", limit: 30, period: 1.minute) do |request|
|
|
request.ip if request.post? && request.path == "/settings/background_jobs/cancel"
|
|
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
|