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,10 @@
23
23
  {
24
24
  "fingerprint": "413b5740add2c365198a540734a9e8c12b1c0483f521e2db145a80f3d582a4cc",
25
25
  "note": "after_sign_in hook redirect is controlled by the host app configuration, not user input"
26
+ },
27
+ {
28
+ "fingerprint": "e0a31d4fea6dd6a6d5caccc8565feea1b03d1d031bd585e56729e5e82437c41c",
29
+ "note": "HEAD vs GET distinction is inconsequential here; require_recent_authentication! remembers the return URL on GET only, and a HEAD simply returns to the default after step-up"
26
30
  }
27
31
  ],
28
32
  "updated": "2026-03-21",
@@ -20,6 +20,15 @@ en:
20
20
  other: "This code will expire in %{count} minutes."
21
21
  ignore: "If you did not request this code, you can safely ignore this email."
22
22
  footer: "This is an automated message. Please do not reply."
23
+ step_up_email:
24
+ subject: "Confirm it's you"
25
+ greeting: "Hi,"
26
+ intro: "You're already signed in, and you've asked to do something sensitive on your account. To confirm it's you, enter this code:"
27
+ expiry:
28
+ one: "This code will expire in %{count} minute."
29
+ other: "This code will expire in %{count} minutes."
30
+ warning: "If you didn't ask for this, don't share the code with anyone. Someone else may be signed in to your account: change your password, if you have one, and check your account for anything you don't recognise."
31
+ footer: "This is an automated message. Please do not reply."
23
32
  account_notice_mailer:
24
33
  existing_account:
25
34
  subject: "Someone tried to sign up with your email"
data/config/routes/api.rb CHANGED
@@ -24,6 +24,13 @@ StandardId::ApiEngine.routes.draw do
24
24
  end
25
25
  end
26
26
 
27
+ # Step-up (recent) authentication for bearer clients, StandardId::StepUp.
28
+ # Matched only while c.step_up.enabled is true.
29
+ constraints(->(_request) { StandardId::StepUp.enabled? }) do
30
+ post "step_up", to: "step_up#create", as: :step_up
31
+ post "step_up/verify", to: "step_up#verify", as: :step_up_verify
32
+ end
33
+
27
34
  namespace :oidc do
28
35
  resource :logout, only: [:show], controller: :logout
29
36
  end
data/config/routes/web.rb CHANGED
@@ -9,6 +9,12 @@ StandardId::WebEngine.routes.draw do
9
9
 
10
10
  resource :login_verify, only: [:show, :update], controller: :login_verify
11
11
  resource :logout, only: [:create], controller: :logout
12
+
13
+ # Step-up (recent) authentication, StandardId::StepUp. Drawn always but
14
+ # matched only while c.step_up.enabled is true, so /step_up 404s otherwise.
15
+ constraints(->(_request) { StandardId::StepUp.enabled? }) do
16
+ resource :step_up, only: [:show, :create, :update], controller: :step_up
17
+ end
12
18
  resource :signup, only: [:show, :create], controller: :signup
13
19
 
14
20
  # Social authentication callbacks (web flow)
@@ -0,0 +1,15 @@
1
+ # When a session (and the refresh tokens derived from it) last proved the
2
+ # account's identity: set at sign-in and on a step-up, never by remember-me or
3
+ # a refresh. Read by `require_recent_authentication!` (StandardId::StepUp).
4
+ #
5
+ # Two nullable datetime columns with no default and no index, so both are
6
+ # metadata-only on PostgreSQL. NULL reads as "not recently", which is what
7
+ # every session and refresh token created before this migration is: the guard
8
+ # asks those users to step up once. Until this has run, the gem writes neither
9
+ # column and the guard raises StandardId::ConfigurationError naming it.
10
+ class AddAuthenticatedAtToStandardIdSessions < ActiveRecord::Migration[8.0]
11
+ def change
12
+ add_column :standard_id_sessions, :authenticated_at, :datetime
13
+ add_column :standard_id_refresh_tokens, :authenticated_at, :datetime
14
+ end
15
+ end
@@ -106,9 +106,12 @@ StandardId.configure do |c|
106
106
 
107
107
  # Old secret_key_base values (newest first) still accepted for StandardId's
108
108
  # keyed digests — session tokens, OTP codes, authorization codes, registration
109
- # access tokens — so rotating the secret does not sign everyone out. New
110
- # digests always use the current secret. Keep an entry for the longest
111
- # session lifetime, and rotate Rails' cookies and message verifiers too
109
+ # access tokens — and for HS256/384/512 JWTs, so rotating the secret does not
110
+ # sign everyone out. New digests and tokens always use the current secret,
111
+ # and a session or registration access token used under an old secret is
112
+ # re-keyed to the current one on that use. Keep an entry until the
113
+ # credentials you want to keep have been used once (at most the longest
114
+ # session lifetime), and rotate Rails' cookies and message verifiers too
112
115
  # (README "Rotating secret_key_base").
113
116
  # Default: []
114
117
  # c.previous_secret_key_bases = [Rails.application.credentials.old_secret_key_base]
@@ -228,6 +231,32 @@ StandardId.configure do |c|
228
231
  # Default: true
229
232
  # c.password.require_numbers = true
230
233
 
234
+ # Pepper: a secret mixed into every password before bcrypt, as
235
+ # bcrypt(HMAC-SHA256(pepper, password)). Off (nil) by default. Turning it on
236
+ # locks nobody out: old digests still verify and move to the pepper as each
237
+ # user signs in. LOSING THE PEPPER FORCES EVERY PASSWORD HASHED UNDER IT TO
238
+ # BE RESET. To rotate, move the old value into previous_peppers.
239
+ # See README "Password pepper".
240
+ # c.password.pepper = Rails.application.credentials.password_pepper
241
+ # c.password.previous_peppers = []
242
+ # c.password.accept_unpeppered_passwords = true
243
+
244
+ # ---------------------------------------------------------------------------
245
+ # Step-up (recent) authentication
246
+ # ---------------------------------------------------------------------------
247
+
248
+ # Off by default. Draws /step_up (web) and POST /step_up, /step_up/verify
249
+ # (API), mints the OIDC auth_time claim, and lets controllers call
250
+ # require_recent_authentication!(within: 5.minutes). Needs migration
251
+ # 20261123000000. See README "Step-up authentication".
252
+ # c.step_up.enabled = false
253
+ # c.step_up.max_age = 300
254
+ # c.step_up.realm = "step_up"
255
+ # c.step_up.delivery = :built_in
256
+ # c.step_up.require_password = true
257
+ # c.step_up.url = nil
258
+ # c.step_up.token_profile_resolver = ->(account:, claims:) { account.profiles.find_by(id: claims[:gid]) }
259
+
231
260
  # ---------------------------------------------------------------------------
232
261
  # Passwordless (OTP)
233
262
  # ---------------------------------------------------------------------------
@@ -297,11 +326,16 @@ StandardId.configure do |c|
297
326
  # 0.43). It runs synchronously in the request, so I18n.locale etc. are still
298
327
  # available. The same subscriber delivers Otp.issue(delivery: :custom) codes.
299
328
  #
329
+ # Read the code with StandardId::Passwordless.issued_code(event), inside the
330
+ # subscriber: it is never part of the payload, and it works with
331
+ # c.events.publish_records = false too.
332
+ #
300
333
  # StandardId::Events.subscribe(StandardId::Events::PASSWORDLESS_CODE_GENERATED) do |event|
301
334
  # next if event[:skip_sender] # Otp.issue(delivery: :manual)
335
+ # code = StandardId::Passwordless.issued_code(event)
302
336
  # case event[:channel]
303
- # when "email" then PasswordlessMailer.with(code: event[:code_challenge].code, to: event[:identifier]).deliver_later
304
- # when "sms" then SmsProvider.send_code(phone: event[:identifier], code: event[:code_challenge].code)
337
+ # when "email" then PasswordlessMailer.with(code: code, to: event[:identifier]).deliver_later
338
+ # when "sms" then SmsProvider.send_code(phone: event[:identifier], code: code)
305
339
  # end
306
340
  # end
307
341
 
@@ -327,6 +361,12 @@ StandardId.configure do |c|
327
361
  # validation entirely — set this in production.
328
362
  # Default: []
329
363
  # c.oauth.allowed_audiences = %w[web mobile admin]
364
+ #
365
+ # Split what this app mints from what its API accepts. Each defaults to
366
+ # allowed_audiences when unset (nil). An identity provider minting tokens
367
+ # for other services lists them as mintable but not accepted:
368
+ # c.oauth.mintable_audiences = %w[web harness inference]
369
+ # c.oauth.accepted_audiences = %w[web]
330
370
 
331
371
  # Scope-to-claims mapping — when a scope is granted, every listed claim is
332
372
  # resolved via claim_resolvers below and embedded in the access token.
@@ -600,7 +640,10 @@ StandardId.configure do |c|
600
640
 
601
641
  # Wraps every outbound provider request (token exchange, userinfo, JWKS),
602
642
  # e.g. in a circuit breaker. Receives provider: (:google, :apple, ...) and
603
- # the request as a block; must call the block and return its result.
643
+ # the request as a block; must call the block and return its result. A
644
+ # refusal by the wrapper itself (an open circuit) becomes
645
+ # StandardId::ProviderUnavailableError, so sign-in fails as "temporarily
646
+ # unavailable" (API: 503) without the circuit's message.
604
647
  # Default: nil (the request runs directly)
605
648
  # c.network_wrapper = ->(provider:, &b) { StandardCircuit.run(:"oauth_#{provider}", &b) }
606
649
 
@@ -71,8 +71,9 @@ module StandardId
71
71
 
72
72
  # Verifies the bearer JWT and returns a decoded session.
73
73
  #
74
- # When `StandardId.config.oauth.allowed_audiences` is non-empty,
75
- # the token's `aud` claim is enforced against that list at decode
74
+ # When the accepted audiences (`config.oauth.accepted_audiences`,
75
+ # else `config.oauth.allowed_audiences`) are non-empty, the token's
76
+ # `aud` claim is enforced against that list at decode
76
77
  # time. A mismatch raises `StandardId::InvalidAudienceError`, which
77
78
  # is caught and treated as an invalid token (returns nil) so the
78
79
  # downstream 401 path in `Api::BaseController` handles it
@@ -94,11 +95,14 @@ module StandardId
94
95
 
95
96
  private
96
97
 
98
+ # The caller has just authenticated `account`, so the session proved its
99
+ # identity now (StandardId::StepUp).
97
100
  def create_session_for(session_class, account:, device_id: nil, device_agent: nil)
98
101
  base_attrs = {
99
102
  account: account,
100
103
  ip_address: StandardId::Utils::IpNormalizer.normalize(@request.remote_ip)
101
104
  }
105
+ base_attrs[:authenticated_at] = Time.current if StandardId::StepUp.session_column?
102
106
 
103
107
  case session_class.name
104
108
  when "StandardId::DeviceSession"
@@ -122,8 +126,7 @@ module StandardId
122
126
  end
123
127
 
124
128
  def configured_allowed_audiences
125
- audiences = StandardId.config.oauth.allowed_audiences
126
- audiences.presence
129
+ StandardId::Oauth::Audiences.accepted.presence
127
130
  end
128
131
  end
129
132
  end
@@ -10,6 +10,13 @@ module StandardId
10
10
  # #auth_provider
11
11
  # refresh_token grant: copied from the presented token to its successor.
12
12
  #
13
+ # It also carries WHEN that authentication happened (`authenticated_at`), so
14
+ # step-up authentication (StandardId::StepUp) can tell how recently the
15
+ # account proved its identity: Session#authenticated_at, "authenticated_at"
16
+ # in an authorization code's metadata, RefreshToken#authenticated_at
17
+ # (migration 20261123000000). A lineage with no time has no
18
+ # `:authenticated_at` key at all.
19
+ #
13
20
  # Sessions and authorization codes already have a JSON `metadata` column, so
14
21
  # the lineage lives there under "auth_method" / "auth_provider". Refresh tokens
15
22
  # get two columns (migration 20261004000000). Anything minted before 0.45, or
@@ -18,12 +25,16 @@ module StandardId
18
25
  module AuthLineage
19
26
  METHOD_KEY = "auth_method".freeze
20
27
  PROVIDER_KEY = "auth_provider".freeze
28
+ AUTHENTICATED_AT_KEY = "authenticated_at".freeze
21
29
 
22
30
  module_function
23
31
 
24
- # @return [Hash] `{ auth_method: String|nil, auth_provider: String|nil }`
25
- def build(auth_method, provider = nil)
26
- { auth_method: auth_method&.to_s.presence, auth_provider: provider&.to_s.presence }
32
+ # @return [Hash] `{ auth_method: String|nil, auth_provider: String|nil }`,
33
+ # plus `authenticated_at: Time` when one is given
34
+ def build(auth_method, provider = nil, authenticated_at: nil)
35
+ lineage = { auth_method: auth_method&.to_s.presence, auth_provider: provider&.to_s.presence }
36
+ lineage[:authenticated_at] = authenticated_at if authenticated_at
37
+ lineage
27
38
  end
28
39
 
29
40
  def empty
@@ -33,24 +44,33 @@ module StandardId
33
44
  # Lineage stored on a session or authorization code `metadata` hash.
34
45
  def from_metadata(metadata)
35
46
  metadata = metadata.is_a?(Hash) ? metadata.stringify_keys : {}
36
- build(metadata[METHOD_KEY], metadata[PROVIDER_KEY])
47
+ build(metadata[METHOD_KEY], metadata[PROVIDER_KEY], authenticated_at: parse_time(metadata[AUTHENTICATED_AT_KEY]))
37
48
  end
38
49
 
50
+ # A session's time is its own `authenticated_at` column, not its metadata.
39
51
  def from_session(session)
40
52
  return empty unless session.respond_to?(:metadata)
41
53
 
42
- from_metadata(session.metadata)
54
+ lineage = from_metadata(session.metadata).except(:authenticated_at)
55
+ authenticated_at = session.authenticated_at if session.respond_to?(:authenticated_at)
56
+ lineage[:authenticated_at] = authenticated_at if authenticated_at
57
+ lineage
43
58
  end
44
59
 
45
60
  def from_refresh_token(record)
46
61
  return empty unless record && refresh_token_columns?
47
62
 
48
- build(record.auth_method, record.auth_provider)
63
+ authenticated_at = record.authenticated_at if record.respond_to?(:authenticated_at)
64
+ build(record.auth_method, record.auth_provider, authenticated_at: authenticated_at)
49
65
  end
50
66
 
51
67
  # Merge into a `metadata` hash. Nothing is added for an empty lineage.
52
68
  def to_metadata(lineage)
53
- { METHOD_KEY => lineage[:auth_method], PROVIDER_KEY => lineage[:auth_provider] }.compact
69
+ {
70
+ METHOD_KEY => lineage[:auth_method],
71
+ PROVIDER_KEY => lineage[:auth_provider],
72
+ AUTHENTICATED_AT_KEY => lineage[:authenticated_at]&.utc&.iso8601(6)
73
+ }.compact
54
74
  end
55
75
 
56
76
  # Attributes for a new RefreshToken row; empty until the host has run the
@@ -58,7 +78,9 @@ module StandardId
58
78
  def refresh_token_attributes(lineage)
59
79
  return {} unless refresh_token_columns?
60
80
 
61
- { auth_method: lineage[:auth_method], auth_provider: lineage[:auth_provider] }
81
+ attributes = { auth_method: lineage[:auth_method], auth_provider: lineage[:auth_provider] }
82
+ attributes[:authenticated_at] = lineage[:authenticated_at] if StandardId::StepUp.refresh_token_column?
83
+ attributes
62
84
  end
63
85
 
64
86
  # The policy's view: missing method → :unspecified.
@@ -66,6 +88,15 @@ module StandardId
66
88
  { auth_method: (lineage[:auth_method].presence || :unspecified).to_sym, provider: lineage[:auth_provider] }
67
89
  end
68
90
 
91
+ def parse_time(value)
92
+ return value if value.is_a?(Time) || value.is_a?(ActiveSupport::TimeWithZone)
93
+ return nil if value.blank?
94
+
95
+ Time.iso8601(value.to_s)
96
+ rescue ArgumentError
97
+ nil
98
+ end
99
+
69
100
  def refresh_token_columns?
70
101
  StandardId::RefreshToken.column_names.include?("auth_method")
71
102
  rescue ActiveRecord::ActiveRecordError
@@ -89,15 +89,22 @@ StandardId::ConfigSchema.define do
89
89
  # Previous `secret_key_base` values, newest first, still ACCEPTED when
90
90
  # looking up and verifying the engine's keyed digests: session tokens
91
91
  # (lookup_hash and the HMAC token_digest), passwordless code digests,
92
- # authorization codes and RFC 7592 registration access tokens. New digests
93
- # are always written under the current secret. See StandardId::KeyedDigest.
92
+ # authorization codes and RFC 7592 registration access tokens. JWTs signed
93
+ # with HS256/384/512 (keyed on `secret_key_base`) also still verify under
94
+ # these; asymmetric keys rotate through `oauth.previous_signing_keys`. New
95
+ # digests and tokens are always written under the current secret. See
96
+ # StandardId::KeyedDigest and JwtService.symmetric_verification_keys.
94
97
  #
95
98
  # Empty (default) means rotating `secret_key_base` invalidates all of them
96
99
  # at once, which is what it always did. To rotate without signing everyone
97
- # out, list the old secret here for at least the longest session lifetime,
98
- # alongside Rails' own rotations for its cookies and message verifiers
100
+ # out, list the old secret here. A session or registration access token
101
+ # that authenticates under it is re-keyed to the current secret on that
102
+ # use, so the entry is needed only until the credentials you want to keep
103
+ # have been used once (at most the longest session lifetime). Rotate Rails'
104
+ # own cookies and message verifiers alongside it
99
105
  # (README "Rotating secret_key_base"). Each extra entry costs one more
100
- # candidate per lookup and one more HMAC per verification.
106
+ # candidate per lookup and one more HMAC per verification (for a JWT, only
107
+ # when it fails to verify under the newer secrets).
101
108
  field :previous_secret_key_bases, type: :array, default: -> { [] }
102
109
 
103
110
  # Scope-aware authentication: maps scope names to profile-based access config.
@@ -169,8 +176,13 @@ StandardId::ConfigSchema.define do
169
176
  # Receives: provider: (Symbol — :google, :apple, ...; :standard_id when the
170
177
  # caller names none) and a block that performs the request.
171
178
  # Must call the block and return its result. Whatever the block raises
172
- # (timeouts, refused connections) raises inside the wrapper; whatever the
173
- # wrapper raises reaches the caller unchanged.
179
+ # (timeouts, refused connections) raises inside the wrapper and, re-raised,
180
+ # reaches the caller unchanged. A refusal by the wrapper itself (an open
181
+ # circuit) becomes StandardId::ProviderUnavailableError, `cause` set to it,
182
+ # so a sign-in fails as "temporarily unavailable" (API: 503) without the
183
+ # circuit's message. Programming errors in the wrapper, and errors it
184
+ # raises after the block returned, pass through unchanged (see
185
+ # StandardId::NetworkWrapper).
174
186
  # nil (the default) runs the block directly.
175
187
  #
176
188
  # c.network_wrapper = ->(provider:, &b) { StandardCircuit.run(:"oauth_#{provider}", &b) }
@@ -353,6 +365,34 @@ StandardId::ConfigSchema.define do
353
365
  # signs that user out of remember-me cookies and voids their reset links.
354
366
  # See StandardId::PasswordCredential#rehash_password.
355
367
  field :rehash_on_login, type: :boolean, default: true
368
+ # A secret mixed into every password before bcrypt, as
369
+ # bcrypt(HMAC-SHA256(pepper, password)), so the digests cannot be cracked
370
+ # from a database dump alone. nil (default) hashes the bare password, as
371
+ # has_secure_password always has. Read it from credentials, never from
372
+ # source; at least 32 random bytes (`SecureRandom.hex(32)`).
373
+ #
374
+ # LOSING THE PEPPER FORCES EVERY PASSWORD HASHED UNDER IT TO BE RESET:
375
+ # there is no way to verify those digests without it.
376
+ #
377
+ # Turning it on locks nobody out: existing (unpeppered) digests still
378
+ # verify, and each user's next password login re-hashes under the pepper
379
+ # (needs rehash_on_login). See StandardId::PasswordPepper and the README,
380
+ # "Password pepper".
381
+ field :pepper, type: :string, default: nil
382
+ # Peppers that were current before, newest first, still ACCEPTED when
383
+ # verifying a password; a login that matches one re-hashes under the
384
+ # current pepper. To rotate, move the old pepper here and set the new one.
385
+ # Keep an entry until no digest made under it can be left (every user has
386
+ # signed in since, or the rest have reset); dropping it early forces those
387
+ # users to reset. Each entry costs one more bcrypt comparison on a wrong
388
+ # password.
389
+ field :previous_peppers, type: :array, default: -> { [] }
390
+ # Whether a password with no pepper still verifies while a pepper is set:
391
+ # digests made before the pepper was turned on. On by default so turning
392
+ # it on locks nobody out. Turn it off only once no unpeppered digest can be
393
+ # left, or those users must reset; it saves one bcrypt comparison per
394
+ # wrong password. Ignored while no pepper is set.
395
+ field :accept_unpeppered_passwords, type: :boolean, default: true
356
396
  # Who tells the owner, by email, that their password was changed or reset
357
397
  # (CREDENTIAL_PASSWORD_CHANGED):
358
398
  # :custom — (default) the engine sends nothing; subscribe to the event
@@ -364,6 +404,46 @@ StandardId::ConfigSchema.define do
364
404
  field :changed_notice_delivery, type: :symbol, default: :custom
365
405
  end
366
406
 
407
+ # Step-up (recent) authentication: `require_recent_authentication!` in web
408
+ # and API controllers, and the flow that re-proves identity with a fresh
409
+ # one-time code (and the password, where the account has one). Off by
410
+ # default: the step-up routes 404, access tokens carry no `auth_time`, and
411
+ # nothing changes unless a controller calls the guard. See StandardId::StepUp
412
+ # and the README, "Step-up authentication".
413
+ scope :step_up do
414
+ # Draws the step-up endpoints (web /step_up, API /step_up and
415
+ # /step_up/verify) and adds the OIDC `auth_time` claim to access tokens.
416
+ # The guard refuses to run while this is false.
417
+ field :enabled, type: :boolean, default: false
418
+ # The default `within:` of require_recent_authentication!, in seconds.
419
+ field :max_age, type: :integer, default: 300
420
+ # The StandardId::Otp realm step-up codes are issued and verified in, kept
421
+ # apart from sign-in codes so one can never stand in for the other.
422
+ field :realm, type: :string, default: "step_up"
423
+ # How the code is delivered (StandardId::Otp delivery modes):
424
+ # :built_in — (default) follow c.passwordless.delivery: the engine's
425
+ # PasswordlessMailer#step_up_email when that is :built_in,
426
+ # else your PASSWORDLESS_CODE_GENERATED subscriber (realm
427
+ # "step_up")
428
+ # :custom — always your subscriber, so the message can say why
429
+ field :delivery, type: :symbol, default: :built_in
430
+ # Also ask for the password when the account has one. Off only for hosts
431
+ # whose second factor is the code alone.
432
+ field :require_password, type: :boolean, default: true
433
+ # Where the web guard sends a stale session. nil (default) is "/step_up",
434
+ # the web engine's page when it is mounted at "/"; set it when the engine
435
+ # is mounted elsewhere or the host draws its own page.
436
+ field :url, type: :string, default: nil
437
+ # The profile the API step-up re-mints the access token for, when its
438
+ # audience is bound to a profile type (oauth.audience_profile_types) and
439
+ # the account may hold several: a callable taking `account:` and
440
+ # `claims:` (the current token's decoded claims, e.g. your own `gid`)
441
+ # and returning the profile, passed to TokenMinter.mint(profile:). nil
442
+ # (default) uses the strict audience → profile lookup, which refuses an
443
+ # account with several active profiles of the bound type.
444
+ field :token_profile_resolver, type: :any, default: nil
445
+ end
446
+
367
447
  scope :reset_password do
368
448
  # Password reset email delivery mode:
369
449
  # :custom — (default) host app handles delivery via event subscriber for
@@ -545,8 +625,26 @@ StandardId::ConfigSchema.define do
545
625
  # Empty (default) = no global audience validation; behavior matches
546
626
  # pre-threading releases. Production deployments should set this
547
627
  # explicitly (e.g., `%w[web api]`).
628
+ #
629
+ # It is the default for both of the two lists below: set either to split
630
+ # what this app mints from what it accepts (StandardId::Oauth::Audiences).
548
631
  field :allowed_audiences, type: :array, default: -> { [] }
549
632
 
633
+ # Audiences this app may issue tokens for: every /oauth/token grant
634
+ # (authorization-code exchange, client_credentials, password, refresh, …),
635
+ # StandardId::TokenMinter and the API step-up re-mint refuse any other.
636
+ # nil (default) = `allowed_audiences`. An identity provider that mints
637
+ # per-service tokens lists those services here without accepting them on
638
+ # its own API (see `accepted_audiences`).
639
+ field :mintable_audiences, type: :array, default: nil
640
+
641
+ # Audiences the API token manager accepts in a bearer's `aud` at decode
642
+ # time; any other is an invalid token (401). nil (default) =
643
+ # `allowed_audiences`. Empty = no decode-time audience check (warned about
644
+ # at boot in production). The Web (cookie) token manager reads no JWT, so
645
+ # neither list applies to it.
646
+ field :accepted_audiences, type: :array, default: nil
647
+
550
648
  # Audience → profile type binding (first-class audience modeling).
551
649
  #
552
650
  # Maps each configured audience string to the profile type (or types)
@@ -31,7 +31,7 @@ module StandardId
31
31
 
32
32
  password_credential = EmailPassword.find_password_credential(email)
33
33
  unless password_credential
34
- BCrypt::Password.new(DUMMY_PASSWORD_DIGEST.value).is_password?(password)
34
+ StandardId::PasswordPepper.dummy_authenticate(password)
35
35
  failed!(email)
36
36
  end
37
37
 
@@ -1,5 +1,3 @@
1
- require "concurrent/delay"
2
-
3
1
  module StandardId
4
2
  # Email + password sign-up and sign-in for JSON clients
5
3
  # (Api::EmailPasswordController), switched on with
@@ -30,8 +28,9 @@ module StandardId
30
28
  module EmailPassword
31
29
  # A digest to compare against when no credential exists, so a miss costs
32
30
  # the same bcrypt work as a hit and timing does not reveal whether the
33
- # address is registered.
34
- DUMMY_PASSWORD_DIGEST = Concurrent::Delay.new { BCrypt::Password.create("").freeze }
31
+ # address is registered. Compared through PasswordPepper.dummy_authenticate,
32
+ # once per pepper a real digest would be tried under.
33
+ DUMMY_PASSWORD_DIGEST = StandardId::PasswordPepper::DUMMY_DIGEST
35
34
 
36
35
  # Identifier#signup_source of a sign-up made through Registration. A reset
37
36
  # runs `after_email_verified` only for these, and
@@ -83,7 +82,7 @@ module StandardId
83
82
  password = password.to_s
84
83
  password_credential = find_password_credential(email)
85
84
  unless password_credential
86
- BCrypt::Password.new(DUMMY_PASSWORD_DIGEST.value).is_password?(password)
85
+ StandardId::PasswordPepper.dummy_authenticate(password)
87
86
  return nil
88
87
  end
89
88
  return nil if password.empty? || !password_credential.authenticate(password)
@@ -157,18 +157,20 @@ module StandardId
157
157
  end
158
158
  private_class_method :host_secret_key_base
159
159
 
160
- # Logs a production-only warning when no global audience allow-list is
161
- # configured. With `allowed_audiences` empty, the API token manager
162
- # skips decode-time aud enforcement, leaving cross-audience JWT replay
163
- # mitigation dependent on per-controller `AudienceVerification`
164
- # inclusion. Extracted to a module method so specs can exercise it
165
- # directly without booting a second Rails app.
160
+ # Logs a production-only warning when the effective accepted audiences
161
+ # (`accepted_audiences`, else `allowed_audiences`) are empty. Then the API
162
+ # token manager skips decode-time aud enforcement, leaving cross-audience
163
+ # JWT replay mitigation dependent on per-controller
164
+ # `AudienceVerification` inclusion. Setting only `mintable_audiences`
165
+ # does not silence it. Extracted to a module method so specs can exercise
166
+ # it directly without booting a second Rails app.
166
167
  def self.warn_if_allowed_audiences_empty_in_production!
167
168
  return unless StandardId::AppEnvironment.production?
168
- return if StandardId.config.oauth.allowed_audiences.present?
169
+ return if StandardId::Oauth::Audiences.accepted.present?
169
170
 
171
+ setting = StandardId.config.oauth.accepted_audiences.nil? ? "allowed_audiences" : "accepted_audiences"
170
172
  Rails.logger.warn(
171
- "StandardId: config.oauth.allowed_audiences is empty in production — " \
173
+ "StandardId: config.oauth.#{setting} is empty in production — " \
172
174
  "JWT audience is not enforced globally. Set this to your expected " \
173
175
  "audiences (e.g., ['web', 'api']) to close cross-audience replay vectors."
174
176
  )
@@ -6,6 +6,22 @@ module StandardId
6
6
  class ExpiredSessionError < InvalidSessionError; end
7
7
  class RevokedSessionError < InvalidSessionError; end
8
8
 
9
+ # The session is valid but did not prove the account's identity recently
10
+ # enough for this action (require_recent_authentication!). Not an
11
+ # InvalidSessionError: signing in again is not the remedy, a step-up is, and
12
+ # a host's `rescue_from InvalidSessionError` must not swallow it into a
13
+ # sign-out. ApiAuthentication renders it as RFC 9470's
14
+ # `insufficient_user_authentication` challenge.
15
+ class StepUpRequiredError < StandardError
16
+ # @return [Integer] the age, in seconds, the authentication may have
17
+ attr_reader :max_age
18
+
19
+ def initialize(message = "A more recent authentication is required", max_age: nil)
20
+ @max_age = max_age&.to_i
21
+ super(message)
22
+ end
23
+ end
24
+
9
25
  # Account errors
10
26
  #
11
27
  # These deliberately do NOT descend from InvalidSessionError, even though
@@ -188,6 +204,48 @@ module StandardId
188
204
  def oauth_error_code = :invalid_client_metadata
189
205
  end
190
206
 
207
+ # The host's `config.network_wrapper` refused a provider request itself (an
208
+ # open circuit breaker, say), as opposed to the request failing in transit:
209
+ # StandardId::NetworkWrapper raises it in place of the wrapper's own error,
210
+ # which stays reachable as `cause` (see NetworkWrapper for the rules). An
211
+ # error the request raises and the wrapper re-raises unchanged (a timeout,
212
+ # a refused connection) is never turned into it; it reaches the provider as
213
+ # it always has. Nor are programming errors in the wrapper, or an error the
214
+ # wrapper raises after the request went through.
215
+ #
216
+ # An OAuthError, so a sign-in that hits it takes the ordinary failure path:
217
+ # the web callback redirects to the login page with the message, and the
218
+ # API renders `temporarily_unavailable` with HTTP 503 (RFC 6749 §4.1.2.1).
219
+ # The message names only the provider, never the wrapper's error, which may
220
+ # carry circuit names or host internals. Plugins map it to their own
221
+ # unavailable error where they have one.
222
+ class ProviderUnavailableError < OAuthError
223
+ # Providers no user would recognise, so the message names none:
224
+ # HttpClient::DEFAULT_PROVIDER, which HttpClient passes when its caller
225
+ # names no provider. Kept here rather than read from HttpClient so the
226
+ # error has no load-order or stubbing dependency on it.
227
+ UNNAMED_PROVIDERS = [:standard_id].freeze
228
+
229
+ # @return [Symbol, nil] the provider the request was for (`:google`, ...)
230
+ attr_reader :provider
231
+
232
+ def initialize(message = nil, provider: nil)
233
+ @provider = provider
234
+ super(message || "#{provider_label(provider)} is temporarily unavailable")
235
+ end
236
+
237
+ def oauth_error_code = :temporarily_unavailable
238
+ def http_status = :service_unavailable
239
+
240
+ private
241
+
242
+ def provider_label(provider)
243
+ return "The provider" if provider.nil? || UNNAMED_PROVIDERS.include?(provider.to_sym)
244
+
245
+ provider.to_s.humanize
246
+ end
247
+ end
248
+
191
249
  # Lifecycle hook errors
192
250
  class AuthenticationDenied < StandardError; end
193
251
 
@@ -11,6 +11,11 @@ module StandardId
11
11
  # config.login_method_policy refused the method for the account, after
12
12
  # the credential was proven and before any session was created.
13
13
  AUTHENTICATION_METHOD_DENIED = "authentication.method.denied"
14
+ # Step-up authentication (StandardId::StepUp): a code was issued to a
15
+ # signed-in account, the account re-proved its identity, or it did not.
16
+ STEP_UP_STARTED = "authentication.step_up.started"
17
+ STEP_UP_SUCCEEDED = "authentication.step_up.succeeded"
18
+ STEP_UP_FAILED = "authentication.step_up.failed"
14
19
 
15
20
  SESSION_CREATING = "session.creating"
16
21
  SESSION_CREATED = "session.created"
@@ -70,8 +75,9 @@ module StandardId
70
75
  CREDENTIAL_PASSWORD_RESET_INITIATED = "credential.password.reset_initiated"
71
76
  CREDENTIAL_PASSWORD_RESET_COMPLETED = "credential.password.reset_completed"
72
77
  CREDENTIAL_PASSWORD_CHANGED = "credential.password.changed"
73
- # A login re-hashed the password at the current bcrypt cost
74
- # (PasswordCredential#rehash_password). The password itself is unchanged.
78
+ # A login re-hashed the password at the current bcrypt cost or under the
79
+ # current c.password.pepper (PasswordCredential#rehash_password). The
80
+ # password itself is unchanged.
75
81
  CREDENTIAL_PASSWORD_REHASHED = "credential.password.rehashed"
76
82
  CREDENTIAL_CLIENT_SECRET_CREATED = "credential.client_secret.created"
77
83
  CREDENTIAL_CLIENT_SECRET_ROTATED = "credential.client_secret.rotated"
@@ -85,7 +91,10 @@ module StandardId
85
91
  PASSWORD_VALIDATION_FAILED,
86
92
  OTP_VALIDATED,
87
93
  OTP_VALIDATION_FAILED,
88
- AUTHENTICATION_METHOD_DENIED
94
+ AUTHENTICATION_METHOD_DENIED,
95
+ STEP_UP_STARTED,
96
+ STEP_UP_SUCCEEDED,
97
+ STEP_UP_FAILED
89
98
  ].freeze
90
99
 
91
100
  SESSION_EVENTS = [
@@ -172,6 +181,8 @@ module StandardId
172
181
  PASSWORD_VALIDATION_FAILED,
173
182
  OTP_VALIDATION_FAILED,
174
183
  AUTHENTICATION_METHOD_DENIED,
184
+ STEP_UP_SUCCEEDED,
185
+ STEP_UP_FAILED,
175
186
  # Session
176
187
  SESSION_CREATED,
177
188
  SESSION_REVOKED,