standard_id 0.60.0 → 0.62.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 (51) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +110 -0
  3. data/README.md +205 -24
  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/social_authentication.rb +5 -4
  7. data/app/controllers/concerns/standard_id/web_authentication.rb +29 -7
  8. data/app/controllers/standard_id/api/step_up_controller.rb +92 -0
  9. data/app/controllers/standard_id/web/step_up_controller.rb +83 -0
  10. data/app/forms/standard_id/web/reset_password_confirm_form.rb +1 -1
  11. data/app/models/standard_id/client_application.rb +30 -1
  12. data/app/models/standard_id/password_credential.rb +77 -9
  13. data/app/models/standard_id/session.rb +45 -1
  14. data/app/views/standard_id/web/step_up/show.html.erb +65 -0
  15. data/config/brakeman.ignore +4 -0
  16. data/config/routes/api.rb +7 -0
  17. data/config/routes/web.rb +6 -0
  18. data/db/migrate/20261123000000_add_authenticated_at_to_standard_id_sessions.rb +15 -0
  19. data/lib/generators/standard_id/install/templates/standard_id_reference.rb +50 -5
  20. data/lib/standard_id/api/token_manager.rb +3 -0
  21. data/lib/standard_id/auth_lineage.rb +39 -8
  22. data/lib/standard_id/config/callable_validator.rb +26 -3
  23. data/lib/standard_id/config/schema.rb +105 -5
  24. data/lib/standard_id/email_password/authentication.rb +1 -1
  25. data/lib/standard_id/email_password/password_reset.rb +1 -1
  26. data/lib/standard_id/email_password.rb +4 -5
  27. data/lib/standard_id/error_reporting.rb +38 -0
  28. data/lib/standard_id/errors.rb +16 -0
  29. data/lib/standard_id/events/definitions.rb +14 -3
  30. data/lib/standard_id/events/subscribers/passwordless_delivery_subscriber.rb +3 -1
  31. data/lib/standard_id/events.rb +47 -0
  32. data/lib/standard_id/health_contributions.rb +27 -0
  33. data/lib/standard_id/http_client.rb +39 -6
  34. data/lib/standard_id/jwt_service.rb +31 -2
  35. data/lib/standard_id/keyed_digest.rb +43 -5
  36. data/lib/standard_id/oauth/direct_mint_flow.rb +9 -3
  37. data/lib/standard_id/oauth/oauth_session_persistence.rb +24 -9
  38. data/lib/standard_id/oauth/password_flow.rb +4 -10
  39. data/lib/standard_id/oauth/token_grant_flow.rb +28 -3
  40. data/lib/standard_id/password_pepper.rb +88 -0
  41. data/lib/standard_id/passwordless/base_strategy.rb +5 -1
  42. data/lib/standard_id/passwordless/code_handoff.rb +72 -0
  43. data/lib/standard_id/passwordless.rb +25 -0
  44. data/lib/standard_id/step_up.rb +236 -0
  45. data/lib/standard_id/testing/otp_helpers.rb +5 -5
  46. data/lib/standard_id/testing/request_helpers.rb +8 -3
  47. data/lib/standard_id/token_minter.rb +6 -2
  48. data/lib/standard_id/version.rb +1 -1
  49. data/lib/standard_id/web/session_manager.rb +9 -2
  50. data/lib/standard_id.rb +4 -0
  51. metadata +10 -1
@@ -10,7 +10,8 @@ module StandardId
10
10
  BASE_SESSION_FIELDS = %i[account_id client_id scopes grant_type aud claims]
11
11
 
12
12
  # Supported signing algorithms categorized by type
13
- # Symmetric: use shared secret (Rails.application.secret_key_base)
13
+ # Symmetric: use shared secret (Rails.application.secret_key_base; tokens
14
+ # signed under a config.previous_secret_key_bases entry still verify)
14
15
  # Asymmetric: use key pairs (RSA or EC private key)
15
16
  SUPPORTED_ALGORITHMS = {
16
17
  # HMAC (symmetric)
@@ -103,6 +104,20 @@ module StandardId
103
104
  end
104
105
  end
105
106
 
107
+ # The secrets an HMAC-signed (HS256/384/512) token is accepted under: the
108
+ # current `secret_key_base` first, then each
109
+ # `config.previous_secret_key_bases` entry. Tokens are always signed with
110
+ # the current one (.signing_key). Asymmetric keys rotate through
111
+ # `oauth.previous_signing_keys` instead, so this is empty for them.
112
+ #
113
+ # Pass it as the key to .verify to give a config-free caller the same
114
+ # rotation window.
115
+ def self.symmetric_verification_keys
116
+ return [] if asymmetric?
117
+
118
+ [Rails.application.secret_key_base, *StandardId::KeyedDigest.previous_secrets].uniq
119
+ end
120
+
106
121
  def self.key_id
107
122
  return nil unless asymmetric?
108
123
 
@@ -214,7 +229,7 @@ module StandardId
214
229
  end
215
230
  end
216
231
 
217
- decoded = JWT.decode(token, verification_key, true, options)
232
+ decoded = asymmetric? ? JWT.decode(token, verification_key, true, options) : decode_symmetric(token, options)
218
233
  decoded.first.with_indifferent_access
219
234
  rescue JWT::InvalidAudError
220
235
  raise StandardId::InvalidAudienceError.new(
@@ -372,6 +387,20 @@ module StandardId
372
387
 
373
388
  private
374
389
 
390
+ # Tries each of .symmetric_verification_keys in turn. Only a signature
391
+ # mismatch moves on to the next secret: an expired token, a wrong issuer
392
+ # or audience is a property of the token, so it raises out at once and
393
+ # .decode handles it as before. With no previous secrets this is the
394
+ # single decode under the current secret it always was.
395
+ def self.decode_symmetric(token, options)
396
+ keys = symmetric_verification_keys
397
+ keys.each_with_index do |key, index|
398
+ return JWT.decode(token, key, true, options)
399
+ rescue JWT::VerificationError
400
+ raise if index == keys.size - 1
401
+ end
402
+ end
403
+
375
404
  # Parses a previous_signing_keys entry into { kid:, key:, algorithm: }
376
405
  # Accepts either:
377
406
  # - A PEM string or Pathname (uses current algorithm's key class)
@@ -7,9 +7,9 @@ module StandardId
7
7
  # Every keyed digest the engine stores (Session#lookup_hash and
8
8
  # #token_digest, CodeChallenge#code_digest, AuthorizationCode#code_hash,
9
9
  # ClientApplication#registration_access_token_digest) is derived from
10
- # `secret_key_base`, so rotating that secret used to strand every one of
11
- # them: all users signed out, every in-flight code and registration access
12
- # token dead.
10
+ # `secret_key_base`, as is the HS256/384/512 JWT signing key, so rotating
11
+ # that secret used to strand every one of them: all users signed out, every
12
+ # in-flight code, registration access token and HMAC-signed JWT dead.
13
13
  #
14
14
  # `config.previous_secret_key_bases` is the opt-in that prevents it.
15
15
  # Digests are always WRITTEN under the current secret; they are READ (looked
@@ -19,6 +19,11 @@ module StandardId
19
19
  # `config.action_dispatch.cookies_rotations`), but keeps no list of previous
20
20
  # `secret_key_base` values a gem could read, hence the setting. The shape
21
21
  # mirrors Rodauth's `hmac_old_secret`.
22
+ #
23
+ # Long-lived credentials (session tokens, registration access tokens) that
24
+ # authenticate under a previous secret are re-keyed on the spot (.rekey), so
25
+ # an old secret only has to stay listed until every such credential has been
26
+ # used once since the rotation, or has expired.
22
27
  module KeyedDigest
23
28
  module_function
24
29
 
@@ -34,8 +39,13 @@ module StandardId
34
39
  # secrets configured this is one element and every caller does exactly the
35
40
  # work it did before.
36
41
  def secrets
37
- previous = Array(StandardId.config.previous_secret_key_bases).map(&:to_s).reject(&:blank?)
38
- [current_secret, *previous].uniq
42
+ [current_secret, *previous_secrets].uniq
43
+ end
44
+
45
+ # `config.previous_secret_key_bases` as strings, blank entries dropped.
46
+ # JwtService also verifies HMAC-signed JWTs under these.
47
+ def previous_secrets
48
+ Array(StandardId.config.previous_secret_key_bases).map(&:to_s).reject(&:blank?)
39
49
  end
40
50
 
41
51
  # HMAC-SHA256 of +data+ under +secret+, hex-encoded. Callers domain-separate
@@ -51,6 +61,34 @@ module StandardId
51
61
  secrets.map { |secret| yield secret }
52
62
  end
53
63
 
64
+ # Rewrites the digest columns of a row that just authenticated under a
65
+ # previous secret to their current-secret values, in a single UPDATE that
66
+ # applies only while the row still holds +from+ (so a concurrent re-key,
67
+ # rotation or revocation write is never overwritten). Runs no callbacks,
68
+ # touches no timestamps and publishes nothing.
69
+ #
70
+ # It is an optimisation of the rotation window, never part of
71
+ # authentication: any error (a read-only replica, a lock timeout, a missing
72
+ # column) is logged without the digests and swallowed, and a savepoint
73
+ # keeps a failed statement from aborting a surrounding transaction.
74
+ #
75
+ # @param model [Class<ActiveRecord::Base>]
76
+ # @param id [Object] the row's primary key
77
+ # @param from [Hash] column => value the row must still hold
78
+ # @param to [Hash] column => current-secret value
79
+ # @return [Boolean] whether the row was rewritten
80
+ def rekey(model, id:, from:, to:)
81
+ update = -> { model.unscoped.where(model.primary_key => id, **from).update_all(to) }
82
+ rows = model.with_connection(&:transaction_open?) ? model.transaction(requires_new: true) { update.call } : update.call
83
+ rows == 1
84
+ rescue StandardError => e
85
+ StandardId.logger.warn(
86
+ "[StandardId::KeyedDigest] Could not re-key #{model.name} #{id} under the current secret_key_base " \
87
+ "(#{e.class}); it still authenticates under the previous secret"
88
+ )
89
+ false
90
+ end
91
+
54
92
  # Constant-time check of +stored+ against every candidate. Compares against
55
93
  # all of them rather than stopping at the first match, so the response time
56
94
  # does not say which secret a digest was written under.
@@ -17,7 +17,7 @@ module StandardId
17
17
 
18
18
  def initialize(account:, audience:, grant_type:, scopes: nil, client_id: nil, claims: {}, expires_in: nil,
19
19
  refresh_token: false, request: nil, auth_method: nil, auth_provider: nil, profile: nil, audit_errors: :raise,
20
- requested_scopes: nil)
20
+ requested_scopes: nil, authenticated_at: nil)
21
21
  super({ audience: audience }, request || NullRequest.new)
22
22
  @profile = profile
23
23
  @audit_requested_scopes = normalize_audit_scopes(requested_scopes)
@@ -36,6 +36,7 @@ module StandardId
36
36
  @request_given = !request.nil?
37
37
  @auth_method = auth_method
38
38
  @auth_provider = auth_provider
39
+ @authenticated_at = authenticated_at
39
40
  end
40
41
 
41
42
  # Public so TokenMinter can report the jti the audit event carried.
@@ -162,7 +163,7 @@ module StandardId
162
163
  # later refresh; nil is recorded as :unspecified, which such a policy
163
164
  # refuses — so pass it when a policy is configured.
164
165
  def refresh_token_auth_lineage
165
- StandardId::AuthLineage.build(@auth_method, @auth_provider)
166
+ StandardId::AuthLineage.build(@auth_method, @auth_provider, authenticated_at: @authenticated_at)
166
167
  end
167
168
 
168
169
  # Resolvers and custom_claims see `request: nil` for a sessionless mint,
@@ -174,9 +175,14 @@ module StandardId
174
175
  # Host-supplied claims ride on top of the standard payload and the
175
176
  # resolver-derived claims, but can never override a reserved JWT key or a
176
177
  # base session field (same rule as config.oauth.custom_claims).
178
+ #
179
+ # Under c.step_up nor can it set `auth_time`, recorded or not: pass
180
+ # +authenticated_at:+ instead.
177
181
  def build_jwt_payload(expires_in)
182
+ payload = super(expires_in)
178
183
  extra = @claims.except(*StandardId::JwtService::RESERVED_JWT_KEYS, *StandardId::JwtService::BASE_SESSION_FIELDS)
179
- super(expires_in).merge(extra).compact
184
+ extra = extra.except(:auth_time) if StandardId::StepUp.enabled?
185
+ payload.merge(extra).compact
180
186
  end
181
187
 
182
188
  # A session is only materialised when the caller passed a real request:
@@ -14,21 +14,26 @@ module StandardId
14
14
  module OauthSessionPersistence
15
15
  module_function
16
16
 
17
- def persist!(session_class:, account:, request:, audience:, grant_type:)
17
+ # +authenticated_at+ (when the account last proved its identity, see
18
+ # StandardId::StepUp) is stamped on the row; a reused row keeps the later
19
+ # of its own and this one.
20
+ def persist!(session_class:, account:, request:, audience:, grant_type:, authenticated_at: nil)
18
21
  case session_class.name
19
22
  when "StandardId::DeviceSession"
20
23
  upsert_device_session!(
21
24
  account: account,
22
25
  request: request,
23
26
  audience: audience,
24
- grant_type: grant_type
27
+ grant_type: grant_type,
28
+ authenticated_at: authenticated_at
25
29
  )
26
30
  when "StandardId::BrowserSession"
27
31
  StandardId::BrowserSession.create!(
28
32
  account: account,
29
33
  ip_address: StandardId::Utils::IpNormalizer.normalize(request.remote_ip),
30
34
  user_agent: request.user_agent.presence || "OAuth:#{grant_type}",
31
- expires_at: StandardId::BrowserSession.expiry
35
+ expires_at: StandardId::BrowserSession.expiry,
36
+ **authenticated_at_attributes(authenticated_at)
32
37
  )
33
38
  else
34
39
  raise StandardId::ConfigurationError,
@@ -49,7 +54,7 @@ module StandardId
49
54
  # audit trail and admin session lists still read it); a new sign-in gets
50
55
  # a new row. Expiry is deliberately NOT part of eligibility: an expired
51
56
  # but unrevoked row is reused with its expires_at bumped, as before.
52
- def upsert_device_session!(account:, request:, audience:, grant_type:)
57
+ def upsert_device_session!(account:, request:, audience:, grant_type:, authenticated_at: nil)
53
58
  user_agent = request.user_agent
54
59
  device_id = stable_device_id(account: account, user_agent: user_agent, audience: audience)
55
60
  ip_address = StandardId::Utils::IpNormalizer.normalize(request.remote_ip)
@@ -69,7 +74,7 @@ module StandardId
69
74
  account.class.where(id: account.id).lock.first
70
75
 
71
76
  existing = active_device_session(account: account, device_id: device_id)
72
- return refresh_device_session!(existing, ip_address: ip_address, user_agent: user_agent) if existing
77
+ return refresh_device_session!(existing, ip_address: ip_address, user_agent: user_agent, authenticated_at: authenticated_at) if existing
73
78
 
74
79
  begin
75
80
  # Savepoint, so a unique violation does not abort the enclosing token
@@ -81,7 +86,8 @@ module StandardId
81
86
  device_id: device_id,
82
87
  device_agent: user_agent.presence || "OAuth:#{grant_type}",
83
88
  ip_address: ip_address || "0.0.0.0",
84
- expires_at: StandardId::DeviceSession.expiry
89
+ expires_at: StandardId::DeviceSession.expiry,
90
+ **authenticated_at_attributes(authenticated_at)
85
91
  )
86
92
  end
87
93
  rescue ActiveRecord::RecordNotUnique
@@ -90,7 +96,7 @@ module StandardId
90
96
  winner = active_device_session(account: account, device_id: device_id)
91
97
  raise unless winner
92
98
 
93
- refresh_device_session!(winner, ip_address: ip_address, user_agent: user_agent)
99
+ refresh_device_session!(winner, ip_address: ip_address, user_agent: user_agent, authenticated_at: authenticated_at)
94
100
  end
95
101
  end
96
102
 
@@ -105,15 +111,24 @@ module StandardId
105
111
  .first
106
112
  end
107
113
 
108
- def refresh_device_session!(session, ip_address:, user_agent:)
114
+ def refresh_device_session!(session, ip_address:, user_agent:, authenticated_at: nil)
115
+ latest = [session.try(:authenticated_at), authenticated_at].compact.max
109
116
  session.update!(
110
117
  expires_at: StandardId::DeviceSession.expiry,
111
118
  ip_address: ip_address || session.ip_address,
112
- device_agent: user_agent || session.device_agent
119
+ device_agent: user_agent || session.device_agent,
120
+ **authenticated_at_attributes(latest)
113
121
  )
114
122
  session
115
123
  end
116
124
 
125
+ # Nothing is written before migration 20261123000000 has run.
126
+ def authenticated_at_attributes(authenticated_at)
127
+ return {} if authenticated_at.nil? || !StandardId::StepUp.session_column?
128
+
129
+ { authenticated_at: authenticated_at }
130
+ end
131
+
117
132
  def stable_device_id(account:, user_agent:, audience:)
118
133
  audience_key = Array(audience).join(",")
119
134
  Digest::SHA256.hexdigest("oauth:#{audience_key}:#{account.id}:#{user_agent}")[0, 36]
@@ -1,12 +1,10 @@
1
- require "concurrent/delay"
2
-
3
1
  module StandardId
4
2
  module Oauth
5
3
  class PasswordFlow < TokenGrantFlow
6
4
  expect_params :username, :password, :client_id
7
5
  permit_params :client_secret, :audience, :scope, :realm
8
6
 
9
- DUMMY_PASSWORD_DIGEST = Concurrent::Delay.new { BCrypt::Password.create("").freeze }
7
+ DUMMY_PASSWORD_DIGEST = StandardId::PasswordPepper::DUMMY_DIGEST
10
8
 
11
9
  def authenticate!
12
10
  validate_client_secret!(params[:client_id], params[:client_secret]) if params[:client_secret].present?
@@ -103,9 +101,9 @@ module StandardId
103
101
  .includes(credential: { identifier: :account })
104
102
  .find_by(login: username)
105
103
 
106
- # Perform a dummy bcrypt comparison when the credential doesn't exist
107
- # to prevent user enumeration via response timing differences.
108
- BCrypt::Password.new(dummy_password_digest).is_password?(password) unless @credential
104
+ # Perform the dummy bcrypt comparisons when the credential doesn't
105
+ # exist to prevent user enumeration via response timing differences.
106
+ StandardId::PasswordPepper.dummy_authenticate(password) unless @credential
109
107
 
110
108
  # has_secure_password's authenticate returns false (not nil) on a wrong
111
109
  # password, so `&.account` would call false.account → NoMethodError (500).
@@ -124,10 +122,6 @@ module StandardId
124
122
  end
125
123
  end
126
124
 
127
- def dummy_password_digest
128
- DUMMY_PASSWORD_DIGEST.value
129
- end
130
-
131
125
  def default_scope
132
126
  "read"
133
127
  end
@@ -176,10 +176,16 @@ module StandardId
176
176
  account: account,
177
177
  request: request,
178
178
  audience: audience,
179
- grant_type: grant_type
179
+ grant_type: grant_type,
180
+ authenticated_at: token_authenticated_at
180
181
  )
181
182
  end
182
183
 
184
+ # With c.step_up on, the OIDC `auth_time` claim (seconds since the epoch)
185
+ # says when the account last proved its identity, for
186
+ # ApiAuthentication#require_recent_authentication!. Only the recorded
187
+ # time may set it: a custom claim of that name is dropped, even when no
188
+ # time was recorded, so no claim can stand in for an authentication.
183
189
  def build_jwt_payload(expires_in)
184
190
  base_payload = {
185
191
  sub: subject_id,
@@ -189,7 +195,25 @@ module StandardId
189
195
  aud: audience
190
196
  }.compact
191
197
 
192
- base_payload.merge(claims_from_scope_mapping).merge(claims_from_custom_claims)
198
+ payload = base_payload.merge(claims_from_scope_mapping).merge(claims_from_custom_claims)
199
+ return payload unless StandardId::StepUp.enabled?
200
+
201
+ payload = payload.except(:auth_time, "auth_time")
202
+ authenticated_at = token_authenticated_at
203
+ payload[:auth_time] = authenticated_at.to_i if authenticated_at
204
+ payload
205
+ end
206
+
207
+ # When the account behind this token last proved its identity: now for a
208
+ # grant that authenticates it (one with a login_method_policy_context),
209
+ # the recorded time for one derived from an earlier authentication
210
+ # (authorization_code, refresh_token), nil when unknown or when there is
211
+ # no account. Read off refresh_token_auth_lineage, which already says how
212
+ # the authentication was made, so both travel together.
213
+ def token_authenticated_at
214
+ return @token_authenticated_at if defined?(@token_authenticated_at)
215
+
216
+ @token_authenticated_at = refresh_token_auth_lineage[:authenticated_at]
193
217
  end
194
218
 
195
219
  def token_expiry
@@ -261,7 +285,8 @@ module StandardId
261
285
  context = login_method_policy_context
262
286
  return StandardId::AuthLineage.empty if context.nil?
263
287
 
264
- StandardId::AuthLineage.build(context[:auth_method], context[:provider])
288
+ @authenticating_at ||= Time.current
289
+ StandardId::AuthLineage.build(context[:auth_method], context[:provider], authenticated_at: @authenticating_at)
265
290
  end
266
291
 
267
292
  # The parent session for the refresh token issued by THIS grant, when the
@@ -0,0 +1,88 @@
1
+ require "concurrent/delay"
2
+ require "openssl"
3
+
4
+ module StandardId
5
+ # The secret mixed into every password before bcrypt sees it
6
+ # (`c.password.pepper`), so a leaked database alone is not enough to crack
7
+ # the digests: the pepper lives in the app's credentials, not in the rows.
8
+ #
9
+ # A peppered digest is bcrypt(HMAC-SHA256(pepper, password)), hex-encoded,
10
+ # never bcrypt(password + pepper): bcrypt reads only the first 72 bytes, so
11
+ # an appended pepper would be cut off a long password, and a raw HMAC can
12
+ # contain the NUL byte bcrypt stops at. The hex form is 64 bytes of [0-9a-f].
13
+ #
14
+ # Digests are WRITTEN under the current pepper and READ under the current
15
+ # pepper, then each of `c.password.previous_peppers`, then with no pepper at
16
+ # all, so turning the pepper on, or rotating it, locks nobody out: a login
17
+ # that matched anything but the current pepper re-hashes under it
18
+ # (PasswordCredential#rehash_password). With no pepper configured there is
19
+ # one candidate, the bare password, and every caller does exactly what
20
+ # has_secure_password did. The shape mirrors Rodauth's password_pepper.
21
+ #
22
+ # Losing the pepper makes every digest made under it unverifiable: each of
23
+ # those users has to reset their password. Keep it with secret_key_base.
24
+ module PasswordPepper
25
+ # The candidate meaning "no pepper": the bare password.
26
+ UNPEPPERED = ""
27
+
28
+ # A digest to compare against when no credential exists, so a miss costs
29
+ # the same bcrypt work as a wrong password (see .dummy_authenticate).
30
+ DUMMY_DIGEST = Concurrent::Delay.new { BCrypt::Password.create("").freeze }
31
+
32
+ module_function
33
+
34
+ # The pepper new digests are written under; UNPEPPERED when none is set.
35
+ def current
36
+ StandardId.config.password.pepper.to_s
37
+ end
38
+
39
+ # Whether any pepper is configured, current or previous. When false the
40
+ # engine never looks past has_secure_password's own behaviour.
41
+ def enabled?
42
+ current.present? || previous.any?
43
+ end
44
+
45
+ # The peppers a stored digest may have been made under, current first,
46
+ # then `c.password.previous_peppers`, then UNPEPPERED unless
47
+ # `c.password.accept_unpeppered_passwords` is off. Blank and repeated
48
+ # entries are dropped. The unpeppered candidate is always kept while no
49
+ # current pepper is set, so the setting cannot lock everyone out.
50
+ def candidates
51
+ list = [current, *previous]
52
+ list << UNPEPPERED if current.empty? || StandardId.config.password.accept_unpeppered_passwords
53
+ list.uniq
54
+ end
55
+
56
+ # What bcrypt hashes for +password+ under +pepper+.
57
+ def apply(password, pepper)
58
+ password = password.to_s
59
+ pepper.empty? ? password : OpenSSL::HMAC.hexdigest("SHA256", pepper, password)
60
+ end
61
+
62
+ # The candidate +password+ matches +digest+ under, or nil when it matches
63
+ # none. Stops at the first match: once the password is right, how long the
64
+ # check took says nothing a caller did not already know. A wrong password
65
+ # costs one bcrypt comparison per candidate, which .dummy_authenticate
66
+ # matches.
67
+ def matching_pepper(digest, password)
68
+ stored = BCrypt::Password.new(digest)
69
+ candidates.find { |pepper| stored.is_password?(apply(password, pepper)) }
70
+ end
71
+
72
+ # The work of a wrong password against a real digest, done against
73
+ # DUMMY_DIGEST, for a login whose credential does not exist: timing must
74
+ # not reveal whether an address is registered. One comparison per
75
+ # candidate, as .matching_pepper makes for a wrong password.
76
+ #
77
+ # @return [nil]
78
+ def dummy_authenticate(password)
79
+ stored = BCrypt::Password.new(DUMMY_DIGEST.value)
80
+ candidates.each { |pepper| stored.is_password?(apply(password, pepper)) }
81
+ nil
82
+ end
83
+
84
+ def previous
85
+ Array(StandardId.config.password.previous_peppers).map(&:to_s).reject(&:empty?)
86
+ end
87
+ end
88
+ end
@@ -261,7 +261,11 @@ module StandardId
261
261
  skip_sender: skip_sender,
262
262
  delivery: delivery
263
263
  }
264
- StandardId::Events.publish(StandardId::Events::PASSWORDLESS_CODE_GENERATED, payload)
264
+ # The raw code reaches subscribers through CodeHandoff, never the
265
+ # payload, so it is there even when publish_records drops the record.
266
+ CodeHandoff.with(challenge) do
267
+ StandardId::Events.publish(StandardId::Events::PASSWORDLESS_CODE_GENERATED, payload)
268
+ end
265
269
  payload
266
270
  end
267
271
 
@@ -0,0 +1,72 @@
1
+ module StandardId
2
+ module Passwordless
3
+ # Hands the raw one-time code to delivery without putting it on the event
4
+ # bus.
5
+ #
6
+ # A challenge stores only an HMAC of its code, so the raw code exists only
7
+ # on the in-memory record the strategy has just created. With
8
+ # `config.events.publish_records = true` (the default) that record is
9
+ # PASSWORDLESS_CODE_GENERATED's `code_challenge:`. With it false, the
10
+ # payload carries `code_challenge_id` / `_gid` instead and there would be
11
+ # no way left to reach the code: neither delivery subscribers nor
12
+ # StandardId::Testing::OtpHelpers could see it.
13
+ #
14
+ # The code is NOT added to the payload as a string (or any object wrapping
15
+ # one): audit and event-logging subscribers serialise whole payloads into
16
+ # append-only rows, logs, error-tracker breadcrumbs and job arguments,
17
+ # which is exactly what `publish_records = false` exists to stop. Instead
18
+ # the strategy registers the challenge here, in this thread's (or fiber's)
19
+ # execution state, for exactly as long as the synchronous publish of
20
+ # PASSWORDLESS_CODE_GENERATED runs. A subscriber that wants the code asks
21
+ # for it by name (StandardId::Passwordless.issued_code(event)); one that
22
+ # serialises the payload never sees it. Once the publish returns the entry
23
+ # is gone, and another thread, a background job or a later step of the
24
+ # request gets nil.
25
+ #
26
+ # Entries are a stack, so an OTP issued from inside a subscriber (nested
27
+ # publish) is answered for its own event and then popped.
28
+ module CodeHandoff
29
+ STATE_KEY = :standard_id_passwordless_code_handoff
30
+
31
+ module_function
32
+
33
+ # Registers +challenge+ as the one being published while the block runs.
34
+ def with(challenge)
35
+ stack = (ActiveSupport::IsolatedExecutionState[STATE_KEY] ||= [])
36
+ stack.push(challenge)
37
+ begin
38
+ yield
39
+ ensure
40
+ stack.pop
41
+ ActiveSupport::IsolatedExecutionState.delete(STATE_KEY) if stack.empty?
42
+ end
43
+ end
44
+
45
+ # The in-memory challenge a PASSWORDLESS_CODE_GENERATED event was
46
+ # published for, or nil.
47
+ #
48
+ # The published record when there is one; otherwise the challenge being
49
+ # published right now on this thread, provided +event+ is a
50
+ # PASSWORDLESS_CODE_GENERATED event and its `code_challenge_id` (when the
51
+ # payload has one) is that challenge's. Anything else gets nil: another
52
+ # event, an event replayed later or elsewhere, or one for a different
53
+ # challenge.
54
+ #
55
+ # @param event [StandardId::Events::Event, Hash] the event or its payload
56
+ # @return [StandardId::CodeChallenge, nil]
57
+ def challenge_for(event)
58
+ record = event[:code_challenge]
59
+ return record unless record.nil?
60
+ return nil unless event[:event_type].to_s == StandardId::Events::PASSWORDLESS_CODE_GENERATED
61
+
62
+ current = ActiveSupport::IsolatedExecutionState[STATE_KEY]&.last
63
+ return nil unless current
64
+
65
+ id = event[:code_challenge_id]
66
+ return nil if id.present? && id.to_s != current.id.to_s
67
+
68
+ current
69
+ end
70
+ end
71
+ end
72
+ end
@@ -1,4 +1,5 @@
1
1
  require "standard_id/passwordless/verification_service"
2
+ require "standard_id/passwordless/code_handoff"
2
3
 
3
4
  module StandardId
4
5
  module Passwordless
@@ -57,6 +58,30 @@ module StandardId
57
58
  )
58
59
  end
59
60
 
61
+ # The raw one-time code a PASSWORDLESS_CODE_GENERATED event was published
62
+ # for. Delivery subscribers should read the code through this rather
63
+ # than `event[:code_challenge].code`: it works whether or not
64
+ # `config.events.publish_records` publishes the record, without the code
65
+ # ever being part of the payload (see CodeHandoff).
66
+ #
67
+ # Call it inside the subscriber, while the event is being published, and
68
+ # pass the string on. Later, or on another thread (a job that received
69
+ # the payload), it returns nil.
70
+ #
71
+ # @param event [StandardId::Events::Event, Hash] the event or its payload
72
+ # @return [String, nil]
73
+ #
74
+ # @example
75
+ # StandardId::Events.subscribe(StandardId::Events::PASSWORDLESS_CODE_GENERATED) do |event|
76
+ # next if event[:skip_sender]
77
+ #
78
+ # code = StandardId::Passwordless.issued_code(event)
79
+ # SmsService.send_code(event[:identifier], code) if code
80
+ # end
81
+ def issued_code(event)
82
+ CodeHandoff.challenge_for(event)&.code.presence
83
+ end
84
+
60
85
  # Resolve the configured OTP code length, clamped to a sane range.
61
86
  # Shared by all OTP generators in the engine so one setting controls the
62
87
  # code space end-to-end.