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,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
@@ -27,6 +27,13 @@ module StandardId
27
27
  CALLABLE_FIELDS = {
28
28
  "profile_resolver" => { signature: "(account, profile_type)", arity: 2, kind: :positional },
29
29
  "sentry_context" => { signature: "(account, session)", arity: 2, kind: :positional },
30
+ "error_reporter" => { signature: "(error, context)", arity: 2, kind: :positional },
31
+ "network_wrapper" => {
32
+ signature: "(provider:, &block)",
33
+ kind: :keyword,
34
+ keywords: %i[provider],
35
+ block: true
36
+ },
30
37
  "after_account_created" => { signature: "(account, request, context)", arity: 3, kind: :positional },
31
38
  "before_sign_in" => { signature: "(account, request, context)", arity: 3, kind: :positional },
32
39
  "after_sign_in" => { signature: "(account, request, context)", arity: 3, kind: :positional },
@@ -142,6 +149,21 @@ module StandardId
142
149
  when :positional then validate_positional!(path, callable, spec)
143
150
  when :keyword then validate_keyword!(path, callable, spec[:keywords], spec[:signature])
144
151
  end
152
+ validate_block_param!(path, callable, spec[:signature]) if spec[:block]
153
+ end
154
+
155
+ # A wrapper callable (network_wrapper) runs the work it is handed as a
156
+ # block. A Proc can only receive that block through an explicit `&`
157
+ # parameter; without one the block is dropped and the work never runs.
158
+ # (A method or `#call` object can `yield` without declaring it, so only
159
+ # Procs are checked.)
160
+ def validate_block_param!(path, callable, signature)
161
+ return unless callable.is_a?(Proc)
162
+ return if callable.parameters.any? { |type, _| type == :block }
163
+
164
+ raise StandardId::ConfigurationError,
165
+ "StandardId config: `#{path}` must take the wrapped work as a block " \
166
+ "(e.g. `->(provider:, &block) { block.call }`). Expected signature #{signature}."
145
167
  end
146
168
 
147
169
  def validate_positional!(path, callable, spec)
@@ -205,10 +227,11 @@ module StandardId
205
227
 
206
228
  # EmailPassword.call_hook passes only the keywords a hook declares, so a
207
229
  # lambda with a required positional argument (`->(request) { }`) would
208
- # raise on its first call. Limited to the email_password hooks, which
209
- # are new: older keyword hooks keep accepting what they always did.
230
+ # raise on its first call. Limited to the email_password hooks and
231
+ # network_wrapper, which are new: older keyword hooks keep accepting
232
+ # what they always did.
210
233
  def validate_no_required_positional!(path, callable, params, signature)
211
- return unless path.start_with?("email_password.") && lambda_callable?(callable)
234
+ return unless (path.start_with?("email_password.") || path == "network_wrapper") && lambda_callable?(callable)
212
235
  return unless params.any? { |type, _| type == :req }
213
236
 
214
237
  raise StandardId::ConfigurationError,
@@ -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.
@@ -162,6 +169,32 @@ StandardId::ConfigSchema.define do
162
169
  # Raise StandardId::LoginMethodDenied.new("message") to refuse with your own.
163
170
  # nil (the default) allows every method, i.e. no behaviour change.
164
171
  field :login_method_policy, type: :any, default: nil
172
+
173
+ # network_wrapper: wraps every outbound HTTP connection StandardId::HttpClient
174
+ # makes (social-provider token, userinfo and JWKS calls), e.g. in a circuit
175
+ # breaker or a tracing span.
176
+ # Receives: provider: (Symbol — :google, :apple, ...; :standard_id when the
177
+ # caller names none) and a block that performs the request.
178
+ # Must call the block and return its result. Whatever the block raises
179
+ # (timeouts, refused connections) raises inside the wrapper; whatever the
180
+ # wrapper raises reaches the caller unchanged.
181
+ # nil (the default) runs the block directly.
182
+ #
183
+ # c.network_wrapper = ->(provider:, &b) { StandardCircuit.run(:"oauth_#{provider}", &b) }
184
+ field :network_wrapper, type: :any, default: nil
185
+
186
+ # error_reporter: receives errors StandardId handles and carries on from —
187
+ # today, an event subscriber that raised after the change it reports had
188
+ # already committed (a completed password reset, a password rehash, a
189
+ # social link).
190
+ # Receives: (error, context), where context is a Hash with at least
191
+ # source: "standard_id" and handled: true, and may also name
192
+ # what failed (event:, action:).
193
+ # nil (the default) reports to Rails.error, as StandardId always has:
194
+ # `Rails.error.report(error, handled: true, source: "standard_id")`.
195
+ #
196
+ # c.error_reporter = ->(error, context) { Sentry.capture_exception(error, extra: context) }
197
+ field :error_reporter, type: :any, default: nil
165
198
  end
166
199
 
167
200
  scope :events do
@@ -327,6 +360,34 @@ StandardId::ConfigSchema.define do
327
360
  # signs that user out of remember-me cookies and voids their reset links.
328
361
  # See StandardId::PasswordCredential#rehash_password.
329
362
  field :rehash_on_login, type: :boolean, default: true
363
+ # A secret mixed into every password before bcrypt, as
364
+ # bcrypt(HMAC-SHA256(pepper, password)), so the digests cannot be cracked
365
+ # from a database dump alone. nil (default) hashes the bare password, as
366
+ # has_secure_password always has. Read it from credentials, never from
367
+ # source; at least 32 random bytes (`SecureRandom.hex(32)`).
368
+ #
369
+ # LOSING THE PEPPER FORCES EVERY PASSWORD HASHED UNDER IT TO BE RESET:
370
+ # there is no way to verify those digests without it.
371
+ #
372
+ # Turning it on locks nobody out: existing (unpeppered) digests still
373
+ # verify, and each user's next password login re-hashes under the pepper
374
+ # (needs rehash_on_login). See StandardId::PasswordPepper and the README,
375
+ # "Password pepper".
376
+ field :pepper, type: :string, default: nil
377
+ # Peppers that were current before, newest first, still ACCEPTED when
378
+ # verifying a password; a login that matches one re-hashes under the
379
+ # current pepper. To rotate, move the old pepper here and set the new one.
380
+ # Keep an entry until no digest made under it can be left (every user has
381
+ # signed in since, or the rest have reset); dropping it early forces those
382
+ # users to reset. Each entry costs one more bcrypt comparison on a wrong
383
+ # password.
384
+ field :previous_peppers, type: :array, default: -> { [] }
385
+ # Whether a password with no pepper still verifies while a pepper is set:
386
+ # digests made before the pepper was turned on. On by default so turning
387
+ # it on locks nobody out. Turn it off only once no unpeppered digest can be
388
+ # left, or those users must reset; it saves one bcrypt comparison per
389
+ # wrong password. Ignored while no pepper is set.
390
+ field :accept_unpeppered_passwords, type: :boolean, default: true
330
391
  # Who tells the owner, by email, that their password was changed or reset
331
392
  # (CREDENTIAL_PASSWORD_CHANGED):
332
393
  # :custom — (default) the engine sends nothing; subscribe to the event
@@ -338,6 +399,45 @@ StandardId::ConfigSchema.define do
338
399
  field :changed_notice_delivery, type: :symbol, default: :custom
339
400
  end
340
401
 
402
+ # Step-up (recent) authentication: `require_recent_authentication!` in web
403
+ # and API controllers, and the flow that re-proves identity with a fresh
404
+ # one-time code (and the password, where the account has one). Off by
405
+ # default: the step-up routes 404, access tokens carry no `auth_time`, and
406
+ # nothing changes unless a controller calls the guard. See StandardId::StepUp
407
+ # and the README, "Step-up authentication".
408
+ scope :step_up do
409
+ # Draws the step-up endpoints (web /step_up, API /step_up and
410
+ # /step_up/verify) and adds the OIDC `auth_time` claim to access tokens.
411
+ # The guard refuses to run while this is false.
412
+ field :enabled, type: :boolean, default: false
413
+ # The default `within:` of require_recent_authentication!, in seconds.
414
+ field :max_age, type: :integer, default: 300
415
+ # The StandardId::Otp realm step-up codes are issued and verified in, kept
416
+ # apart from sign-in codes so one can never stand in for the other.
417
+ field :realm, type: :string, default: "step_up"
418
+ # How the code is delivered (StandardId::Otp delivery modes):
419
+ # :built_in — (default) follow c.passwordless.delivery: the engine's
420
+ # PasswordlessMailer when that is :built_in, else your
421
+ # PASSWORDLESS_CODE_GENERATED subscriber (realm "step_up")
422
+ # :custom — always your subscriber, so the message can say why
423
+ field :delivery, type: :symbol, default: :built_in
424
+ # Also ask for the password when the account has one. Off only for hosts
425
+ # whose second factor is the code alone.
426
+ field :require_password, type: :boolean, default: true
427
+ # Where the web guard sends a stale session. nil (default) is "/step_up",
428
+ # the web engine's page when it is mounted at "/"; set it when the engine
429
+ # is mounted elsewhere or the host draws its own page.
430
+ field :url, type: :string, default: nil
431
+ # The profile the API step-up re-mints the access token for, when its
432
+ # audience is bound to a profile type (oauth.audience_profile_types) and
433
+ # the account may hold several: a callable taking `account:` and
434
+ # `claims:` (the current token's decoded claims, e.g. your own `gid`)
435
+ # and returning the profile, passed to TokenMinter.mint(profile:). nil
436
+ # (default) uses the strict audience → profile lookup, which refuses an
437
+ # account with several active profiles of the bound type.
438
+ field :token_profile_resolver, type: :any, default: nil
439
+ end
440
+
341
441
  scope :reset_password do
342
442
  # Password reset email delivery mode:
343
443
  # :custom — (default) host app handles delivery via event subscriber for
@@ -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
 
@@ -146,7 +146,7 @@ module StandardId
146
146
  account: account
147
147
  )
148
148
  rescue StandardError => e
149
- Rails.error.report(e, handled: true, source: "standard_id")
149
+ StandardId::ErrorReporting.report(e, event: StandardId::Events.namespaced_event_name(StandardId::Events::CREDENTIAL_PASSWORD_RESET_COMPLETED))
150
150
  logger = StandardId.logger
151
151
  return unless logger.respond_to?(:error)
152
152
 
@@ -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)
@@ -0,0 +1,38 @@
1
+ module StandardId
2
+ # Reports an error StandardId has handled and is carrying on from (see
3
+ # `config.error_reporter`). Every such report goes through here, so a host
4
+ # that routes them elsewhere catches all of them.
5
+ module ErrorReporting
6
+ SOURCE = "standard_id".freeze
7
+
8
+ module_function
9
+
10
+ # Without a configured reporter this is exactly the call the engine has
11
+ # always made, `Rails.error.report(error, handled: true, source:
12
+ # "standard_id")`; `context` goes only to a configured reporter.
13
+ #
14
+ # Every caller is a rescue that carries on, so a configured reporter that
15
+ # raises is logged and the error goes to the default report instead.
16
+ #
17
+ # @param error [Exception]
18
+ # @param context [Hash] extra detail for a configured reporter, e.g. the
19
+ # event whose subscriber raised
20
+ # @return [void]
21
+ def report(error, context = {})
22
+ reporter = StandardId.config.error_reporter
23
+ return report_to_rails(error) unless reporter.respond_to?(:call)
24
+
25
+ begin
26
+ reporter.call(error, context.merge(source: SOURCE, handled: true))
27
+ rescue StandardError => e
28
+ Rails.logger&.error("[StandardId] error_reporter raised #{e.class}: #{e.message}; reporting #{error.class} to Rails.error instead")
29
+ report_to_rails(error)
30
+ end
31
+ end
32
+
33
+ def report_to_rails(error)
34
+ Rails.error.report(error, handled: true, source: SOURCE)
35
+ end
36
+ private_class_method :report_to_rails
37
+ end
38
+ end
@@ -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
@@ -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,
@@ -34,7 +34,9 @@ module StandardId
34
34
  return unless self.class.handles?(event.payload)
35
35
 
36
36
  identifier = event[:identifier]
37
- challenge = event[:code_challenge]
37
+ # The record, or (under events.publish_records = false) the one
38
+ # being published, from CodeHandoff.
39
+ challenge = StandardId::Passwordless::CodeHandoff.challenge_for(event)
38
40
  code = challenge&.code
39
41
 
40
42
  return if identifier.blank? || code.blank?
@@ -6,7 +6,54 @@ module StandardId
6
6
  # Event namespace prefix for all StandardId events
7
7
  NAMESPACE = "standard_id"
8
8
 
9
+ # Event names worth an audit row, as Regexps and full Strings that both
10
+ # ActiveSupport::Notifications and standard_audit's `subscribe_to` accept.
11
+ # See `.auditable`.
12
+ AUDITABLE = [
13
+ # What the apps subscribed to before this list existed.
14
+ /\Astandard_id\.authentication\./,
15
+ "#{NAMESPACE}.#{SESSION_CREATED}",
16
+ "#{NAMESPACE}.#{SESSION_REVOKED}",
17
+ "#{NAMESPACE}.#{SESSION_EXPIRED}",
18
+ /\Astandard_id\.account\./,
19
+ /\Astandard_id\.social\./,
20
+ /\Astandard_id\.passwordless\./,
21
+ # Changes to how an account or client authenticates. (Not
22
+ # CREDENTIAL_PASSWORD_REHASHED: the password itself is unchanged.)
23
+ "#{NAMESPACE}.#{CREDENTIAL_PASSWORD_CREATED}",
24
+ "#{NAMESPACE}.#{CREDENTIAL_PASSWORD_RESET_INITIATED}",
25
+ "#{NAMESPACE}.#{CREDENTIAL_PASSWORD_RESET_COMPLETED}",
26
+ "#{NAMESPACE}.#{CREDENTIAL_PASSWORD_CHANGED}",
27
+ "#{NAMESPACE}.#{CREDENTIAL_CLIENT_SECRET_CREATED}",
28
+ "#{NAMESPACE}.#{CREDENTIAL_CLIENT_SECRET_ROTATED}",
29
+ "#{NAMESPACE}.#{CREDENTIAL_CLIENT_SECRET_REVOKED}",
30
+ # OAuth: token theft and revocation, a token sent to the wrong resource,
31
+ # and changes to who may request tokens at all.
32
+ "#{NAMESPACE}.#{OAUTH_REFRESH_TOKEN_REUSE_DETECTED}",
33
+ "#{NAMESPACE}.#{OAUTH_TOKEN_REVOKED}",
34
+ "#{NAMESPACE}.#{OAUTH_AUDIENCE_MISMATCH}",
35
+ "#{NAMESPACE}.#{OAUTH_CLIENT_REGISTERED}",
36
+ "#{NAMESPACE}.#{OAUTH_CLIENT_UPDATED}",
37
+ "#{NAMESPACE}.#{OAUTH_CLIENT_DEREGISTERED}"
38
+ ].map(&:freeze).freeze
39
+
9
40
  class << self
41
+ # The event names a host should persist to its audit log:
42
+ #
43
+ # StandardAudit.configure do |config|
44
+ # StandardId::Events.auditable.each { |pattern| config.subscribe_to(pattern) }
45
+ # end
46
+ #
47
+ # Deliberately left out: per-request noise (session.validating /
48
+ # validated), high-volume token minting (oauth.token.issued,
49
+ # oauth.token.refreshed), and the benign refresh race
50
+ # (oauth.refresh_token.reuse_graced).
51
+ #
52
+ # @return [Array<Regexp, String>] frozen
53
+ def auditable
54
+ AUDITABLE
55
+ end
56
+
10
57
  # Publish an event with the given name and payload
11
58
  #
12
59
  # @param event_name [String, Symbol] The event name (use constants from Definitions)
@@ -0,0 +1,27 @@
1
+ # What StandardId offers standard_health, through its load hook. There is no
2
+ # dependency either way: without standard_health (or with a version older than
3
+ # the hook) the block never runs. With it, the block runs once, whichever gem
4
+ # is required first, and receives standard_health's contribution registry,
5
+ # which exposes only `contribute_check` and `contribute_env_vars`.
6
+ #
7
+ # Apps still decide: the check registers through `register_default_checks`
8
+ # (opt out with `standard_id_migrations: false`), and an env var the app
9
+ # declares in its own env_spec wins over the declaration here.
10
+ ActiveSupport.on_load(:standard_health) do |health|
11
+ # Resolved by name when the check runs, so nothing here loads it early.
12
+ health.contribute_check :standard_id_migrations, "StandardId::Checks::Migrations", critical: false
13
+
14
+ # APP_ENVIRONMENT is the one deploy variable StandardId reads itself.
15
+ # STANDARD_ID_BYPASS_CODE it never reads, but its production guard names it
16
+ # and the apps feed c.passwordless.bypass_code from it. Provider credentials (GOOGLE_CLIENT_ID, APPLE_PRIVATE_KEY, ...) are not
17
+ # declared here: which apply depends on the plugins an app registers.
18
+ health.contribute_env_vars "standard_id" do
19
+ recommended :APP_ENVIRONMENT,
20
+ description: "Decides StandardId's production-only guards (the bypass-code refusal, the empty " \
21
+ "allowed_audiences warning, provider_misconfiguration = :raise). Any value other than staging, " \
22
+ "preview, development or test counts as production; unset falls back to Rails.env"
23
+ forbidden :STANDARD_ID_BYPASS_CODE, in: %w[production],
24
+ description: "Conventional source for c.passwordless.bypass_code, a fixed OTP for e2e tests. StandardId " \
25
+ "refuses to verify any code in production while a bypass code is configured"
26
+ end
27
+ end
@@ -23,19 +23,33 @@ module StandardId
23
23
  IPAddr.new("fe80::/10")
24
24
  ].freeze
25
25
 
26
+ # Provider name passed to `StandardId.config.network_wrapper` when a caller
27
+ # does not name one.
28
+ DEFAULT_PROVIDER = :standard_id
29
+
26
30
  class << self
27
- def post_form(endpoint, params)
31
+ # `provider:` names the remote service (`:google`, `:apple`, ...) for
32
+ # `StandardId.config.network_wrapper`, e.g. to keep one circuit per
33
+ # provider. It has no other effect on the request.
34
+ #
35
+ # The form may also come as bare keywords (`post_form(url, id_token: t)`),
36
+ # which is how callers written before `provider:` existed pass it: once
37
+ # the method takes a keyword, Ruby reads a braceless Hash as keywords, so
38
+ # `**form` keeps those calls working. A form field named `provider` must
39
+ # therefore go in an explicit Hash. With no bare keywords, `params` goes
40
+ # to `set_form_data` as given, so an Array of pairs keeps repeated keys.
41
+ def post_form(endpoint, params = nil, provider: DEFAULT_PROVIDER, **form)
28
42
  uri, resolved_ip = validate_url!(endpoint)
29
43
  request = Net::HTTP::Post.new(uri)
30
- request.set_form_data(params)
31
- start_connection(uri, resolved_ip:) { |http| http.request(request) }
44
+ request.set_form_data(form.empty? ? (params || {}) : (params || {}).to_h.merge(form))
45
+ start_connection(uri, resolved_ip:, provider:) { |http| http.request(request) }
32
46
  end
33
47
 
34
- def get_with_bearer(endpoint, access_token)
48
+ def get_with_bearer(endpoint, access_token, provider: DEFAULT_PROVIDER)
35
49
  uri, resolved_ip = validate_url!(endpoint)
36
50
  request = Net::HTTP::Get.new(uri)
37
51
  request["Authorization"] = "Bearer #{access_token}"
38
- start_connection(uri, resolved_ip:) { |http| http.request(request) }
52
+ start_connection(uri, resolved_ip:, provider:) { |http| http.request(request) }
39
53
  end
40
54
 
41
55
  private
@@ -59,7 +73,26 @@ module StandardId
59
73
  [uri, addresses.first]
60
74
  end
61
75
 
62
- def start_connection(uri, resolved_ip: nil, &block)
76
+ # Private, but provider plugins call it through `send` to fetch a JWKS
77
+ # with a plain GET, so its signature is part of the plugin contract:
78
+ # `provider:` is optional and new keywords must stay optional.
79
+ def start_connection(uri, resolved_ip: nil, provider: DEFAULT_PROVIDER, &block)
80
+ with_network_wrapper(provider) { open_connection(uri, resolved_ip:, &block) }
81
+ end
82
+
83
+ # Runs the block through `StandardId.config.network_wrapper`, or
84
+ # directly when none is configured. The wrapper sees the whole
85
+ # connection (connect, request, response), so a timeout or refused
86
+ # connection raises inside it; whatever it raises or returns is the
87
+ # caller's.
88
+ def with_network_wrapper(provider, &block)
89
+ wrapper = StandardId.config.network_wrapper
90
+ return yield unless wrapper.respond_to?(:call)
91
+
92
+ wrapper.call(**StandardId::Utils::CallableParameterFilter.filter(wrapper, { provider: provider&.to_sym }), &block)
93
+ end
94
+
95
+ def open_connection(uri, resolved_ip: nil, &block)
63
96
  http = Net::HTTP.new(uri.host, uri.port)
64
97
  http.use_ssl = (uri.scheme == "https")
65
98
  http.verify_mode = OpenSSL::SSL::VERIFY_PEER if http.use_ssl?