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
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c5b800c9bdd221e81804f561bee356990391ca705f62412542deb424d00fd0e9
4
- data.tar.gz: deff24e781f7147bca4d0096309f1bcbc37aa6d46295e6bdeff0d47d40805dca
3
+ metadata.gz: 2362d21d45d2771288474468d9f32f18fd4be058329aafeae789e05a4ad6339f
4
+ data.tar.gz: 9b3780603bc7a3a76d936a2d780bc95522bd55034960098c1bef9c476b154211
5
5
  SHA512:
6
- metadata.gz: c4fb45b06cfb55d73e765443943a18a8237f71fdb1093e152870f041c922d4e994bd9d3ff5c4015ada599a3552da9aca829bd7c5ca0fb5bc608e710a92615d7b
7
- data.tar.gz: 779383c04ce9b1d3548399fae80c08f77ed3f470d4bd9efe2b248cff0455aeb9812353b46a74f859e5e674d7e7264bd36f40b86f340696226b0979f0f1194f98
6
+ metadata.gz: f0eaa52443d01056cc784627aceed9bef678249069ab66150091871b4aa985f70ebae651e6271219623a5045a0da0b6c61342e996e7660d946c8e9af3842314b
7
+ data.tar.gz: 67737af10630f42f4625d309dbf872e9a97c6d0fc1d25165000af58e5a34cecb95e87996e2b874d579c750add493d74f9fd3bb712e9c7c9b2db56e751344067a
data/CHANGELOG.md CHANGED
@@ -7,6 +7,82 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.62.0] - 2026-11-23
11
+
12
+ ### Added
13
+
14
+ - **Step-up authentication (opt-in).** `require_recent_authentication!(within:)` in
15
+ `WebAuthentication` and `ApiAuthentication` lets an action run only when the session (or the
16
+ bearer token's new OIDC `auth_time` claim) proved the account's identity recently. Otherwise
17
+ the web guard redirects to `/step_up`, and the API guard answers RFC 9470's
18
+ `insufficient_user_authentication` 401 with `max_age`. The step-up re-proves identity with a
19
+ fresh `StandardId::Otp` code in its own realm (`c.step_up.realm`, default `"step_up"`), sent to
20
+ the account's verified e-mail or phone, plus the password where the account has one. It stamps
21
+ the session, or (API, `POST /step_up` then `/step_up/verify`) returns a fresh access token.
22
+ Publishes `authentication.step_up.started`, `.succeeded` and `.failed`. Sign-ins stamp the new
23
+ `Session#authenticated_at`, never remember-me. `auth_time` is carried through `/authorize`, the
24
+ authorization-code grant and every refresh (`RefreshToken#authenticated_at`).
25
+ `TokenMinter.mint(authenticated_at:)` sets it for a direct mint; while step-up is on, no custom
26
+ claim can. `c.step_up.token_profile_resolver` names the profile the API step-up re-mints for when
27
+ an account may hold several of the audience's bound type. Needs migration
28
+ `20261123000000_add_authenticated_at_to_standard_id_sessions` and `c.step_up.enabled = true`;
29
+ until then no routes are drawn, no claim is minted, and the guard raises a
30
+ `ConfigurationError`. See README, "Step-up authentication".
31
+ - **Password pepper (opt-in).** `c.password.pepper` hashes new passwords as
32
+ bcrypt(HMAC-SHA256(pepper, password)), so the digests cannot be cracked from
33
+ a database dump alone. Verification tries the current pepper, then
34
+ `c.password.previous_peppers`, then no pepper (`c.password.accept_unpeppered_passwords`,
35
+ default `true`), so turning it on or rotating it locks nobody out. A login
36
+ that matched anything but the current pepper re-hashes through
37
+ `PasswordCredential#rehash_password`: it publishes `credential.password.rehashed`
38
+ (new payload key `pepper_changed`), not `credential.password.changed`, and
39
+ voids that user's remember-me cookies and reset links, as a cost change does.
40
+ Logins for unknown addresses pay one dummy bcrypt comparison per candidate
41
+ pepper, matching a wrong password. With no pepper set (the default) nothing
42
+ changes. **Losing the pepper forces every password hashed under it to be
43
+ reset.** See README, "Password pepper".
44
+ - **`StandardId::Passwordless.issued_code(event)`** hands a `PASSWORDLESS_CODE_GENERATED`
45
+ subscriber the raw one-time code without putting it in the event payload, so delivery works
46
+ with `c.events.publish_records = false`. It returns the published record's code when there is
47
+ one; otherwise the code of the challenge being published right now, only for that event and a
48
+ matching `code_challenge_id`, and only while the publish runs (thread- or fiber-local through
49
+ `ActiveSupport::IsolatedExecutionState`). It returns `nil` after the publish, in another
50
+ thread, or in a job that received the payload, so a subscriber that defers delivery must read
51
+ the code first and pass the string on. The payload still never holds the code, so audit,
52
+ logging and breadcrumb subscribers cannot serialise it. `event[:code_challenge].code` keeps
53
+ working while records are published (the default). See `docs/MIGRATION_GUIDE.md`.
54
+
55
+ ### Changed
56
+
57
+ - **HMAC-signed JWTs verify under `config.previous_secret_key_bases`.** For HS256/384/512,
58
+ `JwtService.decode` tries the current `secret_key_base`, then each previous secret in order,
59
+ and moves on only when the signature doesn't match: an expired token, or one with the wrong
60
+ issuer or audience, is refused at once, as before. New tokens are still signed under the current
61
+ secret only, so refreshing an old-secret refresh token returns tokens under the new one. New
62
+ public `JwtService.symmetric_verification_keys` (current secret first, then previous ones; `[]`
63
+ for an asymmetric algorithm) lets a `JwtService.verify` caller pass
64
+ `key: JwtService.symmetric_verification_keys` for the same window. RS*/ES* keys keep rotating
65
+ through `oauth.previous_signing_keys`, and HS tokens are still refused when the configured
66
+ algorithm is asymmetric. Nothing changes unless previous secrets are listed.
67
+ - **Session tokens and RFC 7592 registration access tokens used under a previous
68
+ `secret_key_base` are re-keyed to the current one.** After a successful
69
+ `Session.authenticate_by_token`, web session-cookie load or Action Cable authentication, a
70
+ session whose `lookup_hash` (or HMAC `token_digest`) is still under a previous secret is
71
+ rewritten in one conditional `UPDATE` (new `StandardId::KeyedDigest.rekey`), so the old secret
72
+ stays needed only for credentials not used since the rotation, rather than for the longest
73
+ session lifetime (or forever, for registration access tokens). The `UPDATE` only applies while
74
+ the row still holds the values just read, skips callbacks, `updated_at` and events, runs in a
75
+ savepoint inside an open transaction, and never fails authentication: an error is logged (model,
76
+ id and error class only) and the token still authenticates. With no previous secrets listed,
77
+ nothing is hashed or written. One-time codes, authorization codes and JWTs are not re-keyed.
78
+
79
+ ### Fixed
80
+
81
+ - **The built-in passwordless mailer delivers with `c.events.publish_records = false`.** With
82
+ records off it found no code, sent nothing and reported `"failed"`; it now reads the code
83
+ through `issued_code` and reports `"sent"`. `StandardId::Testing::OtpHelpers`
84
+ (`capture_otp_code`, `capture_otp_codes`) also work with records off.
85
+
10
86
  ## [0.61.0] - 2026-11-23
11
87
 
12
88
  ### Added
data/README.md CHANGED
@@ -177,6 +177,106 @@ Password digests are made by `has_secure_password` at `BCrypt::Engine.cost` (bcr
177
177
 
178
178
  The digest is also the fingerprint of the remember-me cookie and the password-reset link, so the first login after a cost change signs that user out of remember-me on their other browsers and voids any reset link they have not used yet. The login itself, and a remember-me cookie it sets, are unaffected. The rewrite happens one user at a time as each signs in, never on deploy. Turn it off with `config.password.rehash_on_login = false`.
179
179
 
180
+ ### Password pepper
181
+
182
+ Off by default. A pepper is a secret mixed into every password before bcrypt, so a dump of `standard_id_password_credentials` alone is not enough to crack the digests: the attacker also needs the pepper, which lives in your credentials, not your database.
183
+
184
+ ```ruby
185
+ StandardId.configure do |c|
186
+ c.password.pepper = Rails.application.credentials.password_pepper # SecureRandom.hex(32)
187
+ end
188
+ ```
189
+
190
+ > [!WARNING]
191
+ > **If you lose the pepper, every password hashed under it is gone.** There is no way to verify those digests without it, so each of those users has to reset their password. Store it with `secret_key_base`, back it up the same way, and never commit it. Once it is set, removing it or changing it without the steps below locks those users out.
192
+
193
+ How it works:
194
+
195
+ - New digests are `bcrypt(HMAC-SHA256(pepper, password))`, hex-encoded. The pepper is never appended to the password: bcrypt reads only the first 72 bytes, so an appended pepper would be cut off long passwords.
196
+ - Verification tries the current pepper, then each of `c.password.previous_peppers`, then no pepper at all. So **turning the pepper on locks nobody out**: existing digests still verify.
197
+ - A successful password login (web, OAuth password grant, email + password API) that matched anything but the current pepper re-hashes the password under it, through the same path as a bcrypt cost change ([above](#raising-the-bcrypt-cost)): one conditional `UPDATE`, `credential.password.rehashed` with `pepper_changed: true`, and no `credential.password.changed` event or e-mail, because the password itself did not change. Like a cost change, **the re-hash voids that user's outstanding remember-me cookies and password-reset links**, one user at a time as each signs in. It needs `c.password.rehash_on_login` (on by default); with it off, digests stay where they are and keep verifying.
198
+ - A login for an address with no account pays for the same number of bcrypt comparisons as a wrong password (one per candidate pepper), so timing does not reveal which addresses exist. Each extra candidate costs one more bcrypt comparison per wrong password.
199
+
200
+ **Rotating the pepper.** Move the current pepper into `previous_peppers` and set the new one:
201
+
202
+ ```ruby
203
+ c.password.pepper = Rails.application.credentials.password_pepper_2026
204
+ c.password.previous_peppers = [Rails.application.credentials.password_pepper_2025]
205
+ ```
206
+
207
+ Users move to the new pepper as they sign in. Keep the old pepper listed for as long as anyone who has not signed in since might come back. Dropping it sooner forces those users to reset their password. There is no per-row record of which pepper a digest used, so the safe way to retire an old pepper is to wait out your inactivity window, then force a reset for the accounts that have not signed in since the rotation.
208
+
209
+ **Retiring unpeppered digests.** `c.password.accept_unpeppered_passwords` (default `true`) keeps digests made before the pepper was turned on verifiable. Set it to `false` only once none can be left, on the same terms as dropping an old pepper. It is ignored while no pepper is set.
210
+
211
+ **Turning the pepper off.** Set `pepper = nil` and list the old value in `previous_peppers`. Users move back to bare digests as they sign in.
212
+
213
+ `has_secure_password`'s own `password_challenge` attribute compares the bare password and does not know about the pepper. To check a user's current password, call `password_credential.authenticate(password)`.
214
+
215
+ ### Step-up authentication
216
+
217
+ Off by default. Before a sensitive action (changing an e-mail address, deleting an account, viewing recovery codes), ask a signed-in user to prove it is them again, unless they did so a moment ago. Nothing changes for a host that never calls the guard.
218
+
219
+ **1. Run the migration and turn it on.**
220
+
221
+ ```bash
222
+ bin/rails standard_id:install:migrations
223
+ bin/rails db:migrate # 20261123000000_add_authenticated_at_to_standard_id_sessions
224
+ ```
225
+
226
+ ```ruby
227
+ StandardId.configure do |c|
228
+ c.step_up.enabled = true
229
+ # c.step_up.max_age = 300 # default `within:`, in seconds
230
+ # c.step_up.require_password = true # also ask for the password when the account has one
231
+ # c.step_up.delivery = :built_in # or :custom: your PASSWORDLESS_CODE_GENERATED subscriber, realm "step_up"
232
+ # c.step_up.url = "/step_up" # where the web guard redirects
233
+ end
234
+ ```
235
+
236
+ **2. Guard the action.**
237
+
238
+ ```ruby
239
+ class AccountSettingsController < ApplicationController
240
+ include StandardId::WebAuthentication
241
+ before_action :authenticate_account!
242
+ before_action -> { require_recent_authentication!(within: 5.minutes) }, only: %i[edit update]
243
+ end
244
+
245
+ class Api::RecoveryCodesController < ActionController::API
246
+ include StandardId::ApiAuthentication
247
+ before_action -> { require_recent_authentication!(within: 5.minutes) }
248
+ end
249
+ ```
250
+
251
+ The guard raises `StandardId::ConfigurationError` while `c.step_up.enabled` is off or the migration has not run. It never passes or refuses silently.
252
+
253
+ **What counts as recent.** Each session row records `authenticated_at`, the last time it proved the account's identity. Every interactive sign-in sets it (password, passwordless, social, sign-up), and so does a step-up. Remember-me does not: a cookie is not a fresh proof, so a remembered visitor steps up before a guarded action. Sessions created before the migration have no time and step up once. Bearer tokens carry the OIDC `auth_time` claim, minted only while `c.step_up.enabled` is on:
254
+
255
+ | Token | `auth_time` |
256
+ | --- | --- |
257
+ | password, passwordless OTP, social, email + password grants | the grant itself |
258
+ | `authorization_code` | the browser session's `authenticated_at` at `/authorize` |
259
+ | `refresh_token` | the original grant's, carried on each refresh token (never refreshed into a newer time) |
260
+ | `TokenMinter.mint` | `authenticated_at:` when you pass it, else none |
261
+ | `client_credentials`, implicit | none |
262
+
263
+ A token with no `auth_time` is never recent. While step-up is on, only the recorded authentication sets it: an `auth_time` from `oauth.custom_claims` or `TokenMinter` `claims:` is dropped, recorded time or not.
264
+
265
+ **Web flow.** A stale session is redirected to `/step_up`, and a GET's URL is remembered. The page sends a one-time code to the account's verified e-mail address, or its verified phone number if it has no e-mail. The user enters the code and, when the account has a password, the password. On success the session's `authenticated_at` is set to now and the user returns to the guarded page. Inertia apps render `<namespace>/step_up/show` with `channel`, `target`, `code_sent`, `password_required`, `step_up_path` and `flash`. Signed-out visitors go to login, as before.
266
+
267
+ **API flow.** A stale or `auth_time`-less token gets RFC 9470's challenge:
268
+
269
+ ```http
270
+ HTTP/1.1 401 Unauthorized
271
+ WWW-Authenticate: Bearer realm="StandardId", error="insufficient_user_authentication", error_description="A more recent authentication is required", max_age=300
272
+
273
+ {"error":"insufficient_user_authentication","error_description":"A more recent authentication is required","max_age":300}
274
+ ```
275
+
276
+ The client steps up with its current token. `POST /step_up` sends the code and answers `202 {"channel":"email","password_required":true}`. `POST /step_up/verify` with `{"code":"123456","password":"…"}` answers with a new access token whose `auth_time` is now. That token keeps the old one's `client_id`, `scope` and `aud`, under `grant_type: "step_up"` (lifetime `oauth.token_lifetimes[:step_up]`, else the default). The client then retries with it. No refresh token is issued, so tokens refreshed later carry the original sign-in time. When the audience is bound to a profile type and an account may hold several such profiles, set `c.step_up.token_profile_resolver = ->(account:, claims:) { … }` to name the profile the token is for (from your own claim, e.g. `gid`); otherwise the strict lookup refuses an ambiguous account. Override `render_step_up_required(error)` to answer differently.
277
+
278
+ **The code.** It is a `StandardId::Otp` code in its own realm (`c.step_up.realm`, default `"step_up"`), so a sign-in code cannot stand in for it, and it is bound to the account it was issued to. It is checked before the password, so each code buys at most one password guess, and a wrong password spends it. Issuing is limited by `passwordless.retry_delay` and the `rate_limits.otp_start_*` limits; verifying by `rate_limits.otp_verify_per_ip`. Events: `authentication.step_up.started`, `.succeeded` and `.failed` (see the event table).
279
+
180
280
  ### OAuth Hardening Options
181
281
 
182
282
  Two spec-conformance settings default to the historical (looser) behaviour so
@@ -827,15 +927,23 @@ Subscribe to the `PASSWORDLESS_CODE_GENERATED` event to deliver OTP codes:
827
927
  # config/initializers/standard_id_events.rb
828
928
  StandardId::Events.subscribe(StandardId::Events::PASSWORDLESS_CODE_GENERATED) do |event|
829
929
  next if event[:skip_sender] # Otp.issue(delivery: :manual) — the caller delivers
930
+ code = StandardId::Passwordless.issued_code(event)
830
931
  case event[:channel]
831
932
  when "email"
832
- UserMailer.send_code(event[:identifier], event[:code_challenge].code).deliver_now
933
+ UserMailer.send_code(event[:identifier], code).deliver_now
833
934
  when "sms"
834
- SmsService.send_code(event[:identifier], event[:code_challenge].code)
935
+ SmsService.send_code(event[:identifier], code)
835
936
  end
836
937
  end
837
938
  ```
838
939
 
940
+ `StandardId::Passwordless.issued_code(event)` returns the raw code while the event is being
941
+ published, and `nil` afterwards or on another thread, so read it in the subscriber and pass the
942
+ string on. The code is never part of the payload: audit and event-logging subscribers serialise
943
+ payloads, and the code would end up in their rows. It works with `c.events.publish_records = false`,
944
+ where the payload carries `code_challenge_id` instead of the record. `event[:code_challenge].code`
945
+ still works while records are published.
946
+
839
947
  Set `c.passwordless.delivery = :custom` (the default) so the engine's built-in
840
948
  `PasswordlessMailer` stays out of the way; with `:built_in` the engine emails
841
949
  the code itself — `otp_email` ("Your sign-in code") for the `"authentication"`
@@ -859,10 +967,12 @@ parent's `default from:` does not apply to them.
859
967
  Event payload includes:
860
968
  - `channel` - `"email"` or `"sms"`
861
969
  - `identifier` - The email address or phone number
862
- - `code_challenge` - The code challenge object with `.code` method. The raw code exists only on
863
- this in-memory record: the database stores an HMAC of it (`code_digest`), so read `.code` in the
864
- subscriber and pass the string on; a challenge reloaded later (e.g. in a job that received the
865
- record) returns `nil`
970
+ - `code_challenge` - The code challenge record (left out under `c.events.publish_records = false`).
971
+ The raw code exists only on this in-memory record: the database stores an HMAC of it
972
+ (`code_digest`), and the record does not serialise it. Read the code with
973
+ `StandardId::Passwordless.issued_code(event)` (or `.code` on the record) in the subscriber and
974
+ pass the string on; a challenge reloaded later (e.g. in a job that received the record) returns
975
+ `nil`
866
976
  - `expires_at` - When the code expires
867
977
  - `realm` - The OTP realm (`"authentication"` for sign-in)
868
978
  - `skip_sender` - `true` for `Otp.issue(delivery: :manual)`; don't deliver
@@ -1010,6 +1120,9 @@ Every StandardId event automatically carries tracing metadata (`event_id`, `time
1010
1120
  | | `authentication.password.failed` | `account_lookup`, `error_code`, `error_message` | After password verification fails |
1011
1121
  | | `authentication.otp.failed` | `identifier`, `channel`, `error_code`, `error_message` | After OTP verification fails |
1012
1122
  | | `authentication.method.denied` | `account`, `auth_method`, `provider`, `flow`, `error_message` | `config.login_method_policy` refused the method, after the credential was proven and before any session or token was created (0.45+) |
1123
+ | | `authentication.step_up.started` | `account`, `channel` | A step-up code was issued to a signed-in account (`c.step_up`) |
1124
+ | | `authentication.step_up.succeeded` | `account`, `channel`, `methods` | The account re-proved its identity (`methods`: `["otp"]` or `["otp", "password"]`) |
1125
+ | | `authentication.step_up.failed` | `account`, `stage`, `channel`, `error_code` | A step-up could not start (`stage: :start`, e.g. `no_verified_identifier`) or was refused (`stage: :verify`: `invalid_code`, `invalid_password`, `max_attempts`, …) |
1013
1126
  | Session | `session.creating` | `account`, `session_type`, `ip_address`, `user_agent` | Before a session record is created |
1014
1127
  | | `session.created` | `session`, `account`, `session_type`, `token_issued`, `ip_address`, `user_agent` | After session persistence completes |
1015
1128
  | | `session.validating` | `session` | Before validating an existing session |
@@ -1055,7 +1168,7 @@ Every StandardId event automatically carries tracing metadata (`event_id`, `time
1055
1168
  | | `credential.password.reset_initiated` | `credential`, `account`, `reset_token_expires_at` | After a password reset is initiated |
1056
1169
  | | `credential.password.reset_completed` | `credential`, `account` | After a password reset is confirmed |
1057
1170
  | | `credential.password.changed` | `credential`, `credential_id` (sent even with `events.publish_records = false`), `account`, `reason` (`:password_reset` / `:changed`) | After a new password is committed: by a reset, or by host code assigning `password` (never for a re-hash of the same password). Drives `password.changed_notice_delivery` |
1058
- | | `credential.password.rehashed` | `credential`, `account`, `previous_cost`, `cost` | After a login re-hashed the password at the current bcrypt cost (`password.rehash_on_login`); the password is unchanged |
1171
+ | | `credential.password.rehashed` | `credential`, `account`, `previous_cost`, `cost`, `pepper_changed` | After a login re-hashed the password at the current bcrypt cost or under the current `password.pepper` (`password.rehash_on_login`); the password is unchanged |
1059
1172
  | | `credential.client_secret.created` | `credential`, `client_id` | After a client secret is created |
1060
1173
  | | `credential.client_secret.rotated` | `credential`, `client_id`, `old_secret_revoked_at` | After a client secret rotation |
1061
1174
 
@@ -2043,7 +2156,7 @@ module StandardId
2043
2156
  end
2044
2157
  ```
2045
2158
 
2046
- Pass `provider:` to every `HttpClient` call so the host's `config.network_wrapper` can tell providers apart (see [Social Login Setup](#social-login-setup)). The keyword is new in the release after 0.60.0; a plugin that supports older standard_id releases should check for it, e.g. `HttpClient.method(:post_form).parameters.include?([:key, :provider])`, and leave it out when absent.
2159
+ Pass `provider:` to every `HttpClient` call so the host's `config.network_wrapper` can tell providers apart (see [Social Login Setup](#social-login-setup)). The keyword is new in 0.61.0; a plugin that supports older standard_id releases should check for it, e.g. `HttpClient.method(:post_form).parameters.include?([:key, :provider])`, and leave it out when absent.
2047
2160
 
2048
2161
  **Required interface:** `provider_name`, `authorization_url`, `get_user_info`.
2049
2162
 
@@ -2222,8 +2335,9 @@ patch "/login_verify", params: { code: code }
2222
2335
  codes = capture_otp_codes { ... } # every code issued in the block: identifier, channel, realm, code
2223
2336
  ```
2224
2337
 
2225
- They read `PASSWORDLESS_CODE_GENERATED`, as a delivery subscriber does, so they see nothing when
2226
- `c.events.publish_records = false`. A challenge you create yourself
2338
+ They read `PASSWORDLESS_CODE_GENERATED` with `StandardId::Passwordless.issued_code`, as a delivery
2339
+ subscriber does, so they work whether or not `c.events.publish_records` is on. A challenge you
2340
+ create yourself
2227
2341
  (`CodeChallenge.create!(code: "123456", ...)` or the `:standard_id_code_challenge` factory) still
2228
2342
  verifies with the code you gave it.
2229
2343
 
@@ -2259,8 +2373,10 @@ bundle exec rspec spec/controllers/
2259
2373
  ### Rotating `secret_key_base`
2260
2374
 
2261
2375
  Session tokens, passwordless codes, authorization codes and RFC 7592 registration access tokens are
2262
- stored as digests keyed on `secret_key_base`, so changing it invalidates all of them: everyone is
2263
- signed out. To rotate without that, list the old secret, newest first:
2376
+ stored as digests keyed on `secret_key_base`, and JWTs signed with HS256/384/512 (the default
2377
+ `oauth.signing_algorithm` is `:hs256`) are signed with it, so changing it invalidates all of them:
2378
+ everyone is signed out and every access and refresh token fails. To rotate without that, list the
2379
+ old secret, newest first:
2264
2380
 
2265
2381
  ```ruby
2266
2382
  StandardId.configure do |c|
@@ -2270,11 +2386,41 @@ end
2270
2386
 
2271
2387
  Digests are then still looked up and verified under the old secret (one indexed query covers every
2272
2388
  candidate session lookup hash), while everything new is written under the current one
2273
- (`StandardId::KeyedDigest`). Nothing is re-written in place, so keep the entry until the longest
2274
- session lifetime you issue (`session.*_lifetime`, and the lifetime of any long-lived
2275
- `ServiceSession`) has passed, then remove it.
2276
-
2277
- This covers StandardId's own digests only. The rest of the app needs Rails' rotations too:
2389
+ (`StandardId::KeyedDigest`). HMAC-signed JWTs work the same way: `JwtService.decode` verifies a
2390
+ token under the current secret and then under each previous one, while `encode` always signs with
2391
+ the current secret, so access and refresh tokens issued before the rotation keep working until they
2392
+ expire and every refreshed token is signed under the new secret. Code that calls the config-free
2393
+ `JwtService.verify` itself can pass `key: StandardId::JwtService.symmetric_verification_keys` for the
2394
+ same window. Asymmetric signing keys (RS*/ES*) are unaffected: rotate those with
2395
+ `oauth.previous_signing_keys`.
2396
+
2397
+ **Credentials move to the new secret when they are used.**
2398
+ - A session token, or an RFC 7592 registration access token, that authenticates under a previous
2399
+ secret is re-keyed on the spot. Its `lookup_hash`/`token_digest`, or its digest, is rewritten
2400
+ under the current secret in a single conditional UPDATE.
2401
+ - This happens on the authenticating paths: `Session.authenticate_by_token`, the web session
2402
+ cookie, Action Cable, and the RFC 7592 endpoints.
2403
+ - A credential that already matches under the current secret causes no write. A write that fails
2404
+ (a read-only replica, a lock timeout) is logged and the request still succeeds; that credential
2405
+ is simply tried again next time.
2406
+ - A refresh grant always returns tokens signed under the current secret.
2407
+
2408
+ **How long to keep the old secret.** Only credentials that have not been used since the rotation
2409
+ still depend on it. Keep the entry for as long as you are willing to wait for idle users to come
2410
+ back: once you remove it, anything untouched since the rotation stops working. Those users sign in
2411
+ again, and a client re-registers. The longest lifetime you issue is the point after which nothing
2412
+ can depend on the old secret any more:
2413
+ - `session.*_lifetime`
2414
+ - long-lived `ServiceSession`s
2415
+ - `oauth.refresh_token_lifetime`
2416
+ - registration access tokens, which last as long as their client
2417
+
2418
+ One-time codes and authorization codes are single-use and short-lived, so they are not rewritten.
2419
+ They need the entry only for `passwordless.code_ttl` (10 minutes by default) and the authorization
2420
+ code TTL (10 minutes).
2421
+
2422
+ This covers StandardId's own digests and HMAC-signed JWTs only. The rest of the app needs Rails'
2423
+ rotations too:
2278
2424
 
2279
2425
  - **Cookies**, including the encrypted `session_token` cookie and the Rails session that carry the
2280
2426
  web session: `config.action_dispatch.cookies_rotations` (see the Rails security guide,
@@ -2282,9 +2428,6 @@ This covers StandardId's own digests only. The rest of the app needs Rails' rota
2282
2428
  - **Message verifiers** (`generates_token_for`, so remember-me and password-reset tokens, and the
2283
2429
  signed passwordless OTP payload): `Rails.application.message_verifiers.rotate(secret_key_base:
2284
2430
  old)` in a `before_initialize` block.
2285
- - **JWTs signed with HS256** (the default `oauth.signing_algorithm`) use `secret_key_base` directly
2286
- and are not covered: access tokens fail until re-issued and HS256 refresh tokens stop refreshing.
2287
- Use an asymmetric `oauth.signing_key` if you need to rotate without that.
2288
2431
 
2289
2432
  ## OTP Start Limits
2290
2433
 
@@ -27,6 +27,7 @@ module StandardId
27
27
  browser_session = StandardId::BrowserSession.eager_load(:account).by_token(session_token).first
28
28
  return nil unless browser_session&.active?
29
29
 
30
+ browser_session.rekey_token(session_token)
30
31
  browser_session.account
31
32
  end
32
33
  end
@@ -6,6 +6,10 @@ module StandardId
6
6
  if StandardId.config.alias_current_user
7
7
  define_method(:current_user) { current_account }
8
8
  end
9
+
10
+ # Only require_recent_authentication! raises it, so a controller that
11
+ # never calls the guard never reaches this.
12
+ rescue_from StandardId::StepUpRequiredError, with: :render_step_up_required
9
13
  end
10
14
 
11
15
  delegate :current_session, :current_account, :revoke_current_session!, to: :session_manager
@@ -24,6 +28,32 @@ module StandardId
24
28
  authentication_guard.require_scopes!(session_manager, *required_scopes)
25
29
  end
26
30
 
31
+ # Step-up guard for a sensitive action (opt-in, see StandardId::StepUp):
32
+ # verifies the access token, then requires its `auth_time` claim to be
33
+ # within +within+ (default c.step_up.max_age). A stale or missing
34
+ # `auth_time` raises StandardId::StepUpRequiredError, rendered as RFC 9470's
35
+ # challenge (#render_step_up_required); the client steps up through
36
+ # POST /step_up and /step_up/verify and retries with the token that returns.
37
+ # Needs c.step_up.enabled; raises StandardId::ConfigurationError otherwise.
38
+ def require_recent_authentication!(within: StandardId::StepUp.max_age)
39
+ StandardId::StepUp.ensure_usable!
40
+ api_session = verify_access_token!
41
+ return api_session if StandardId::StepUp.recent?(api_session, within: within)
42
+
43
+ raise StandardId::StepUpRequiredError.new(max_age: within)
44
+ end
45
+
46
+ # RFC 9470 §3: 401 with `error="insufficient_user_authentication"` and the
47
+ # `max_age` the authentication may have. Override to answer differently.
48
+ def render_step_up_required(error)
49
+ description = error.message
50
+ challenge = %(Bearer realm="StandardId", error="insufficient_user_authentication", error_description="#{description}")
51
+ challenge += %(, max_age=#{error.max_age}) if error.max_age
52
+ response.set_header("WWW-Authenticate", challenge)
53
+ render json: { error: "insufficient_user_authentication", error_description: description, max_age: error.max_age }.compact,
54
+ status: :unauthorized
55
+ end
56
+
27
57
  def session_manager
28
58
  @session_manager ||= StandardId::Api::SessionManager.new(token_manager, request:)
29
59
  end
@@ -23,6 +23,12 @@ module StandardId
23
23
  # session creation (for lifecycle hooks). Returns the PasswordCredential on
24
24
  # success, nil on failure.
25
25
  #
26
+ # - `require_recent_authentication!(within:)` -- Step-up guard (opt-in, see
27
+ # StandardId::StepUp): lets the action run only when the current session
28
+ # proved the account's identity within `within` (default
29
+ # c.step_up.max_age), else redirects to the step-up page and returns here
30
+ # after it.
31
+ #
26
32
  # - `session_manager` -- Returns the StandardId::Web::SessionManager instance
27
33
  # for the current request. Useful for direct session operations like
28
34
  # `session_manager.sign_in_account(account)` in passwordless flows.
@@ -79,6 +85,26 @@ module StandardId
79
85
  redirect_to_login
80
86
  end
81
87
 
88
+ # Step-up guard for a sensitive action, as a before_action:
89
+ #
90
+ # before_action -> { require_recent_authentication!(within: 5.minutes) }, only: %i[edit update]
91
+ #
92
+ # Signed out: the same redirect to login as authenticate_account!. Signed
93
+ # in, but the session last proved the account's identity longer ago than
94
+ # +within+ (or never, as for a remember-me session): redirects to
95
+ # c.step_up.url (default "/step_up"), remembering a GET's URL so the
96
+ # step-up comes back to it. Needs c.step_up.enabled; raises
97
+ # StandardId::ConfigurationError otherwise rather than silently passing or
98
+ # refusing.
99
+ def require_recent_authentication!(within: StandardId::StepUp.max_age)
100
+ StandardId::StepUp.ensure_usable!
101
+ return authenticate_account! unless authenticated?
102
+ return if StandardId::StepUp.recent?(current_session, within: within)
103
+
104
+ session[:return_to_after_step_up] = request.url if request.get?
105
+ redirect_with_inertia(StandardId.config.step_up.url.presence || "/step_up")
106
+ end
107
+
82
108
  # Store the current URL to redirect back after authentication
83
109
  def store_location_for_redirect
84
110
  session[:return_to_after_authenticating] = request.url if request.get?
@@ -129,9 +155,9 @@ module StandardId
129
155
  StandardId::PasswordCredential.find_by(login:).tap do |password_credential|
130
156
  authenticated = password_credential&.authenticate(password)
131
157
 
132
- # Perform a dummy bcrypt comparison when the credential doesn't exist
133
- # to prevent user enumeration via response timing differences.
134
- BCrypt::Password.new(dummy_password_digest).is_password?(password) unless password_credential
158
+ # Perform the dummy bcrypt comparisons when the credential doesn't
159
+ # exist to prevent user enumeration via response timing differences.
160
+ StandardId::PasswordPepper.dummy_authenticate(password) unless password_credential
135
161
 
136
162
  unless authenticated
137
163
  StandardId::Events.publish(
@@ -193,10 +219,6 @@ module StandardId
193
219
  @token_manager ||= StandardId::Web::TokenManager.new(request)
194
220
  end
195
221
 
196
- def dummy_password_digest
197
- @dummy_password_digest ||= BCrypt::Password.create("").freeze
198
- end
199
-
200
222
  def authentication_guard
201
223
  @authentication_guard ||= StandardId::Web::AuthenticationGuard.new
202
224
  end
@@ -0,0 +1,92 @@
1
+ module StandardId
2
+ module Api
3
+ # Step-up for bearer clients (StandardId::StepUp), answering the
4
+ # `insufficient_user_authentication` challenge
5
+ # ApiAuthentication#require_recent_authentication! renders:
6
+ #
7
+ # POST /step_up → a code goes to the account's verified e-mail
8
+ # (or phone); says where, and whether the
9
+ # password is needed too
10
+ # POST /step_up/verify → { code, password } → a fresh access token whose
11
+ # `auth_time` is now; retry the request with it
12
+ #
13
+ # Both need the current access token. The new token keeps that token's
14
+ # client_id, scope and audience, under grant_type "step_up"
15
+ # (oauth.token_lifetimes[:step_up], else the default lifetime). No refresh
16
+ # token is issued: the client keeps its own, and tokens refreshed from it
17
+ # carry the original sign-in's auth_time. For an audience bound to a
18
+ # profile type, set c.step_up.token_profile_resolver when an account may
19
+ # hold several such profiles. Routed only while c.step_up.enabled is true.
20
+ class StepUpController < BaseController
21
+ authenticated_controller
22
+
23
+ rate_limit to: StandardId.config.rate_limits.otp_verify_per_ip,
24
+ within: 15.minutes,
25
+ name: "api-step-up-verify-ip",
26
+ only: :verify,
27
+ store: StandardId::RateLimitHandling::RATE_LIMIT_STORE
28
+
29
+ before_action :verify_access_token!
30
+ # A token whose account config.account_scope no longer finds is no
31
+ # longer anyone's to step up.
32
+ before_action -> { render_bearer_unauthorized! if current_account.nil? }
33
+
34
+ def create
35
+ result = StandardId::StepUp.start(account: current_account, request: request)
36
+ return render_failure(result) unless result.success? || result.error_code == :cooldown
37
+
38
+ render json: {
39
+ channel: result.channel,
40
+ password_required: StandardId::StepUp.password_required?(current_account)
41
+ }, status: :accepted
42
+ end
43
+
44
+ def verify
45
+ result = StandardId::StepUp.verify(
46
+ account: current_account,
47
+ code: string_param(:code),
48
+ password: string_param(:password),
49
+ request: request
50
+ )
51
+ return render_failure(result) unless result.success?
52
+
53
+ minted = StandardId::TokenMinter.mint(
54
+ account: current_account,
55
+ audience: current_session.aud,
56
+ scopes: Array(current_session.scopes).join(" ").presence,
57
+ client_id: current_session.client_id,
58
+ grant_type: "step_up",
59
+ authenticated_at: Time.current,
60
+ profile: token_profile
61
+ )
62
+ render json: {
63
+ access_token: minted.access_token,
64
+ token_type: minted.token_type,
65
+ expires_in: minted.expires_in,
66
+ scope: minted.scope
67
+ }.compact, status: :ok
68
+ end
69
+
70
+ private
71
+
72
+ # c.step_up.token_profile_resolver's choice, for an audience whose
73
+ # account may hold several profiles of the bound type.
74
+ def token_profile
75
+ resolver = StandardId.config.step_up.token_profile_resolver
76
+ return nil unless resolver.respond_to?(:call)
77
+
78
+ resolver.call(account: current_account, claims: current_session.claims.to_h.with_indifferent_access)
79
+ end
80
+
81
+ def string_param(key)
82
+ value = params[key]
83
+ value.is_a?(String) ? value : nil
84
+ end
85
+
86
+ def render_failure(result)
87
+ status = (result.error_code == :rate_limited) ? :too_many_requests : :unprocessable_content
88
+ render json: { error: result.error_code.to_s, error_description: result.error_message }, status: status
89
+ end
90
+ end
91
+ end
92
+ end
@@ -0,0 +1,83 @@
1
+ module StandardId
2
+ module Web
3
+ # The step-up page WebAuthentication#require_recent_authentication! sends a
4
+ # stale session to (StandardId::StepUp):
5
+ #
6
+ # GET /step_up → "send me a code", or the code (+ password) form once sent
7
+ # POST /step_up → issues a code to the account's verified e-mail (or phone)
8
+ # PATCH /step_up → checks it; on success marks the current session as
9
+ # just authenticated and returns to the guarded page
10
+ #
11
+ # Signed-out visitors go to login, as for any authenticated page. Routed
12
+ # only while c.step_up.enabled is true. Inertia apps render
13
+ # "<namespace>/step_up/show" with #step_up_page_props.
14
+ class StepUpController < BaseController
15
+ authenticated_controller
16
+
17
+ include StandardId::InertiaRendering
18
+
19
+ layout "public"
20
+
21
+ rate_limit to: StandardId.config.rate_limits.otp_verify_per_ip,
22
+ within: 15.minutes,
23
+ name: "step-up-verify-ip",
24
+ only: :update,
25
+ store: StandardId::RateLimitHandling::RATE_LIMIT_STORE
26
+
27
+ def show
28
+ render_with_inertia props: step_up_page_props
29
+ end
30
+
31
+ def create
32
+ result = StandardId::StepUp.start(account: current_account, request: request)
33
+
34
+ if result.success? || result.error_code == :cooldown
35
+ session[:step_up_code_sent] = true
36
+ flash[:notice] = result.success? ? "We sent you a code" : "A code was sent moments ago. Check your inbox"
37
+ redirect_with_inertia engine_path(step_up_path), status: :see_other
38
+ else
39
+ flash.now[:alert] = result.error_message
40
+ render_with_inertia action: :show, props: step_up_page_props, status: :unprocessable_content
41
+ end
42
+ end
43
+
44
+ def update
45
+ result = StandardId::StepUp.verify(
46
+ account: current_account,
47
+ code: string_param(:code),
48
+ password: string_param(:password),
49
+ request: request
50
+ )
51
+
52
+ unless result.success?
53
+ flash.now[:alert] = result.error_message
54
+ render_with_inertia action: :show, props: step_up_page_props, status: :unprocessable_content
55
+ return
56
+ end
57
+
58
+ StandardId::StepUp.mark!(current_session)
59
+ session.delete(:step_up_code_sent)
60
+ destination = session.delete(:return_to_after_step_up)
61
+ destination = safe_post_signin_default unless safe_destination?(destination)
62
+ redirect_after_authentication destination, notice: "Thanks, you're verified"
63
+ end
64
+
65
+ private
66
+
67
+ # Where the code goes is the account's own verified address, shown so
68
+ # its owner knows where to look.
69
+ def step_up_page_props
70
+ channel, target = StandardId::StepUp.destination_for(current_account)
71
+ {
72
+ flash: { notice: flash[:notice], alert: flash[:alert] }.compact,
73
+ channel: channel,
74
+ target: target,
75
+ code_sent: session[:step_up_code_sent] == true,
76
+ password_required: StandardId::StepUp.password_required?(current_account),
77
+ step_up_path: engine_path(step_up_path)
78
+ }
79
+ end
80
+ helper_method :step_up_page_props
81
+ end
82
+ end
83
+ end