standard_id 0.61.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 (43) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +76 -0
  3. data/README.md +163 -20
  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/web_authentication.rb +29 -7
  7. data/app/controllers/standard_id/api/step_up_controller.rb +92 -0
  8. data/app/controllers/standard_id/web/step_up_controller.rb +83 -0
  9. data/app/models/standard_id/client_application.rb +30 -1
  10. data/app/models/standard_id/password_credential.rb +76 -8
  11. data/app/models/standard_id/session.rb +45 -1
  12. data/app/views/standard_id/web/step_up/show.html.erb +65 -0
  13. data/config/brakeman.ignore +4 -0
  14. data/config/routes/api.rb +7 -0
  15. data/config/routes/web.rb +6 -0
  16. data/db/migrate/20261123000000_add_authenticated_at_to_standard_id_sessions.rb +15 -0
  17. data/lib/generators/standard_id/install/templates/standard_id_reference.rb +39 -5
  18. data/lib/standard_id/api/token_manager.rb +3 -0
  19. data/lib/standard_id/auth_lineage.rb +39 -8
  20. data/lib/standard_id/config/schema.rb +79 -5
  21. data/lib/standard_id/email_password/authentication.rb +1 -1
  22. data/lib/standard_id/email_password.rb +4 -5
  23. data/lib/standard_id/errors.rb +16 -0
  24. data/lib/standard_id/events/definitions.rb +14 -3
  25. data/lib/standard_id/events/subscribers/passwordless_delivery_subscriber.rb +3 -1
  26. data/lib/standard_id/jwt_service.rb +31 -2
  27. data/lib/standard_id/keyed_digest.rb +43 -5
  28. data/lib/standard_id/oauth/direct_mint_flow.rb +9 -3
  29. data/lib/standard_id/oauth/oauth_session_persistence.rb +24 -9
  30. data/lib/standard_id/oauth/password_flow.rb +4 -10
  31. data/lib/standard_id/oauth/token_grant_flow.rb +28 -3
  32. data/lib/standard_id/password_pepper.rb +88 -0
  33. data/lib/standard_id/passwordless/base_strategy.rb +5 -1
  34. data/lib/standard_id/passwordless/code_handoff.rb +72 -0
  35. data/lib/standard_id/passwordless.rb +25 -0
  36. data/lib/standard_id/step_up.rb +236 -0
  37. data/lib/standard_id/testing/otp_helpers.rb +5 -5
  38. data/lib/standard_id/testing/request_helpers.rb +8 -3
  39. data/lib/standard_id/token_minter.rb +6 -2
  40. data/lib/standard_id/version.rb +1 -1
  41. data/lib/standard_id/web/session_manager.rb +9 -2
  42. data/lib/standard_id.rb +2 -0
  43. metadata +8 -1
@@ -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.
@@ -0,0 +1,236 @@
1
+ module StandardId
2
+ # Step-up (recent) authentication: before a sensitive action, ask a
3
+ # signed-in account to prove its identity again unless it did so recently.
4
+ # The shape follows Rodauth's confirm_password / password_grace_period.
5
+ #
6
+ # When the account last proved its identity is tracked on what authenticates
7
+ # the request:
8
+ #
9
+ # * a BrowserSession or DeviceSession row: Session#authenticated_at, set by
10
+ # an interactive sign-in and by a step-up, never by remember-me (a cookie
11
+ # is not a fresh proof) or by a refresh;
12
+ # * a bearer access token: the OIDC `auth_time` claim, minted from the
13
+ # same time (the authorize step's browser session for an authorization
14
+ # code, the original grant for a refresh, now for a step-up).
15
+ #
16
+ # A host guards an action with `require_recent_authentication!(within:)`
17
+ # (WebAuthentication, ApiAuthentication). A stale web session is sent to the
18
+ # step-up page; a stale bearer token gets RFC 9470's
19
+ # `insufficient_user_authentication` challenge and steps up through the API.
20
+ #
21
+ # Re-proving identity takes a fresh one-time code from StandardId::Otp in its
22
+ # own realm (`c.step_up.realm`, never the sign-in realm), sent to the
23
+ # account's verified e-mail address or else its verified phone number, and,
24
+ # when the account has a password and `c.step_up.require_password` is on, the
25
+ # password too. The code is checked first, so each code buys at most one
26
+ # password guess.
27
+ #
28
+ # Off by default (`c.step_up.enabled`): nothing is drawn, minted or written
29
+ # differently until a host turns it on and calls the guard.
30
+ module StepUp
31
+ # The outcome of .start and .verify.
32
+ #
33
+ # - success?: true/false
34
+ # - channel: "email" or "sms", where the code went (nil when there is none)
35
+ # - error_code: on failure — :no_verified_identifier, :cooldown,
36
+ # :rate_limited, :invalid_request (from .start); :blank_code,
37
+ # :invalid_code, :max_attempts, :not_found, :server_error,
38
+ # :invalid_password (from .verify)
39
+ # - error_message: human-readable, safe to show the account's owner
40
+ Result = Data.define(:success?, :channel, :error_code, :error_message)
41
+
42
+ ERROR_MESSAGES = {
43
+ no_verified_identifier: "There is no verified e-mail address or phone number to send a code to",
44
+ invalid_password: "The password is incorrect",
45
+ invalid_code: "The code is invalid or has expired",
46
+ blank_code: "Please enter the code",
47
+ max_attempts: "Too many attempts. Please request a new code",
48
+ not_found: "The code is invalid or has expired"
49
+ }.freeze
50
+
51
+ module_function
52
+
53
+ def config
54
+ StandardId.config.step_up
55
+ end
56
+
57
+ def enabled?
58
+ config.enabled == true
59
+ end
60
+
61
+ def realm
62
+ config.realm.presence || "step_up"
63
+ end
64
+
65
+ # The default `within:` for require_recent_authentication!.
66
+ def max_age
67
+ config.max_age.to_i.seconds
68
+ end
69
+
70
+ def session_column?
71
+ StandardId::Session.column_names.include?("authenticated_at")
72
+ rescue ActiveRecord::ActiveRecordError
73
+ false
74
+ end
75
+
76
+ def refresh_token_column?
77
+ StandardId::RefreshToken.column_names.include?("authenticated_at")
78
+ rescue ActiveRecord::ActiveRecordError
79
+ false
80
+ end
81
+
82
+ # What the guard needs before it can answer at all. A guard that silently
83
+ # never passes (or always does) would be worse than one that says why.
84
+ #
85
+ # @raise [StandardId::ConfigurationError]
86
+ def ensure_usable!
87
+ unless enabled?
88
+ raise StandardId::ConfigurationError,
89
+ "require_recent_authentication! needs c.step_up.enabled = true (README, \"Step-up authentication\")"
90
+ end
91
+ return if session_column?
92
+
93
+ raise StandardId::ConfigurationError,
94
+ "c.step_up needs migration 20261123000000_add_authenticated_at_to_standard_id_sessions: " \
95
+ "run bin/rails standard_id:install:migrations && bin/rails db:migrate"
96
+ end
97
+
98
+ # When +session+ last proved the account's identity, or nil: a session
99
+ # row's #authenticated_at, or a decoded access token's `auth_time` claim.
100
+ #
101
+ # @return [Time, nil]
102
+ def authenticated_at(session)
103
+ return nil if session.nil?
104
+ return session.authenticated_at if session.respond_to?(:authenticated_at)
105
+ return nil unless session.respond_to?(:claims)
106
+
107
+ auth_time = session.claims.to_h.with_indifferent_access[:auth_time]
108
+ Time.at(Integer(auth_time)) if auth_time.present?
109
+ rescue ArgumentError, TypeError
110
+ nil
111
+ end
112
+
113
+ # Whether +session+ proved the account's identity within +within+ (a
114
+ # Duration or seconds). A time in the future counts as not recent.
115
+ def recent?(session, within: max_age)
116
+ at = authenticated_at(session)
117
+ return false if at.nil?
118
+
119
+ now = Time.current
120
+ at <= now && at >= now - within.to_i.seconds
121
+ end
122
+
123
+ # Records that +session+ (a session row) proved the account's identity at
124
+ # +at+. A single UPDATE: nothing else on the row changes.
125
+ def mark!(session, at: Time.current)
126
+ return unless session.is_a?(StandardId::Session) && session.persisted? && session_column?
127
+
128
+ session.update_columns(authenticated_at: at)
129
+ end
130
+
131
+ # Where a step-up code for +account+ goes: its verified e-mail identifier,
132
+ # else its verified phone number, else nil.
133
+ #
134
+ # @return [Array(String, String), nil] `[channel, target]`
135
+ def destination_for(account)
136
+ identifiers = StandardId::Identifier.where(account_id: account.id).where.not(verified_at: nil).order(:created_at).to_a
137
+ email = identifiers.find { |identifier| identifier.is_a?(StandardId::EmailIdentifier) }
138
+ return ["email", email.value] if email
139
+
140
+ phone = identifiers.find { |identifier| identifier.is_a?(StandardId::PhoneNumberIdentifier) }
141
+ ["sms", phone.value] if phone
142
+ end
143
+
144
+ # Whether the step-up for +account+ asks for its password as well.
145
+ def password_required?(account)
146
+ config.require_password && password_credentials(account).any?
147
+ end
148
+
149
+ # Issues a step-up code to +account+'s verified e-mail or phone and
150
+ # publishes STEP_UP_STARTED. A :cooldown failure means a code sent moments
151
+ # ago is still usable; nothing new was sent.
152
+ #
153
+ # @return [Result]
154
+ def start(account:, request: nil)
155
+ channel, target = destination_for(account)
156
+ return failure(account, :start, nil, :no_verified_identifier) if target.nil?
157
+
158
+ issued = StandardId::Otp.issue(
159
+ realm: realm,
160
+ target: target,
161
+ channel: channel.to_sym,
162
+ request: request,
163
+ delivery: config.delivery,
164
+ metadata: { "account_id" => account.id.to_s }
165
+ )
166
+ unless issued.success?
167
+ return Result.new(success?: false, channel: channel, error_code: issued.error_code, error_message: issued.error_message) if issued.error_code == :cooldown
168
+
169
+ return failure(account, :start, channel, issued.error_code, issued.error_message)
170
+ end
171
+
172
+ StandardId::Events.publish(StandardId::Events::STEP_UP_STARTED, account: account, channel: channel)
173
+ Result.new(success?: true, channel: channel, error_code: nil, error_message: nil)
174
+ end
175
+
176
+ # Checks a step-up: the code, then (when .password_required?) the
177
+ # password. Publishes STEP_UP_SUCCEEDED or STEP_UP_FAILED. Marking the
178
+ # session, or minting a fresh token, is the caller's job.
179
+ #
180
+ # @return [Result]
181
+ def verify(account:, code:, password: nil, request: nil)
182
+ channel, target = destination_for(account)
183
+ return failure(account, :verify, nil, :no_verified_identifier) if target.nil?
184
+
185
+ otp = StandardId::Otp.verify(realm: realm, target: target, channel: channel.to_sym, code: code.to_s.strip, request: request)
186
+ return failure(account, :verify, channel, otp.error_code || :invalid_code) unless otp.success?
187
+ # A code is only good for the account it was issued to.
188
+ return failure(account, :verify, channel, :invalid_code) unless issued_to?(otp.challenge, account)
189
+
190
+ methods = ["otp"]
191
+ if password_required?(account)
192
+ return failure(account, :verify, channel, :invalid_password) unless password_matches?(account, password)
193
+
194
+ methods << "password"
195
+ end
196
+
197
+ StandardId::Events.publish(StandardId::Events::STEP_UP_SUCCEEDED, account: account, channel: channel, methods: methods)
198
+ Result.new(success?: true, channel: channel, error_code: nil, error_message: nil)
199
+ end
200
+
201
+ def password_credentials(account)
202
+ StandardId::PasswordCredential
203
+ .joins(credential: :identifier)
204
+ .where(standard_id_identifiers: { account_id: account.id })
205
+ end
206
+
207
+ def password_matches?(account, password)
208
+ return false if password.blank?
209
+
210
+ password_credentials(account).any? { |credential| credential.authenticate(password) }
211
+ end
212
+
213
+ # The bypass code (non-production E2E only) verifies with no challenge.
214
+ def issued_to?(challenge, account)
215
+ return true if challenge.nil?
216
+
217
+ challenge.metadata.to_h["account_id"].to_s == account.id.to_s
218
+ end
219
+
220
+ def failure(account, stage, channel, error_code, error_message = nil)
221
+ StandardId::Events.publish(
222
+ StandardId::Events::STEP_UP_FAILED,
223
+ account: account,
224
+ stage: stage,
225
+ channel: channel,
226
+ error_code: error_code.to_s
227
+ )
228
+ Result.new(
229
+ success?: false,
230
+ channel: channel,
231
+ error_code: error_code,
232
+ error_message: ERROR_MESSAGES[error_code] || error_message || "Step-up failed"
233
+ )
234
+ end
235
+ end
236
+ end
@@ -5,10 +5,10 @@ module StandardId
5
5
  # A challenge stores only an HMAC of its code (migration 20261122000000),
6
6
  # so `StandardId::CodeChallenge.last.code` is nil once the row is read back
7
7
  # from the database. The raw code exists only on the record the engine has
8
- # just created, which it publishes as PASSWORDLESS_CODE_GENERATED's
9
- # `code_challenge:`; these helpers capture it from there, exactly as a
10
- # delivery subscriber does. (With `config.events.publish_records = false`
11
- # the record is not published, and there is nothing to capture.)
8
+ # just created; these helpers capture it from PASSWORDLESS_CODE_GENERATED
9
+ # with StandardId::Passwordless.issued_code, exactly as a delivery
10
+ # subscriber does, so they work whether or not
11
+ # `config.events.publish_records` publishes the record.
12
12
  #
13
13
  # Usage in rails_helper.rb:
14
14
  #
@@ -31,7 +31,7 @@ module StandardId
31
31
  def capture_otp_codes
32
32
  codes = []
33
33
  subscription = StandardId::Events.subscribe(StandardId::Events::PASSWORDLESS_CODE_GENERATED) do |event|
34
- code = event[:code_challenge]&.code
34
+ code = StandardId::Passwordless.issued_code(event)
35
35
  next if code.blank?
36
36
 
37
37
  codes << IssuedCode.new(identifier: event[:identifier], channel: event[:channel], realm: event[:realm], code: code)
@@ -19,13 +19,18 @@ module StandardId
19
19
  # @param user_agent [String] the user agent string (default: "RSpec")
20
20
  # @return [StandardId::BrowserSession] the created session
21
21
  #
22
- def create_browser_session(account, user_agent: "RSpec")
23
- StandardId::BrowserSession.create!(
22
+ # The session counts as a fresh sign-in for require_recent_authentication!
23
+ # (StandardId::StepUp); pass +authenticated_at:+ an older time, or nil, to
24
+ # exercise the step-up path.
25
+ def create_browser_session(account, user_agent: "RSpec", authenticated_at: Time.current)
26
+ attributes = {
24
27
  account: account,
25
28
  ip_address: "127.0.0.1",
26
29
  user_agent: user_agent,
27
30
  expires_at: StandardId::BrowserSession.expiry
28
- )
31
+ }
32
+ attributes[:authenticated_at] = authenticated_at if StandardId::StepUp.session_column?
33
+ StandardId::BrowserSession.create!(**attributes)
29
34
  end
30
35
 
31
36
  # Build a JWT token for API/service authentication.
@@ -78,15 +78,19 @@ module StandardId
78
78
  # A String is split on whitespace. Changes the event only, never the
79
79
  # token — so for a direct mint, the event's requested_scopes may be
80
80
  # caller-supplied rather than what the token's `scope` claim says.
81
+ # @param authenticated_at [Time, nil] when the host last saw the account
82
+ # prove its identity: the token's `auth_time` claim (under
83
+ # c.step_up.enabled) and the refresh token's authenticated_at. nil
84
+ # (default) claims nothing, so require_recent_authentication! refuses it.
81
85
  # @return [Result]
82
86
  def mint(account:, audience:, grant_type:, scopes: nil, client_id: nil, claims: {}, expires_in: nil,
83
87
  refresh_token: false, request: nil, auth_method: nil, auth_provider: nil, profile: nil, audit_errors: :raise,
84
- requested_scopes: nil)
88
+ requested_scopes: nil, authenticated_at: nil)
85
89
  flow = StandardId::Oauth::DirectMintFlow.new(
86
90
  account: account, audience: audience, grant_type: grant_type, scopes: scopes, client_id: client_id,
87
91
  claims: claims, expires_in: expires_in, refresh_token: refresh_token, request: request,
88
92
  auth_method: auth_method, auth_provider: auth_provider, profile: profile, audit_errors: audit_errors,
89
- requested_scopes: requested_scopes
93
+ requested_scopes: requested_scopes, authenticated_at: authenticated_at
90
94
  )
91
95
  response = flow.execute
92
96
  Result.new(
@@ -1,3 +1,3 @@
1
1
  module StandardId
2
- VERSION = "0.61.0"
2
+ VERSION = "0.62.0"
3
3
  end
@@ -71,6 +71,9 @@ module StandardId
71
71
  lineage = StandardId::AuthLineage.build(auth_method || :unspecified, provider)
72
72
  token_manager.create_browser_session(account, auth_lineage: lineage).tap do |browser_session|
73
73
  @created_session = browser_session
74
+ # An interactive sign-in proves the account's identity now
75
+ # (StandardId::StepUp). Remember-me, below, does not.
76
+ StandardId::StepUp.mark!(browser_session)
74
77
  # Store in both session and encrypted cookie for backward compatibility
75
78
  # Action Cable will use the encrypted cookie
76
79
  session[:session_token] = browser_session.token
@@ -219,7 +222,9 @@ module StandardId
219
222
  session_token ||= session[:session_token] if rails_session_loaded? || rails_session_cookie_present?
220
223
  return if session_token.blank?
221
224
 
222
- StandardId::BrowserSession.eager_load(:account).by_token(session_token).first
225
+ browser_session = StandardId::BrowserSession.eager_load(:account).by_token(session_token).first
226
+ browser_session.rekey_token(session_token) if browser_session&.active?
227
+ browser_session
223
228
  end
224
229
 
225
230
  def load_session_from_remember_token
@@ -253,7 +258,9 @@ module StandardId
253
258
  @reset_session&.call
254
259
 
255
260
  # Recorded as :remember_me, the method the policy approved above, so
256
- # tokens later derived from this session are re-checked as such.
261
+ # tokens later derived from this session are re-checked as such. No
262
+ # authenticated_at: a cookie is not a fresh proof of identity, so a
263
+ # step-up guard asks a remembered visitor to step up.
257
264
  lineage = StandardId::AuthLineage.build(:remember_me)
258
265
  token_manager.create_browser_session(password_credential.account, auth_lineage: lineage).tap do |browser_session|
259
266
  # Store in both session and encrypted cookie for backward compatibility
data/lib/standard_id.rb CHANGED
@@ -18,6 +18,7 @@ require "standard_id/health_contributions"
18
18
  require "standard_id/errors"
19
19
  require "standard_id/error_reporting"
20
20
  require "standard_id/keyed_digest"
21
+ require "standard_id/password_pepper"
21
22
  require "standard_id/events"
22
23
  require "standard_id/events/subscribers/base"
23
24
  require "standard_id/events/subscribers/logging_subscriber"
@@ -41,6 +42,7 @@ require "standard_id/api/authentication_guard"
41
42
  require "standard_id/utils/callable_parameter_filter"
42
43
  require "standard_id/login_method_policy"
43
44
  require "standard_id/auth_lineage"
45
+ require "standard_id/step_up"
44
46
  require "standard_id/account_cleanup"
45
47
  require "standard_id/oauth/audience_profile_resolver"
46
48
  require "standard_id/oauth/audience_scope_resolver"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: standard_id
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.61.0
4
+ version: 0.62.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Rarebit One
@@ -162,6 +162,7 @@ files:
162
162
  - app/controllers/standard_id/api/oidc/logout_controller.rb
163
163
  - app/controllers/standard_id/api/passwordless_controller.rb
164
164
  - app/controllers/standard_id/api/sessions_controller.rb
165
+ - app/controllers/standard_id/api/step_up_controller.rb
165
166
  - app/controllers/standard_id/api/userinfo_controller.rb
166
167
  - app/controllers/standard_id/api/well_known/jwks_controller.rb
167
168
  - app/controllers/standard_id/api/well_known/oauth_authorization_server_controller.rb
@@ -178,6 +179,7 @@ files:
178
179
  - app/controllers/standard_id/web/reset_password/start_controller.rb
179
180
  - app/controllers/standard_id/web/sessions_controller.rb
180
181
  - app/controllers/standard_id/web/signup_controller.rb
182
+ - app/controllers/standard_id/web/step_up_controller.rb
181
183
  - app/controllers/standard_id/web/verify_email/base_controller.rb
182
184
  - app/controllers/standard_id/web/verify_email/confirm_controller.rb
183
185
  - app/controllers/standard_id/web/verify_email/start_controller.rb
@@ -245,6 +247,7 @@ files:
245
247
  - app/views/standard_id/web/reset_password/start/show.html.erb
246
248
  - app/views/standard_id/web/sessions/index.html.erb
247
249
  - app/views/standard_id/web/signup/show.html.erb
250
+ - app/views/standard_id/web/step_up/show.html.erb
248
251
  - config/brakeman.ignore
249
252
  - config/initializers/generators.rb
250
253
  - config/locales/en.yml
@@ -274,6 +277,7 @@ files:
274
277
  - db/migrate/20261028000000_add_value_lookup_indexes_to_standard_id_tables.rb
275
278
  - db/migrate/20261028100000_remove_redundant_standard_id_indexes.rb
276
279
  - db/migrate/20261122000000_add_code_digest_to_standard_id_code_challenges.rb
280
+ - db/migrate/20261123000000_add_authenticated_at_to_standard_id_sessions.rb
277
281
  - lib/generators/standard_id/install/install_generator.rb
278
282
  - lib/generators/standard_id/install/templates/standard_id.rb
279
283
  - lib/generators/standard_id/install/templates/standard_id_reference.rb
@@ -356,8 +360,10 @@ files:
356
360
  - lib/standard_id/oauth/token_grant_flow.rb
357
361
  - lib/standard_id/oauth/token_lifetime_resolver.rb
358
362
  - lib/standard_id/otp.rb
363
+ - lib/standard_id/password_pepper.rb
359
364
  - lib/standard_id/passwordless.rb
360
365
  - lib/standard_id/passwordless/base_strategy.rb
366
+ - lib/standard_id/passwordless/code_handoff.rb
361
367
  - lib/standard_id/passwordless/email_strategy.rb
362
368
  - lib/standard_id/passwordless/sms_strategy.rb
363
369
  - lib/standard_id/passwordless/verification_service.rb
@@ -369,6 +375,7 @@ files:
369
375
  - lib/standard_id/routing.rb
370
376
  - lib/standard_id/scope_config.rb
371
377
  - lib/standard_id/session_type_resolver.rb
378
+ - lib/standard_id/step_up.rb
372
379
  - lib/standard_id/testing.rb
373
380
  - lib/standard_id/testing/authentication_helpers.rb
374
381
  - lib/standard_id/testing/config_helpers.rb