standard_id 0.61.0 → 0.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +145 -0
  3. data/README.md +236 -32
  4. data/app/channels/concerns/standard_id/cable_authentication.rb +1 -0
  5. data/app/controllers/concerns/standard_id/api_authentication.rb +30 -0
  6. data/app/controllers/concerns/standard_id/audience_verification.rb +6 -5
  7. data/app/controllers/concerns/standard_id/web_authentication.rb +29 -7
  8. data/app/controllers/standard_id/api/base_controller.rb +10 -5
  9. data/app/controllers/standard_id/api/oauth/base_controller.rb +1 -0
  10. data/app/controllers/standard_id/api/step_up_controller.rb +92 -0
  11. data/app/controllers/standard_id/web/step_up_controller.rb +83 -0
  12. data/app/mailers/standard_id/passwordless_mailer.rb +20 -2
  13. data/app/models/standard_id/client_application.rb +30 -1
  14. data/app/models/standard_id/password_credential.rb +76 -8
  15. data/app/models/standard_id/session.rb +45 -1
  16. data/app/views/standard_id/passwordless_mailer/step_up_email.html.erb +24 -0
  17. data/app/views/standard_id/passwordless_mailer/step_up_email.text.erb +12 -0
  18. data/app/views/standard_id/web/step_up/show.html.erb +65 -0
  19. data/config/brakeman.ignore +4 -0
  20. data/config/locales/en.yml +9 -0
  21. data/config/routes/api.rb +7 -0
  22. data/config/routes/web.rb +6 -0
  23. data/db/migrate/20261123000000_add_authenticated_at_to_standard_id_sessions.rb +15 -0
  24. data/lib/generators/standard_id/install/templates/standard_id_reference.rb +49 -6
  25. data/lib/standard_id/api/token_manager.rb +7 -4
  26. data/lib/standard_id/auth_lineage.rb +39 -8
  27. data/lib/standard_id/config/schema.rb +105 -7
  28. data/lib/standard_id/email_password/authentication.rb +1 -1
  29. data/lib/standard_id/email_password.rb +4 -5
  30. data/lib/standard_id/engine.rb +10 -8
  31. data/lib/standard_id/errors.rb +58 -0
  32. data/lib/standard_id/events/definitions.rb +14 -3
  33. data/lib/standard_id/events/subscribers/passwordless_delivery_subscriber.rb +12 -5
  34. data/lib/standard_id/http_client.rb +6 -13
  35. data/lib/standard_id/jwt_service.rb +31 -2
  36. data/lib/standard_id/keyed_digest.rb +43 -5
  37. data/lib/standard_id/network_wrapper.rb +78 -0
  38. data/lib/standard_id/oauth/audiences.rb +42 -0
  39. data/lib/standard_id/oauth/authorization_code_authorization_flow.rb +1 -1
  40. data/lib/standard_id/oauth/direct_mint_flow.rb +9 -3
  41. data/lib/standard_id/oauth/oauth_session_persistence.rb +24 -9
  42. data/lib/standard_id/oauth/password_flow.rb +4 -10
  43. data/lib/standard_id/oauth/token_grant_flow.rb +31 -4
  44. data/lib/standard_id/password_pepper.rb +88 -0
  45. data/lib/standard_id/passwordless/base_strategy.rb +5 -1
  46. data/lib/standard_id/passwordless/code_handoff.rb +72 -0
  47. data/lib/standard_id/passwordless.rb +25 -0
  48. data/lib/standard_id/step_up.rb +236 -0
  49. data/lib/standard_id/testing/otp_helpers.rb +5 -5
  50. data/lib/standard_id/testing/request_helpers.rb +8 -3
  51. data/lib/standard_id/token_minter.rb +9 -4
  52. data/lib/standard_id/version.rb +1 -1
  53. data/lib/standard_id/web/session_manager.rb +9 -2
  54. data/lib/standard_id.rb +4 -0
  55. metadata +12 -1
@@ -23,6 +23,12 @@ module StandardId
23
23
  # session creation (for lifecycle hooks). Returns the PasswordCredential on
24
24
  # success, nil on failure.
25
25
  #
26
+ # - `require_recent_authentication!(within:)` -- Step-up guard (opt-in, see
27
+ # StandardId::StepUp): lets the action run only when the current session
28
+ # proved the account's identity within `within` (default
29
+ # c.step_up.max_age), else redirects to the step-up page and returns here
30
+ # after it.
31
+ #
26
32
  # - `session_manager` -- Returns the StandardId::Web::SessionManager instance
27
33
  # for the current request. Useful for direct session operations like
28
34
  # `session_manager.sign_in_account(account)` in passwordless flows.
@@ -79,6 +85,26 @@ module StandardId
79
85
  redirect_to_login
80
86
  end
81
87
 
88
+ # Step-up guard for a sensitive action, as a before_action:
89
+ #
90
+ # before_action -> { require_recent_authentication!(within: 5.minutes) }, only: %i[edit update]
91
+ #
92
+ # Signed out: the same redirect to login as authenticate_account!. Signed
93
+ # in, but the session last proved the account's identity longer ago than
94
+ # +within+ (or never, as for a remember-me session): redirects to
95
+ # c.step_up.url (default "/step_up"), remembering a GET's URL so the
96
+ # step-up comes back to it. Needs c.step_up.enabled; raises
97
+ # StandardId::ConfigurationError otherwise rather than silently passing or
98
+ # refusing.
99
+ def require_recent_authentication!(within: StandardId::StepUp.max_age)
100
+ StandardId::StepUp.ensure_usable!
101
+ return authenticate_account! unless authenticated?
102
+ return if StandardId::StepUp.recent?(current_session, within: within)
103
+
104
+ session[:return_to_after_step_up] = request.url if request.get?
105
+ redirect_with_inertia(StandardId.config.step_up.url.presence || "/step_up")
106
+ end
107
+
82
108
  # Store the current URL to redirect back after authentication
83
109
  def store_location_for_redirect
84
110
  session[:return_to_after_authenticating] = request.url if request.get?
@@ -129,9 +155,9 @@ module StandardId
129
155
  StandardId::PasswordCredential.find_by(login:).tap do |password_credential|
130
156
  authenticated = password_credential&.authenticate(password)
131
157
 
132
- # Perform a dummy bcrypt comparison when the credential doesn't exist
133
- # to prevent user enumeration via response timing differences.
134
- BCrypt::Password.new(dummy_password_digest).is_password?(password) unless password_credential
158
+ # Perform the dummy bcrypt comparisons when the credential doesn't
159
+ # exist to prevent user enumeration via response timing differences.
160
+ StandardId::PasswordPepper.dummy_authenticate(password) unless password_credential
135
161
 
136
162
  unless authenticated
137
163
  StandardId::Events.publish(
@@ -193,10 +219,6 @@ module StandardId
193
219
  @token_manager ||= StandardId::Web::TokenManager.new(request)
194
220
  end
195
221
 
196
- def dummy_password_digest
197
- @dummy_password_digest ||= BCrypt::Password.create("").freeze
198
- end
199
-
200
222
  def authentication_guard
201
223
  @authentication_guard ||= StandardId::Web::AuthenticationGuard.new
202
224
  end
@@ -99,17 +99,22 @@ module StandardId
99
99
  end
100
100
 
101
101
  def handle_oauth_error(error)
102
- # A lib-level rate limit (StandardId::RateLimiter) knows its window;
103
- # say so, as the controller-level limits do.
104
- if error.respond_to?(:retry_after) && error.retry_after.to_i.positive?
105
- response.set_header("Retry-After", error.retry_after.to_i.to_s)
106
- end
102
+ set_retry_after_header(error)
107
103
  render json: {
108
104
  error: error.oauth_error_code,
109
105
  error_description: error.message
110
106
  }, status: error.http_status
111
107
  end
112
108
 
109
+ # A lib-level rate limit (StandardId::RateLimiter) knows its window;
110
+ # say so, as the controller-level limits do. Shared with
111
+ # Api::Oauth::BaseController's own OAuth error handler.
112
+ def set_retry_after_header(error)
113
+ return unless error.respond_to?(:retry_after) && error.retry_after.to_i.positive?
114
+
115
+ response.set_header("Retry-After", error.retry_after.to_i.to_s)
116
+ end
117
+
113
118
  def render_bearer_unauthorized!(error_description: default_invalid_token_message, error_code: "invalid_token")
114
119
  response.set_header(
115
120
  "WWW-Authenticate",
@@ -29,6 +29,7 @@ module StandardId
29
29
  status = exception.respond_to?(:http_status) ? exception.http_status : :bad_request
30
30
  description = exception.message.presence || "An error occurred processing the request"
31
31
 
32
+ set_retry_after_header(exception)
32
33
  render json: {
33
34
  error: error_code.to_s,
34
35
  error_description: description
@@ -0,0 +1,92 @@
1
+ module StandardId
2
+ module Api
3
+ # Step-up for bearer clients (StandardId::StepUp), answering the
4
+ # `insufficient_user_authentication` challenge
5
+ # ApiAuthentication#require_recent_authentication! renders:
6
+ #
7
+ # POST /step_up → a code goes to the account's verified e-mail
8
+ # (or phone); says where, and whether the
9
+ # password is needed too
10
+ # POST /step_up/verify → { code, password } → a fresh access token whose
11
+ # `auth_time` is now; retry the request with it
12
+ #
13
+ # Both need the current access token. The new token keeps that token's
14
+ # client_id, scope and audience, under grant_type "step_up"
15
+ # (oauth.token_lifetimes[:step_up], else the default lifetime). No refresh
16
+ # token is issued: the client keeps its own, and tokens refreshed from it
17
+ # carry the original sign-in's auth_time. For an audience bound to a
18
+ # profile type, set c.step_up.token_profile_resolver when an account may
19
+ # hold several such profiles. Routed only while c.step_up.enabled is true.
20
+ class StepUpController < BaseController
21
+ authenticated_controller
22
+
23
+ rate_limit to: StandardId.config.rate_limits.otp_verify_per_ip,
24
+ within: 15.minutes,
25
+ name: "api-step-up-verify-ip",
26
+ only: :verify,
27
+ store: StandardId::RateLimitHandling::RATE_LIMIT_STORE
28
+
29
+ before_action :verify_access_token!
30
+ # A token whose account config.account_scope no longer finds is no
31
+ # longer anyone's to step up.
32
+ before_action -> { render_bearer_unauthorized! if current_account.nil? }
33
+
34
+ def create
35
+ result = StandardId::StepUp.start(account: current_account, request: request)
36
+ return render_failure(result) unless result.success? || result.error_code == :cooldown
37
+
38
+ render json: {
39
+ channel: result.channel,
40
+ password_required: StandardId::StepUp.password_required?(current_account)
41
+ }, status: :accepted
42
+ end
43
+
44
+ def verify
45
+ result = StandardId::StepUp.verify(
46
+ account: current_account,
47
+ code: string_param(:code),
48
+ password: string_param(:password),
49
+ request: request
50
+ )
51
+ return render_failure(result) unless result.success?
52
+
53
+ minted = StandardId::TokenMinter.mint(
54
+ account: current_account,
55
+ audience: current_session.aud,
56
+ scopes: Array(current_session.scopes).join(" ").presence,
57
+ client_id: current_session.client_id,
58
+ grant_type: "step_up",
59
+ authenticated_at: Time.current,
60
+ profile: token_profile
61
+ )
62
+ render json: {
63
+ access_token: minted.access_token,
64
+ token_type: minted.token_type,
65
+ expires_in: minted.expires_in,
66
+ scope: minted.scope
67
+ }.compact, status: :ok
68
+ end
69
+
70
+ private
71
+
72
+ # c.step_up.token_profile_resolver's choice, for an audience whose
73
+ # account may hold several profiles of the bound type.
74
+ def token_profile
75
+ resolver = StandardId.config.step_up.token_profile_resolver
76
+ return nil unless resolver.respond_to?(:call)
77
+
78
+ resolver.call(account: current_account, claims: current_session.claims.to_h.with_indifferent_access)
79
+ end
80
+
81
+ def string_param(key)
82
+ value = params[key]
83
+ value.is_a?(String) ? value : nil
84
+ end
85
+
86
+ def render_failure(result)
87
+ status = (result.error_code == :rate_limited) ? :too_many_requests : :unprocessable_content
88
+ render json: { error: result.error_code.to_s, error_description: result.error_message }, status: status
89
+ end
90
+ end
91
+ end
92
+ end
@@ -0,0 +1,83 @@
1
+ module StandardId
2
+ module Web
3
+ # The step-up page WebAuthentication#require_recent_authentication! sends a
4
+ # stale session to (StandardId::StepUp):
5
+ #
6
+ # GET /step_up → "send me a code", or the code (+ password) form once sent
7
+ # POST /step_up → issues a code to the account's verified e-mail (or phone)
8
+ # PATCH /step_up → checks it; on success marks the current session as
9
+ # just authenticated and returns to the guarded page
10
+ #
11
+ # Signed-out visitors go to login, as for any authenticated page. Routed
12
+ # only while c.step_up.enabled is true. Inertia apps render
13
+ # "<namespace>/step_up/show" with #step_up_page_props.
14
+ class StepUpController < BaseController
15
+ authenticated_controller
16
+
17
+ include StandardId::InertiaRendering
18
+
19
+ layout "public"
20
+
21
+ rate_limit to: StandardId.config.rate_limits.otp_verify_per_ip,
22
+ within: 15.minutes,
23
+ name: "step-up-verify-ip",
24
+ only: :update,
25
+ store: StandardId::RateLimitHandling::RATE_LIMIT_STORE
26
+
27
+ def show
28
+ render_with_inertia props: step_up_page_props
29
+ end
30
+
31
+ def create
32
+ result = StandardId::StepUp.start(account: current_account, request: request)
33
+
34
+ if result.success? || result.error_code == :cooldown
35
+ session[:step_up_code_sent] = true
36
+ flash[:notice] = result.success? ? "We sent you a code" : "A code was sent moments ago. Check your inbox"
37
+ redirect_with_inertia engine_path(step_up_path), status: :see_other
38
+ else
39
+ flash.now[:alert] = result.error_message
40
+ render_with_inertia action: :show, props: step_up_page_props, status: :unprocessable_content
41
+ end
42
+ end
43
+
44
+ def update
45
+ result = StandardId::StepUp.verify(
46
+ account: current_account,
47
+ code: string_param(:code),
48
+ password: string_param(:password),
49
+ request: request
50
+ )
51
+
52
+ unless result.success?
53
+ flash.now[:alert] = result.error_message
54
+ render_with_inertia action: :show, props: step_up_page_props, status: :unprocessable_content
55
+ return
56
+ end
57
+
58
+ StandardId::StepUp.mark!(current_session)
59
+ session.delete(:step_up_code_sent)
60
+ destination = session.delete(:return_to_after_step_up)
61
+ destination = safe_post_signin_default unless safe_destination?(destination)
62
+ redirect_after_authentication destination, notice: "Thanks, you're verified"
63
+ end
64
+
65
+ private
66
+
67
+ # Where the code goes is the account's own verified address, shown so
68
+ # its owner knows where to look.
69
+ def step_up_page_props
70
+ channel, target = StandardId::StepUp.destination_for(current_account)
71
+ {
72
+ flash: { notice: flash[:notice], alert: flash[:alert] }.compact,
73
+ channel: channel,
74
+ target: target,
75
+ code_sent: session[:step_up_code_sent] == true,
76
+ password_required: StandardId::StepUp.password_required?(current_account),
77
+ step_up_path: engine_path(step_up_path)
78
+ }
79
+ end
80
+ helper_method :step_up_page_props
81
+ end
82
+ end
83
+ end
@@ -3,10 +3,13 @@ module StandardId
3
3
  # when `c.passwordless.delivery = :built_in`.
4
4
  #
5
5
  # * #otp_email — the sign-in code (realm "authentication").
6
+ # * #step_up_email — the step-up code (realm `c.step_up.realm`, default
7
+ # "step_up"): an account that is already signed in confirming a sensitive
8
+ # action. It tells the recipient what to do if that wasn't them.
6
9
  # * #verification_email — every other realm: WebEngine verify_email/start
7
10
  # (realm "verification") and `Otp.issue(realm: ...)` for contact
8
- # verification, step-up and the like. It must not tell the recipient the
9
- # code is for signing in.
11
+ # verification and the like. It must not tell the recipient the code is
12
+ # for signing in.
10
13
  #
11
14
  # Copy lives under `standard_id.passwordless_mailer.<action>.*` in
12
15
  # config/locales/en.yml; override any key in the host's locale files, or
@@ -47,6 +50,21 @@ module StandardId
47
50
  )
48
51
  end
49
52
 
53
+ # @param email [String]
54
+ # @param otp_code [String]
55
+ # @param realm [String, nil] the OTP realm, available to overriding templates
56
+ # @param expires_in_minutes [Integer, nil] defaults to passwordless.code_ttl
57
+ def step_up_email
58
+ assign_otp_params
59
+ @realm = params[:realm]
60
+
61
+ mail(
62
+ to: @email,
63
+ from: StandardId.config.passwordless.mailer_from,
64
+ subject: otp_copy(:subject)
65
+ )
66
+ end
67
+
50
68
  # Copy for the current action from
51
69
  # standard_id.passwordless_mailer.<action>.<key>, in I18n.locale. Falls
52
70
  # back to the gem's English copy when the host has no translation for
@@ -214,13 +214,42 @@ module StandardId
214
214
 
215
215
  # Constant-time check of an RFC 7592 registration access token, under the
216
216
  # current secret or any of `config.previous_secret_key_bases`.
217
+ # A token accepted under a previous secret is re-keyed (see
218
+ # #rekey_registration_access_token): these tokens live as long as the
219
+ # client, so without it the old secret could never be dropped.
217
220
  def authenticate_registration_access_token(token)
218
221
  return false unless dynamically_registered? && token.present?
219
222
 
220
- StandardId::KeyedDigest.secure_match?(
223
+ matched = StandardId::KeyedDigest.secure_match?(
221
224
  registration_access_token_digest,
222
225
  StandardId::KeyedDigest.candidates { |secret| self.class.digest_registration_access_token(token.to_s, secret:) }
223
226
  )
227
+ rekey_registration_access_token(token.to_s) if matched
228
+ matched
229
+ end
230
+
231
+ # Rewrites the digest of an accepted registration access token under the
232
+ # current secret when it was stored under a previous one, in one
233
+ # conditional UPDATE (StandardId::KeyedDigest.rekey). No write when it is
234
+ # already current; never raises.
235
+ #
236
+ # @return [Boolean] whether the row was rewritten
237
+ def rekey_registration_access_token(token)
238
+ return false if StandardId::KeyedDigest.previous_secrets.empty?
239
+
240
+ current = self.class.digest_registration_access_token(token)
241
+ return false if registration_access_token_digest == current
242
+
243
+ rekeyed = StandardId::KeyedDigest.rekey(
244
+ StandardId::ClientApplication, id: id,
245
+ from: { registration_access_token_digest: registration_access_token_digest },
246
+ to: { registration_access_token_digest: current }
247
+ )
248
+ if rekeyed
249
+ self.registration_access_token_digest = current
250
+ clear_attribute_changes([:registration_access_token_digest])
251
+ end
252
+ rekeyed
224
253
  end
225
254
 
226
255
  # The RFC 7591 token_endpoint_auth_method a client information response
@@ -37,22 +37,64 @@ module StandardId
37
37
  # has_secure_password's setter, remembering the digest it made so the
38
38
  # commit can tell a new password from a direct write of the digest. An
39
39
  # empty assignment changes nothing, as has_secure_password ignores it.
40
+ # Under c.password.pepper the digest is made from the peppered password
41
+ # (StandardId::PasswordPepper); without one, has_secure_password makes it.
40
42
  def password=(unencrypted_password)
41
- super
43
+ # has_secure_password's own test (nil clears, "" is ignored), so a
44
+ # whitespace-only password is peppered like any other.
45
+ if StandardId::PasswordPepper.current.present? && !unencrypted_password.nil? && !unencrypted_password.empty?
46
+ @password = unencrypted_password
47
+ self.password_digest = self.class.password_digest_for(unencrypted_password)
48
+ else
49
+ super
50
+ end
42
51
  @assigned_password_digest = (password_digest if unencrypted_password.present?)
43
52
  end
44
53
 
54
+ # has_secure_password's check, trying each pepper the digest may have been
55
+ # made under (StandardId::PasswordPepper.candidates): the current one, the
56
+ # previous ones, then none. Remembers which one matched, so
57
+ # #rehash_password can move the digest to the current pepper. With no
58
+ # pepper configured this is has_secure_password's own comparison.
59
+ #
60
+ # has_secure_password's +password_challenge+ validation compares the bare
61
+ # password and does not know about the pepper; check a current password
62
+ # with this method instead.
63
+ #
64
+ # @return [self, false]
65
+ def authenticate_password(unencrypted_password)
66
+ digest = password_digest
67
+ return false if digest.blank?
68
+
69
+ pepper = StandardId::PasswordPepper.matching_pepper(digest, unencrypted_password)
70
+ return false if pepper.nil?
71
+
72
+ @authenticated_pepper = [digest, pepper]
73
+ self
74
+ end
75
+ alias_method :authenticate, :authenticate_password
76
+
45
77
  # The bcrypt cost has_secure_password hashes a new password at, worked out
46
78
  # the way ActiveModel::SecurePassword does.
47
79
  def self.password_cost
48
80
  ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost
49
81
  end
50
82
 
83
+ # A new digest for +password+: bcrypt at .password_cost of the password
84
+ # under the current pepper (the bare password when none is set).
85
+ def self.password_digest_for(password)
86
+ peppered = StandardId::PasswordPepper.apply(password, StandardId::PasswordPepper.current)
87
+ BCrypt::Password.create(peppered, cost: password_cost)
88
+ end
89
+
51
90
  # Re-hashes +password+ when the stored digest was made at a bcrypt cost
52
- # other than .password_cost, so raising BCrypt::Engine.cost reaches
91
+ # other than .password_cost, or under a pepper other than the current one
92
+ # (a previous pepper, or none: see StandardId::PasswordPepper), so raising
93
+ # BCrypt::Engine.cost, or setting or rotating c.password.pepper, reaches
53
94
  # existing passwords as their owners sign in instead of only new ones.
54
95
  # Every password login calls it once +password+ has authenticated; turn it
55
- # off with c.password.rehash_on_login = false.
96
+ # off with c.password.rehash_on_login = false. It is not a password change:
97
+ # CREDENTIAL_PASSWORD_CHANGED is not published and no notice is sent.
56
98
  #
57
99
  # +authenticated_digest+ is the digest +password+ was checked against. The
58
100
  # write is one UPDATE conditional on the row still holding it, so a reset
@@ -70,10 +112,14 @@ module StandardId
70
112
  #
71
113
  # @return [Boolean] whether the digest was replaced
72
114
  def rehash_password(password, authenticated_digest = password_digest)
73
- return false unless StandardId.config.password.rehash_on_login && password_rehash_needed?
115
+ return false unless StandardId.config.password.rehash_on_login
116
+
117
+ pepper_changed = pepper_rehash_needed?(password, authenticated_digest)
118
+ return false if pepper_changed.nil?
119
+ return false unless pepper_changed || password_rehash_needed?
74
120
 
75
121
  previous_cost = BCrypt::Password.new(password_digest).cost
76
- attributes = { password_digest: BCrypt::Password.create(password, cost: self.class.password_cost), updated_at: Time.current }
122
+ attributes = { password_digest: self.class.password_digest_for(password), updated_at: Time.current }
77
123
  # The savepoint keeps a failed UPDATE from aborting the caller's
78
124
  # transaction (PostgreSQL refuses every later statement in it).
79
125
  rehashed = self.class.transaction(requires_new: true) do
@@ -86,7 +132,7 @@ module StandardId
86
132
  # Held until the caller's transaction commits, so a login that rolls
87
133
  # back (a policy refusal inside EmailPassword::Authentication's lock)
88
134
  # reports no rehash.
89
- ActiveRecord.after_all_transactions_commit { publish_password_rehashed(previous_cost) }
135
+ ActiveRecord.after_all_transactions_commit { publish_password_rehashed(previous_cost, pepper_changed) }
90
136
  true
91
137
  rescue StandardError => e
92
138
  report_failure("rehash password credential #{id}", e)
@@ -105,16 +151,38 @@ module StandardId
105
151
  false
106
152
  end
107
153
 
154
+ # Whether +digest+ holds +password+ under a pepper other than the current
155
+ # one: true or false, or nil when +password+ does not match +digest+ at
156
+ # all, which must not be re-hashed. Always false while no pepper is
157
+ # configured, without another bcrypt comparison, so a host without one
158
+ # rehashes exactly as before. Reuses the pepper #authenticate matched for
159
+ # this digest; otherwise works it out again.
160
+ def pepper_rehash_needed?(password, digest)
161
+ return false unless StandardId::PasswordPepper.enabled?
162
+
163
+ pepper = if @authenticated_pepper&.first == digest
164
+ @authenticated_pepper.last
165
+ else
166
+ StandardId::PasswordPepper.matching_pepper(digest, password)
167
+ end
168
+ return nil if pepper.nil?
169
+
170
+ pepper != StandardId::PasswordPepper.current
171
+ rescue BCrypt::Errors::InvalidHash
172
+ nil
173
+ end
174
+
108
175
  # The event carries the account: load the chain (a no-op where the caller
109
176
  # preloaded it) so a subscriber under strict loading can walk it.
110
- def publish_password_rehashed(previous_cost)
177
+ def publish_password_rehashed(previous_cost, pepper_changed = false)
111
178
  ActiveRecord::Associations::Preloader.new(records: [self], associations: { credential: { identifier: :account } }).call
112
179
  StandardId::Events.publish(
113
180
  StandardId::Events::CREDENTIAL_PASSWORD_REHASHED,
114
181
  credential: self,
115
182
  account: account,
116
183
  previous_cost: previous_cost,
117
- cost: self.class.password_cost
184
+ cost: self.class.password_cost,
185
+ pepper_changed: pepper_changed
118
186
  )
119
187
  rescue StandardError => e
120
188
  report_failure("publish CREDENTIAL_PASSWORD_REHASHED for password credential #{id}", e)
@@ -53,8 +53,10 @@ module StandardId
53
53
 
54
54
  session = by_token(token).first
55
55
  return nil if session.nil?
56
+ return nil unless session.authenticate_token(token)
56
57
 
57
- session.authenticate_token(token) ? session : nil
58
+ session.rekey_token(token)
59
+ session
58
60
  end
59
61
 
60
62
  # Keyed digest of an opaque session token — the default scheme.
@@ -110,6 +112,39 @@ module StandardId
110
112
  false
111
113
  end
112
114
 
115
+ # Re-keys a session that authenticated with +token+ under a previous
116
+ # `secret_key_base`: rewrites `lookup_hash`, and an HMAC `token_digest`,
117
+ # under the current secret in one conditional UPDATE (StandardId::KeyedDigest.rekey).
118
+ # Without it an old secret would have to stay in
119
+ # `config.previous_secret_key_bases` for the longest session lifetime.
120
+ #
121
+ # Call it only once +token+ has been accepted for this session. It writes
122
+ # nothing when both values are already current (always so with no
123
+ # previous secrets configured), when +token+ is not the one the stored
124
+ # lookup hash was derived from, or for a BCrypt digest (not keyed), and it
125
+ # never raises.
126
+ #
127
+ # @return [Boolean] whether the row was rewritten
128
+ def rekey_token(token)
129
+ return false if token.blank? || StandardId::KeyedDigest.previous_secrets.empty?
130
+ return false unless self.class.lookup_hashes_for(token).include?(lookup_hash)
131
+
132
+ updates = {}
133
+ current_lookup_hash = self.class.lookup_hash_for(token)
134
+ updates[:lookup_hash] = current_lookup_hash unless lookup_hash == current_lookup_hash
135
+ updates[:token_digest] = self.class.hmac_token_digest(token) if token_digest_under_previous_secret?(token)
136
+ return false if updates.empty?
137
+
138
+ rekeyed = StandardId::KeyedDigest.rekey(
139
+ StandardId::Session, id: id, from: { lookup_hash: lookup_hash, token_digest: token_digest }, to: updates
140
+ )
141
+ if rekeyed
142
+ updates.each { |attribute, value| self[attribute] = value }
143
+ clear_attribute_changes(updates.keys)
144
+ end
145
+ rekeyed
146
+ end
147
+
113
148
  # Counts returned by the bulk-revocation class methods. Callers use these to
114
149
  # emit their own aggregate event (see
115
150
  # StandardId::Api::Oauth::RevocationsController#emit_token_revoked) — the
@@ -278,6 +313,15 @@ module StandardId
278
313
  self.lookup_hash = self.class.lookup_hash_for(token)
279
314
  end
280
315
 
316
+ # An HMAC digest of +token+ that is not the current secret's but verifies
317
+ # under a previous one.
318
+ def token_digest_under_previous_secret?(token)
319
+ return false if token_digest.blank? || token_digest.start_with?("$2")
320
+ return false if token_digest == self.class.hmac_token_digest(token)
321
+
322
+ authenticate_token(token)
323
+ end
324
+
281
325
  # Revoke any still-active refresh tokens before the session row is deleted,
282
326
  # so tokens don't become orphaned but usable.
283
327
  def revoke_active_refresh_tokens
@@ -0,0 +1,24 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <style>
6
+ body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background-color: #f5f5f5; margin: 0; padding: 0; }
7
+ .container { max-width: 480px; margin: 40px auto; background-color: #ffffff; border-radius: 8px; padding: 40px; }
8
+ .code { font-size: 32px; font-weight: bold; letter-spacing: 8px; text-align: center; padding: 20px; background-color: #f0f0f0; border-radius: 6px; margin: 24px 0; font-family: monospace; }
9
+ .footer { margin-top: 32px; font-size: 13px; color: #888888; text-align: center; }
10
+ </style>
11
+ </head>
12
+ <body>
13
+ <div class="container">
14
+ <p><%= otp_copy(:greeting) %></p>
15
+ <p><%= otp_copy(:intro) %></p>
16
+ <div class="code"><%= @otp_code %></div>
17
+ <p><%= otp_copy(:expiry, count: @expires_in_minutes) %></p>
18
+ <p><%= otp_copy(:warning) %></p>
19
+ <div class="footer">
20
+ <p><%= otp_copy(:footer) %></p>
21
+ </div>
22
+ </div>
23
+ </body>
24
+ </html>
@@ -0,0 +1,12 @@
1
+ <%= otp_copy(:greeting) %>
2
+
3
+ <%= otp_copy(:intro) %>
4
+
5
+ <%= @otp_code %>
6
+
7
+ <%= otp_copy(:expiry, count: @expires_in_minutes) %>
8
+
9
+ <%= otp_copy(:warning) %>
10
+
11
+ --
12
+ <%= otp_copy(:footer) %>
@@ -0,0 +1,65 @@
1
+ <%# ERB fallback for non-Inertia rendering. Inertia clients receive the same
2
+ data through step_up_page_props. %>
3
+ <% props = step_up_page_props %>
4
+ <% content_for :title, "Confirm it's you" %>
5
+
6
+ <div class="flex min-h-full flex-col justify-center py-12 sm:px-6 lg:px-8">
7
+ <div class="sm:mx-auto sm:w-full sm:max-w-md">
8
+ <h2 class="mt-6 text-center text-2xl/9 font-bold tracking-tight text-gray-900 dark:text-white">Confirm it's you</h2>
9
+ <p class="mt-2 text-center text-sm text-gray-500 dark:text-gray-400">
10
+ <% if props[:target] %>
11
+ For your security, we need to check it's you before continuing. We'll send a code to
12
+ <span id="step-up-target" class="font-semibold text-gray-900 dark:text-white"><%= props[:target] %></span>.
13
+ <% else %>
14
+ There is no verified e-mail address or phone number on your account to send a code to.
15
+ <% end %>
16
+ </p>
17
+ </div>
18
+
19
+ <div class="mt-10 sm:mx-auto sm:w-full sm:max-w-[480px]">
20
+ <div class="bg-white px-6 py-12 shadow sm:rounded-lg sm:px-12 dark:bg-gray-800/50 dark:shadow-none dark:outline dark:outline-1 dark:-outline-offset-1 dark:outline-white/10">
21
+
22
+ <% if flash[:alert].present? %>
23
+ <div class="mb-4 rounded-md bg-red-50 p-4 text-sm text-red-700 dark:bg-red-900/20 dark:text-red-300"><%= flash[:alert] %></div>
24
+ <% end %>
25
+ <% if flash[:notice].present? %>
26
+ <div class="mb-4 rounded-md bg-green-50 p-4 text-sm text-green-700 dark:bg-green-900/20 dark:text-green-300"><%= flash[:notice] %></div>
27
+ <% end %>
28
+
29
+ <% if props[:target] && props[:code_sent] %>
30
+ <%= form_with url: step_up_path, method: :patch, local: true, html: { id: "step-up-verify-form", class: "space-y-6" } do |form| %>
31
+ <div>
32
+ <%= form.label :code, "Verification code", class: "block text-sm/6 font-medium text-gray-900 dark:text-white" %>
33
+ <div class="mt-2">
34
+ <%= form.text_field :code, required: true, autofocus: true, autocomplete: "one-time-code", inputmode: "numeric", maxlength: otp_code_length, class: "block w-full rounded-md bg-white px-3 py-1.5 text-base text-gray-900 outline outline-1 -outline-offset-1 outline-gray-300 placeholder:text-gray-400 focus:outline focus:outline-2 focus:-outline-offset-2 focus:outline-indigo-600 sm:text-sm/6 dark:bg-white/5 dark:text-white dark:outline-white/10 dark:placeholder:text-gray-500 dark:focus:outline-indigo-500" %>
35
+ </div>
36
+ </div>
37
+
38
+ <% if props[:password_required] %>
39
+ <div>
40
+ <%= form.label :password, "Password", class: "block text-sm/6 font-medium text-gray-900 dark:text-white" %>
41
+ <div class="mt-2">
42
+ <%= form.password_field :password, required: true, autocomplete: "current-password", class: "block w-full rounded-md bg-white px-3 py-1.5 text-base text-gray-900 outline outline-1 -outline-offset-1 outline-gray-300 placeholder:text-gray-400 focus:outline focus:outline-2 focus:-outline-offset-2 focus:outline-indigo-600 sm:text-sm/6 dark:bg-white/5 dark:text-white dark:outline-white/10 dark:placeholder:text-gray-500 dark:focus:outline-indigo-500" %>
43
+ </div>
44
+ </div>
45
+ <% end %>
46
+
47
+ <div>
48
+ <%= form.submit "Confirm", class: "flex w-full justify-center rounded-md bg-indigo-600 px-3 py-1.5 text-sm/6 font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 dark:bg-indigo-500 dark:shadow-none dark:hover:bg-indigo-400 dark:focus-visible:outline-indigo-500" %>
49
+ </div>
50
+ <% end %>
51
+ <% end %>
52
+
53
+ <% if props[:target] %>
54
+ <%= form_with url: step_up_path, method: :post, local: true, html: { id: "step-up-send-form", class: props[:code_sent] ? "mt-6 text-center text-sm/6" : "" } do |send_form| %>
55
+ <% if props[:code_sent] %>
56
+ <span class="text-gray-500 dark:text-gray-400">Didn't get a code?</span>
57
+ <button type="submit" id="step-up-resend-button" class="font-semibold text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-300">Resend code</button>
58
+ <% else %>
59
+ <%= send_form.submit "Send code", id: "step-up-send-button", class: "flex w-full justify-center rounded-md bg-indigo-600 px-3 py-1.5 text-sm/6 font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 dark:bg-indigo-500 dark:shadow-none dark:hover:bg-indigo-400 dark:focus-visible:outline-indigo-500" %>
60
+ <% end %>
61
+ <% end %>
62
+ <% end %>
63
+ </div>
64
+ </div>
65
+ </div>