Repository navigation
Add 2FA interface for extension gems to hook into - #5843
santiagorodriguez96 wants to merge 14 commits into
Conversation
| # POST /users/two_factor | ||
| # All methods POST here. Warden picks the right strategy via valid?. | ||
| def create | ||
| self.resource = warden.authenticate!(auth_options) |
There was a problem hiding this comment.
Main point of this review. authenticate! here runs every strategy of the scope, so a first-factor strategy, like a passkey one, can take the 2FA request. In cedarcode/devise-webauthn#164, a pending passkey sign-in made the passkey strategy consume its challenge and show a passkey error on the 2FA page. Could create run only the 2FA strategies?
self.resource = warden.authenticate!(*two_factor_strategies, auth_options)
def two_factor_strategies
Devise.two_factor_method_configs.values_at(*resource_class.two_factor_modules).filter_map { |config| config[:strategy] }
end| private | ||
|
|
||
| def initiate_two_factor_authentication!(resource) | ||
| session["devise.two_factor.resource_id"] = resource.id |
There was a problem hiding this comment.
The pending key has no scope. With 2FA on two scopes, a password sign-in as Admin id 5 leaves resource_id = 5, and the users' 2FA step then loads User id 5. That signs in User 5 with only its second factor. Could the key include the scope, as warden.user.#{scope}.key does?
There was a problem hiding this comment.
Fixed as part of 365815c ✅
Now we store the two factor token in the session associated to a key that depends on the scope 🙂
| session["devise.two_factor.resource_id"] = resource.id | ||
| session["devise.two_factor.remember_me"] = remember_me? | ||
| default_method = resource.enabled_two_factors.first | ||
| redirect!(new_two_factor_challenge_path(scope, default_method)) |
There was a problem hiding this comment.
API-only apps have no session, and a JSON client cannot follow this redirect. devise-webauthn returns a 401 JSON with a signed two_factor_token and reads it back from the request body when skip_session_storage includes :params_auth. Could the pending state sit behind an object apps can replace? PasswordsController#update has the same issue.
There was a problem hiding this comment.
Hmmm I looked at how Devise handles this today... rememberable only reads a signed cookie, and timeoutable only uses the Warden session, for instance.
Overall, I think that for apps without a session, the README suggests http_authenticatable and leaves token auth to extensions. Having said that, I think we are breaking HTTP Basic auth with the current approach. As it goes through DatabaseAuthenticatable too, a user with 2FA enabled who signs in with HTTP Basic gets redirected to a challenge page they can never complete, and they are locked out. I'll take a look at this and fix it on this PR.
|
|
||
| def authenticate! | ||
| resource = find_pending_resource | ||
| return fail!(:two_factor_session_expired) unless resource |
There was a problem hiding this comment.
Nothing expires the pending sign-in, so it stays valid until the session ends, even after a password change. devise-webauthn uses a token that expires after 5 minutes. Could this store a timestamp and the authenticatable_salt, so it expires and a password change cancels it?
There was a problem hiding this comment.
Good call!
Fixed in 365815c by using Rails message verifier ✅
| if to.respond_to?(:two_factor_methods) && to.two_factor_methods | ||
| keys = keys + Array(to.two_factor_methods) | ||
| end | ||
| STRATEGIES.values_at(*keys).compact.uniq.reverse |
There was a problem hiding this comment.
Same root as the comment on create. Because of reverse, the 2FA strategies run first, also on sessions#create. An extension that keeps the base valid? would fail! there and block password sign-in while a 2FA is pending. If create names its strategies, the strategies change here is not needed.
|
|
||
| def auth_options | ||
| default_method = @authenticating_resource.enabled_two_factors.first | ||
| { scope: resource_name, recall: "#{controller_path}#new_#{default_method}" } |
There was a problem hiding this comment.
recall always points to the default method. A user who switches to their other method and enters a wrong code lands on the default method's page. Could the form post the method, checked against enabled_two_factors?
There was a problem hiding this comment.
Actually, I intentionally did it like this in order to keep it simple for now. I believe we can iterate on this on a follow up PR to tackle this if we want. What do you think?
Motivation
Closes #5842.
How it works
The application opts in by adding
:two_factor_authenticatableto the model and listing the methods it wants to enable:Extension gems register themselves via a single API:
register_two_factor_methodadds the strategy to Devise'sSTRATEGIESmap and stores the model concern path in a registry. When the user model is loaded,two_factor_methods=looks each method up in that registry and includes the corresponding model concern – so each extension brings its own model module without needing to be a full Devise module itself.Sign in flow
DatabaseAuthenticatablevalidates it as before.remember_mein the session and redirects to the default method's challenge action – instead of callingsuccess!.Devise::TwoFactorController. Devise auto-generates anew_<method>action per registered method, which renders the method's challenge view.createaction, and Warden picks the right strategy via each strategy'svalid?. The baseDevise::Strategies::TwoFactorthen restoresremember_me, cleans up the session, and signs the user in.fail!and Warden recalls back to the challenge action.PasswordsController#updateis also intercepted: when a user with 2FA enabled completes a password reset, they're redirected to the 2FA challenge instead of being signed in directly.Generic URL helpers (
new_two_factor_challenge_path(scope, method),two_factor_path(scope)) and atwo_factor_method_linksview helper round out the public surface so extensions don't need to share a layout or hardcode route names – they just render their own challenge view and call the helper to render switch links to the user's other enabled methods.Conventions
For the pieces above to wire up automatically, extensions follow a small set of naming conventions keyed off the short name passed to
register_two_factor_method(e.g.:webauthn):<method>_two_factor_enabled?– instance method on the model concern. Returnstruewhen this user has the method configured (e.g.webauthn_two_factor_enabled?returns true when the user has at least one registered credential). Devise uses this to decide whether a user has 2FA on at all, and which methods are currently available for a given user.new_<method>– controller action. Auto-generated by Devise as an empty action that rendersnew_<method>.html.erb. Extensions can override it (see "Customizing the challenge action" below). Aset_authenticating_resourcebefore_actionexposes the resource being challenged as@authenticating_resourcefor use in challenge views and custom actions.app/views/devise/two_factor/new_<method>.html.erb– challenge view, shipped by the extension gem and resolved through Rails engine view lookup (apps can override by placing a file at the same path).app/views/devise/two_factor/_<method>_link.html.erb– switch-link partial, rendered by thetwo_factor_method_linkshelper when a user has multiple methods enabled so they can jump to an alternate factor from any challenge page.Advanced: customizing the challenge action
Simple methods (e.g. OTP code entry) work out of the box with the auto-generated
new_<method>action – no extra wiring needed. Methods that require setup logic on every render (e.g. WebAuthn generating a fresh challenge nonce and stashing it in the session) can inject a custom action via anActiveSupport.on_loadhook:The auto-generated action is only defined when the extension hasn't already provided one, so the injected method takes precedence.
Validating the interface
In order to test this, I adapted two real 2FA gems on top of this PR —
devise-webauthnanddevise-otp— and wired them up together in our demo app fordevise-webauthn, so that a single application offers users a choice between WebAuthn and TOTP.Both gems plug into the new interface via
Devise.register_two_factor_methodwithout needing to touchDevise's password authentication logic, and the demo app shows them coexisting – the user can pick either factor at the challenge step using the links generated by thetwo_factor_method_linkshelper.What's intentionally out of scope
after_two_factor_verification)Lockableis untouched, and failed 2FA attempts don't incrementfailed_attempts. Rate limiting for 2FA is better handled at the application or middleware level.I hope this lands as a solid foundation that we can build these features on top of.
A note on the scope of this PR
I'm aware this PR is on the ambitious side for a single change but fell into the "why does every 2FA gem reinvent this?" rabbit hole while building
devise-webauthn, and had a lot of fun working through what a shared interface might look like – so here we are. Happy to split into smaller PRs if reviewers would prefer that!A note on AI tooling
Claude Code was used to generate parts of the implementation. I was deeply involved in the design throughout – every architectural decision is something I worked through and chose deliberately. I've also reviewed and edited the generated code before submitting this PR.